Compare commits

..

No commits in common. "95067aeb8a7c126af62eac9d610de6975e433cea" and "ff84a993063ee61fb7cf230cdbd69634db7c76d9" have entirely different histories.

87 changed files with 1280 additions and 10999 deletions

View File

@ -161,26 +161,6 @@ rg "class .*Service|module.exports" app/service/qimenMethods
- 接口文档:`methods/system.json` 分组「站内信」(module=inbox),变更记录见 `methods/changes/system.json` 版本 `2026.08.30-inbox-group-members-groupids-array`、`2026.08.30-inbox-group-quicklist-dual-dim-filter`(修正/取代 `2026.08.30-inbox-group-quicklist-store-id`)、`2026.08.29-inbox-group-quick-list-members`
- 索引迁移(待发布时执行):`database/migrations/20260830150000-add-store-id-index-to-wms-inbox-group.js` 为 wms_inbox_group.store_id 新增索引 idx_store_id(幂等 up/down,尚未执行)
## 5.3 workbench(工作台绑定码 / 登录码 / token)能力速查
| method | 实现文件 | 函数 | 登录 | 鉴权/权限 |
|---|---|---|---|---|
| index.getWorkbenchBindCode | app/service/systemMethods/index.js → app/service/systems/workbench.js | getWorkbenchBindCode / getWorkbenchBindCode | 免登录 | 免权限(systemInit 声明) |
| workbench.bind | app/service/systemMethods/workbench.js → app/service/systems/workbench.js | bind / bindWorkbench | 需登录 | 需权限(未声明免权限) |
| workbench.getWorkbenchInfo | app/service/systemMethods/workbench.js → app/service/systems/workbench.js | getWorkbenchInfo / getWorkbenchInfoByToken | 免登录 | 免权限(systemInit 声明) |
| index.LoginWorkbenchByCode | app/service/systemMethods/index.js → app/service/systems/workbench.js | LoginWorkbenchByCode / loginWorkbenchByCode | 免登录 | 免权限(systemInit 声明) |
| workbench.resetLoginCode | app/service/systemMethods/workbench.js → app/service/systems/workbench.js | resetLoginCode / resetLoginCode | 需登录 | 需权限(未声明免权限) |
| workbench.removeMember | app/service/systemMethods/workbench.js → app/service/systems/workbench.js | removeMember / removeWorkbenchMember | 免登录 | 免权限(systemInit 声明) |
| workbench.bindMember | app/service/systemMethods/workbench.js → app/service/systems/workbench.js | bindMember / bindWorkbenchMember | 免登录 | 免权限(systemInit 声明) |
- 绑定流程:设备调 `index.getWorkbenchBindCode` 拿 client_code + 绑定码(缓存 `workbench:bind:client:{clientCode}` / `workbench:bind:code:{code}`,TTL 120s)→ 管理员调 `workbench.bind`(code + 工作台ID)写入随机 64 位 token 并删除旧 `workbench:token:{旧token}` 缓存 → 设备侧长轮询(60s 超时,每秒轮询)拿到 token;超时/缓存失效时重新生成绑定码后才返回
- token 登录:`index.LoginWorkbenchByCode` 以 `wms_workbench.login_code` 换取 token(无匹配返回 code=403 业务失败;工作台无 token 时自动生成持久化);`workbench.getWorkbenchInfo` 以 token 获取工作台信息(缓存优先、查库兜底、无信息返回 code=403 业务失败)
- 字段:`wms_workbench` 新增 `login_code`(前缀 wblc + 随机段共 64 位,全局唯一索引 uk_login_code)、`token`(随机 64 位,索引 idx_token);`workbench.create` 自动生成 login_code;`workbench.update` 不受理 login_code/token 传入;`workbench.list` 返回 login_code、不返回 token
- 成员副表:`wms_workbench_member`(工作台成员/用户登录,user_id 可空兼容非系统账号用户、user_name 名称快照、软删除);`workbench.bindMember` 免登录免鉴权(入参 userId 可空 + userName 姓名必填 + 工作台 token)新增成员行;`workbench.removeMember` 免登录免鉴权(入参行 ids + 工作台 token)按 token 解析工作台后仅软删除归属该工作台的成员行
- 403 口径:/system 网关不支持方法内设置 HTTP 状态码,按现有惯例返回 `flag=failure、code=403` 业务失败(与 stock/warehouse.js 同款)
- 接口文档:`methods/system.json` 分组「工作台模块」(module=workbench)与「基础模块」(module=index),变更记录见 `methods/changes/system.json` 版本 `2026.09.03-workbench-login-code-token`、`2026.09.03-workbench-member-remove`、`2026.09.03-workbench-member-bind`
- 迁移:`database/migrations/20260903100000-add-login-code-token-to-wms-workbench.js`(幂等 up/down,已在开发库执行;生产库待发布时按标准流程执行)
## method结束
## 6. 全量 Service Method 能力清单(自动扫描)
@ -192,7 +172,7 @@ rg "class .*Service|module.exports" app/service/qimenMethods
- 临时清单输出:temp/tmp-service-method-inventory.md
<!-- SERVICE_METHOD_INVENTORY:BEGIN -->
自动生成时间: 2026-09-03T09:57:21.473Z
自动生成时间: 2026-08-28T20:06:02.056Z
扫描范围: app/service/**/*.js
文件数: 203
@ -287,14 +267,14 @@ rg "class .*Service|module.exports" app/service/qimenMethods
- list
- app/service/systemMethods/dashboard.js (17)
- storeStats, storeSideStoreStats, queryWarehouseStats, mergeStoreStats, emptyStoreStats, warehouseStats, hot_order_rank, express_ratio, storeSideExpressRatio, queryWarehouseExpressRatio, mergeChartData, formatChartData, emptyChartData, platform_distribution, storeSidePlatformDistribution, queryWarehousePlatformDistribution, order_trend
- app/service/systemMethods/inbox.js (13)
- group, message, after_sales, bindCode, groupList, groupQuickList, groupMembers, groupDisable, groupUpdate, groupReset, groupMessages, retry, reply
- app/service/systemMethods/index.js (57)
- 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
- app/service/systemMethods/inbox.js (11)
- group, message, after_sales, bindCode, groupList, groupDisable, groupUpdate, groupReset, groupMessages, retry, reply
- app/service/systemMethods/index.js (55)
- 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
- app/service/systemMethods/order/archiveOrder.js (2)
- list, detail
- app/service/systemMethods/order/base.js (57)
- maskListSensitiveValue, isInterceptedOrderStatus, isLockedOrderStatus, assertOrderNotIntercepted, getWarehouseId, getOrderLogOperator, getOrderLogWarehouseId, normalizePagination, normalizeWhereInput, normalizeOrderIds, isMergeableWhereCondition, mergeWhereObjects, getModuleConfig, getDefaultWhere, getBadgeCountCacheKey, formatBadgeCountValue, formatWeightTypeLabel, formatCreateChannelLabel, normalizeWaveScanResult, normalizeWaveStrategyVersion, normalizeLockStatusFlag, normalizeOrderListItem, getBadgeCountByModule, getOrderModel, resolveOrderTableType, getOrderModelByTableType, getOrderItemsModelByTableType, getOrderExpressesByOrderId, normalizeOrderListRow, attachOrderExpressNumbers, attachOrderWaveIndex, extractOrderListExpressVirtualFilter, extractBuyerMessageHasVirtualFilter, extractStockQueryVirtualFilter, extractWaveIndexVirtualFilter, extractWaveScopeVirtualFilter, findOrderIdsByWaveIndexCondition, in, buildWaveScopeFilterCondition, buildBuyerMessageHasCondition, appendConditionToWhere, normalizeExpressFilterValues, findOrderIdsByExpressNumbers, findOrderIdsByStockQuery, appendOrderIdsFilterToWhere, buildListOrder, buildWhere, listByModule, detail, attachStockDetailsToOrderItems, getOrderOperationLogs, resolveReviewStep, normalizeReviewOrderIds, buildOrderWhere, buildReviewOrderWhere, updateReviewOrder, updateOrderInspectionState
- maskListSensitiveValue, isInterceptedOrderStatus, isLockedOrderStatus, assertOrderNotIntercepted, getWarehouseId, getOrderLogOperator, getOrderLogWarehouseId, normalizePagination, normalizeWhereInput, normalizeOrderIds, isMergeableWhereCondition, mergeWhereObjects, getModuleConfig, getDefaultWhere, getBadgeCountCacheKey, formatBadgeCountValue, formatWeightTypeLabel, formatCreateChannelLabel, normalizeWaveScanResult, normalizeWaveStrategyVersion, normalizeLockStatusFlag, normalizeOrderListItem, getBadgeCountByModule, getOrderModel, resolveOrderTableType, getOrderModelByTableType, getOrderItemsModelByTableType, getOrderExpressesByOrderId, normalizeOrderListRow, attachOrderExpressNumbers, attachOrderWaveIndex, extractOrderListExpressVirtualFilter, extractBuyerMessageHasVirtualFilter, extractStockQueryVirtualFilter, extractWaveIndexVirtualFilter, extractWaveScopeVirtualFilter, findOrderIdsByWaveIndexCondition, in, buildWaveScopeWhereCondition, buildBuyerMessageHasCondition, appendConditionToWhere, normalizeExpressFilterValues, findOrderIdsByExpressNumbers, findOrderIdsByStockQuery, appendOrderIdsFilterToWhere, buildListOrder, buildWhere, listByModule, detail, attachStockDetailsToOrderItems, getOrderOperationLogs, resolveReviewStep, normalizeReviewOrderIds, buildOrderWhere, buildReviewOrderWhere, updateReviewOrder, updateOrderInspectionState
- app/service/systemMethods/order/deliveryExpectionOrder.js (2)
- list, detail
- app/service/systemMethods/order/deliveryOrder.js (5)
@ -307,8 +287,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods
- export, exportTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress, list, manualOutboundOrder, badgeCount, queryOrderLogs, queryOrderLogList, updateExpressWeighingWeight, bindExpressPackageMaterial, bindExpressPackageMaterialByWaybill, pullReviewDataByWaybill
- app/service/systemMethods/order/outboundOrder.js (2)
- list, manualOutboundOrder
- app/service/systemMethods/order/packing.js (11)
- list, get, setEndTime, forceRecord, export, exportTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress
- app/service/systemMethods/order/packing.js (4)
- list, get, setEndTime, forceRecord
- app/service/systemMethods/order/pendingOrder.js (41)
- list, detail, reverseReviewOrder, assertOrdersWithoutWaybill, syncWavesAfterReverseReview, allocateStorage, allocateStorageProgress, normalizeAllocateStorageTaskProgress, normalizeAllocateStorageTaskCount, normalizeAllocateStorageTaskCounts, normalizeAllocateStorageRequestId, getAllocateStorageTaskCacheKey, setAllocateStorageTaskProgress, getAllocateStorageTaskProgress, getAllocateExpressTaskCacheKey, normalizeAllocateExpressTaskId, setAllocateExpressTaskProgress, getAllocateExpressTaskProgress, getSyncOrderIdsTaskCacheKey, normalizeSyncOrderIdsRequestId, setSyncOrderIdsTaskProgress, getSyncOrderIdsTaskProgress, cancelAllocateStorage, syncOrderIds, syncOrderIdsProgress, allocateExpressCode, allocateExpressCodeTaskProgress, markPendingOutboundOrder, cancelOrder, normalizePendingOutboundOrderIds, normalizePendingCancelOrderIds, isCancelablePendingOrder, updateOrderPlatform, updateOrderExpress, updateAddress, updateRemark, cloneOrder, parseAddress, _parseAddressBatchOneShot, _parseSingleAddress, catch
- app/service/systemMethods/order/print.js (4)
@ -335,16 +315,14 @@ rg "class .*Service|module.exports" app/service/qimenMethods
- list
- app/service/systemMethods/report.js (7)
- generate, generateTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress
- app/service/systemMethods/report/definition.js (4)
- typeList, save, list, delete
- app/service/systemMethods/report/deliveryLog.js (1)
- list
- app/service/systemMethods/report/deliveryPlan.js (3)
- save, copy, list
- app/service/systemMethods/returnReceived.js (12)
- _call, create, list, detail, delete, export, exportTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress
- app/service/systemMethods/returnUnpack.js (20)
- _call, create, addDetail, updateDetail, removeDetail, cancel, submit, forceRecord, list, detailList, videoList, detail, export, exportTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress, delete
- app/service/systemMethods/report/deliveryPlan.js (2)
- save, list
- app/service/systemMethods/returnReceived.js (5)
- _call, create, list, detail, delete
- app/service/systemMethods/returnUnpack.js (15)
- _call, create, addDetail, updateDetail, removeDetail, cancel, submit, forceRecord, list, detailList, videoList, detail, export, exportTaskProgress, delete
- app/service/systemMethods/returnWaybill.js (6)
- _call, create, update, list, detail, delete
- app/service/systemMethods/setting/account.js (7)
@ -405,8 +383,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods
- createStore, createWarehouse, joinStore, joinWarehouse, getStoreRoles, auditApply
- app/service/systemMethods/storeWarehouse.js (0)
- <no-class-method-found>
- app/service/systemMethods/storeWarehouse/store.js (27)
- list, sign, confirmSign, rename, unbind, adjustPrintQuantity, queryPrintQuantityLogs, getPolicyConfig, getPolicyConfigFields, savePolicyConfig, listApiConfig, saveApiConfig, deleteQimenConfig, openAccount, createUser, export, exportTaskProgress, exportPrintQuantityLogs, exportPrintQuantityLogsTaskProgress, queryStorePrintQuantityLogs, exportStorePrintQuantityLogs, exportStorePrintQuantityLogsTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress
- app/service/systemMethods/storeWarehouse/store.js (25)
- list, sign, confirmSign, rename, unbind, adjustPrintQuantity, queryPrintQuantityLogs, getPolicyConfig, getPolicyConfigFields, savePolicyConfig, listApiConfig, saveApiConfig, deleteQimenConfig, openAccount, createUser, exportPrintQuantityLogs, exportPrintQuantityLogsTaskProgress, queryStorePrintQuantityLogs, exportStorePrintQuantityLogs, exportStorePrintQuantityLogsTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress
- app/service/systemMethods/storeWarehouse/warehouse.js (3)
- list, sign, confirmSign
- app/service/systemMethods/user.js (9)
@ -415,8 +393,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods
- getWarehouseZones, getWarehouseTree, getChildren, create, update, delete, detail, checkBarcodeUnique, toggleActive, getPath, getPickPath, updateRackPosition, recalculatePickPath, updateNeighbors, getAreaRacks, getSpacesByRack, createRackWithSpaces, getSpaceInfo, updateSpaceInfo, getBatchFieldValue, hasBatchField, normalizeBatchString, getCurrentWarehouseCode, batchUpdateSpaceInfo, exportRackSpaces
- app/service/systemMethods/waybill/warehouse.js (9)
- list, detail, export, exportTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress
- app/service/systemMethods/workbench.js (12)
- list, detail, create, update, delete, business, bindCamera, bind, getWorkbenchInfo, resetLoginCode, removeMember, bindMember
- app/service/systemMethods/workbench.js (8)
- list, detail, create, update, delete, business, bindCamera, checkBarcode
- app/service/systems/account_platform.js (11)
- getActiveInclude, getPrimaryRoleBinding, formatActiveContext, switchActiveRole, getActiveRoleByPlatform, getMultiplePlatformActiveRoles, getAllPlatformActives, clearPlatformActive, clearPlatformCache, getAvailableRoles, getCurrentContext
- app/service/systems/afterSale.js (29)
@ -435,12 +413,12 @@ rg "class .*Service|module.exports" app/service/qimenMethods
- list, detail, create, update, delete
- 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 (50)
- getStoreSubjectConfigCacheKey, normalizeStoreSubjectConfig, getStoreSubjectConfig, findCodeOption, getOptionName, appendOrderOperationLog, getOrderLogOperator, getOrderLogWarehouseId, flushOrderOperationLogs, findPlatformOptionByCode, getPlatformSnapshotCode, getPlatformSnapshotName, resolvePlatformSnapshot, resolveExpressCodeFromSetting, resolveExpressSettingSnapshot, resolveEnableExternalExpressCode, resolveExpressSnapshot, addOrder, isPrimaryKeyDuplicate, formatOrderCreateError, resolveOrderStep, generateItemsHash, calculateCRC32, normalizeOrderFromKey, resolveOperatorName, prepareOrderData, addOrderLines, buildOrderItemSnapshot, safeParseFloat, withPatchedCtxUser, buildAsyncProcessContext, buildExpressAllocateRequest, enqueueAutoWaybillAllocation, buildStorageAllocateRequest, getStoreWarehousePolicyConfig, normalizePolicyFlag, resolveCutoffOrderConfig, isPastCutoffTime, Date, isAllocationWindowClosed, buildAutoGroupingStructure, findAutoGroupingWaveId, appendOrderToWave, countCandidateGroupOrders, createGroupingWave, markWaveAutoGrouping, finishAutoGroupingIfNeeded, runAutoGrouping, runAsyncProcessStep, asyncProcessOrderCreated
- app/service/systems/delivery_order.js (48)
- getStoreSubjectConfigCacheKey, normalizeStoreSubjectConfig, getStoreSubjectConfig, findCodeOption, getOptionName, appendOrderOperationLog, getOrderLogOperator, getOrderLogWarehouseId, flushOrderOperationLogs, findPlatformOptionByCode, getPlatformSnapshotCode, getPlatformSnapshotName, resolvePlatformSnapshot, resolveExpressCodeFromSetting, resolveExpressSettingSnapshot, resolveEnableExternalExpressCode, resolveExpressSnapshot, addOrder, isPrimaryKeyDuplicate, formatOrderCreateError, resolveOrderStep, generateItemsHash, calculateCRC32, normalizeOrderFromKey, resolveOperatorName, prepareOrderData, addOrderLines, buildOrderItemSnapshot, safeParseFloat, withPatchedCtxUser, buildAsyncProcessContext, buildExpressAllocateRequest, enqueueAutoWaybillAllocation, buildStorageAllocateRequest, getStoreWarehousePolicyConfig, normalizePolicyFlag, resolveCutoffOrderConfig, isPastCutoffTime, buildAutoGroupingStructure, findAutoGroupingWaveId, appendOrderToWave, countCandidateGroupOrders, createGroupingWave, markWaveAutoGrouping, finishAutoGroupingIfNeeded, runAutoGrouping, runAsyncProcessStep, asyncProcessOrderCreated
- app/service/systems/entry_order.js (16)
- addOrder, getLineCount, received, success, fail, findByOrderCode, findByStatus, getStatsByWarehouse, updateSyncStatus, updateOrderStatus, calculateReceivedQuantities, batchUpdateReceived, getOrderProgress, tryCreateEntryOrder, addItems, reviewEntry
- app/service/systems/excel.js (26)
- getContentType, sanitizeSheetName, normalizeHeaders, normalizeColumns, prepareSheetData, hasEmbeddedImages, buildWorksheet, buildWorkbook, buildExcelJsWorkbook, inferImageExtension, resolveImageSource, mergeCellStyle, applyStyledRows, applyTextColumnsToSheetJs, applyTextColumnsToExcelJs, addEmbeddedImages, generateBuffer, writeFile, writeAtomicBufferFile, sanitizeFilename, buildUploadKey, generateAndUpload, sendFile, parseBuffer, parseFile, workbookToJSON
- app/service/systems/excel.js (24)
- getContentType, sanitizeSheetName, normalizeHeaders, normalizeColumns, prepareSheetData, hasEmbeddedImages, buildWorksheet, buildWorkbook, buildExcelJsWorkbook, inferImageExtension, resolveImageSource, mergeCellStyle, applyStyledRows, addEmbeddedImages, generateBuffer, writeFile, writeAtomicBufferFile, sanitizeFilename, buildUploadKey, generateAndUpload, sendFile, parseBuffer, parseFile, workbookToJSON
- app/service/systems/express_platform.js (16)
- getOrderLogOperator, buildOrderExpressVerPatch, buildExpressPlatformTraceId, OrderExpress, cleanupFailedWaybillOrders, buildFailedOrderCleanupList, polyapi, cainiao, parsePlatformPrintData, stringifyPlatformPrintData, buildWaybillOrderMetaMap, buildWaybillSettlementRelationMap, lockAndDeductWaybillSettlement, persistWaybillSuccessUpdates, normalizePddExtData, pdd
- app/service/systems/express_policy.js (10)
@ -451,10 +429,10 @@ 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/inbound_direct_log.js (14)
- getItems, _addSingleItem, _bindReceivingDetail, addItem, removeItem, commit, notifyEntryOrderCompleted, _queryCompletedEntryItems, _buildCompletedItemLines, _sendOpenApiCallback, operationLog, qimenEntrySync, _syncReceivingStorageStatus, _applyReceivingStockOccupancy
- app/service/systems/inbox/group.js (10)
- list, quickList, members, disable, update, reset, validateExpressInterfaces, validateSystemExpressCode, findGroupsByExpress, findStoreAfterSalesGroups
- app/service/systems/inbound_direct_log.js (11)
- getItems, _addSingleItem, _bindReceivingDetail, addItem, removeItem, commit, _sendOpenApiCallback, operationLog, qimenEntrySync, _syncReceivingStorageStatus, _applyReceivingStockOccupancy
- app/service/systems/inbox/group.js (8)
- list, disable, update, reset, validateExpressInterfaces, validateSystemExpressCode, findGroupsByExpress, findStoreAfterSalesGroups
- app/service/systems/license_plate.js (7)
- getTencentCloudConfig, getTencentCloudRegion, normalizeBase64Image, buildTencentCloudRequest, sendTencentCloudRequest, recognizeLicensePlate, formatLicensePlateResult
- app/service/systems/location_space.js (16)
@ -483,16 +461,16 @@ rg "class .*Service|module.exports" app/service/qimenMethods
- createBusinessError, normalizeOrderId, normalizeWaybillCode, normalizePackageMaterialCode, normalizePackageMaterialId, normalizeBindOrderId, getCurrentWarehouseId, findActivePackageMaterialById, findActivePackageMaterialByCode, findValidOrderExpressByOrderAndWaybill, findOrderInterceptStatus, assertOrderNotIntercepted, normalizeWeighingWeight, findValidOrderExpressRows, updateWeighingWeight, updateWeighingWeightByWaybill, _updateWaveAllOrdersWeight, _buildWaveWeighingSummary, _getStoreName, _getWaveSysLogisticsName, _updateSingleOrderWeight, _updateWaveOrderWeight, _writeWeighActionLog, _tryWaveCompatibility, _upsertPackageMaterialItemRelation, bindExpressPackageMaterial, bindExpressPackageMaterialByWaybill, _bindSingleExpressPackageMaterial, _bindWavePackageMaterialByBusinessKey, _writePackageMaterialActionLog
- app/service/systems/order_outbound.js (1)
- markOutboundOrder
- app/service/systems/order_packing.js (10)
- _getRecordingComputerId, _buildVideoUrl, createBusinessError, _buildListWhere, _buildListOrder, list, exportPackTask, get, setEndTime, forceRecord
- app/service/systems/order_packing.js (6)
- _getRecordingComputerId, _buildVideoUrl, list, get, setEndTime, forceRecord
- app/service/systems/order_pending_exception.js (2)
- markPendingException, reversePendingException
- app/service/systems/order_print.js (55)
- isOrderLocked, buildLockedWavePlatformResult, buildLockedOrderPlatformPrintItem, shouldLoadPickingDetails, normalizeItemSnapshot, getFirstNonEmptyFieldText, buildPrintItemAggregationKey, buildPrintOrderRowMapWithPicking, normalizeContractPolicyConfig, getWavePlatformPrintData, getOrderPrintData, getPrintDataByWaybillCodes, queryWaybillsByCodes, getMainWaybillMapByOrderIds, normalizeUnlockGroupRules, isOrderMatchedByUnlockGroupRule, unlockWavePlatformPrintDataByGroup, normalizeWaveIds, normalizeOrderIds, getContextWarehouseId, resolveWarehouseId, queryWavesByIds, queryOrdersByWaveIds, queryOrdersByIds, queryOrderExpressByOrderIds, queryWaveOrderIndexMapByOrderIds, querySmallGroupBoxNoMap, queryWaveTotalOrderCountMap, assertBusinessWaybillCompleteness, buildOrderExpressMap, isCainiaoPlatformCode, isJdPlatformCode, isPddPlatformCode, isDouyinPlatformCode, collectCainiaoExpressLookupCodes, queryCainiaoCpCodeMap, queryCainiaoExpressInterfaceList, queryJdExpressInterfaceList, queryPddExpressInterfaceList, queryDouyinExpressInterfaceList, pickCainiaoExpressInterface, pickJdExpressInterface, pickPddExpressInterface, pickDouyinExpressInterface, enrichCainiaoOrderExpressRows, enrichJdOrderExpressRows, enrichPddDyOrderExpressRows, getPolicyConfigMapByStore, resolvePrintPlatformCode, loadTemplateSampleByPlatform, buildOrderPlatformPrintItem, extractSinglePlatformPrintData, groupOrderPrintItemsByPlatform, groupOrderPrintItemsByWaveAndPlatform, filterFullyAssignedExpressWaves
- app/service/systems/order_print.js (54)
- isOrderLocked, buildLockedWavePlatformResult, buildLockedOrderPlatformPrintItem, shouldLoadPickingDetails, normalizeItemSnapshot, getFirstNonEmptyFieldText, buildPrintItemAggregationKey, buildPrintOrderRowMapWithPicking, normalizeContractPolicyConfig, getWavePlatformPrintData, getOrderPrintData, getPrintDataByWaybillCodes, queryWaybillsByCodes, getMainWaybillMapByOrderIds, normalizeUnlockGroupRules, isOrderMatchedByUnlockGroupRule, unlockWavePlatformPrintDataByGroup, normalizeWaveIds, normalizeOrderIds, getContextWarehouseId, resolveWarehouseId, queryWavesByIds, queryOrdersByWaveIds, queryOrdersByIds, queryOrderExpressByOrderIds, queryWaveOrderIndexMapByOrderIds, queryWaveTotalOrderCountMap, assertBusinessWaybillCompleteness, buildOrderExpressMap, isCainiaoPlatformCode, isJdPlatformCode, isPddPlatformCode, isDouyinPlatformCode, collectCainiaoExpressLookupCodes, queryCainiaoCpCodeMap, queryCainiaoExpressInterfaceList, queryJdExpressInterfaceList, queryPddExpressInterfaceList, queryDouyinExpressInterfaceList, pickCainiaoExpressInterface, pickJdExpressInterface, pickPddExpressInterface, pickDouyinExpressInterface, enrichCainiaoOrderExpressRows, enrichJdOrderExpressRows, enrichPddDyOrderExpressRows, getPolicyConfigMapByStore, resolvePrintPlatformCode, loadTemplateSampleByPlatform, buildOrderPlatformPrintItem, extractSinglePlatformPrintData, groupOrderPrintItemsByPlatform, groupOrderPrintItemsByWaveAndPlatform, filterFullyAssignedExpressWaves
- app/service/systems/order_review.js (14)
- createBusinessError, normalizeWaybillCode, isLockedStatus, isInterceptStatus, toPlainRecord, parseItemSnapshot, findOrderExpressByWaybill, findOrderById, findOrderItems, loadBarcodesByStockIds, loadImagesByStockIds, findWaveById, buildGroupInterceptList, pullReviewDataByWaybill
- app/service/systems/order_storage_allocation.js (5)
- allocatePicking, allocateStorage, syncOrderIds, cancelAllocateStorage, releaseInterceptLocksByOrderIds
- app/service/systems/order_storage_allocation.js (4)
- allocatePicking, allocateStorage, syncOrderIds, cancelAllocateStorage
- app/service/systems/pack_task_auto_finish.js (1)
- executeAutoFinishPackTasks
- app/service/systems/pick_compensation.js (9)
@ -515,18 +493,20 @@ rg "class .*Service|module.exports" app/service/qimenMethods
- qimenClient, send, sendRequest
- app/service/systems/receiving_entry_match.js (12)
- matchAfterEntryCompleted, _bindEntryOrderReceiving, bindEntryOrderReceiving, _getRecentReceivingOrders, _findReceivingByRemark, _compareDetails, _sendCallback, _sendQimenCallback, _sendOpenApiCallback, _markReceivingPartialStorage, _commitBinding, unbindEntryOrderReceiving
- app/service/systems/report.js (16)
- getDefinition, parseFieldsField, definitionToView, resolveTypeEntry, resolveQuerier, listRegisteredTypes, validateTypeFields, resolveOrderedFields, buildFilename, buildWorkbookSheets, generate, generateBuffer, saveDefinition, findDefinitionById, listDefinitions, deleteDefinition
- app/service/systems/report.js (7)
- getDefinition, parseJsonField, resolveQuerier, buildFilename, buildWorkbookSheets, generate, generateBuffer
- app/service/systems/report/queries/generic.js (0)
- <no-class-method-found>
- app/service/systems/report/queries/index.js (0)
- <no-class-method-found>
- app/service/systems/report/queries/sevenDayStockFlow.js (0)
- <no-class-method-found>
- app/service/systems/reportDelivery.js (29)
- normalizeScheduleTimes, parseJsonArray, readJsonArray, readJsonObject, normalizeNotifyTemplate, normalizePlanName, normalizeNotifyGroupIds, normalizeNotifyMemberIds, validateNotifyGroupExists, savePlan, copyPlan, planToView, listPlans, listLogs, hitTimePoints, bizDateOfTrigger, bizDateOfTimePoint, resolveStoreWarehouse, markDelivered, markFailed, markExporting, buildMessageContent, resolveNotifyGroups, Date, deliverByChannel, sendNotifyIfConfigured, processOne, parseScheduleTimes, dispatch
- app/service/systems/return_received.js (18)
- createBusinessError, create, notifyPending, _handleInterceptAfterSale, _updateOrderInterceptStatus, list, exportList, _generateExportExcel, detail, delete, _findByIdChecked, _enrichReturn, _resolveStoreRemark, _resolveStoreRemarkMap, _buildListWhere, _resolveConditionValue, _extractConditionValue, _buildListOrder
- app/service/systems/return_unpack.js (43)
- _getRecordingComputerId, _buildVideoUrl, createBusinessError, create, addDetail, updateDetail, removeDetail, cancel, _resolveSubmitEndTime, submit, _notifyUnpacked, forceRecord, list, detailList, videoList, exportUnpack, _resolveStoreNameMap, _resolveExpressNameMap, _extractDetailColor, detail, _buildWaybillMatch, _findWaybillFlexible, queryByWaybill, _resolveWarehouseName, _resolveStoreIdByWaybill, _resolveReturnOrderInfo, delete, _findByIdChecked, _assertUnpacking, _findDetailChecked, _recalcMain, _enrichRow, _flattenVideos, _enrichDetailsWithStock, _resolveStoreRemark, VALUES, _generateUnpackNo, _buildListWhere, _buildDetailListWhere, _buildVideoListWhere, _buildVideoListOrder, _resolveConditionValue, _buildListOrder
- app/service/systems/reportDelivery.js (17)
- normalizeScheduleTimes, savePlan, planToView, listPlans, listLogs, hitTimePoints, bizDateOfTrigger, bizDateOfTimePoint, resolveStoreWarehouse, markDelivered, markFailed, markExporting, buildMessageContent, deliverByChannel, processOne, parseScheduleTimes, dispatch
- app/service/systems/return_received.js (15)
- createBusinessError, create, notifyPending, _handleInterceptAfterSale, _updateOrderInterceptStatus, list, detail, delete, _findByIdChecked, _enrichReturn, _resolveStoreRemark, _buildListWhere, _resolveConditionValue, _extractConditionValue, _buildListOrder
- app/service/systems/return_unpack.js (42)
- _getRecordingComputerId, _buildVideoUrl, createBusinessError, create, addDetail, updateDetail, removeDetail, cancel, submit, _notifyUnpacked, forceRecord, list, detailList, videoList, exportUnpack, _resolveStoreNameMap, _resolveExpressNameMap, _extractDetailColor, detail, _buildWaybillMatch, _findWaybillFlexible, queryByWaybill, _resolveWarehouseName, _resolveStoreIdByWaybill, _resolveReturnOrderInfo, delete, _findByIdChecked, _assertUnpacking, _findDetailChecked, _recalcMain, _enrichRow, _flattenVideos, _enrichDetailsWithStock, _resolveStoreRemark, VALUES, _generateUnpackNo, _buildListWhere, _buildDetailListWhere, _buildVideoListWhere, _buildVideoListOrder, _resolveConditionValue, _buildListOrder
- app/service/systems/return_waybill.js (12)
- createBusinessError, create, update, list, detail, delete, _findByIdChecked, _assertStoreContract, _formatRow, _buildListWhere, _resolveConditionValue, _buildListOrder
- app/service/systems/setting/account.js (31)
@ -567,22 +547,22 @@ rg "class .*Service|module.exports" app/service/qimenMethods
- normalizeExpenseRecordValue, normalizeExpenseRecordCondition, normalizeFilterValues, buildEntryStockTransactionExistsCondition, buildHasReceivingCondition, preprocessEntryListWhere, list, get, IN, enrichItemsWithAvailableReceivingDetails, normalizeCancelEntryOrderIds, getOwnedEntryOrderById, cancel, _rollbackReceivingStorageStatus, addItem, commit, removeItem, getReceivingDetailsForBind, containerList, _applyReceivingInboundUsage, quickInbound, receivingCompare, _buildMergedComparison, exportEntryOrders, exportStoreEntryOrders
- app/service/systems/storage/expiry.js (1)
- list
- app/service/systems/storage/index.js (15)
- findByStockAndBatch, findBySpace, findAvailableByWarehouse, findExpiringSoon, updateQuantity, lockQuantity, unlockQuantity, allocateQuantity, interceptLockQuantity, interceptReceiveQuantity, interceptUnlockQuantity, min, offsetGapOnInbound, getStockSummary, getSpaceUsage
- app/service/systems/storage/index.js (10)
- findByStockAndBatch, findBySpace, findAvailableByWarehouse, findExpiringSoon, updateQuantity, lockQuantity, unlockQuantity, allocateQuantity, getStockSummary, getSpaceUsage
- app/service/systems/storage/inventory.js (13)
- createTransferStockTransactions, transferLocation, transferByProduct, resolveStockQueryToStockIds, getInventoryList, getStorageListByStockId, _aggregateStorageRowsBySpace, _loadInventoryWarningRanges, _formatBatchStorageRows, quickPutaway, directPutaway, exportInventoryList, _generateEntryOrderCode
- app/service/systems/storage/management.js (1)
- replenishmentDemand
- app/service/systems/storage/receiving.js (44)
- getReceivingList, _resolveStockQueryReceivingIds, _resolveReceivingStoreNameMap, getStoreReceivingList, getReceivingDetail, batchCancelReceiving, rejectReceiving, reviewReceiving, buildReviewReportSheets, sendStoreBoundNotice, resolveReceivingCreatorName, sendReviewNotice, resolveReviewDetailItemCodeMap, isEmptyValue, buildSequelizeCondition, processConditionValue, buildReceivingNumberPrefix, generateNextReceivingNumber, isReceivingNumberDuplicateError, create, save, bindStore, get, addDetail, bindDetailProduct, updateDetail, getStockStoreInfo, updateReceivingStats, deleteDetail, detailChange, invalid, formatReportDate, formatDeliveryMethod, getCompletionContactFields, Map, buildCompletionReportSheets, uploadCompletionExcelReport, sendCompletionNotice, sendStoreUnmatchedNotice, completeReceiving, _syncProductDataFromReceiving, scanDetail, exportReceivingList, exportStoreReceivingList
- app/service/systems/storage/receiving.js (43)
- getReceivingList, _resolveStockQueryReceivingIds, getStoreReceivingList, getReceivingDetail, batchCancelReceiving, rejectReceiving, reviewReceiving, buildReviewReportSheets, sendStoreBoundNotice, resolveReceivingCreatorName, sendReviewNotice, resolveReviewDetailItemCodeMap, isEmptyValue, buildSequelizeCondition, processConditionValue, buildReceivingNumberPrefix, generateNextReceivingNumber, isReceivingNumberDuplicateError, create, save, bindStore, get, addDetail, bindDetailProduct, updateDetail, getStockStoreInfo, updateReceivingStats, deleteDetail, detailChange, invalid, formatReportDate, formatDeliveryMethod, getCompletionContactFields, Map, buildCompletionReportSheets, uploadCompletionExcelReport, sendCompletionNotice, sendStoreUnmatchedNotice, completeReceiving, _syncProductDataFromReceiving, scanDetail, exportReceivingList, exportStoreReceivingList
- app/service/systems/storage/report.js (5)
- loadReportReferenceMaps, buildExportFilename, export, _resolveKeywordToStockIds, search
- app/service/systems/storage/stock_warehouse.js (3)
- _buildStockDetailCacheKey, getStockDetails, invalidateStockDetailCache
- app/service/systems/store_express_binding_policy.js (17)
- getCurrentWarehouseId, createError, normalizeText, normalizeInteger, normalizeWeightType, normalizeJsonArray, ensureExpressExists, getListWhereSpecialFieldMap, buildListWhere, normalizePagination, formatPolicyRow, list, ensureCustomNameUnique, add, findPolicyById, edit, del
- app/service/systems/store_warehouse.js (80)
- 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_warehouse.js (78)
- 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, listForStore, 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/upload.js (18)
@ -593,8 +573,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods
- closeFinishedWaves
- app/service/systems/waybill.js (5)
- toOrder, list, detail, export, buildWaybillExportFile
- app/service/systems/workbench.js (47)
- list, detail, create, update, delete, bindCamera, business, _countWaveOrders, _countWaveOrdersCached, _getWaveOrderIds, Set, _buildPackChangeSummary, _writePackOperationLog, _updateOrderPackStatus, _packOrder, resolvePackTaskEndTime, _finishPack, _sendWeight, _writeWeighOpLog, _queryOrder, getWorkbenchBindClientCacheKey, getWorkbenchBindCodeCacheKey, getWorkbenchTokenCacheKey, generateRandomChars, generateWorkbenchToken, generateWorkbenchLoginCode, normalizeWorkbenchBindCode, generateUniqueWorkbenchLoginCode, createUniqueWorkbenchClientCode, createUniqueWorkbenchBindCode, buildWorkbenchBindState, getWorkbenchBindRemainingSeconds, setWorkbenchBindState, createWorkbenchBindSession, refreshWorkbenchBindCode, formatWorkbenchBindData, waitForWorkbenchBindComplete, getWorkbenchBindCode, formatWorkbenchTokenInfo, bindWorkbench, getWorkbenchInfoByToken, loginWorkbenchByCode, resetLoginCode, resolveWorkbenchByToken, normalizeWorkbenchMemberIds, removeWorkbenchMember, bindWorkbenchMember
- app/service/systems/workbench.js (20)
- list, detail, create, update, delete, bindCamera, business, _countWaveOrders, _getWaveOrderIds, Set, _buildPackChangeSummary, _writePackOperationLog, _updateOrderPackStatus, _packOrder, resolvePackTaskEndTime, _finishPack, _sendWeight, _writeWeighOpLog, _queryOrder, checkBarcodeExists
- app/service/warehouse.js (7)
- resolveWarehouseMethod, getWarehouseMethodService, dispatchWarehouseMethod, validateWarehouseParams, parseJsonBody, normalizeSignFields, processRequest
- app/service/warehouseMethods/inbox.js (2)
@ -608,11 +588,3 @@ rg "class .*Service|module.exports" app/service/qimenMethods

View File

@ -77,7 +77,6 @@ module.exports = {
ORDER_WAVE_AUTO_GROUP: '自动加团',
ORDER_WAVE_STRATEGY_FETCH: '策略抓取波次',
ORDER_WAVE_CLAIM: '领取波次',
ORDER_AUTO_EXPRESS_SKIP: '跳过自动分配快递',
ORDER_PICK_COMPLETE: '拣货完成',
ORDER_RECHECK: '订单复核',
ORDER_RECHECK_BATCH: '批量复核',

View File

@ -25,172 +25,7 @@ function isInterceptedOrderStatus(status) {
return normalizedStatus !== INTERCEPT_STATUS_NONE;
}
/** 团购波次类型。 */
const WAVE_TYPE_GROUP_BUY = 1;
/** 散单波次类型。 */
const WAVE_TYPE_SCATTER = 2;
/**
* 返回不允许写入拦截请求状态(requested / intercepting)的阻断原因文案;空字符串表示允许写入。
*
* 规则:
* - 团购波次(wave_type=1):inspection_status === 'fin'(已复核)→ 不允许写入拦截请求状态;
* - 散单波次(wave_type=2):weighing_weight > 0(已称重)→ 不允许写入拦截请求状态;
* - 其余情况(无波次 / 其他波次类型 / 未复核 / 未称重)不阻断。
*
* @param {Object} params 参数。
* @param {number|string} [params.waveType] 波次类型。
* @param {string} [params.inspectionStatus] 订单复核状态。
* @param {number|string} [params.weighingWeight] 散单称重重量。
* @return {string} 阻断原因;空字符串表示允许写入。
*/
function getInterceptRequestBlockReason({ waveType, inspectionStatus, weighingWeight } = {}) {
const normalizedWaveType = Number(waveType || 0);
if (normalizedWaveType === WAVE_TYPE_GROUP_BUY) {
return String(inspectionStatus || '').trim() === 'fin' ? '团购单已复核' : '';
}
if (normalizedWaveType === WAVE_TYPE_SCATTER) {
return Number(weighingWeight || 0) > 0 ? '散单已称重' : '';
}
return '';
}
/**
* 判断订单是否因「团购已复核 / 散单已称重」而不允许写入拦截请求状态。
*
* @param {Object} params 参数,同 getInterceptRequestBlockReason。
* @return {boolean} true 表示不允许写入拦截请求状态。
*/
function isInterceptRequestBlockedByRecheckOrWeigh(params = {}) {
return getInterceptRequestBlockReason(params) !== '';
}
/**
* 拉取单订单的拦截请求前置校验信息(波次类型 + 散单称重重量)。
*
* @param {Object} ctx Egg 上下文。
* @param {Object} params 参数。
* @param {number|string} params.orderId 订单 ID。
* @param {number|string} [params.waveId] 波次 ID。
* @param {number|string} params.warehouseId 仓库 ID。
* @param {Object} [params.transaction] 可选事务对象。
* @return {Promise<{ waveType: number, weighingWeight: number }>} 校验信息。
*/
async function resolveInterceptRequestGuardInfo(ctx, params = {}) {
const { orderId, waveId, warehouseId, transaction } = params;
let waveType = 0;
if (Number(waveId || 0) > 0 && ctx && ctx.model && ctx.model.WaveBatch) {
try {
const waveRow = await ctx.model.WaveBatch.findOne({
where: { wave_id: Number(waveId), warehouse_id: warehouseId },
attributes: [ 'wave_id', 'wave_type' ],
raw: true,
transaction,
});
waveType = Number(waveRow && waveRow.wave_type || 0);
} catch (error) { /* 查询失败不阻断主流程,按无波次处理 */ }
}
let weighingWeight = 0;
if (ctx && ctx.model && ctx.model.OrderExpress) {
try {
const expressRows = await ctx.model.OrderExpress.findAll({
where: { order_id: Number(orderId || 0) },
attributes: [ 'weighing_weight' ],
raw: true,
transaction,
});
for (const row of (Array.isArray(expressRows) ? expressRows : [])) {
weighingWeight = Math.max(weighingWeight, Number(row && row.weighing_weight || 0));
}
} catch (error) { /* 查询失败不阻断主流程,按未称重处理 */ }
}
return { waveType, weighingWeight };
}
/**
* 批量拉取订单的拦截请求前置校验信息(波次类型 + 散单称重重量)。
*
* @param {Object} ctx Egg 上下文。
* @param {Object} params 参数。
* @param {Array<Object>} params.orderRows 订单行数组(需含 id、wave_id 字段)。
* @param {number|string} params.warehouseId 仓库 ID。
* @param {Object} [params.transaction] 可选事务对象。
* @return {Promise<Map<number, { waveType: number, weighingWeight: number }>>} 按订单 ID 索引的校验信息。
*/
async function resolveInterceptRequestGuardInfoMap(ctx, params = {}) {
const orderRows = Array.isArray(params.orderRows) ? params.orderRows : [];
const { warehouseId, transaction } = params;
const infoMap = new Map();
if (orderRows.length === 0 || !ctx) {
return infoMap;
}
const orderIds = orderRows
.map(row => Number(row && row.id || 0))
.filter(orderId => Number.isInteger(orderId) && orderId > 0);
const waveIds = [ ...new Set(orderRows
.map(row => Number(row && row.wave_id || 0))
.filter(waveId => Number.isInteger(waveId) && waveId > 0)) ];
for (const orderId of orderIds) {
infoMap.set(orderId, { waveType: 0, weighingWeight: 0 });
}
if (waveIds.length > 0 && ctx.model && ctx.model.WaveBatch) {
try {
const { Op } = ctx.app && ctx.app.Sequelize || {};
const waves = await ctx.model.WaveBatch.findAll({
where: { wave_id: { [Op.in]: waveIds }, warehouse_id: warehouseId },
attributes: [ 'wave_id', 'wave_type' ],
raw: true,
transaction,
});
const waveTypeMap = new Map((Array.isArray(waves) ? waves : [])
.map(wave => [ Number(wave && wave.wave_id || 0), Number(wave && wave.wave_type || 0) ]));
for (const row of orderRows) {
const info = infoMap.get(Number(row.id));
if (info) {
info.waveType = waveTypeMap.get(Number(row.wave_id || 0)) || 0;
}
}
} catch (error) { /* 查询失败不阻断主流程,按无波次处理 */ }
}
if (orderIds.length > 0 && ctx.model && ctx.model.OrderExpress) {
try {
const { Op } = ctx.app && ctx.app.Sequelize || {};
const expressRows = await ctx.model.OrderExpress.findAll({
where: { order_id: { [Op.in]: orderIds }, warehouse_id: warehouseId },
attributes: [ 'order_id', 'weighing_weight' ],
raw: true,
transaction,
});
for (const expressRow of (Array.isArray(expressRows) ? expressRows : [])) {
const info = infoMap.get(Number(expressRow && expressRow.order_id || 0));
if (info) {
info.weighingWeight = Math.max(
info.weighingWeight,
Number(expressRow && expressRow.weighing_weight || 0)
);
}
}
} catch (error) { /* 查询失败不阻断主流程,按未称重处理 */ }
}
return infoMap;
}
module.exports = {
INTERCEPT_STATUS_NONE,
isInterceptedOrderStatus,
WAVE_TYPE_GROUP_BUY,
WAVE_TYPE_SCATTER,
getInterceptRequestBlockReason,
isInterceptRequestBlockedByRecheckOrWeigh,
resolveInterceptRequestGuardInfo,
resolveInterceptRequestGuardInfoMap,
};

View File

@ -468,11 +468,9 @@ function resolveItemQuantity(item) {
* @param {number} [options.fallbackItemsCount] 订单级商品种类数(items_count),仅当商品总数与明细累加均为 0 时兜底。
* @param {number} [options.waveSource] 波次来源(wms_wave_batch.source),与 waveType 共同决定商品明细行尾是否追加「波次总单数×数量」。
* @param {number} [options.waveType] 波次类型(wms_wave_batch.wave_type)。
* @param {number} [options.boxNo] 小团购篮号(box_no),waveType=1 且 waveSource∈{1,2}(策略任务波次)时前置到波次号前。
* @param {string} [options.packageMaterialName] 推荐包材名称,非空时追加到波次号前。
* @return {Array<string>} 自定义区文本行数组。首行头部分在快递渠道名后追加 商品总数【n】(优先取订单级商品总数 items_total,其次商品明细数量累加,最后 items_count 兜底);
* 当 waveSource=0 且 waveType=1 时,商品明细行尾追加「波次总单数×该行商品数量」;
* 小团购(waveType=1 且 waveSource∈{1,2})时波次号前追加篮号「{boxNo}-」。
* 当 waveSource=0 且 waveType=1 时,商品明细行尾追加「波次总单数×该行商品数量」。
*/
function buildWaybillCustomProductInfoLines(items, policyConfig = {}, options = {}) {
const safeItems = Array.isArray(items) ? items : [];
@ -557,17 +555,12 @@ function buildWaybillCustomProductInfoLines(items, policyConfig = {}, options =
const hasWaveCustomPrefix = waveTotalOrders > 0
&& waveIndex > 0
&& Boolean(waveNo);
// 小团购波次(wave_type=1 且 source∈{1,2} 策略任务):篮号前置到波次号前,其他波次类型不动
const boxNo = toNumber(safeOptions.boxNo, 0);
const isSmallGroupWave = waveType === 1 && (waveSource === 1 || waveSource === 2) && boxNo > 0;
const packageMaterialName = String(safeOptions.packageMaterialName || '').trim();
const packageMaterialLabel = packageMaterialName ? `【${packageMaterialName}】` : '';
const waveBodyText = hasWaveCustomPrefix
? `${waveNo} [${waveTotalOrders}-${waveIndex}]`
: waveNo;
const waveHeaderText = isSmallGroupWave
? packageMaterialLabel + `${boxNo}-${waveBodyText}`
: packageMaterialLabel + waveBodyText;
const waveHeaderText = packageMaterialLabel + waveBodyText;
// 商品总数:优先取订单级商品总数(items_total,权威字段),
// 其次累加所有商品明细的数量,最后用商品种类数(items_count)兜底。
@ -1337,7 +1330,6 @@ function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orde
fallbackItemsCount: Number(safeOrderDelivery.items_count || 0),
waveSource: Number(safeOrderDelivery.wave_source || 0),
waveType: Number(safeOrderDelivery.wave_type || 0),
boxNo: Number(safeOrderDelivery.box_no || 0),
}
);
const customProductInfo = appendExtraCustomLines(
@ -1491,7 +1483,6 @@ function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDeli
fallbackItemsCount: Number(safeOrderDelivery.items_count || 0),
waveSource: Number(safeOrderDelivery.wave_source || 0),
waveType: Number(safeOrderDelivery.wave_type || 0),
boxNo: Number(safeOrderDelivery.box_no || 0),
}
);
const customProductInfo = appendExtraCustomLines(
@ -1688,7 +1679,6 @@ function applyDouyinExpressFieldMapping(platform, skeleton, orderExpress, orderD
fallbackItemsCount: Number(safeOrderDelivery.items_count || 0),
waveSource: Number(safeOrderDelivery.wave_source || 0),
waveType: Number(safeOrderDelivery.wave_type || 0),
boxNo: Number(safeOrderDelivery.box_no || 0),
}
);
const customProductInfo = appendExtraCustomLines(
@ -1832,7 +1822,6 @@ function applyCainiaoExpressFieldMapping(
fallbackItemsCount: Number(safeOrderDelivery.items_count || 0),
waveSource: Number(safeOrderDelivery.wave_source || 0),
waveType: Number(safeOrderDelivery.wave_type || 0),
boxNo: Number(safeOrderDelivery.box_no || 0),
}
);
const customControlText = appendExtraCustomLines(
@ -2043,7 +2032,6 @@ function applyXhsExpressFieldMapping(
fallbackItemsCount: Number(safeOrderDelivery.items_count || 0),
waveSource: Number(safeOrderDelivery.wave_source || 0),
waveType: Number(safeOrderDelivery.wave_type || 0),
boxNo: Number(safeOrderDelivery.box_no || 0),
}
);
const customProductInfo = appendExtraCustomLines(
@ -2163,7 +2151,6 @@ function applySphExpressFieldMapping(
fallbackItemsCount: Number(safeOrderDelivery.items_count || 0),
waveSource: Number(safeOrderDelivery.wave_source || 0),
waveType: Number(safeOrderDelivery.wave_type || 0),
boxNo: Number(safeOrderDelivery.box_no || 0),
}
);
const customProductInfo = appendExtraCustomLines(
@ -2339,7 +2326,6 @@ function applyJdExpressFieldMapping(
fallbackItemsCount: Number(safeOrderDelivery.items_count || 0),
waveSource: Number(safeOrderDelivery.wave_source || 0),
waveType: Number(safeOrderDelivery.wave_type || 0),
boxNo: Number(safeOrderDelivery.box_no || 0),
}
);
const customProductInfo = appendExtraCustomLines(

View File

@ -2,7 +2,7 @@
module.exports = app => {
const { Sequelize, model } = app;
const { STRING, BIGINT, DECIMAL, TEXT, ENUM, DATE, INTEGER, CHAR, SMALLINT, TINYINT, JSON } = Sequelize;
const { STRING, BIGINT, DECIMAL, TEXT, ENUM, DATE, INTEGER, CHAR, SMALLINT, JSON } = Sequelize;
// 状态机枚举定义
const StatusEnum = {
@ -425,36 +425,6 @@ module.exports = app => {
defaultValue: '',
comment: '波次号,空字符串表示未分配',
},
wave_scope: {
type: TINYINT(4),
allowNull: false,
defaultValue: 0,
comment: '波次范围:0未分配波次 1大团购 2散单 3小团购',
},
grab_operator_id: {
type: BIGINT(20),
allowNull: true,
defaultValue: null,
comment: '抓取人工号ID',
},
grab_operator: {
type: STRING(50),
allowNull: true,
defaultValue: null,
comment: '抓取人',
},
claim_operator_id: {
type: BIGINT(20),
allowNull: true,
defaultValue: null,
comment: '领料人工号ID',
},
claim_operator: {
type: STRING(50),
allowNull: true,
defaultValue: null,
comment: '领料人',
},
wave_strategy_version: {
type: INTEGER(10),
allowNull: false,

View File

@ -128,7 +128,6 @@ module.exports = app => {
indexes: [
{ name: 'idx_order_id', fields: [ 'order_id' ] },
{ name: 'idx_warehouse_id', fields: [ 'warehouse_id' ] },
{ name: 'idx_warehouse_create_time', fields: [ 'warehouse_id', 'create_time' ] },
{ name: 'idx_workbench_id', fields: [ 'workbench_id' ] },
{ name: 'idx_wave_id', fields: [ 'wave_id' ] },
{ name: 'idx_waybill_code', fields: [ 'waybill_code' ] },

View File

@ -72,12 +72,6 @@ module.exports = app => {
defaultValue: 0,
comment: '锁定数量',
},
intercept_locked_quantity: {
type: INTEGER(12),
allowNull: false,
defaultValue: 0,
comment: '拦截锁定数量',
},
available_quantity: {
type: INTEGER(12),
allowNull: false,
@ -263,15 +257,9 @@ module.exports = app => {
};
/**
* 计算当前记录的可用数量(统一口径)。
*
* 可用数量口径:可用数量 = 库存数量 - 锁定数量 - 拦截锁定数量。
*
* @return {number} 可用数量。
*/
// 实例方法
Storage.prototype.getAvailableQuantity = function() {
return this.quantity - this.locked_quantity - Number(this.intercept_locked_quantity || 0);
return this.quantity - this.locked_quantity;
};
Storage.prototype.isAvailable = function() {

View File

@ -70,16 +70,6 @@ module.exports = app => {
allowNull: true,
comment: '变更后锁定数量',
},
before_intercept_locked_quantity: {
type: INTEGER(12),
allowNull: true,
comment: '变更前拦截锁定数量',
},
after_intercept_locked_quantity: {
type: INTEGER(12),
allowNull: true,
comment: '变更后拦截锁定数量',
},
batch_no: {
type: STRING(100),
allowNull: true,

View File

@ -39,11 +39,8 @@ module.exports = app => {
});
const DEFAULT_CUTOFF_ORDER_TIME = '18:00';
const CUTOFF_ORDER_TIME_MIN = '00:00';
const CUTOFF_ORDER_TIME_MIN = '12:00';
const CUTOFF_ORDER_TIME_MAX = '23:59';
const DEFAULT_ALLOCATE_START_TIME = '08:00';
const ALLOCATE_START_TIME_MIN = '00:00';
const ALLOCATE_START_TIME_MAX = '23:59';
const DEFAULT_SUBJECT_CONFIG = Object.freeze({
max_notice_webhook_count: DEFAULT_MAX_NOTICE_WEBHOOK_COUNT,
@ -70,7 +67,6 @@ module.exports = app => {
auto_outbound_rules: DEFAULT_AUTO_OUTBOUND_RULES,
cutoff_order_enabled: 1,
cutoff_order_time: DEFAULT_CUTOFF_ORDER_TIME,
allocate_start_time: DEFAULT_ALLOCATE_START_TIME,
});
const normalizeSubjectConfigText = (value, defaultValue) => {
@ -373,28 +369,6 @@ module.exports = app => {
}
}
if (Object.prototype.hasOwnProperty.call(parsed, 'allocate_start_time')) {
const allocateStartTime = normalizeSubjectConfigText(parsed.allocate_start_time, DEFAULT_ALLOCATE_START_TIME);
if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(allocateStartTime)) {
throw new Error('subject_config.allocate_start_time 格式必须为 HH:mm(如 08:00)');
}
if (allocateStartTime < ALLOCATE_START_TIME_MIN || allocateStartTime > ALLOCATE_START_TIME_MAX) {
normalized.allocate_start_time = DEFAULT_ALLOCATE_START_TIME;
} else {
normalized.allocate_start_time = allocateStartTime;
}
} else {
// 旧数据补齐默认开始自动分配时间
normalized.allocate_start_time = DEFAULT_ALLOCATE_START_TIME;
}
// 跨字段校验:仅当显式同时提交两个时间字段且相等时拒绝(自动分配窗口为空)
if (Object.prototype.hasOwnProperty.call(parsed, 'allocate_start_time')
&& Object.prototype.hasOwnProperty.call(parsed, 'cutoff_order_time')
&& normalized.allocate_start_time === normalized.cutoff_order_time) {
throw new Error('subject_config.allocate_start_time 不能等于 subject_config.cutoff_order_time(自动分配窗口为空)');
}
return normalized;
};

View File

@ -219,18 +219,7 @@ module.exports = app => {
type: 'flag',
default: 1,
required: false,
description: '启用后,订单创建时间早于开始自动分配时间或超过截单时间(开始时间晚于截单时间时截单时间视为次日),不再自动分配快递和储位,不再自动加团',
}),
Object.freeze({
key: 'allocate_start_time',
name: '开始自动分配时间',
type: 'string',
default: '08:00',
required: false,
maxLength: 5,
min: '00:00',
max: '23:59',
description: '开始自动分配时间,格式 HH:mm,如 08:00;早于该时间的订单与超过截单时间行为一致,不自动分配快递和储位,不自动加团;晚于截单时间时截单时间视为次日',
description: '启用后,当天订单创建时间超过截单时间,不再自动分配快递和储位,不再自动加团',
}),
Object.freeze({
key: 'cutoff_order_time',
@ -239,7 +228,7 @@ module.exports = app => {
default: '18:00',
required: false,
maxLength: 5,
min: '00:00',
min: '12:00',
max: '23:59',
description: '截单时间,格式 HH:mm,如 16:00',
}),
@ -253,14 +242,6 @@ module.exports = app => {
max: 720,
description: '售后单设为等待外部反馈后,默认多少小时需二次跟进。具体类型可在代码枚举中覆盖',
}),
Object.freeze({
key: 'notify_manual_sync',
name: '是否通知手工单回传',
type: 'flag',
default: 0,
required: false,
description: '手工单同步回传后是否通知货主(订单同步完成通知),默认否',
}),
]);
const POLICY_CONFIG_FIELD_MAP = Object.freeze(POLICY_CONFIG_FIELDS.reduce((result, field) => {
result[field.key] = field;
@ -456,21 +437,6 @@ module.exports = app => {
}
}
// 跨字段校验:开始自动分配时间与截单时间相同会导致自动分配窗口为空,保存时拒绝
if (!sanitizeOnly) {
const startTimeField = POLICY_CONFIG_FIELD_MAP.allocate_start_time;
const cutoffTimeField = POLICY_CONFIG_FIELD_MAP.cutoff_order_time;
const startTimeForCheck = Object.prototype.hasOwnProperty.call(normalized, 'allocate_start_time')
? String(normalized.allocate_start_time || '').trim()
: String(startTimeField && startTimeField.default || '08:00');
const cutoffTimeForCheck = Object.prototype.hasOwnProperty.call(normalized, 'cutoff_order_time')
? String(normalized.cutoff_order_time || '').trim()
: String(cutoffTimeField && cutoffTimeField.default || '18:00');
if (startTimeForCheck && cutoffTimeForCheck && startTimeForCheck === cutoffTimeForCheck) {
throw new Error(`${fieldName}.allocate_start_time 不能等于 ${fieldName}.cutoff_order_time(自动分配窗口为空)`);
}
}
return Object.keys(normalized).length ? normalized : null;
};

View File

@ -46,16 +46,6 @@ module.exports = app => {
allowNull: true,
comment: '拣货员',
},
claim_operator: {
type: STRING(50),
allowNull: true,
comment: '领料人',
},
claim_time: {
type: DATE,
allowNull: true,
comment: '领料时间',
},
picking_start_time: {
type: DATE,
allowNull: true,

View File

@ -20,6 +20,11 @@ module.exports = app => {
allowNull: false,
comment: '工作台名称(用户自定义)',
},
barcode: {
type: STRING(100),
allowNull: true,
comment: '工作台条码(用户自定义,仓库内唯一)',
},
status: {
type: TINYINT,
allowNull: false,
@ -42,16 +47,6 @@ module.exports = app => {
allowNull: true,
comment: '设备ID列表,如 [1,2,3],触发打包任务时透传到 wms_pack_task.device_ids',
},
login_code: {
type: STRING(64),
allowNull: true,
comment: '工作台登录码(前缀+随机,64位,全局唯一)',
},
token: {
type: STRING(64),
allowNull: true,
comment: '工作台令牌(随机64位,绑定后生成)',
},
created_at: {
type: DATE,
allowNull: false,
@ -77,19 +72,11 @@ module.exports = app => {
comment: '工作台表',
indexes: [
{ name: 'idx_warehouse_id', fields: [ 'warehouse_id' ] },
{ name: 'uk_login_code', unique: true, fields: [ 'login_code' ] },
{ name: 'idx_token', fields: [ 'token' ] },
{ name: 'idx_barcode', fields: [ 'barcode' ] },
{ name: 'uk_warehouse_barcode', unique: true, fields: [ 'warehouse_id', 'barcode', 'deleted_at' ] },
{ name: 'idx_deleted_at', fields: [ 'deleted_at' ] },
],
});
Workbench.associate = () => {
app.model.Workbench.hasMany(app.model.WorkbenchMember, {
foreignKey: 'workbench_id',
sourceKey: 'id',
as: 'members',
});
};
return Workbench;
};

View File

@ -1,71 +0,0 @@
'use strict';
module.exports = app => {
const { STRING, BIGINT, DATE } = app.Sequelize;
const WorkbenchMember = app.model.define('workbench_member', {
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
comment: '主键ID',
},
workbench_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '工作台ID,关联 wms_workbench.id',
},
user_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '账号ID,关联 wms_account.id;非系统账号用户为 NULL',
},
user_name: {
type: STRING(128),
allowNull: true,
comment: '成员名称快照(非系统账号用户显示名)',
},
created_at: {
type: DATE,
allowNull: false,
comment: '创建时间',
},
updated_at: {
type: DATE,
allowNull: false,
comment: '更新时间',
},
deleted_at: {
type: DATE,
allowNull: true,
comment: '软删除时间',
},
}, {
tableName: 'wms_workbench_member',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
paranoid: true,
deletedAt: 'deleted_at',
comment: '工作台成员/用户登录副表',
indexes: [
{ name: 'idx_workbench_id', fields: [ 'workbench_id' ] },
{ name: 'idx_user_id', fields: [ 'user_id' ] },
],
});
WorkbenchMember.associate = () => {
app.model.WorkbenchMember.belongsTo(app.model.Workbench, {
foreignKey: 'workbench_id',
targetKey: 'id',
as: 'workbench',
});
app.model.WorkbenchMember.belongsTo(app.model.Account, {
foreignKey: 'user_id',
targetKey: 'id',
as: 'user',
});
};
return WorkbenchMember;
};

View File

@ -2,8 +2,6 @@
const MainService = require('../main');
const { getInterceptRequestBlockReason, resolveInterceptRequestGuardInfo } = require('../../lib/intercept_guard');
class OpenapiOrderService extends MainService {
/**
* 取消发货单。
@ -56,82 +54,61 @@ class OpenapiOrderService extends MainService {
const printStatus = String(existingOrder.print_status || 'none').trim();
if (pickStatus !== 'none' || printStatus !== 'none') {
// 拦截前置校验:团购单已复核 / 散单已称重后不允许写入拦截请求状态
const guardInfo = await resolveInterceptRequestGuardInfo(ctx, {
orderId: existingOrder.id,
waveId: existingOrder.wave_id,
warehouseId,
await existingOrder.update({
intercept_status: 'intercepting',
updated_at: new Date(),
}, {
transaction,
});
const blockReason = getInterceptRequestBlockReason({
waveType: guardInfo.waveType,
inspectionStatus: String(existingOrder.inspection_status || '').trim(),
weighingWeight: guardInfo.weighingWeight,
});
if (!blockReason) {
await existingOrder.update({
intercept_status: 'intercepting',
updated_at: new Date(),
}, {
transaction,
});
// 同步更新运单表拦截标记
try {
const { ctx: ctxExpress } = this;
const expressWarehouseId = ctxExpress.user && ctxExpress.user.store_id ? Number(ctxExpress.user.store_id) : 0;
if (expressWarehouseId > 0) {
await ctxExpress.model.OrderExpress.update(
{ is_intercept: 'Y' },
{ where: { order_id: existingOrder.id, warehouse_id: expressWarehouseId }, transaction }
);
}
} catch (expressErr) {
this.ctx.logger.warn(
`[openapi order cancel] 更新运单拦截标记失败, orderId=${existingOrder.id}, error=${expressErr.message}`
// 同步更新运单表拦截标记
try {
const { ctx } = this;
const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0;
if (warehouseId > 0) {
await ctx.model.OrderExpress.update(
{ is_intercept: 'Y' },
{ where: { order_id: existingOrder.id, warehouse_id: warehouseId }, transaction }
);
}
} else {
this.ctx.logger.info(
`[openapi order cancel] 订单${blockReason},跳过写入拦截请求状态, orderId=${existingOrder.id}`
} catch (expressErr) {
this.ctx.logger.warn(
`[openapi order cancel] 更新运单拦截标记失败, orderId=${existingOrder.id}, error=${expressErr.message}`
);
}
await transaction.commit();
// 写入拦截操作日志(失败不影响主流程;未写入拦截请求状态时不记录)
if (!blockReason) {
try {
const { ctx: ctx2 } = this;
if (ctx2.model && ctx2.model.OperationLog) {
const whId2 = ctx2.user && ctx2.user.store_id ? Number(ctx2.user.store_id) : 0;
await ctx2.model.OperationLog.create({
business_type: 'order',
business_id: String(existingOrder.id),
operation_code: 'ORDER_INTERCEPT_REQUEST',
operator_id: ctx2.user?.employees_id || ctx2.user?.id || null,
operator_name: ctx2.user?.employees_name || 'OpenAPI',
external_log_type: 'NONE',
warehouse_id: whId2 || null,
platform_code: 'OPENAPI',
message: 'OpenAPI取消订单-触发拦截',
});
}
} catch (logErr) {
this.ctx.logger.warn('[OpenAPIOrderCancel] 写入拦截操作日志失败,不影响主流程', logErr);
// 写入拦截操作日志(失败不影响主流程)
try {
const { ctx: ctx2 } = this;
if (ctx2.model && ctx2.model.OperationLog) {
const whId2 = ctx2.user && ctx2.user.store_id ? Number(ctx2.user.store_id) : 0;
await ctx2.model.OperationLog.create({
business_type: 'order',
business_id: String(existingOrder.id),
operation_code: 'ORDER_INTERCEPT_REQUEST',
operator_id: ctx2.user?.employees_id || ctx2.user?.id || null,
operator_name: ctx2.user?.employees_name || 'OpenAPI',
external_log_type: 'NONE',
warehouse_id: whId2 || null,
platform_code: 'OPENAPI',
message: 'OpenAPI取消订单-触发拦截',
});
}
} catch (logErr) {
this.ctx.logger.warn('[OpenAPIOrderCancel] 写入拦截操作日志失败,不影响主流程', logErr);
}
// 创建售后工单 + 通知快递群(失败不影响主流程)
try {
const { ctx: ctxWorkOrder } = this;
const whId = ctxWorkOrder.user && ctxWorkOrder.user.store_id ? Number(ctxWorkOrder.user.store_id) : 0;
const { ctx } = this;
const whId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0;
if (whId > 0) {
await ctxWorkOrder.service.systems.afterSale.createInterceptWorkOrdersAndNotify({
await ctx.service.systems.afterSale.createInterceptWorkOrdersAndNotify({
orderIds: [ existingOrder.id ],
warehouseId: whId,
creatorLabel: ctxWorkOrder.user?.employees_name || 'OpenAPI系统',
creatorLabel: ctx.user?.employees_name || 'OpenAPI系统',
});
}
} catch (workOrderErr) {
@ -140,9 +117,7 @@ class OpenapiOrderService extends MainService {
);
}
return this.fail(blockReason
? `订单${blockReason},无法拦截执行,已转快递拦截`
: '取消失败,已通知拦截执行');
return this.fail('取消失败,已通知拦截执行');
}
// 检查是否在波次中,若在波次中需清除波次关联

View File

@ -2,8 +2,6 @@
const MainService = require('../main');
const { getInterceptRequestBlockReason, resolveInterceptRequestGuardInfo } = require('../../lib/intercept_guard');
class orderServer extends MainService {
constructor(ctx) {
@ -214,66 +212,45 @@ class orderServer extends MainService {
const printStatus = String(existingOrder.print_status || 'none').trim();
if (pickStatus !== 'none' || printStatus !== 'none') {
// 拦截前置校验:团购单已复核 / 散单已称重后不允许写入拦截请求状态
const guardInfo = await resolveInterceptRequestGuardInfo(ctx, {
orderId: existingOrder.id,
waveId: existingOrder.wave_id,
warehouseId: info.warehouseId,
await existingOrder.update({
intercept_status: 'intercepting',
updated_at: new Date(),
}, {
transaction,
});
const blockReason = getInterceptRequestBlockReason({
waveType: guardInfo.waveType,
inspectionStatus: String(existingOrder.inspection_status || '').trim(),
weighingWeight: guardInfo.weighingWeight,
});
if (!blockReason) {
await existingOrder.update({
intercept_status: 'intercepting',
updated_at: new Date(),
}, {
transaction,
});
// 同步更新运单表拦截标记
try {
await ctx.model.OrderExpress.update(
{ is_intercept: 'Y' },
{ where: { order_id: existingOrder.id, warehouse_id: info.warehouseId }, transaction }
);
} catch (expressErr) {
ctx.logger.warn(
`[qimen order cancel] 更新运单拦截标记失败, orderId=${existingOrder.id}, error=${expressErr.message}`
);
}
} else {
ctx.logger.info(
`[qimen order cancel] 订单${blockReason},跳过写入拦截请求状态, orderId=${existingOrder.id}`
// 同步更新运单表拦截标记
try {
await ctx.model.OrderExpress.update(
{ is_intercept: 'Y' },
{ where: { order_id: existingOrder.id, warehouse_id: info.warehouseId }, transaction }
);
} catch (expressErr) {
ctx.logger.warn(
`[qimen order cancel] 更新运单拦截标记失败, orderId=${existingOrder.id}, error=${expressErr.message}`
);
}
await transaction.commit();
// 写入拦截操作日志(失败不影响主流程;未写入拦截请求状态时不记录)
if (!blockReason) {
try {
if (ctx.model && ctx.model.OperationLog) {
const customerId2 = String(info.customerId || '').trim();
await ctx.model.OperationLog.create({
business_type: 'order',
business_id: String(existingOrder.id),
operation_code: 'ORDER_INTERCEPT_REQUEST',
operator_id: null,
operator_name: customerId2 ? `qimen:${customerId2}` : 'qimen',
external_log_type: 'NONE',
warehouse_id: info.warehouseId || null,
platform_code: customerId2 || 'SYSTEM',
message: '奇门取消订单-触发拦截',
});
}
} catch (logErr) {
ctx.logger.warn('[QimenOrderCancel] 写入拦截操作日志失败,不影响主流程', logErr);
// 写入拦截操作日志(失败不影响主流程)
try {
if (ctx.model && ctx.model.OperationLog) {
const customerId2 = String(info.customerId || '').trim();
await ctx.model.OperationLog.create({
business_type: 'order',
business_id: String(existingOrder.id),
operation_code: 'ORDER_INTERCEPT_REQUEST',
operator_id: null,
operator_name: customerId2 ? `qimen:${customerId2}` : 'qimen',
external_log_type: 'NONE',
warehouse_id: info.warehouseId || null,
platform_code: customerId2 || 'SYSTEM',
message: '奇门取消订单-触发拦截',
});
}
} catch (logErr) {
ctx.logger.warn('[QimenOrderCancel] 写入拦截操作日志失败,不影响主流程', logErr);
}
// 创建售后工单 + 通知快递群(仅限有运单的订单,与正常货主发起拦截一致;失败不影响主流程)
@ -292,83 +269,38 @@ class orderServer extends MainService {
);
}
if (!blockReason) {
await this.sendCancelInterceptNotice({
orderCode,
existingOrder,
info,
});
}
return this.fail(blockReason
? `订单${blockReason},无法拦截执行,已转快递拦截`
: '取消失败,已通知拦截执行');
await this.sendCancelInterceptNotice({
orderCode,
existingOrder,
info,
});
return this.fail('取消失败,已通知拦截执行');
}
// 已同步订单不允许取消,转为拦截处理
const syncStatus = String(existingOrder.sync_status || '').trim();
if (syncStatus === 'fin') {
// 拦截前置校验:团购单已复核 / 散单已称重后不允许写入拦截请求状态
const syncGuardInfo = await resolveInterceptRequestGuardInfo(ctx, {
orderId: existingOrder.id,
waveId: existingOrder.wave_id,
warehouseId: info.warehouseId,
await existingOrder.update({
intercept_status: 'requested',
updated_at: new Date(),
}, {
transaction,
});
const syncBlockReason = getInterceptRequestBlockReason({
waveType: syncGuardInfo.waveType,
inspectionStatus: String(existingOrder.inspection_status || '').trim(),
weighingWeight: syncGuardInfo.weighingWeight,
});
if (!syncBlockReason) {
await existingOrder.update({
intercept_status: 'requested',
updated_at: new Date(),
}, {
transaction,
});
// 同步更新运单表拦截标记
try {
await ctx.model.OrderExpress.update(
{ is_intercept: 'Y' },
{ where: { order_id: existingOrder.id, warehouse_id: info.warehouseId }, transaction }
);
} catch (expressErr) {
ctx.logger.warn(
`[qimen order cancel] 更新运单拦截标记失败(sync), orderId=${existingOrder.id}, error=${expressErr.message}`
);
}
} else {
ctx.logger.info(
`[qimen order cancel] 订单${syncBlockReason},跳过写入拦截请求状态(sync), orderId=${existingOrder.id}`
// 同步更新运单表拦截标记
try {
await ctx.model.OrderExpress.update(
{ is_intercept: 'Y' },
{ where: { order_id: existingOrder.id, warehouse_id: info.warehouseId }, transaction }
);
} catch (expressErr) {
ctx.logger.warn(
`[qimen order cancel] 更新运单拦截标记失败(sync), orderId=${existingOrder.id}, error=${expressErr.message}`
);
}
await transaction.commit();
// 写入拦截操作日志(失败不影响主流程;未写入拦截请求状态时不记录)
if (!syncBlockReason) {
try {
if (ctx.model && ctx.model.OperationLog) {
const customerId2 = String(info.customerId || '').trim();
await ctx.model.OperationLog.create({
business_type: 'order',
business_id: String(existingOrder.id),
operation_code: 'ORDER_INTERCEPT_REQUEST',
operator_id: null,
operator_name: customerId2 ? `qimen:${customerId2}` : 'qimen',
external_log_type: 'NONE',
warehouse_id: info.warehouseId || null,
platform_code: customerId2 || 'SYSTEM',
message: '奇门取消订单-触发拦截(已同步订单转拦截)',
});
}
} catch (logErr) {
ctx.logger.warn('[QimenOrderCancel] 写入拦截操作日志失败(sync),不影响主流程', logErr);
}
}
// 创建售后工单 + 通知快递群(仅限有运单的订单,与正常货主发起拦截一致;失败不影响主流程)
try {
const interceptExpress = await this.getInterceptExpressInfo(existingOrder.id);
@ -385,16 +317,12 @@ class orderServer extends MainService {
);
}
if (!syncBlockReason) {
await this.sendCancelInterceptNotice({
orderCode,
existingOrder,
info,
});
}
return this.fail(syncBlockReason
? `订单${syncBlockReason},无法取消,已转快递拦截`
: '订单已同步,不可取消,已转为拦截处理');
await this.sendCancelInterceptNotice({
orderCode,
existingOrder,
info,
});
return this.fail('订单已同步,不可取消,已转为拦截处理');
}
// 检查是否在波次中,若在波次中需清除波次关联

View File

@ -1052,10 +1052,10 @@ class indexService extends MainService {
*/
constructor(ctx) {
super(ctx);
const _noNeedLogin = 'getI18nMessage,putI18nCollect,test,getCainiaoStfTemplates,polyapiAuthorizeUrl,getWorkbenchBindCode,LoginWorkbenchByCode';
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';
const _noNeedLogin = 'getI18nMessage,putI18nCollect,test,getCainiaoStfTemplates,polyapiAuthorizeUrl';
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';
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';
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';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
async fastWhereTree(data) {
@ -3357,45 +3357,5 @@ class indexService extends MainService {
const result = await service.systems.waybill.toOrder({ waybill_code: waybillCode });
return this.success('查询成功', result);
}
/**
* 获取工作台绑定码(免登录、免鉴权)
* 不传 client_code:返回新会话的 client_code + 绑定码;
* 传 client_code:等待绑定完成返回 token,超时/缓存失效时重新生成绑定码后返回。
* @param {Object} data - { clientCode | client_code }
*/
async getWorkbenchBindCode(data) {
const { service } = this;
try {
const result = await service.systems.workbench.getWorkbenchBindCode(data || {});
if (result && result.success) {
return this.success('获取工作台绑定码成功', result);
}
return this.fail(result && result.message ? result.message : '获取工作台绑定码失败', undefined);
} catch (error) {
return this.fail(error.message);
}
}
/**
* 通过工作台登录码登录,获取 token(免登录、免鉴权)
* @param {Object} data - { loginCode | login_code }
*/
async LoginWorkbenchByCode(data) {
const { service } = this;
try {
const result = await service.systems.workbench.loginWorkbenchByCode(data || {});
if (result && result.success) {
return this.success('工作台登录成功', result);
}
const statusCode = result && result.statusCode;
return this.fail(
result && result.message ? result.message : '工作台登录失败',
statusCode ? { code: statusCode } : undefined
);
} catch (error) {
return this.fail(error.message);
}
}
}
module.exports = indexService;

View File

@ -1130,8 +1130,8 @@ class OrderBaseService extends MainService {
/**
* 提取 wave_scope(波次范围)虚拟筛选条件。
* 将其从 where 中移除并解析为波次范围值集合,后续直接生成订单表 wave_scope 字段过滤。
* 取值约定:0=未分配波次,1=大团购,2=散单,3=小团购;value 支持单个值或数组(多选)。
* 将其从 where 中移除并解析为波次范围值集合,后续通过 wms_wave_batch 反查波次ID注入条件。
* 取值约定:0=未分配波次,1=团购,2=散单;value 支持单个值或数组(多选)。
* @param {Object} whereInput 标准化后的 where 条件。
* @return {{ where: Object, waveScope: number[]|null }} 清洗后的 where 与波次范围值集合。
*/
@ -1163,8 +1163,8 @@ class OrderBaseService extends MainService {
));
for (const scope of normalizedScopes) {
if (!Number.isInteger(scope) || scope < 0 || scope > 3) {
throw new Error('wave_scope 参数不合法,仅支持 0(未分配波次)/1(大团购)/2(散单)/3(小团购)');
if (!Number.isInteger(scope) || scope < 0 || scope > 2) {
throw new Error('wave_scope 参数不合法,仅支持 0(未分配波次)/1(团购)/2(散单)');
}
}
@ -1240,28 +1240,80 @@ class OrderBaseService extends MainService {
}
/**
* 根据波次范围(wave_scope)构建订单表 wave_scope 字段过滤条件。
* 订单表已冗余 wave_scope 字段(写入波次时维护),直接按字段过滤,
* 无需再反查 wms_wave_batch。
* @param {Array<number>} waveScopes 波次范围值集合(0/1/2/3)。
* @return {Object|null} Sequelize 条件,无有效范围时返回 null。
* 根据波次范围(wave_scope)构建订单表 wave_id 过滤条件。
* 0(未分配波次)直接生成 wave_id = 0;1(团购)/2(散单)先查 wms_wave_batch
* 得到对应 wave_type 的波次ID集合,再生成 wave_id in (...)。
* @param {Array<number>} waveScopes 波次范围值集合(0/1/2)。
* @param {number|string} [warehouseId] 仓库ID。
* @return {Promise<Object|null>} Sequelize 条件,无有效范围时返回 null。
*/
buildWaveScopeFilterCondition(waveScopes = []) {
const { Op } = this.app.Sequelize;
async buildWaveScopeWhereCondition(waveScopes = [], warehouseId = this.getWarehouseId()) {
const contextWarehouseId = this.getWarehouseId();
if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') {
throw new Error('缺少当前用户仓库上下文 store_id');
}
if (warehouseId !== null && warehouseId !== undefined && warehouseId !== ''
&& String(warehouseId) !== String(contextWarehouseId)) {
throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。');
}
const normalizedScopes = Array.from(new Set(
(Array.isArray(waveScopes) ? waveScopes : [ waveScopes ])
.filter(scope => scope !== undefined && scope !== null && scope !== '')
.map(scope => Number(scope))
)).filter(scope => Number.isInteger(scope) && scope >= 0 && scope <= 3);
)).filter(scope => Number.isInteger(scope) && scope >= 0 && scope <= 2);
if (normalizedScopes.length === 0) {
return null;
}
const { Op } = this.app.Sequelize;
const waveTypeScopes = normalizedScopes.filter(scope => scope === 1 || scope === 2);
const conditions = [];
if (normalizedScopes.includes(0)) {
conditions.push({ wave_id: 0 });
}
if (waveTypeScopes.length > 0) {
const waveBatchModel = this.ctx.model && this.ctx.model.WaveBatch;
const waveIds = [];
if (waveBatchModel && typeof waveBatchModel.findAll === 'function') {
const waveRows = await waveBatchModel.findAll({
attributes: [ 'wave_id' ],
where: {
warehouse_id: contextWarehouseId,
wave_type: {
[Op.in]: waveTypeScopes,
},
},
raw: true,
});
for (const row of Array.isArray(waveRows) ? waveRows : []) {
const waveId = Number(row && row.wave_id || 0);
if (waveId > 0) {
waveIds.push(waveId);
}
}
}
// 空集合时 Op.in: [] 生成恒假条件,保证团购/散单无波次时结果为空
conditions.push({
wave_id: {
[Op.in]: Array.from(new Set(waveIds)),
},
});
}
if (conditions.length === 1) {
return conditions[0];
}
return {
wave_scope: {
[Op.in]: normalizedScopes,
},
[Op.or]: conditions,
};
}
@ -1698,7 +1750,7 @@ class OrderBaseService extends MainService {
}
if (waveScope) {
const waveScopeCondition = this.buildWaveScopeFilterCondition(waveScope);
const waveScopeCondition = await this.buildWaveScopeWhereCondition(waveScope, contextWarehouseId);
queryWhere = this.appendConditionToWhere(queryWhere, waveScopeCondition);
}
@ -1779,11 +1831,6 @@ class OrderBaseService extends MainService {
/**
* 查询订单详情。
*
* 兜底查询:当表位类型为配送表(dispatch)且查询不到订单时,
* 自动回退到待处理表(current)再查询一次,避免订单在配送表与
* 待处理表之间流转后详情查询落空。
*
* @param {Object} data 请求体。
* @return {Promise<Object>} 订单头、商品明细和运单信息。
*/
@ -1802,30 +1849,18 @@ class OrderBaseService extends MainService {
}
const orderId = orderIds[0];
const orderModel = await this.getOrderModelByTableType(tableType, warehouseId);
const orderWhere = this.buildOrderWhere([ orderId ], warehouseId);
// 实际使用的表位类型:配送表(dispatch)查询不到时兜底查询待处理表(current)
let actualTableType = tableType;
let orderModel = await this.getOrderModelByTableType(actualTableType, warehouseId);
let order = await orderModel.findOne({
const order = await orderModel.findOne({
where: orderWhere,
raw: true,
});
if (!order && actualTableType === 'dispatch') {
actualTableType = 'current';
orderModel = await this.getOrderModelByTableType(actualTableType, warehouseId);
order = await orderModel.findOne({
where: orderWhere,
raw: true,
});
}
if (!order) {
throw new Error('订单不存在或不属于当前仓库');
}
const orderItemsModel = await this.getOrderItemsModelByTableType(actualTableType, warehouseId);
const orderItemsModel = await this.getOrderItemsModelByTableType(tableType, warehouseId);
const orderItems = await orderItemsModel.findAll({
where: {
order_id: orderId,

View File

@ -2,9 +2,6 @@
const MainService = require('../../main');
const PACKING_EXPORT_TASK_CACHE_KEY_PREFIX = 'packing_export_task_';
const PACKING_EXPORT_TASK_CACHE_TTL_SECONDS = 1800;
/**
* 系统方法层:order.packing(打包任务接口包装层)。
* 主要职责:统一包装系统方法接口,处理权限、日志等公共逻辑,调用底层 service 实现业务功能。
@ -14,12 +11,9 @@ class OrderPackingMethodService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
// 免权限方法列表:export/exportTaskProgress 免权限(异步任务模式,与 order.export 口径一致,无 wms_permission 记录)
const _noNeedRight = 'list,get,export,exportTaskProgress';
// 免日志方法列表:导出与进度查询不记录操作日志(与订单导出口径一致)
const _noNeedLog = 'list,get,export,exportTaskProgress';
// 免鉴权(仓库有效期检查)方法列表:导出与进度查询不检查仓库有效期(与订单导出口径一致)
const _noNeedAuth = 'list,get,export,exportTaskProgress';
const _noNeedRight = 'list,get';
const _noNeedLog = 'list,get';
const _noNeedAuth = 'list,get';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -97,268 +91,6 @@ class OrderPackingMethodService extends MainService {
const result = await service.systems.orderPacking.forceRecord({ id });
return this.success('ok', result);
}
/**
* 提交打包任务导出任务(异步任务模式,与 order.export 口径一致)。
* 入参 where/sort 与 list 完全一致;提交后立即返回 task_id,
* 后台异步生成单 Sheet Excel(打包任务列表)并上传,
* 通过 exportTaskProgress 查询进度与下载链接。
*
* @param {Object} data 请求体。
* @param {Object} [data.where] 筛选条件(与 list 的 where 语义一致)。
* @param {Object} [data.sort] 排序参数(与 list 的 sort 语义一致)。
* @return {Promise<Object>} 统一成功包装响应(含 task_id/status/progress 等任务信息)。
*/
async export(data = {}) {
const { service } = this;
const { sort } = data;
const { where } = this.prepareWhereContext(data, {
specialFieldMap: {
quickWhere: {
bucket: 'quick',
},
},
});
// 仓库隔离:由服务端从当前上下文自动注入,禁止前端传入
const warehouseId = Number(this.ctx.user && this.ctx.user.store_id || 0);
const enforcedWhere = { ...where };
if (warehouseId > 0) {
enforcedWhere.warehouse_id = { operator: 'eq', value: warehouseId };
}
const taskId = this.generateExportTaskId(warehouseId);
const taskPayload = {
task_id: taskId,
status: 'submitted',
progress: 0,
current_count: 0,
total_count: 0,
message: '打包任务导出任务已提交',
result: null,
error: '',
};
await this.setExportTaskProgress(taskId, taskPayload);
setImmediate(async () => {
try {
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'running',
progress: 5,
current_count: 0,
total_count: 0,
message: '打包任务导出任务执行中',
result: null,
error: '',
});
const result = await service.systems.orderPacking.exportPackTask({
where: enforcedWhere,
sort,
warehouseId,
onProgress: async progress => {
const safeProgress = this.isPlainObject(progress) ? progress : {};
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: safeProgress.status || 'running',
progress: safeProgress.progress,
current_count: safeProgress.currentCount,
total_count: safeProgress.totalCount,
message: safeProgress.message || '打包任务导出任务执行中',
result: safeProgress.result || null,
error: '',
});
},
});
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'success',
progress: 100,
current_count: result.current_count || 0,
total_count: result.total_count || 0,
message: '打包任务导出任务完成',
result,
error: '',
});
} catch (error) {
const errorMessage = error && error.message ? error.message : `${error}`;
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'failed',
progress: 100,
current_count: 0,
total_count: 0,
message: '打包任务导出任务失败',
result: null,
error: errorMessage,
});
}
});
return this.success('ok', {
...taskPayload,
update_time: Date.now(),
});
}
/**
* 查询打包任务导出任务进度(与 order.exportTaskProgress 口径一致)。
*
* @param {Object} data 请求体。
* @param {string} [data.task_id] 任务ID(下划线写法)。
* @param {string} [data.taskId] 任务ID(驼峰写法)。
* @return {Promise<Object>} 统一成功包装响应
* (含 task_id/status/progress/current_count/total_count/message/error/download_url/update_time)。
*/
async exportTaskProgress(data = {}) {
const taskId = this.normalizeExportTaskId(data);
if (!taskId) {
return this.success('ok', {
task_id: '',
status: 'not_found',
progress: 0,
current_count: 0,
total_count: 0,
message: '任务不存在',
result: null,
error: '',
download_url: '',
update_time: Date.now(),
});
}
const cachedTask = await this.getExportTaskProgress(taskId);
if (!cachedTask) {
return this.success('ok', {
task_id: taskId,
status: 'not_found',
progress: 0,
current_count: 0,
total_count: 0,
message: '任务不存在',
result: null,
error: '',
download_url: '',
update_time: Date.now(),
});
}
const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {};
const downloadUrl = String(
safeResult.url
|| safeResult.cdnUrl
|| safeResult.cosUrl
|| safeResult.fileKey
|| ''
);
return this.success('ok', {
task_id: taskId,
...cachedTask,
download_url: downloadUrl,
});
}
/**
* 生成打包任务导出任务ID。
* @param {number|string} [warehouseId=''] 仓库ID(缺省兜底取当前上下文 store_id)。
* @return {string} 导出任务ID。
*/
generateExportTaskId(warehouseId = '') {
const normalizedWarehouseId = warehouseId || this.ctx?.user?.store_id || 'unknown';
const timestamp = Date.now();
const randomToken = Math.random().toString(36).slice(2, 10);
return `packing_export_${normalizedWarehouseId}_${timestamp}_${randomToken}`;
}
/**
* 归一化打包任务导出任务ID。
* @param {Object} data 请求体。
* @param {string} [data.task_id] 任务ID(下划线写法)。
* @param {string} [data.taskId] 任务ID(驼峰写法)。
* @return {string} 归一化后的任务ID。
*/
normalizeExportTaskId(data = {}) {
const normalizedData = this.isPlainObject(data) ? data : {};
return String(normalizedData.task_id || normalizedData.taskId || '').trim();
}
/**
* 获取打包任务导出任务缓存键。
* @param {string} taskId 任务ID。
* @return {string} 缓存键。
*/
getExportTaskCacheKey(taskId = '') {
const normalizedTaskId = String(taskId || '').trim();
if (!normalizedTaskId) {
return '';
}
return `${PACKING_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`;
}
/**
* 写入打包任务导出任务进度缓存(Redis TTL 30 分钟)。
* @param {string} taskId 任务ID。
* @param {Object} payload 任务状态载荷。
* @return {Promise<void>} 无返回值。
*/
async setExportTaskProgress(taskId = '', payload = {}) {
const cacheKey = this.getExportTaskCacheKey(taskId);
if (!cacheKey || typeof this.app.setCacheAsync !== 'function') {
return;
}
const safePayload = this.isPlainObject(payload) ? payload : {};
const normalizeCount = value => {
const numericValue = Number(value);
return Number.isFinite(numericValue) && numericValue >= 0 ? Math.round(numericValue) : 0;
};
const progressPayload = {
task_id: String(taskId || '').trim(),
status: String(safePayload.status || 'submitted').trim() || 'submitted',
progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0,
current_count: normalizeCount(safePayload.current_count),
total_count: normalizeCount(safePayload.total_count),
message: String(safePayload.message || ''),
result: safePayload.result ?? null,
error: String(safePayload.error || ''),
update_time: Date.now(),
};
try {
await this.app.setCacheAsync(cacheKey, progressPayload, PACKING_EXPORT_TASK_CACHE_TTL_SECONDS);
} catch (error) {
const errorMessage = error && error.message ? error.message : `${error}`;
this.ctx.logger.warn(`[order.packing.export] 写入导出任务缓存失败: ${errorMessage}`);
}
}
/**
* 读取打包任务导出任务进度缓存。
* @param {string} taskId 任务ID。
* @return {Promise<Object|null>} 任务缓存,未命中返回 null。
*/
async getExportTaskProgress(taskId = '') {
const cacheKey = this.getExportTaskCacheKey(taskId);
if (!cacheKey || typeof this.app.getCacheAsync !== 'function') {
return null;
}
try {
const cached = await this.app.getCacheAsync(cacheKey);
if (!this.isPlainObject(cached)) {
return null;
}
return cached;
} catch (error) {
const errorMessage = error && error.message ? error.message : `${error}`;
this.ctx.logger.warn(`[order.packing.export] 读取导出任务缓存失败: ${errorMessage}`);
return null;
}
}
}
module.exports = OrderPackingMethodService;

View File

@ -2,8 +2,6 @@
const OrderBaseService = require('./base');
const { getInterceptRequestBlockReason, resolveInterceptRequestGuardInfoMap } = require('../../../lib/intercept_guard');
const PENDING_OUTBOUND_STATUS = 'padding';
const PENDING_CANCEL_STATUS = 'cancel';
const PENDING_CANCEL_STEP = 9;
@ -696,10 +694,6 @@ class PendingOrderService extends OrderBaseService {
* 仅返回订单头、商品明细与运单信息;
* 待处理详情不再返回 logs 字段,也不触发操作日志查询。
*
* 兜底查询:忽略请求中的 tableType 等表位参数,
* 固定先查询配送表(dispatch),查询不到时回退到待处理表(current)再查询一次,
* 避免订单在配送表与待处理表之间流转后详情查询落空。
*
* @param {Object} data 请求体。
* @return {Promise<Object>} 订单头、商品明细和运单信息。
*/
@ -707,6 +701,7 @@ class PendingOrderService extends OrderBaseService {
const requestData = this.isPlainObject(data) ? data : {};
const warehouseId = this.getWarehouseId();
const orderIds = this.normalizeOrderIds(requestData);
const tableType = this.resolveOrderTableType(requestData);
if (orderIds.length === 0) {
throw new Error('订单ID不能为空');
@ -717,30 +712,18 @@ class PendingOrderService extends OrderBaseService {
}
const orderId = orderIds[0];
const orderModel = await this.getOrderModelByTableType(tableType, warehouseId);
const orderWhere = this.buildOrderWhere([ orderId ], warehouseId);
// 忽略传入的 tableType:固定先查配送表(dispatch),查不到再兜底待处理表(current)
let actualTableType = 'dispatch';
let orderModel = await this.getOrderModelByTableType(actualTableType, warehouseId);
let order = await orderModel.findOne({
const order = await orderModel.findOne({
where: orderWhere,
raw: true,
});
if (!order) {
actualTableType = 'current';
orderModel = await this.getOrderModelByTableType(actualTableType, warehouseId);
order = await orderModel.findOne({
where: orderWhere,
raw: true,
});
}
if (!order) {
throw new Error('订单不存在或不属于当前仓库');
}
const orderItemsModel = await this.getOrderItemsModelByTableType(actualTableType, warehouseId);
const orderItemsModel = await this.getOrderItemsModelByTableType(tableType, warehouseId);
const orderItems = await orderItemsModel.findAll({
where: {
order_id: orderId,
@ -2455,35 +2438,11 @@ class PendingOrderService extends OrderBaseService {
throw new Error('订单当前状态不允许取消');
}
// 拉取拦截请求前置校验信息(波次类型 + 散单称重重量):团购单已复核 / 散单已称重后不允许写入拦截请求状态
const guardInfoMap = await resolveInterceptRequestGuardInfoMap(this.ctx, {
orderRows: existingOrders,
warehouseId,
transaction,
});
// 已同步订单不允许取消,转为拦截处理
const syncedOrders = existingOrders.filter(
order => String(order.sync_status || '').trim() === 'fin'
);
if (syncedOrders.length > 0) {
// 已复核/已称重订单不允许写入拦截请求状态,直接拒绝取消
const blockedSyncedOrders = syncedOrders.filter(order => {
const guardInfo = guardInfoMap.get(Number(order.id)) || {};
return getInterceptRequestBlockReason({
waveType: guardInfo.waveType,
inspectionStatus: String(order.inspection_status || '').trim(),
weighingWeight: guardInfo.weighingWeight,
}) !== '';
});
if (blockedSyncedOrders.length > 0) {
await transaction.rollback();
const blockedCodes = blockedSyncedOrders
.map(order => String(order.delivery_order_code || order.pre_delivery_order_code || order.id || '').trim())
.filter(Boolean)
.join(', ');
throw new Error(`订单已完成复核/称重,无法取消:${blockedCodes}`);
}
const syncedOrderIds = syncedOrders.map(order => Number(order.id)).filter(
id => Number.isInteger(id) && id > 0
);
@ -2521,33 +2480,6 @@ class PendingOrderService extends OrderBaseService {
// 拦截标记已写入,提交后抛出业务错误(调用方按"已转拦截"处理)
await transaction.commit();
// 写入拦截操作日志(不影响主流程)
try {
const operator = this.getOrderLogOperator() || {};
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
if (syncedOrderIds.length > 0 && this.ctx.model && this.ctx.model.OperationLog) {
const operatorId = operator.id != null ? String(operator.id) : null;
const operatorName = operator.name ? String(operator.name) : 'system';
const logNow = new Date();
await this.ctx.model.OperationLog.bulkCreate(
syncedOrderIds.map(orderId => ({
business_type: 'order',
business_id: String(orderId),
operation_code: 'ORDER_INTERCEPT_REQUEST',
operator_id: operatorId,
operator_name: operatorName,
external_log_type: 'NONE',
warehouse_id: logWarehouseId || null,
platform_code: 'SYSTEM',
message: '订单已同步,不可取消,转为拦截处理',
created_at: logNow,
}))
);
}
} catch (logErr) {
this.ctx.logger.warn('[PendingOrderService.cancelOrder] 写入拦截操作日志失败,不影响业务', logErr);
}
const syncedCodes = syncedOrders
.map(order => String(order.delivery_order_code || order.pre_delivery_order_code || order.id || '').trim())
.filter(Boolean)
@ -4373,7 +4305,6 @@ ${numbered}`;
payload.total_order_count = Number(result.total_order_count || 0);
payload.intercepted_order_count = Number(result.intercepted_order_count || 0);
payload.intercepted_order_ids = this.normalizeIdsInput(result.intercepted_order_ids);
payload.skipped_order_ids = this.normalizeIdsInput(result.skipped_order_ids);
payload.duration_ms = Number(result.duration_ms || cachedProgress.duration_ms || 0);
}
@ -4596,7 +4527,7 @@ ${numbered}`;
}
const orderRows = await orderModel.findAll({
attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code', 'wave_id', 'inspection_status' ],
attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code' ],
where: {
warehouse_id: warehouseId,
id: {
@ -4615,33 +4546,7 @@ ${numbered}`;
const operator = this.getOrderLogOperator();
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
// 拉取拦截请求前置校验信息(波次类型 + 散单称重重量):团购单已复核 / 散单已称重的订单不允许写入拦截请求状态,跳过拦截
const guardInfoMap = await resolveInterceptRequestGuardInfoMap(ctx, {
orderRows: validOrderRows,
warehouseId,
});
const skippedInterceptOrderIds = [];
const eligibleOrderRows = [];
for (const row of (Array.isArray(validOrderRows) ? validOrderRows : [])) {
const guardInfo = guardInfoMap.get(Number(row.id)) || {};
const blockReason = getInterceptRequestBlockReason({
waveType: guardInfo.waveType,
inspectionStatus: String(row.inspection_status || '').trim(),
weighingWeight: guardInfo.weighingWeight,
});
if (blockReason) {
skippedInterceptOrderIds.push(Number(row.id));
ctx.logger.info(
`[order.pendingOrder.batchIntercept] 订单${blockReason},跳过拦截, orderId=${row.id}`
);
} else {
eligibleOrderRows.push(row);
}
}
const normalizedOrderRows = Array.isArray(validOrderRows) ? validOrderRows : [];
const eligibleOrderCount = eligibleOrderRows.length;
const totalOrderCount = orderIds.length;
const validOrderCount = normalizedOrderRows.length;
@ -4672,10 +4577,10 @@ ${numbered}`;
return;
}
// 分批更新拦截状态,每批最多500条(仅处理未命中「已复核/已称重」前置校验的订单)
// 分批更新拦截状态,每批最多500条
const UPDATE_CHUNK_SIZE = 500;
for (let i = 0; i < eligibleOrderRows.length; i += UPDATE_CHUNK_SIZE) {
const chunkRows = eligibleOrderRows.slice(i, i + UPDATE_CHUNK_SIZE);
for (let i = 0; i < normalizedOrderRows.length; i += UPDATE_CHUNK_SIZE) {
const chunkRows = normalizedOrderRows.slice(i, i + UPDATE_CHUNK_SIZE);
if (chunkRows.length === 0) {
continue;
}
@ -4766,8 +4671,8 @@ ${numbered}`;
}
// 更新进度
const progressPercent = eligibleOrderCount > 0
? Math.min(99, Math.round((interceptedOrderIds.length / eligibleOrderCount) * 100))
const progressPercent = validOrderCount > 0
? Math.min(99, Math.round((interceptedOrderIds.length / validOrderCount) * 100))
: 0;
await this.setBatchInterceptTaskProgress(normalizedTaskId, 'running', {
@ -4790,13 +4695,9 @@ ${numbered}`;
order_ids: orderIds,
intercepted_order_ids: interceptedOrderIds,
intercepted_order_count: interceptedOrderIds.length,
skipped_order_ids: skippedInterceptOrderIds,
skipped_order_count: skippedInterceptOrderIds.length,
total_order_count: totalOrderCount,
duration_ms: durationMs,
message: skippedInterceptOrderIds.length > 0
? `已拦截 ${interceptedOrderIds.length} 条订单,跳过 ${skippedInterceptOrderIds.length} 条(已复核/已称重)`
: `已拦截 ${interceptedOrderIds.length} 条订单`,
message: `已拦截 ${interceptedOrderIds.length} 条订单`,
},
});
} catch (error) {
@ -6104,7 +6005,6 @@ ${numbered}`;
* 执行批量解除拦截后台任务。
*
* 直接对给定订单ID数组,将 intercept_status 更新为 'none',并写入操作日志 ORDER_INTERCEPT_CANCEL。
* 同时释放订单对应的拦截锁定库存(intercept_locked_quantity 回落到可用数量,失败不阻断主流程)。
* 仅处理当前仓库上下文内的订单。
*
* @param {Object} params 任务参数。
@ -6272,10 +6172,6 @@ ${numbered}`;
);
}
// 注意:解除拦截不操作拦截锁定数量字段——业务上「拦截→取消拦截」两个环节均不动库存口径,
// 拦截锁定数量仅在库内拦截确定(confirmIntercept/interceptScan)时占用,
// 其回落由后续特定的入库处理链路统一接管,取消拦截环节不做释放。
// 写入操作日志 ORDER_INTERCEPT_CANCEL
const logPayloads = chunkRows.map(row => {
const orderId = Number(row.id || 0);

View File

@ -1942,7 +1942,6 @@ class RecheckOrderService extends OrderBaseService {
waveNo: String(waveRow.wave_no || '').trim(),
warehouseId,
operator,
orderIds: normalOrderIds,
normalOrderCount: normalOrders.length,
interceptedOrderCount: interceptedOrders.length,
totalOrderCount: orderList.length,
@ -1958,17 +1957,13 @@ class RecheckOrderService extends OrderBaseService {
}
/**
* 写入复核操作日志(内部方法)。
* - 写 wms_wave_pick_action_log 一条复核动作日志;
* - 双写 wms_operation_log:团购批量复核按波次写一条 ORDER_RECHECK_BATCH,
* 同时按订单逐单写 ORDER_RECHECK,保证订单操作日志列表中可见。
* 写入复核操作日志到 wms_wave_pick_action_log(内部方法)。
*
* @param {Object} params 日志参数。
* @param {number} [params.orderId] 订单ID(单订单复核场景)。
* @param {string} [params.waybillNo] 运单号(单订单复核场景)。
* @param {number} [params.waveId] 波次ID(团购批量复核场景)。
* @param {string} [params.waveNo] 波次号(团购批量复核场景)。
* @param {number[]} [params.orderIds] 复核成功的订单ID数组(团购批量复核场景,用于逐单写订单级日志)。
* @param {number} params.warehouseId 仓库ID。
* @param {{ id: string|null, name: string }} params.operator 操作人信息。
* @param {number} [params.normalOrderCount] 复核成功的订单数(批量场景)。
@ -1983,7 +1978,6 @@ class RecheckOrderService extends OrderBaseService {
waybillNo,
waveId,
waveNo,
orderIds,
warehouseId,
operator,
normalOrderCount,
@ -2096,25 +2090,6 @@ class RecheckOrderService extends OrderBaseService {
totalOrderCount: totalOrderCount || 0,
},
}]);
// 逐单补写订单级复核日志(business_id=订单ID),保证订单操作日志列表中可见
const orderIdList = (Array.isArray(orderIds) ? orderIds : [])
.map(id => Number(id))
.filter(id => id > 0);
if (orderIdList.length > 0) {
const waveNoText = waveNo ? `(波次 ${String(waveNo).trim()})` : '';
await operationLogService.createOperationLogs(orderIdList.map(oid => ({
businessType: 'order',
businessId: String(oid),
operationCode: 'ORDER_RECHECK',
operator: { id: String(operatorId || ''), name: operatorName },
extras: {
warehouseId: warehouseId || 0,
message: `订单${oid}复核完成${waveNoText}`,
orderId: oid,
},
})));
}
}
} else {
// 单订单复核
@ -3758,7 +3733,7 @@ class RecheckOrderService extends OrderBaseService {
* 每个订单的拦截处理:
* 1. 更新 wms_order_delivery:intercept_status = intercepted_at_warehouse、step=4、outbound_status=fin
* 2. 同步更新运单表:is_intercept='Y'、is_back='Y'(库内拦截确认,货物在库内需退回)
* 3. 释放储位分配(cancelAllocateStorage 拦截模式:库存不归还可用,移入拦截锁定字段 intercept_locked_quantity)
* 3. 释放储位分配(cancelAllocateStorage,归还库存)
* 4. 释放订单锁(lock_status='none')
* 5. 写入操作日志(ORDER_INTERCEPT_CONFIRM)
* 全部订单处理完后,按成功订单 ID 汇总批量创建售后工单 + 通知快递群。
@ -3865,11 +3840,10 @@ class RecheckOrderService extends OrderBaseService {
);
}
// 拦截成功后释放储位分配(拦截模式:库存移入拦截锁定,不归还可用)
// 拦截成功后释放储位分配(归还库存)
try {
await this.service.systems.orderStorageAllocation.cancelAllocateStorage({
order_ids: [ orderId ],
interceptMode: true,
});
} catch (allocErr) {
ctx.logger.warn(
@ -3966,7 +3940,7 @@ class RecheckOrderService extends OrderBaseService {
* 3. 检查是否存在关联的未完结售后工单(wms_after_sale),若有则调用 handleWorkOrder 写入
* "库内拦截成功"步骤并将工单置为 completed
* 4. 同步更新 wms_order_delivery 的 intercept_status 为 intercepted_at_warehouse,
* 并释放储位分配(拦截模式:库存移入拦截锁定,不归还可用)与订单锁(仅订单级状态更新,不标记订单下其他面单)
* 并释放储位分配与订单锁(仅订单级状态更新,不标记订单下其他面单)
*
* 注:库内拦截确认需标记退回 is_back='Y';发起拦截链路仅写 is_intercept,不写 is_back。
*
@ -4089,11 +4063,10 @@ class RecheckOrderService extends OrderBaseService {
{ where: orderWhere }
);
// 释放储位分配(拦截模式:库存移入拦截锁定,不归还可用)
// 释放储位分配
try {
await service.systems.orderStorageAllocation.cancelAllocateStorage({
order_ids: [ orderId ],
interceptMode: true,
});
} catch (allocErr) {
ctx.logger.warn(

View File

@ -755,34 +755,6 @@ class WaveService extends OrderBaseService {
return errno === 1062 || code === 'ER_DUP_ENTRY';
}
/**
* 根据波次元信息推导订单 wave_scope(波次范围)。
*
* 口径:
* - wave_type=1 且 source=0 → 1(大团购);
* - wave_type=1 且 source=2 → 3(小团购);
* - 其余(散单等)→ 2(散单)。
* 未分配波次(wave_id=0)由调用方直接置 0。
*
* @param {number|string} waveType 波次类型(1-团购 2-散单)。
* @param {number|string} source 波次来源(0-普通 1-管理后台策略 2-PDA策略)。
* @return {number} wave_scope:1-大团购 2-散单 3-小团购。
*/
resolveWaveScopeByWaveMeta(waveType, source) {
const normalizedWaveType = Number(waveType) === 2 ? 2 : 1;
const normalizedSource = [ 0, 1, 2 ].includes(Number(source)) ? Number(source) : 0;
if (normalizedWaveType === 1 && normalizedSource === 0) {
return 1;
}
if (normalizedWaveType === 1 && normalizedSource === 2) {
return 3;
}
return 2;
}
/**
* 新增一条“已就绪”波次批次记录,并返回自增 wave_id。
*
@ -1003,9 +975,6 @@ class WaveService extends OrderBaseService {
: 0;
const normalizedSourceInput = Number(normalizedOptions.source);
const normalizedSource = [ 0, 1, 2 ].includes(normalizedSourceInput) ? normalizedSourceInput : 0;
const logOperator = this.getOrderLogOperator() || {};
const claimOperator = String(logOperator.name || '').trim() || null;
const grabOperatorId = Number(logOperator.id || 0) > 0 ? Number(logOperator.id) : null;
const normalizedMinGroupOrderFetchQuantity = Number.isInteger(Number(minGroupOrderFetchQuantity))
&& Number(minGroupOrderFetchQuantity) > 0
? Number(minGroupOrderFetchQuantity)
@ -1070,9 +1039,6 @@ class WaveService extends OrderBaseService {
await model.update({
wave_id: waveId,
wave_no: waveNo,
wave_scope: this.resolveWaveScopeByWaveMeta(1, normalizedSource),
grab_operator_id: grabOperatorId,
grab_operator: claimOperator,
}, {
where: {
id: { [Op.in]: candidateOrderIds },
@ -1081,23 +1047,6 @@ class WaveService extends OrderBaseService {
transaction,
});
// 抓取波次(source=1/2)无需领料:将抓取人冗余写入领料人字段,便于追溯
if ([ 1, 2 ].includes(normalizedSource) && claimOperator) {
await ctx.model.WaveBatch.update(
{
claim_operator: claimOperator,
claim_time: new Date(),
},
{
where: {
wave_id: waveId,
warehouse_id: warehouseId,
},
transaction,
}
);
}
const grabbedRows = await model.findAll({
where: {
id: { [Op.in]: candidateOrderIds },
@ -1868,14 +1817,10 @@ class WaveService extends OrderBaseService {
'source',
'keyword',
'task_no',
'wave_no',
'pick_mode',
'review_status',
'pick_user_id',
'review_user_id',
'pick_user_name',
'review_user_name',
'claim_operator',
'cart_id',
'start_time_start',
'start_time_end',
@ -1926,11 +1871,7 @@ class WaveService extends OrderBaseService {
'strategy_id',
'pick_user_id',
'review_user_id',
'pick_user_name',
'review_user_name',
'claim_operator',
'task_no',
'wave_no',
'cart_id',
'keyword',
'start_time_start',
@ -1993,47 +1934,6 @@ class WaveService extends OrderBaseService {
replacements.whereTaskNo = `%${normalizedTaskNo}%`;
}
const appendNameCondition = (fieldKey, columnName, replacementKey) => {
const raw = normalizedWhere[fieldKey];
if (raw === undefined || raw === null || raw === '') {
return;
}
// 支持操作符对象:{ operator: 'like' | 'notlike' | 'eq', value },默认 like
let operator = 'like';
let value = raw;
if (this.isPlainObject(raw)) {
operator = String(raw.operator || 'like').trim().toLowerCase();
value = raw.value;
}
if (value === undefined || value === null || value === '') {
return;
}
const normalizedValue = String(value).trim();
if (!normalizedValue) {
throw new Error(`${fieldKey} 参数不合法`);
}
if (operator === 'eq') {
conditions.push(`${columnName} = :${replacementKey}`);
replacements[replacementKey] = normalizedValue;
} else if (operator === 'notlike') {
conditions.push(`(${columnName} NOT LIKE :${replacementKey} OR ${columnName} IS NULL)`);
replacements[replacementKey] = `%${normalizedValue}%`;
} else if (operator !== 'like') {
throw new Error(`${fieldKey} 不支持的 operator: ${operator}`);
} else {
conditions.push(`${columnName} LIKE :${replacementKey}`);
replacements[replacementKey] = `%${normalizedValue}%`;
}
};
appendNameCondition('pick_user_name', 't.pick_user_name', 'wherePickUserName');
appendNameCondition('review_user_name', 't.review_user_name', 'whereReviewUserName');
appendNameCondition('claim_operator', 't.claim_operator', 'whereClaimOperator');
appendNameCondition('wave_no', 't.batch_no_array', 'whereWaveNo');
const keyword = normalizedWhere.keyword;
if (keyword !== undefined && keyword !== null && keyword !== '') {
const normalizedKeyword = String(keyword).trim();
@ -4568,9 +4468,9 @@ class WaveService extends OrderBaseService {
SUM(CASE WHEN od.post_status = 'error' THEN 1 ELSE 0 END) AS post_error_count,
SUM(CASE WHEN od.print_status = 'none' THEN 1 ELSE 0 END) AS print_none_count,
SUM(CASE WHEN od.print_status = 'fin' THEN 1 ELSE 0 END) AS print_fin_count,
SUM(CASE WHEN od.recheck_status = 'fin' THEN 1 ELSE 0 END) AS review_fin_count,
SUM(CASE WHEN od.recheck_status = 'error' THEN 1 ELSE 0 END) AS review_error_count,
SUM(CASE WHEN od.recheck_status NOT IN ('fin', 'error') THEN 1 ELSE 0 END) AS review_none_count,
SUM(CASE WHEN od.inspection_status = 'fin' THEN 1 ELSE 0 END) AS review_fin_count,
SUM(CASE WHEN od.inspection_status = 'error' THEN 1 ELSE 0 END) AS review_error_count,
SUM(CASE WHEN od.inspection_status NOT IN ('fin', 'error') THEN 1 ELSE 0 END) AS review_none_count,
SUM(CASE WHEN od.pick_status = 'none' THEN 1 ELSE 0 END) AS pick_none_count,
SUM(CASE WHEN od.pick_status = 'fin' THEN 1 ELSE 0 END) AS pick_fin_count,
SUM(CASE WHEN od.pick_status = 'error' THEN 1 ELSE 0 END) AS pick_error_count,
@ -4822,8 +4722,6 @@ class WaveService extends OrderBaseService {
t.current_cart_code_snapshot,
c.cart_name AS cart_name,
t.batch_no,
t.claim_operator_id,
t.claim_operator,
t.device_id,
t.start_time,
t.finish_time,
@ -5010,8 +4908,6 @@ class WaveService extends OrderBaseService {
current_cart_code_snapshot: String(item && item.current_cart_code_snapshot || '').trim(),
cart_name: String(item && item.cart_name || '').trim(),
batch_no: String(item && item.batch_no || '').trim(),
claim_operator_id: Number(item && item.claim_operator_id || 0) || null,
claim_operator: String(item && item.claim_operator || '').trim() || null,
device_id: String(item && item.device_id || '').trim(),
start_time: item && item.start_time || null,
start_at: item && item.start_time || null,
@ -7195,9 +7091,6 @@ class WaveService extends OrderBaseService {
}
const warehouseId = contextWarehouseId;
const logOperator = this.getOrderLogOperator() || {};
const grabOperatorId = Number(logOperator.id || 0) > 0 ? Number(logOperator.id) : null;
const grabOperator = String(logOperator.name || '').trim() || null;
const rawIds = data && (
data.ids !== undefined
? data.ids
@ -7313,9 +7206,6 @@ class WaveService extends OrderBaseService {
await orderModel.update({
wave_id: waveId,
wave_no: waveNo,
wave_scope: this.resolveWaveScopeByWaveMeta(2, 0),
grab_operator_id: grabOperatorId,
grab_operator: grabOperator,
}, {
where: {
id: { [Op.in]: fetchableOrderIds },
@ -7536,7 +7426,6 @@ class WaveService extends OrderBaseService {
const orderUpdateResult = await orderModel.update({
wave_id: 0,
wave_no: '',
wave_scope: 0,
wave_strategy_version: 0,
wave_scan_result: 0,
}, {
@ -8628,7 +8517,6 @@ class WaveService extends OrderBaseService {
const orderUpdateResult = await orderModel.update({
wave_id: 0,
wave_no: '',
wave_scope: 0,
wave_strategy_version: 0,
wave_scan_result: 0,
}, {
@ -11004,8 +10892,6 @@ class WaveService extends OrderBaseService {
* @param {number|string} params.waveType 波次类型(1-团购,2-散单)。
* @param {string} params.wavePrefix 波次前缀。
* @param {number|string} [params.source=0] 波次来源。
* @param {string} [params.claimOperator] 抓取人姓名:抓取波次(source=1/2)无需领料,
* 将该值冗余写入波次表领料人字段(claim_operator)。
* @param {Object} params.transaction 事务对象。
* @return {Promise<{ waveId: number, waveNo: string, selectedOrderIds: Array<number> }>} 创建结果。
*/
@ -11015,10 +10901,6 @@ class WaveService extends OrderBaseService {
const wavePrefix = String(params.wavePrefix || '').trim() || (waveType === 2 ? 'A' : 'B');
const sourceInput = Number(params.source);
const source = [ 0, 1, 2 ].includes(sourceInput) ? sourceInput : 0;
const claimOperator = String(params.claimOperator || '').trim() || null;
const claimOperatorId = Number(params.claimOperatorId || 0) > 0
? Number(params.claimOperatorId)
: null;
const transaction = params.transaction;
const orderIds = this.normalizeIdsInput(params.orderIds || []);
if (orderIds.length === 0) {
@ -11078,9 +10960,6 @@ class WaveService extends OrderBaseService {
await orderModel.update({
wave_id: waveId,
wave_no: waveNo,
wave_scope: this.resolveWaveScopeByWaveMeta(waveType, source),
grab_operator_id: claimOperatorId,
grab_operator: claimOperator,
}, {
where: {
id: { [Op.in]: fetchableOrderIds },
@ -11132,23 +11011,6 @@ class WaveService extends OrderBaseService {
});
}
// 抓取波次(source=1/2)无需领料:将抓取人冗余写入领料人字段,便于追溯
if ([ 1, 2 ].includes(source) && claimOperator) {
await this.ctx.model.WaveBatch.update(
{
claim_operator: claimOperator,
claim_time: new Date(),
},
{
where: {
wave_id: waveId,
warehouse_id: warehouseId,
},
transaction,
}
);
}
await this.rebuildOrderWaveIndex({
warehouseId,
waveId,
@ -11189,8 +11051,6 @@ class WaveService extends OrderBaseService {
const strategyType = Number(strategyRow.strategy_type || plan.strategy_type || 0);
const operatorInfo = this.isPlainObject(plan.operator) ? plan.operator : {};
const operatorId = Number((operatorInfo.operator_id ?? operatorInfo.id) || 0);
const claimOperator = String(operatorInfo.operator_name || operatorInfo.name || '').trim() || null;
const claimOperatorId = operatorId > 0 ? operatorId : null;
await this.ensureNoActiveWavePickTaskForOperator({
warehouseId,
@ -11254,8 +11114,6 @@ class WaveService extends OrderBaseService {
waveType: 1,
wavePrefix: wavePrefixResolution.wavePrefix,
source: waveBatchSource,
claimOperator,
claimOperatorId,
transaction,
});
result.selected_wave_ids.push(created.waveId);
@ -11323,8 +11181,6 @@ class WaveService extends OrderBaseService {
waveType: 2,
wavePrefix: wavePrefixResolution.wavePrefix,
source: waveBatchSource,
claimOperator,
claimOperatorId,
transaction,
});
@ -11380,11 +11236,6 @@ class WaveService extends OrderBaseService {
const warehouseId = this.normalizeRequiredPositiveInteger(plan.warehouse_id, 'warehouse_id');
const strategyId = this.normalizeRequiredPositiveInteger(plan.strategy_id, 'strategy_id');
const strategyType = Number(strategyRow.strategy_type || plan.strategy_type || 0);
const operatorInfo = this.isPlainObject(plan.operator) ? plan.operator : {};
const claimOperator = String(operatorInfo.operator_name || operatorInfo.name || '').trim() || null;
const claimOperatorId = Number((operatorInfo.operator_id ?? operatorInfo.id) || 0) > 0
? Number((operatorInfo.operator_id ?? operatorInfo.id))
: null;
const transaction = await this.ctx.model.transaction();
try {
@ -11428,8 +11279,6 @@ class WaveService extends OrderBaseService {
waveType: 1,
wavePrefix: wavePrefixResolution.wavePrefix,
source: waveBatchSource,
claimOperator,
claimOperatorId,
transaction,
});
createdWaveIds.push(created.waveId);
@ -11459,8 +11308,6 @@ class WaveService extends OrderBaseService {
waveType: 2,
wavePrefix: wavePrefixResolution.wavePrefix,
source: waveBatchSource,
claimOperator,
claimOperatorId,
transaction,
});
createdWaveIds.push(createdWave.waveId);
@ -11632,34 +11479,20 @@ class WaveService extends OrderBaseService {
});
}
// 查询所有选中波次的 wave_no(用于任务主表 batch_no_array 与任务波次关联记录)
const waveNoMap = new Map();
if (selectedWaveIds.length > 0) {
const waveNoRows = await this.ctx.model.query(
`SELECT wave_id, wave_no
FROM wms_wave_batch
WHERE wave_id IN (:waveIds)
AND warehouse_id = :warehouseId`,
// 散单模式:从波次表读取 wave_no 并写入任务 batch_no
let resolvedBatchNo = null;
if ([ 2, 3, 4 ].includes(pickMode) && selectedWaveIds.length > 0) {
const batchRows = await this.ctx.model.query(
'SELECT wave_no FROM wms_wave_batch WHERE wave_id = :waveId AND warehouse_id = :warehouseId LIMIT 1',
{
replacements: { waveIds: selectedWaveIds, warehouseId },
replacements: { waveId: selectedWaveIds[0], warehouseId },
type: this.ctx.model.QueryTypes.SELECT,
transaction,
}
);
for (const row of Array.isArray(waveNoRows) ? waveNoRows : []) {
const wid = Number(row && row.wave_id || 0);
const wno = String(row && row.wave_no || '').trim();
if (wid > 0 && wno) {
waveNoMap.set(wid, wno);
}
}
resolvedBatchNo = (batchRows.length > 0 && batchRows[0].wave_no) ? String(batchRows[0].wave_no).trim() : null;
}
// 散单模式:取第一个选中波次的 wave_no 写入任务 batch_no
const resolvedBatchNo = [ 2, 3, 4 ].includes(pickMode) && selectedWaveIds.length > 0
? (waveNoMap.get(selectedWaveIds[0]) || null)
: null;
const taskPayload = this.buildTaskCreatePayload({
plan: effectivePlan,
data: effectiveRequestData,
@ -11670,14 +11503,6 @@ class WaveService extends OrderBaseService {
if (resolvedBatchNo !== null) {
taskPayload.batch_no = resolvedBatchNo;
}
// 逗号分隔写入任务主表 batch_no_array,便于统计与查询
const batchNoArray = selectedWaveIds
.map(waveId => waveNoMap.get(waveId) || '')
.filter(Boolean)
.join(',');
if (batchNoArray) {
taskPayload.batch_no_array = batchNoArray;
}
if (selectedWaveIds.length > 0 && [ 1, 2 ].includes(waveBatchSource)) {
await this.ctx.model.query(`
@ -11700,6 +11525,29 @@ class WaveService extends OrderBaseService {
const taskId = Number(taskCreateResult.task_id || 0);
const taskNo = String(taskCreateResult.task_no || '').trim();
// 查询所有选中波次的 wave_no,用于填充任务波次关联记录
const waveNoMap = new Map();
if (selectedWaveIds.length > 0) {
const waveNoRows = await this.ctx.model.query(
`SELECT wave_id, wave_no
FROM wms_wave_batch
WHERE wave_id IN (:waveIds)
AND warehouse_id = :warehouseId`,
{
replacements: { waveIds: selectedWaveIds, warehouseId },
type: this.ctx.model.QueryTypes.SELECT,
transaction,
}
);
for (const row of Array.isArray(waveNoRows) ? waveNoRows : []) {
const wid = Number(row && row.wave_id || 0);
const wno = String(row && row.wave_no || '').trim();
if (wid > 0 && wno) {
waveNoMap.set(wid, wno);
}
}
}
const taskWaveRows = this.buildTaskWaveRows({
taskId,
plan: effectivePlan,
@ -11885,9 +11733,8 @@ class WaveService extends OrderBaseService {
source: sourceCode,
wave_count: selectedWaveIds.length,
order_count: selectedOrderIds.length,
box_count: pickMode === 5 ? 1 : 0,
box_count: 0,
batch_no: null,
batch_no_array: null,
pick_user_id: pickUserId,
pick_user_name: pickUserName,
current_cart_id: Number(options && options.cartId || 0) > 0 ? Number(options.cartId) : null,
@ -12433,7 +12280,6 @@ class WaveService extends OrderBaseService {
const insertPayload = {
...payload,
task_no: candidateTaskNo,
batch_no_array: String(payload.batch_no_array || '').trim() || null,
};
try {
@ -12450,7 +12296,6 @@ class WaveService extends OrderBaseService {
order_count,
box_count,
batch_no,
batch_no_array,
pick_user_id,
pick_user_name,
current_cart_id,
@ -12474,7 +12319,6 @@ class WaveService extends OrderBaseService {
:order_count,
:box_count,
:batch_no,
:batch_no_array,
:pick_user_id,
:pick_user_name,
:current_cart_id,
@ -12937,7 +12781,6 @@ class WaveService extends OrderBaseService {
await orderModel.update({
wave_id: 0,
wave_no: '',
wave_scope: 0,
wave_strategy_version: 0,
wave_scan_result: 0,
}, {

View File

@ -137,7 +137,7 @@ class PickService extends MainService {
[this.app.Sequelize.Op.in]: normalizedOrderIds,
},
},
attributes: [ 'id', 'intercept_status', 'claim_status', 'claim_operator_id', 'claim_operator' ],
attributes: [ 'id', 'intercept_status', 'claim_status' ],
raw: true,
});
@ -155,14 +155,11 @@ class PickService extends MainService {
}
}
// 领料语义(普通波次 source=0):未领料或领料人非本人的订单不参与拣货数量计算,直接剔除
// 领料语义(普通波次 source=0):未领料订单(claim_status != fin)不参与拣货数量计算,直接剔除
const unclaimedOrderIds = excludeUnclaimed
? new Set(normalizedOrderIds.filter(id => {
const row = orderRowMap.get(id);
if (!row || String(row && row.claim_status || '') !== 'fin') {
return true;
}
return Number(row && row.claim_operator_id || 0) !== operatorId;
return !row || String(row && row.claim_status || '') !== 'fin';
}))
: new Set();
if (unclaimedOrderIds.size > 0) {
@ -181,11 +178,6 @@ class PickService extends MainService {
throw Object.assign(new Error(emptyReason), { code: 400 });
}
// 取首个活跃订单的领料人冗余写入任务主表(整波领单同波次领料人一致)
const firstActiveOrderRow = orderRowMap.get(activeOrderIds[0]) || null;
const claimOperatorId = Number(firstActiveOrderRow && firstActiveOrderRow.claim_operator_id || 0);
const claimOperator = String(firstActiveOrderRow && firstActiveOrderRow.claim_operator || '').trim();
const orderNoMap = new Map((Array.isArray(orderRows) ? orderRows : [])
.map(row => [ Number(row && row.id || 0), '' ]));
@ -198,10 +190,6 @@ class PickService extends MainService {
task_no,
warehouse_id,
wave_id,
claim_operator_id,
claim_operator,
batch_no,
batch_no_array,
pick_mode,
status,
source,
@ -217,10 +205,6 @@ class PickService extends MainService {
:taskNo,
:warehouseId,
:waveId,
:claimOperatorId,
:claimOperator,
:batchNo,
:batchNoArray,
:pickMode,
0,
:source,
@ -239,10 +223,6 @@ class PickService extends MainService {
taskNo,
warehouseId,
waveId,
claimOperatorId: claimOperatorId > 0 ? claimOperatorId : null,
claimOperator: claimOperator || null,
batchNo: waveNo,
batchNoArray: waveNo,
pickMode,
source,
orderCount: activeOrderIds.length,
@ -395,14 +375,14 @@ class PickService extends MainService {
}
);
// 更新任务主表的 box_count(大团购固定 1,其余按实际筐数)
// 更新任务主表的 box_count
await ctx.model.query(
`UPDATE wms_wave_pick_task
SET box_count = :boxCount,
update_time = NOW()
WHERE id = :taskId`,
{
replacements: { taskId, boxCount: pickMode === 5 ? 1 : boxValuesSql.length },
replacements: { taskId, boxCount: boxValuesSql.length },
transaction,
}
);
@ -474,7 +454,7 @@ class PickService extends MainService {
await transaction.commit();
// 写入 order_operation_log 开始拣货日志
// 写入 order_operation_log 抓取波次日志
try {
const operationLogService = this.ctx
&& this.ctx.service
@ -484,13 +464,13 @@ class PickService extends MainService {
const logPayloads = activeOrderIds.map(orderId => ({
businessType: 'order',
businessId: `${orderId}`,
operationCode: 'ORDER_PICKING',
operationCode: 'ORDER_WAVE_GRAB',
operator: {
id: operatorId ? String(operatorId) : null,
name: operatorName || 'system',
},
extras: {
message: `订单${orderId}开始拣货(波次 ${waveNo})`,
message: `订单${orderId}抓取波次成功`,
warehouseId,
externalLogType: 'API',
},
@ -850,10 +830,9 @@ class PickService extends MainService {
warehouseId: normalizedWarehouseId,
waveId: targetWaveId,
waveNo: targetWaveNo,
claimOperatorId: operatorId,
});
if (claimGateStats.total_order_count > 0 && claimGateStats.unclaimed_order_count > 0) {
return this.fail('订单未领料或领料人不是本人,请先领料后再拣货', {
return this.fail('订单未领料,请先领料后再拣货', {
action: 'wave_claim',
wave_id: targetWaveId,
wave_no: targetWaveNo,
@ -1032,7 +1011,7 @@ class PickService extends MainService {
} catch (e) {
// 查询失败不影响主流程,退回默认拣货模式
}
const pickMode = isGroupWave ? 5 : (isManualIdsWave ? 3 : 2);
const pickMode = isGroupWave ? 1 : (isManualIdsWave ? 3 : 2);
if (selectedOrderIds.length === 0) {
let orderModel = null;
@ -1463,7 +1442,7 @@ class PickService extends MainService {
} catch (e) {
// 查询失败不影响主流程,退回默认拣货模式
}
const pickMode = isGroupWave ? 5 : (isManualIdsWaveWP ? 3 : 2);
const pickMode = isGroupWave ? 1 : (isManualIdsWaveWP ? 3 : 2);
try {
const createdTask = await this.createWavePickTask({
@ -1629,16 +1608,14 @@ class PickService extends MainService {
* 统计口径:
* - total_order_count:波次下全部订单数(含拦截订单);
* - intercepted_order_count:拦截订单数(intercept_status != none);
* - unclaimed_order_count:非拦截且需要领料的订单数,包括未领料
* (claim_status != fin)与已领料但领料人非本人(claim_operator_id != 操作人)两种;
* 拦截订单不阻隔拣货,不计入该数量。
* - unclaimed_order_count:非拦截且未领料(claim_status != fin)订单数,
* 拦截订单未领料不阻隔拣货,不计入该数量。
*
* @param {Object} params 统计参数。
* @param {Object} params.orderModel 订单分表模型。
* @param {number} params.warehouseId 仓库ID。
* @param {number} params.waveId 波次ID。
* @param {string} [params.waveNo=''] 波次编码(wave_id 未命中时回退按 wave_no 统计)。
* @param {number} [params.claimOperatorId=0] 当前操作人工号(判断领料人是否本人)。
* @return {Promise<{total_order_count: number, intercepted_order_count: number, unclaimed_order_count: number}>}
* 统计结果。
*/
@ -1648,7 +1625,6 @@ class PickService extends MainService {
const warehouseId = Number(params && params.warehouseId || 0);
const waveId = Number(params && params.waveId || 0);
const waveNo = String(params && params.waveNo || '').trim();
const claimOperatorId = Number(params && params.claimOperatorId || 0);
if (!orderModel || typeof orderModel.findAll !== 'function') {
ctx.logger.warn('[pick.getWaveClaimGateStats] 订单模型不可用,返回空统计');
return { total_order_count: 0, intercepted_order_count: 0, unclaimed_order_count: 0 };
@ -1661,7 +1637,7 @@ class PickService extends MainService {
warehouse_id: warehouseId,
wave_id: waveId,
},
attributes: [ 'id', 'claim_status', 'intercept_status', 'claim_operator_id' ],
attributes: [ 'id', 'claim_status', 'intercept_status' ],
raw: true,
});
rows = Array.isArray(rows) ? rows : [];
@ -1672,7 +1648,7 @@ class PickService extends MainService {
warehouse_id: warehouseId,
wave_no: waveNo,
},
attributes: [ 'id', 'claim_status', 'intercept_status', 'claim_operator_id' ],
attributes: [ 'id', 'claim_status', 'intercept_status' ],
raw: true,
});
rows = Array.isArray(fallbackRows) ? fallbackRows : [];
@ -1686,17 +1662,9 @@ class PickService extends MainService {
.map(item => Number(item && item.id || 0))
.filter(id => Number.isInteger(id) && id > 0));
const unclaimedOrderCount = rows
.filter(item => {
const orderIdItem = Number(item && item.id || 0);
if (!orderIds.includes(orderIdItem) || interceptedOrderIds.has(orderIdItem)) {
return false;
}
if (String(item && item.claim_status || '') !== 'fin') {
return true;
}
// 已领料但领料人不是本人:仍视为需要领料
return claimOperatorId > 0 && Number(item && item.claim_operator_id || 0) !== claimOperatorId;
})
.filter(item => String(item && item.claim_status || '') !== 'fin'
&& orderIds.includes(Number(item && item.id || 0))
&& !interceptedOrderIds.has(Number(item && item.id || 0)))
.length;
return {
@ -1873,7 +1841,7 @@ class PickService extends MainService {
warehouse_id: normalizedWarehouseId,
wave_id: targetWaveId,
},
attributes: [ 'id', 'claim_status', 'print_status', 'intercept_status', 'claim_operator_id' ],
attributes: [ 'id', 'claim_status', 'print_status', 'intercept_status' ],
raw: true,
});
let waveOrders = Array.isArray(waveOrderRows) ? waveOrderRows : [];
@ -1883,7 +1851,7 @@ class PickService extends MainService {
warehouse_id: normalizedWarehouseId,
wave_no: targetWaveNo,
},
attributes: [ 'id', 'claim_status', 'print_status', 'intercept_status', 'claim_operator_id' ],
attributes: [ 'id', 'claim_status', 'print_status', 'intercept_status' ],
raw: true,
});
waveOrders = Array.isArray(fallbackRows) ? fallbackRows : [];
@ -1903,23 +1871,7 @@ class PickService extends MainService {
.filter(id => Number.isInteger(id) && id > 0));
const unclaimedOrderIds = [ ...new Set(waveOrders
.filter(item => {
const orderIdItem = Number(item && item.id || 0);
if (interceptedWaveOrderIds.has(orderIdItem)) {
return false;
}
if (String(item && item.claim_status || '') !== 'fin') {
return true;
}
// 已领料但领料人不是本人:重新领料并覆盖领料人
return Number(item && item.claim_operator_id || 0) !== operatorId;
})
.map(item => Number(item && item.id || 0))
.filter(id => Number.isInteger(id) && id > 0)) ];
const ownClaimedOrderIds = [ ...new Set(waveOrders
.filter(item => String(item && item.claim_status || '') === 'fin'
&& Number(item && item.claim_operator_id || 0) === operatorId
.filter(item => String(item && item.claim_status || '') !== 'fin'
&& !interceptedWaveOrderIds.has(Number(item && item.id || 0)))
.map(item => Number(item && item.id || 0))
.filter(id => Number.isInteger(id) && id > 0)) ];
@ -1940,9 +1892,9 @@ class PickService extends MainService {
return this.success('ok', {
data: {
...baseResponse,
claimed_order_count: ownClaimedOrderIds.length,
claimed_order_count: 0,
status: 'already_claimed',
tip: '该波次订单已领料(本人),无需重复领取',
tip: '该波次已领料,无需重复领取',
},
code: 200,
});
@ -1969,15 +1921,12 @@ class PickService extends MainService {
const transaction = await ctx.model.transaction();
try {
await orderModel.update(
{
claim_status: 'fin',
claim_operator_id: operatorId > 0 ? operatorId : null,
claim_operator: operatorName,
},
{ claim_status: 'fin' },
{
where: {
id: { [Op.in]: unclaimedOrderIds },
warehouse_id: normalizedWarehouseId,
claim_status: { [Op.ne]: 'fin' },
},
transaction,
}
@ -1997,40 +1946,24 @@ class PickService extends MainService {
.map(item => Number(item && item.id || 0))
.filter(id => Number.isInteger(id) && id > 0)) ];
if (claimedOrderIds.length > 0) {
// 回写波次表领料人、领料时间
await ctx.model.WaveBatch.update(
{
claim_operator: operatorName,
claim_time: new Date(),
if (claimedOrderIds.length > 0
&& operationLogService
&& typeof operationLogService.createOperationLogs === 'function') {
await operationLogService.createOperationLogs(claimedOrderIds.map(orderId => ({
businessType: 'order',
businessId: `${orderId}`,
operationCode: 'ORDER_WAVE_CLAIM',
operator: {
id: operatorId ? String(operatorId) : null,
name: operatorName || 'system',
},
{
where: {
wave_id: targetWaveId,
warehouse_id: normalizedWarehouseId,
},
transaction,
}
);
if (operationLogService
&& typeof operationLogService.createOperationLogs === 'function') {
await operationLogService.createOperationLogs(claimedOrderIds.map(orderId => ({
businessType: 'order',
businessId: `${orderId}`,
operationCode: 'ORDER_WAVE_CLAIM',
operator: {
id: operatorId ? String(operatorId) : null,
name: operatorName || 'system',
},
operationAction: 'UPDATE',
extras: {
message: `整波领单完成(波次 ${targetWaveNo})`,
warehouseId: normalizedWarehouseId,
externalLogType: 'API',
},
})), { transaction });
}
operationAction: 'UPDATE',
extras: {
message: `整波领单完成(波次 ${targetWaveNo})`,
warehouseId: normalizedWarehouseId,
externalLogType: 'API',
},
})), { transaction });
}
await transaction.commit();

View File

@ -2,9 +2,6 @@
const MainService = require('../main');
const RETURN_RECEIVED_EXPORT_TASK_CACHE_KEY_PREFIX = 'return_received_export_task_';
const RETURN_RECEIVED_EXPORT_TASK_CACHE_TTL_SECONDS = 1800;
/**
* 系统方法层:returnReceived(退回收到模块接口包装层)。
* 主要职责:统一包装系统方法接口,处理权限、where 解析等公共逻辑,
@ -105,263 +102,6 @@ class ReturnReceivedMethodService extends MainService {
const { id } = data;
return this._call(() => this.service.systems.returnReceived.delete(Number(id)), '删除失败');
}
/**
* 提交退回收到登记列表导出任务(异步任务模式,与 returnUnpack.export 口径一致)。
* 入参 where/sort 与 list 完全一致;提交后立即返回 task_id,
* 后台异步生成单 Sheet Excel(退回收到登记列表)并上传,
* 通过 exportTaskProgress 查询进度与下载链接。
* warehouse_id 由服务端从 ctx.user.store_id 注入,禁止前端传入。
*
* @param {Object} data 请求体。
* @param {Object} [data.where] 筛选条件(与 list 的 where 语义一致)。
* @param {Object} [data.sort] 排序参数(与 list 的 sort 语义一致)。
* @return {Promise<Object>} 统一成功包装响应(含 task_id/status/progress 等任务信息)。
*/
async export(data = {}) {
const { service } = this;
const { sort } = data;
const { where } = this.prepareWhereContext(data, {});
// 仓库隔离:由服务端从当前上下文自动注入,禁止前端传入
const warehouseId = Number(this.ctx.user && this.ctx.user.store_id || 0);
const enforcedWhere = { ...where };
if (warehouseId > 0) {
enforcedWhere.warehouse_id = { operator: 'eq', value: warehouseId };
}
const taskId = this.generateExportTaskId(warehouseId);
const taskPayload = {
task_id: taskId,
status: 'submitted',
progress: 0,
current_count: 0,
total_count: 0,
message: '退回收到导出任务已提交',
result: null,
error: '',
};
await this.setExportTaskProgress(taskId, taskPayload);
setImmediate(async () => {
try {
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'running',
progress: 5,
current_count: 0,
total_count: 0,
message: '退回收到导出任务执行中',
result: null,
error: '',
});
const result = await service.systems.returnReceived.exportList({
where: enforcedWhere,
sort,
warehouseId,
onProgress: async progress => {
const safeProgress = this.isPlainObject(progress) ? progress : {};
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: safeProgress.status || 'running',
progress: safeProgress.progress,
current_count: safeProgress.currentCount,
total_count: safeProgress.totalCount,
message: safeProgress.message || '退回收到导出任务执行中',
result: safeProgress.result || null,
error: '',
});
},
});
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'success',
progress: 100,
current_count: result.current_count || 0,
total_count: result.total_count || 0,
message: '退回收到导出任务完成',
result,
error: '',
});
} catch (error) {
const errorMessage = error && error.message ? error.message : `${error}`;
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'failed',
progress: 100,
current_count: 0,
total_count: 0,
message: '退回收到导出任务失败',
result: null,
error: errorMessage,
});
}
});
return this.success('ok', {
...taskPayload,
update_time: Date.now(),
});
}
/**
* 查询退回收到导出任务进度(与 order.exportTaskProgress 口径一致)。
*
* @param {Object} data 请求体。
* @param {string} [data.task_id] 任务ID(下划线写法)。
* @param {string} [data.taskId] 任务ID(驼峰写法)。
* @return {Promise<Object>} 统一成功包装响应
* (含 task_id/status/progress/current_count/total_count/message/error/download_url/update_time)。
*/
async exportTaskProgress(data = {}) {
const taskId = this.normalizeExportTaskId(data);
if (!taskId) {
return this.success('ok', {
task_id: '',
status: 'not_found',
progress: 0,
current_count: 0,
total_count: 0,
message: '任务不存在',
result: null,
error: '',
download_url: '',
update_time: Date.now(),
});
}
const cachedTask = await this.getExportTaskProgress(taskId);
if (!cachedTask) {
return this.success('ok', {
task_id: taskId,
status: 'not_found',
progress: 0,
current_count: 0,
total_count: 0,
message: '任务不存在',
result: null,
error: '',
download_url: '',
update_time: Date.now(),
});
}
const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {};
const downloadUrl = String(
safeResult.url
|| safeResult.cdnUrl
|| safeResult.cosUrl
|| safeResult.fileKey
|| ''
);
return this.success('ok', {
task_id: taskId,
...cachedTask,
download_url: downloadUrl,
});
}
/**
* 生成退回收到导出任务ID。
* @param {number|string} [warehouseId=''] 仓库ID(缺省兜底取当前上下文 store_id)。
* @return {string} 导出任务ID。
*/
generateExportTaskId(warehouseId = '') {
const normalizedWarehouseId = warehouseId || this.ctx?.user?.store_id || 'unknown';
const timestamp = Date.now();
const randomToken = Math.random().toString(36).slice(2, 10);
return `return_received_export_${normalizedWarehouseId}_${timestamp}_${randomToken}`;
}
/**
* 归一化退回收到导出任务ID。
* @param {Object} data 请求体。
* @param {string} [data.task_id] 任务ID(下划线写法)。
* @param {string} [data.taskId] 任务ID(驼峰写法)。
* @return {string} 归一化后的任务ID。
*/
normalizeExportTaskId(data = {}) {
const normalizedData = this.isPlainObject(data) ? data : {};
return String(normalizedData.task_id || normalizedData.taskId || '').trim();
}
/**
* 获取退回收到导出任务缓存键。
* @param {string} taskId 任务ID。
* @return {string} 缓存键。
*/
getExportTaskCacheKey(taskId = '') {
const normalizedTaskId = String(taskId || '').trim();
if (!normalizedTaskId) {
return '';
}
return `${RETURN_RECEIVED_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`;
}
/**
* 写入退回收到导出任务进度缓存(Redis TTL 30 分钟)。
* @param {string} taskId 任务ID。
* @param {Object} payload 任务状态载荷。
* @return {Promise<void>} 无返回值。
*/
async setExportTaskProgress(taskId = '', payload = {}) {
const cacheKey = this.getExportTaskCacheKey(taskId);
if (!cacheKey || typeof this.app.setCacheAsync !== 'function') {
return;
}
const safePayload = this.isPlainObject(payload) ? payload : {};
const normalizeCount = value => {
const numericValue = Number(value);
return Number.isFinite(numericValue) && numericValue >= 0 ? Math.round(numericValue) : 0;
};
const progressPayload = {
task_id: String(taskId || '').trim(),
status: String(safePayload.status || 'submitted').trim() || 'submitted',
progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0,
current_count: normalizeCount(safePayload.current_count),
total_count: normalizeCount(safePayload.total_count),
message: String(safePayload.message || ''),
result: safePayload.result ?? null,
error: String(safePayload.error || ''),
update_time: Date.now(),
};
try {
await this.app.setCacheAsync(cacheKey, progressPayload, RETURN_RECEIVED_EXPORT_TASK_CACHE_TTL_SECONDS);
} catch (error) {
const errorMessage = error && error.message ? error.message : `${error}`;
this.ctx.logger.warn(`[returnReceived.export] 写入导出任务缓存失败: ${errorMessage}`);
}
}
/**
* 读取退回收到导出任务进度缓存。
* @param {string} taskId 任务ID。
* @return {Promise<Object|null>} 任务缓存,未命中返回 null。
*/
async getExportTaskProgress(taskId = '') {
const cacheKey = this.getExportTaskCacheKey(taskId);
if (!cacheKey || typeof this.app.getCacheAsync !== 'function') {
return null;
}
try {
const cached = await this.app.getCacheAsync(cacheKey);
if (!this.isPlainObject(cached)) {
return null;
}
return cached;
} catch (error) {
const errorMessage = error && error.message ? error.message : `${error}`;
this.ctx.logger.warn(`[returnReceived.export] 读取导出任务缓存失败: ${errorMessage}`);
return null;
}
}
}
module.exports = ReturnReceivedMethodService;

View File

@ -23,7 +23,7 @@ class StockReportMethodService extends MainService {
* @param {Object} data 请求体
* @param {Object} [data.where] 查询条件
* @param {Object} [data.sort] 排序参数
* @param {string} [data.sort.sortField] 排序字段(兼容:sort_field;白名单:stock_id、item_code、item_name、begin_total、inbound_total、outbound_total、end_total)
* @param {string} [data.sort.sortField] 排序字段(兼容:sort_field)
* @param {string} [data.sort.sortOrder] 排序顺序(兼容:sort_order)
* @param {string|Date} [data.where.start_time] 开始时间
* @param {string|Date} [data.where.end_time] 结束时间
@ -32,7 +32,6 @@ class StockReportMethodService extends MainService {
* @param {number|number[]} [data.where.stock_id] 商品库存ID(单数)
* @param {number[]} [data.where.stock_ids] 商品库存ID列表(复数)
* @param {string} [data.where.keyword] 商品关键字(按 item_code/item_name/goods_code/barcode 模糊匹配)
* @param {Object} [data.pagination] 分页参数 { page, pageSize }(兼容 page_size);也支持顶层 data.page / data.pageSize / data.page_size(与其他 list 一致,顶层值优先);未传或非法时默认 { page: 1, pageSize: 20 },响应始终返回 data.pagination 分页信息
* @return {Promise<Object>} 统一 success 包装
*/
async search(data = {}) {
@ -52,10 +51,10 @@ class StockReportMethodService extends MainService {
sortOrder: whereSortOrderCamel,
} = whereValue;
// 兼容 stock_id(单数,支持数组)和 stock_ids(数组)
// 兼容 stock_id(单数)和 stock_ids(数组)
const stockIds = stockIdsRaw !== undefined
? stockIdsRaw
: (stockIdRaw !== undefined ? (Array.isArray(stockIdRaw) ? stockIdRaw : [ stockIdRaw ]) : null);
: (stockIdRaw !== undefined ? [ stockIdRaw ] : null);
const { sort = {} } = data;
const {
@ -65,25 +64,10 @@ class StockReportMethodService extends MainService {
sortOrder: sortOrderCamel,
} = sort || {};
// 分页参数:与项目其他 list 接口保持一致——
// 支持 data.pagination { page, pageSize }(pageSize 兼容 page_size),
// 同时兼容顶层 data.page(分页)与 data.pageSize / data.page_size(分页大小,顶层值优先)
const { pagination: inputPagination, page: topLevelPage, pageSize: topLevelPageSize, page_size: topLevelPageSizeSnake } = data;
const pagination = {
...(inputPagination && typeof inputPagination === 'object' ? inputPagination : {}),
};
if (topLevelPage !== undefined) {
pagination.page = topLevelPage;
}
const resolvedTopLevelPageSize = topLevelPageSize !== undefined ? topLevelPageSize : topLevelPageSizeSnake;
if (resolvedTopLevelPageSize !== undefined) {
pagination.pageSize = resolvedTopLevelPageSize;
}
const result = await service.systems.storage.report.search(startTime, endTime, bySpace, storeIds, {
sortField: sortFieldCamel || sortFieldSnake || whereSortFieldCamel || whereSortField,
sortOrder: sortOrderCamel || sortOrderSnake || whereSortOrderCamel || whereSortOrder,
}, 'warehouse', stockIds, keyword, pagination);
}, 'warehouse', stockIds, keyword);
return this.success('ok', result);
}
@ -125,10 +109,10 @@ class StockReportMethodService extends MainService {
? warehouseIdsRaw
: (warehouseIdRaw !== undefined ? [ warehouseIdRaw ] : undefined);
// 兼容 stock_id(单数,支持数组)和 stock_ids(数组)
// 兼容 stock_id(单数)和 stock_ids(数组)
const stockIds = stockIdsRaw !== undefined
? stockIdsRaw
: (stockIdRaw !== undefined ? (Array.isArray(stockIdRaw) ? stockIdRaw : [ stockIdRaw ]) : null);
: (stockIdRaw !== undefined ? [ stockIdRaw ] : null);
const { sort = {} } = data;
const {
@ -196,10 +180,10 @@ class StockReportMethodService extends MainService {
? warehouseIdsRaw
: (warehouseIdRaw !== undefined ? [ warehouseIdRaw ] : undefined);
// 兼容 stock_id(单数,支持数组)和 stock_ids(数组)
// 兼容 stock_id(单数)和 stock_ids(数组)
const stockIds = stockIdsRaw !== undefined
? stockIdsRaw
: (stockIdRaw !== undefined ? (Array.isArray(stockIdRaw) ? stockIdRaw : [ stockIdRaw ]) : null);
: (stockIdRaw !== undefined ? [ stockIdRaw ] : null);
const { sort = {} } = data;
const {
@ -306,10 +290,10 @@ class StockReportMethodService extends MainService {
sortOrder: whereSortOrderCamel,
} = whereValue;
// 兼容 stock_id(单数,支持数组)和 stock_ids(数组)
// 兼容 stock_id(单数)和 stock_ids(数组)
const stockIds = stockIdsRaw !== undefined
? stockIdsRaw
: (stockIdRaw !== undefined ? (Array.isArray(stockIdRaw) ? stockIdRaw : [ stockIdRaw ]) : null);
: (stockIdRaw !== undefined ? [ stockIdRaw ] : null);
const { sort = {} } = data;
const {

View File

@ -166,7 +166,6 @@ class StockTransactionMethodService extends MainService {
orderId,
sort: sortOption,
pagination,
mode: 'store',
});
return this.success('ok', result);

View File

@ -166,13 +166,12 @@ class entryService extends MainService {
* 提交确认完成导入/PDA 直接入库(从 storage.entry 模块暴露)。
* @param {Object} data 请求体
* @param {number} data.entry_order_id 入库单 ID
* @param {number} [data.noNeedNotice=0] 是否跳过入库完成通知:0 通知,1 不通知(默认 0)
* @return {Promise<Object>} 统一 success 包装
*/
async commit(data = {}) {
const { service } = this;
const { entry_order_id, noNeedNotice = 0 } = data || {};
const result = await service.systems.inboundDirectLog.commit(entry_order_id, noNeedNotice);
const { entry_order_id } = data || {};
const result = await service.systems.inboundDirectLog.commit(entry_order_id);
return this.success('ok', result);
}
@ -230,13 +229,12 @@ class entryService extends MainService {
* 快捷直入/虚拟入库(system method 包装层)。
* @param {Object} data 请求体
* @param {number} data.id 入库单ID
* @param {number} [data.noNeedNotice=0] 是否跳过入库完成通知:0 通知,1 不通知(默认 0)
* @return {Promise<Object>} 统一 success 包装
*/
async quickInbound(data = {}) {
const { service } = this;
const { id, noNeedNotice = 0 } = data;
const result = await service.systems.storage.entry.quickInbound({ id, noNeedNotice });
const { id } = data;
const result = await service.systems.storage.entry.quickInbound({ id });
if (result && result.code === 200) {
return this.success(result.message || 'ok', result);
}

View File

@ -51,10 +51,8 @@ class InventoryMethodService extends MainService {
/**
* 提取 stock_query 虚拟筛选条件(与订单查询一致)。
* 将其从 where 中移除并返回清洗后的 where 与 stock_query 关键字。
* 兼容 value 为字符串或数组的场景(如 { operator: 'contains', value: ['A', 'B'] }),
* 数组按多关键字处理,由底层 service 取并集解析 stock_id。
* @param {Object} whereInput 原始 where 条件。
* @return {{ where: Object, stockQuery: string|string[] }} 清洗后的 where 与 stock_query 值。
* @return {{ where: Object, stockQuery: string }} 清洗后的 where 与 stock_query 值。
*/
extractStockQueryVirtualFilter(whereInput = {}) {
const normalizedWhere = this.isPlainObject(whereInput)
@ -73,14 +71,6 @@ class InventoryMethodService extends MainService {
? stockQueryCondition.value
: stockQueryCondition;
// value 为数组时逐项清洗为字符串数组(多关键字并集搜索)
if (Array.isArray(rawValue)) {
const stockQuery = rawValue
.map(item => String(item).trim())
.filter(Boolean);
return { where: normalizedWhere, stockQuery };
}
const stockQuery = typeof rawValue === 'string' ? rawValue.trim() : '';
return { where: normalizedWhere, stockQuery };
@ -90,7 +80,7 @@ class InventoryMethodService extends MainService {
* 库存列表查询(查 wms_storage),支持 where 条件、分页、排序、批次分组。
* @param {Object} data 请求体
* @param {Object} [data.where] 查询条件
* @param {Object} [data.where.stock_query] 虚拟筛选字段:按商品编码(item_code)/名称(item_name)/货物编码(goods_code)/条码(barcode)/SKU ID 模糊匹配,如 { operator: 'like', value: '111' };value 支持数组(如 { operator: 'contains', value: ['111'] }),多关键字取并集匹配
* @param {Object} [data.where.stock_query] 虚拟筛选字段:按商品编码(item_code)/名称(item_name)/货物编码(goods_code)/条码(barcode)/SKU ID 模糊匹配,如 { operator: 'like', value: '111' }
* @param {Object} [data.pagination] 分页参数 { page, pageSize }
* @param {Object} [data.sort] 排序参数 { sortField, sortOrder }
* @param {boolean} [data.group_by_batch=false] 是否按批次查询

View File

@ -2,316 +2,32 @@
const MainService = require('../../main');
const STORAGE_TRANSACTION_EXPORT_TASK_CACHE_KEY_PREFIX = 'storage_transaction_export_task_';
const STORAGE_TRANSACTION_EXPORT_TASK_CACHE_TTL_SECONDS = 1800;
class StorageTransactionService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,export,exportTaskProgress';
const _noNeedLog = 'list,export,exportTaskProgress';
const _noNeedAuth = 'list,export,exportTaskProgress';
const _noNeedRight = 'list';
const _noNeedLog = 'list';
const _noNeedAuth = 'list';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 解析 list/export 通用过滤入参(where 白名单字段 + 时间区间 + keyword)。
* @param {Object} data 请求体
* @return {Object} 归一化后的过滤参数
*/
_parseListFilters(data = {}) {
const { whereValue = {} } = this.prepareWhereContext(data);
const { keyword: topKeyword } = data;
const {
transaction_type: transactionType,
stock_id: stockIdRaw,
stock_ids: stockIdsRaw,
space_id: spaceId,
store_id: storeIdRaw,
store_ids: storeIdsRaw,
order_type: orderType,
order_no: orderNo,
batch_no: batchNo,
inventory_type: inventoryType,
operator_name: operatorName,
order_id: orderId,
start_time: startTime,
end_time: endTime,
created_at: createdAt,
keyword: whereKeyword,
} = whereValue;
// created_at 支持 between:规范化后 value 为 [start, end] 数组
const createdRange = Array.isArray(createdAt) ? createdAt : [];
const resolvedStartTime = startTime ?? createdRange[0] ?? null;
const resolvedEndTime = endTime ?? createdRange[1] ?? null;
// 兼容 stock_id(单数)与 stock_ids(数组),store_id 同理
const stockIds = stockIdsRaw !== undefined
? stockIdsRaw
: (stockIdRaw !== undefined ? [ stockIdRaw ] : null);
const storeIds = storeIdsRaw !== undefined
? storeIdsRaw
: (storeIdRaw !== undefined ? [ storeIdRaw ] : null);
const keyword = topKeyword ?? whereKeyword ?? '';
// 仓库ID 由服务端从当前上下文注入,禁止前端传参
const warehouseId = Number(this.ctx.user && this.ctx.user.store_id);
return {
warehouseId,
startTime: resolvedStartTime,
endTime: resolvedEndTime,
storeIds,
stockIds,
spaceId,
keyword,
transactionType,
orderType,
orderNo,
batchNo,
inventoryType,
operatorName,
orderId,
};
}
/**
* 库位维度出入库流水逐条明细列表(wms_storage_transaction)。
* 支持 where 条件、keyword 快捷搜索、分页、排序;仓库ID由服务端从当前上下文自动注入。
* group_by_batch 参数已废弃:本接口不再聚合,恒返回逐条明细。
* 出入库记录列表查询,支持 where 条件、分页、排序。
* @param {Object} data 请求体
* @param {Object} [data.where] 查询条件
* @param {Object} [data.where.created_at] 创建时间区间(operator: between,value: [start, end])
* @param {Object} [data.pagination] 分页参数 { page, pageSize }
* @param {Object} [data.sort] 排序参数 { sortField, sortOrder }
* @param {string} [data.keyword] 商品关键字(按 item_code/item_name/goods_code/barcode 模糊匹配)
* @param {boolean} [data.group_by_batch=false] 是否按批次查询明细
* @return {Promise<Object>} 统一 success 包装
*/
async list(data = {}) {
const { service } = this;
const { pagination = {}, sort = {} } = data;
const filters = this._parseListFilters(data);
const result = await service.systems.stockTransaction.list({
...filters,
sort,
pagination,
});
const { pagination, sort, group_by_batch, keyword } = data;
this.prepareWhereContext(data);
const result = await service.systems.stockTransaction.list(pagination, sort, group_by_batch, keyword);
return this.success('ok', result);
}
/**
* 提交库位流水导出异步任务。
* 与 list 使用相同查询条件(where/sort/keyword),异步执行,立即返回任务ID。
* @param {Object} data 请求体
* @param {Object} [data.where] 查询条件(与 list 完全一致)
* @param {Object} [data.sort] 排序参数(与 list 完全一致)
* @param {string} [data.keyword] 商品关键字(与 list 完全一致)
* @return {Promise<Object>} 统一 success 包装(返回任务ID)
*/
async export(data = {}) {
const { service } = this;
const { sort = {} } = data;
const filters = this._parseListFilters(data);
const taskId = this.generateExportTaskId();
const taskPayload = {
task_id: taskId,
status: 'submitted',
progress: 0,
message: '导出任务已提交',
result: null,
error: '',
};
await this.setExportTaskProgress(taskId, taskPayload);
setImmediate(async () => {
try {
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'running',
progress: 10,
message: '导出任务执行中',
result: null,
error: '',
});
const result = await service.systems.stockTransaction.exportStorageList({
...filters,
sort,
});
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'success',
progress: 100,
message: '导出任务完成',
result,
error: '',
});
} catch (error) {
const errorMessage = error && error.message ? error.message : `${error}`;
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'failed',
progress: 100,
message: '导出任务失败',
result: null,
error: errorMessage,
});
}
});
return this.success('ok', {
...taskPayload,
update_time: Date.now(),
});
}
/**
* 查询库位流水导出任务进度。
* @param {Object} data 请求体
* @param {string} [data.task_id] 任务ID(下划线写法)
* @param {string} [data.taskId] 任务ID(驼峰写法)
* @return {Promise<Object>} 统一 success 包装
*/
async exportTaskProgress(data = {}) {
const taskId = this.normalizeExportTaskId(data);
if (!taskId) {
return this.success('ok', {
task_id: '',
status: 'not_found',
progress: 0,
message: '任务不存在',
result: null,
error: '',
download_url: '',
update_time: Date.now(),
});
}
const cachedTask = await this.getExportTaskProgress(taskId);
if (!cachedTask) {
return this.success('ok', {
task_id: taskId,
status: 'not_found',
progress: 0,
message: '任务不存在',
result: null,
error: '',
download_url: '',
update_time: Date.now(),
});
}
const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {};
const downloadUrl = String(
safeResult.url
|| safeResult.cdnUrl
|| safeResult.cosUrl
|| safeResult.fileKey
|| ''
);
return this.success('ok', {
task_id: taskId,
...cachedTask,
download_url: downloadUrl,
});
}
/**
* 生成库位流水导出任务ID。
* @return {string} 导出任务ID
*/
generateExportTaskId() {
const warehouseId = this.ctx?.user?.store_id || 'unknown';
const timestamp = Date.now();
const randomToken = Math.random().toString(36).slice(2, 10);
return `storage_transaction_export_${warehouseId}_${timestamp}_${randomToken}`;
}
/**
* 归一化库位流水导出任务ID。
* @param {Object} data 请求体
* @param {string} [data.task_id] 任务ID(下划线写法)
* @param {string} [data.taskId] 任务ID(驼峰写法)
* @return {string} 归一化后的任务ID
*/
normalizeExportTaskId(data = {}) {
const normalizedData = this.isPlainObject(data) ? data : {};
return String(normalizedData.task_id || normalizedData.taskId || '').trim();
}
/**
* 获取库位流水导出任务缓存键。
* @param {string} taskId 任务ID
* @return {string} 缓存键
*/
getExportTaskCacheKey(taskId = '') {
const normalizedTaskId = String(taskId || '').trim();
if (!normalizedTaskId) {
return '';
}
return `${STORAGE_TRANSACTION_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`;
}
/**
* 写入库位流水导出任务进度缓存。
* @param {string} taskId 任务ID
* @param {Object} payload 任务状态载荷
* @return {Promise<void>} 无返回值
*/
async setExportTaskProgress(taskId = '', payload = {}) {
const cacheKey = this.getExportTaskCacheKey(taskId);
if (!cacheKey || typeof this.app.setCacheAsync !== 'function') {
return;
}
const safePayload = this.isPlainObject(payload) ? payload : {};
const progressPayload = {
task_id: String(taskId || '').trim(),
status: String(safePayload.status || 'submitted').trim() || 'submitted',
progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0,
message: String(safePayload.message || ''),
result: safePayload.result ?? null,
error: String(safePayload.error || ''),
update_time: Date.now(),
};
try {
await this.app.setCacheAsync(cacheKey, progressPayload, STORAGE_TRANSACTION_EXPORT_TASK_CACHE_TTL_SECONDS);
} catch (error) {
const errorMessage = error && error.message ? error.message : `${error}`;
this.ctx.logger.warn(`[storage.transaction.export] 写入导出任务缓存失败: ${errorMessage}`);
}
}
/**
* 读取库位流水导出任务进度缓存。
* @param {string} taskId 任务ID
* @return {Promise<Object|null>} 任务缓存
*/
async getExportTaskProgress(taskId = '') {
const cacheKey = this.getExportTaskCacheKey(taskId);
if (!cacheKey || typeof this.app.getCacheAsync !== 'function') {
return null;
}
try {
const cached = await this.app.getCacheAsync(cacheKey);
if (!this.isPlainObject(cached)) {
return null;
}
return cached;
} catch (error) {
const errorMessage = error && error.message ? error.message : `${error}`;
this.ctx.logger.warn(`[storage.transaction.export] 读取导出任务缓存失败: ${errorMessage}`);
return null;
}
}
}
module.exports = StorageTransactionService;

View File

@ -5,10 +5,10 @@ const MainService = require('../main');
class WorkbenchService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = 'business,getWorkbenchInfo,removeMember,bindMember';
const _noNeedRight = 'list,detail,business,getWorkbenchInfo,removeMember,bindMember';
const _noNeedLog = 'list,detail,getWorkbenchInfo,removeMember,bindMember';
const _noNeedAuth = 'list,detail,business,getWorkbenchInfo,removeMember,bindMember';
const _noNeedLogin = 'business';
const _noNeedRight = 'list,detail,checkBarcode,business';
const _noNeedLog = 'list,detail,checkBarcode';
const _noNeedAuth = 'list,detail,checkBarcode,business';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -122,100 +122,19 @@ class WorkbenchService extends MainService {
}
/**
* 工作台绑定:校验缓存绑定码与工作台ID,写入随机 token(需登录、需权限)
* @param data - { code, id }
* 检查条码是否已存在
* @param data
*/
async bind(data) {
async checkBarcode(data) {
const { service } = this;
try {
const result = await service.systems.workbench.bindWorkbench(data || {});
if (result && result.success) {
return this.success('绑定成功', result);
}
const statusCode = result && result.statusCode;
return this.fail(
result && result.message ? result.message : '绑定失败',
statusCode ? { code: statusCode } : undefined
);
} catch (error) {
return this.fail(error.message);
}
}
/**
* 使用 token 获取工作台信息(免登录、免鉴权)
* @param data - { token }
*/
async getWorkbenchInfo(data) {
const { service } = this;
try {
const result = await service.systems.workbench.getWorkbenchInfoByToken(data || {});
if (result && result.success) {
return this.success('获取成功', result);
}
const statusCode = result && result.statusCode;
return this.fail(
result && result.message ? result.message : '获取工作台信息失败',
statusCode ? { code: statusCode } : undefined
);
} catch (error) {
return this.fail(error.message);
}
}
/**
* 重置工作台登录码(需登录、需权限)
* @param data - { id }
*/
async resetLoginCode(data) {
const { service } = this;
try {
const { id } = data || {};
if (!id) return this.fail('工作台ID不能为空');
const result = await service.systems.workbench.resetLoginCode(parseInt(id));
return this.success('重置成功', result);
} catch (error) {
return this.fail(error.message);
}
}
/**
* 移除工作台成员(免登录、免鉴权,以工作台 token 鉴权)
* @param data - { ids, token }
*/
async removeMember(data) {
const { service } = this;
try {
const result = await service.systems.workbench.removeWorkbenchMember(data || {});
if (result && result.success) {
return this.success('移除成功', result);
}
const statusCode = result && result.statusCode;
return this.fail(
result && result.message ? result.message : '移除成员失败',
statusCode ? { code: statusCode } : undefined
);
} catch (error) {
return this.fail(error.message);
}
}
/**
* 绑定工作台成员(免登录、免鉴权,以工作台 token 鉴权)
* @param data - { userId | user_id, userName | user_name | name, token }
*/
async bindMember(data) {
const { service } = this;
try {
const result = await service.systems.workbench.bindWorkbenchMember(data || {});
if (result && result.success) {
return this.success('绑定成功', result);
}
const statusCode = result && result.statusCode;
return this.fail(
result && result.message ? result.message : '绑定成员失败',
statusCode ? { code: statusCode } : undefined
const { barcode, excludeId } = data || {};
if (!barcode) return this.fail('条码不能为空');
const exists = await service.systems.workbench.checkBarcodeExists(
String(barcode).trim(),
excludeId ? parseInt(excludeId) : undefined
);
return this.success('ok', { exists });
} catch (error) {
return this.fail(error.message);
}

View File

@ -1,10 +1,5 @@
'use strict';
const fs = require('fs');
const fsp = require('fs/promises');
const os = require('os');
const path = require('path');
const crypto = require('crypto');
const Service = require('egg').Service;
/**
@ -2020,13 +2015,13 @@ class AfterSaleService extends Service {
async exportAfterSales(options = {}) {
const { where = {}, sort = {}, onProgress } = options;
const reportProgress = async (status, progress, message, extra = {}) => {
const reportProgress = (status, progress, message, extra = {}) => {
if (typeof onProgress === 'function') {
await onProgress({ status, progress, message, ...extra });
onProgress({ status, progress, message, ...extra });
}
};
await reportProgress('running', 5, '正在准备导出数据...');
reportProgress('running', 5, '正在准备导出数据...');
// 先统计总数
const { count: totalCount } = await this.ctx.model.AfterSale.findAndCountAll({
@ -2034,7 +2029,7 @@ class AfterSaleService extends Service {
raw: true,
});
await reportProgress('running', 10, `共 ${totalCount} 条记录,开始导出...`, { totalCount, currentCount: 0 });
reportProgress('running', 10, `共 ${totalCount} 条记录,开始导出...`, { totalCount, currentCount: 0 });
// 分页查询并导出
const pageSize = 500;
@ -2047,7 +2042,7 @@ class AfterSaleService extends Service {
allRows.push(...rows);
const progress = 10 + Math.floor(((page / totalPages) * 80));
await reportProgress('running', progress, `正在导出... (${allRows.length}/${totalCount})`, {
reportProgress('running', progress, `正在导出... (${allRows.length}/${totalCount})`, {
totalCount,
currentCount: allRows.length,
});
@ -2056,12 +2051,12 @@ class AfterSaleService extends Service {
await new Promise(resolve => setImmediate(resolve));
}
await reportProgress('running', 90, '正在上传文件...', { totalCount, currentCount: allRows.length });
reportProgress('running', 90, '正在上传文件...', { totalCount, currentCount: allRows.length });
// 生成 Excel 文件并上传 COS
const exportResult = await this._generateAndUploadExcel(allRows);
await reportProgress('success', 100, '导出完成', {
reportProgress('success', 100, '导出完成', {
totalCount,
currentCount: allRows.length,
result: exportResult,
@ -2076,28 +2071,16 @@ class AfterSaleService extends Service {
/**
* 生成 Excel 并上传 COS,返回下载信息。
* 与其他导出(order/return_received 等)口径一致:流式写临时文件 → uploadFile → uploadSuccessNotify。
*
* @param {Array<Object>} rows 售后单数据行
* @return {Promise<Object>} { filename, fileKey, url, cdnUrl, cosUrl }
* @return {Promise<Object>} { url, fileKey, fileName }
*/
async _generateAndUploadExcel(rows = []) {
const { ctx } = this;
const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-after-sale-export-'));
const now = new Date();
const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`;
const filename = `售后单导出_${dateToken}.xlsx`;
const filePath = path.join(tempDir, filename);
const ExcelJS = require('exceljs');
const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({
filename: filePath,
useStyles: false,
useSharedStrings: false,
});
try {
const ExcelJS = require('exceljs');
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet('售后单列表');
// 定义列
@ -2127,70 +2110,46 @@ class AfterSaleService extends Service {
// 写入数据行
for (const row of rows) {
worksheet.addRow(row).commit();
}
worksheet.commit();
await workbook.commit();
// ---- 上传文件(与 order/return_received 导出口径一致)----
const uploadService = ctx?.service?.systems?.upload;
if (!uploadService || typeof uploadService.uploadFile !== 'function') {
throw new Error('上传服务不可用');
worksheet.addRow(row);
}
const stat = await fsp.stat(filePath);
const randomToken = crypto.randomBytes(6).toString('hex');
const uploadKey = `exports/after_sale/${Date.now()}_${randomToken}.xlsx`;
const uploadStream = fs.createReadStream(filePath);
uploadStream.filename = filename;
uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
uploadStream.fileSize = stat.size;
// 生成 buffer
const buffer = await workbook.xlsx.writeBuffer();
const uploadResult = await uploadService.uploadFile(uploadStream, {
key: uploadKey,
category: 'document',
mimetype: 'xls,xlsx,csv',
});
// 上传到 COS
const now = new Date();
const dateStr = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`;
const timestamp = Date.now();
const fileName = `after_sale_export_${dateStr}_${timestamp}.xlsx`;
const fileKey = `export/after_sale/${fileName}`;
let fileRecord = null;
if (typeof uploadService.uploadSuccessNotify === 'function') {
fileRecord = await uploadService.uploadSuccessNotify({
url: uploadResult.fileName,
fileKey: uploadResult.fileName,
fileName: filename,
fileType: 'document',
mimeType: uploadStream.mimeType,
fileSize: stat.size,
category: 'document',
businessType: 'afterSaleExport',
description: `售后单导出,共 ${rows.length} 条记录`,
});
let url = '';
try {
if (ctx.service.systems && ctx.service.systems.upload && typeof ctx.service.systems.upload.uploadToCos === 'function') {
const uploadResult = await ctx.service.systems.upload.uploadToCos({
buffer,
fileKey,
fileName,
mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
});
url = uploadResult && uploadResult.url ? uploadResult.url : '';
}
} catch (uploadError) {
ctx.logger.warn(`[afterSale.export] COS 上传失败: ${uploadError.message}`);
}
// 优先取 uploadFile 返回的完整 URL,其次取 uploadSuccessNotify 落库记录,最后回退 COS key
const safeUploadResult = typeof uploadResult === 'object' && uploadResult !== null ? uploadResult : {};
const resolvedFileRecord = (fileRecord && (fileRecord.data || fileRecord)) || null;
const fileUrlFromRecord = resolvedFileRecord
? (resolvedFileRecord.file_url || resolvedFileRecord.fileUrl || resolvedFileRecord.url || '')
: '';
const uploadResultUrl = safeUploadResult.url || safeUploadResult.cdnUrl || safeUploadResult.cosUrl || '';
return {
filename,
fileKey: safeUploadResult.fileName || uploadKey,
url: uploadResultUrl || fileUrlFromRecord || safeUploadResult.fileName || uploadKey,
cdnUrl: safeUploadResult.cdnUrl || safeUploadResult.url || '',
cosUrl: safeUploadResult.cosUrl || '',
url,
fileKey,
fileName,
};
} catch (error) {
const workbookStream = workbook.stream;
if (workbookStream && typeof workbookStream.destroy === 'function') {
workbookStream.destroy();
}
ctx.logger.error(`[afterSale.export] 生成/上传 Excel 失败: ${error.message}`);
throw error;
} finally {
await fsp.rm(tempDir, { recursive: true, force: true });
ctx.logger.error(`[afterSale.export] 生成 Excel 失败: ${error.message}`);
return {
url: '',
fileKey: '',
fileName: '',
};
}
}

View File

@ -24,7 +24,6 @@ const ORDER_OPERATION_CODES = Object.freeze({
PLATFORM_FALLBACK: 'ORDER_PLATFORM_FALLBACK',
EXPRESS_FALLBACK: 'ORDER_EXPRESS_FALLBACK',
EXPRESS_POLICY_MATCH: 'ORDER_EXPRESS_POLICY_MATCH',
AUTO_EXPRESS_SKIP: 'ORDER_AUTO_EXPRESS_SKIP',
});
const STORE_SUBJECT_CONFIG_CACHE_TTL_SECONDS = 600;
@ -1923,14 +1922,12 @@ class DeliveryOrderService extends Service {
/**
* 构建储位分配显式请求体。
*
* 自动分配不传 allow_storage_location:默认禁止分配到存储储位,
* 仅当货主关闭存拣分离(storage_separation=0)时由底层按策略放行。
*
* @param {Object} context 异步处理上下文。
* @return {Object} 储位分配请求。
*/
buildStorageAllocateRequest(context) {
return {
allow_storage_location: true,
order_ids: [ Number(context && context.orderId || 0) ],
// 显式携带仓库上下文,避免依赖 ctx.user(Qimen 链路无登录用户)
warehouse_id: Number(context && context.warehouseId || 0),
@ -1986,12 +1983,11 @@ class DeliveryOrderService extends Service {
}
/**
* 解析自动分配时间窗口配置,货主-仓库级优先,未启用时由仓库级兜底。
* 解析截单配置,货主-仓库级优先,未启用时由仓库级兜底。
*
* @param {Object} policyConfig 货主-仓库级策略配置。
* @param {Object|null} warehouseSubjectConfig 仓库级主体配置。
* @return {{cutoffEnabled: boolean, cutoffTime: string, allocateStartTime: string}}
* 最终生效的截单开关、截单时间与开始自动分配时间。
* @return {{cutoffEnabled: boolean, cutoffTime: string}} 最终生效的截单开关与截单时间。
*/
resolveCutoffOrderConfig(policyConfig, warehouseSubjectConfig) {
const policyEnabled = this.normalizePolicyFlag(
@ -2000,16 +1996,12 @@ class DeliveryOrderService extends Service {
const policyTime = (policyConfig && typeof policyConfig.cutoff_order_time === 'string'
? policyConfig.cutoff_order_time.trim()
: '') || '18:00';
const policyStartTime = (policyConfig && typeof policyConfig.allocate_start_time === 'string'
? policyConfig.allocate_start_time.trim()
: '') || '08:00';
// 货主-仓库级已启用截单,直接使用
if (policyEnabled) {
return {
cutoffEnabled: true,
cutoffTime: policyTime,
allocateStartTime: policyStartTime,
};
}
@ -2018,20 +2010,15 @@ class DeliveryOrderService extends Service {
const warehouseTime = (typeof warehouseSubjectConfig.cutoff_order_time === 'string'
? warehouseSubjectConfig.cutoff_order_time.trim()
: '') || '18:00';
const warehouseStartTime = (typeof warehouseSubjectConfig.allocate_start_time === 'string'
? warehouseSubjectConfig.allocate_start_time.trim()
: '') || '08:00';
return {
cutoffEnabled: true,
cutoffTime: warehouseTime,
allocateStartTime: warehouseStartTime,
};
}
return {
cutoffEnabled: false,
cutoffTime: '18:00',
allocateStartTime: '08:00',
};
}
@ -2059,54 +2046,6 @@ class DeliveryOrderService extends Service {
return nowTotalMinutes >= cutoffTotalMinutes;
}
/**
* 判断当前时间是否处于自动分配窗口之外。
*
* 同天窗口(开始时间早于截单时间):now < start 或 now >= cutoff 时禁止;
* 跨天窗口(开始时间晚于截单时间,截单时间视为次日):now in [cutoff, start) 时禁止;
* 开始时间与截单时间相同时窗口恒空,防御性全天禁止。
*
* @param {string} allocateStartTimeStr 开始自动分配时间,格式 HH:mm。
* @param {string} cutoffTimeStr 截单时间,格式 HH:mm。
* @param {Date} [nowDate=new Date()] 当前时间(测试可注入)。
* @return {boolean} 是否禁止自动分配。
*/
isAllocationWindowClosed(allocateStartTimeStr, cutoffTimeStr, nowDate = new Date()) {
const parseTime = value => {
if (!value || typeof value !== 'string') {
return null;
}
const trimmed = value.trim();
if (!/^\d{2}:\d{2}$/.test(trimmed)) {
return null;
}
const [ hours, minutes ] = trimmed.split(':').map(Number);
return hours * 60 + minutes;
};
const startMinutes = parseTime(allocateStartTimeStr);
const cutoffMinutes = parseTime(cutoffTimeStr);
const nowMinutes = nowDate.getHours() * 60 + nowDate.getMinutes();
if (startMinutes === null || cutoffMinutes === null) {
return false;
}
if (startMinutes === cutoffMinutes) {
return true; // 窗口为空,防御性全天禁止
}
if (startMinutes < cutoffMinutes) {
// 同天窗口 [start, cutoff)
return nowMinutes < startMinutes || nowMinutes >= cutoffMinutes;
}
// 跨天窗口:截单时间视为次日 [start, 24:00) ∪ [00:00, cutoff)
return nowMinutes >= cutoffMinutes && nowMinutes < startMinutes;
}
/**
* 构建自动加团结构信息。
*
@ -2595,83 +2534,6 @@ class DeliveryOrderService extends Service {
}
}
/**
* 查找订单备注命中仓库「自动分配快递排除备注」的关键字。
*
* 备注范围:remark(备注)、buyer_message(买家留言)、seller_message(卖家留言),
* 任一字段包含任一关键字即视为命中;命中时返回第一个命中的关键字,未命中返回空串。
*
* @param {Object} order 订单行数据。
* @param {Object|null} warehouseSubjectConfig 仓库主体配置(subject_config)。
* @return {string} 命中的排除关键字,未命中返回空字符串。
*/
findAutoExpressExcludedRemark(order, warehouseSubjectConfig) {
const rawRemarks = warehouseSubjectConfig
&& warehouseSubjectConfig.auto_allocate_express_exclude_remarks;
const keywords = (Array.isArray(rawRemarks) ? rawRemarks : [])
.map(item => (typeof item === 'string' ? item : String(item === undefined || item === null ? '' : item)).trim())
.filter(Boolean);
if (keywords.length === 0 || !order || typeof order !== 'object') {
return '';
}
const remarkText = [ 'remark', 'buyer_message', 'seller_message' ]
.map(field => String(order[field] === undefined || order[field] === null ? '' : order[field]))
.join(' ')
.trim();
if (!remarkText) {
return '';
}
return keywords.find(keyword => remarkText.includes(keyword)) || '';
}
/**
* 补写「跳过自动分配快递」的订单操作日志。
*
* 订单备注命中仓库「自动分配快递排除备注」关键字时不自动分配快递,
* 写一条操作记录说明跳过原因与命中的关键字,便于仓库人员在订单日志中查看。
* 写入失败仅记录告警,不影响订单创建主流程。
*
* @param {Object} context 异步处理上下文。
* @param {string} matchedKeyword 命中的排除关键字。
* @return {Promise<void>} 无返回值。
*/
async appendAutoExpressSkipLog(context, matchedKeyword) {
const orderId = Number(context && context.orderId || 0);
const warehouseId = Number(context && context.warehouseId || 0);
const operationLogService = this.ctx
&& this.ctx.service
&& this.ctx.service.systems
&& this.ctx.service.systems.operationLog;
if (!operationLogService || typeof operationLogService.createOperationLogs !== 'function' || orderId <= 0) {
return;
}
try {
await operationLogService.createOperationLogs([{
businessType: 'order',
businessId: `${orderId}`,
operationCode: ORDER_OPERATION_CODES.AUTO_EXPRESS_SKIP,
operator: {
id: null,
name: 'system',
},
extras: {
warehouseId,
message: `订单备注命中「自动分配快递排除备注」关键字「${matchedKeyword}」,跳过自动分配快递`,
},
}]);
} catch (error) {
this.ctx.logger.warn('[DeliveryOrderService.appendAutoExpressSkipLog] 写入操作日志失败,不影响主流程', {
orderId,
warehouseId,
matchedKeyword,
error: error && error.message,
});
}
}
// 订单异步流程
/**
* 订单创建后的异步流程。
@ -2709,23 +2571,15 @@ class DeliveryOrderService extends Service {
// 截单时间兜底:货主-仓库级未启用时,fallback 到仓库级配置
const warehouseSubjectConfig = await this.getStoreSubjectConfig(context.warehouseId);
const { cutoffEnabled, cutoffTime, allocateStartTime } = this.resolveCutoffOrderConfig(policyConfig, warehouseSubjectConfig);
const { cutoffEnabled, cutoffTime } = this.resolveCutoffOrderConfig(policyConfig, warehouseSubjectConfig);
// 早于开始自动分配时间或超过截单时间(开始时间晚于截单时间时截单时间视为次日),均不自动分配
const isAllocationBlocked = cutoffEnabled
&& this.isAllocationWindowClosed(allocateStartTime, cutoffTime);
const isCutoffActive = cutoffEnabled && this.isPastCutoffTime(cutoffTime);
// 如果需要审核,不触发自动分配快递、储位、加团
const needApproval = Number(policyConfig && policyConfig.need_order_approval) !== 0;
// 仓库「自动分配快递排除备注」:订单备注命中任一关键字时跳过自动分配快递
const excludedRemarkKeyword = this.findAutoExpressExcludedRemark(context.order, warehouseSubjectConfig);
const isExpressExcludedByRemark = Boolean(excludedRemarkKeyword);
const isAutoAllocateExpressEnabled = !isAllocationBlocked && !needApproval
&& !isExpressExcludedByRemark
&& this.normalizePolicyFlag(policyConfig.auto_allocate_express);
const isAutoAllocateStorageEnabled = !isAllocationBlocked && !needApproval && this.normalizePolicyFlag(policyConfig.auto_allocate_storage);
const isAutoAllocateExpressEnabled = !isCutoffActive && !needApproval && this.normalizePolicyFlag(policyConfig.auto_allocate_express);
const isAutoAllocateStorageEnabled = !isCutoffActive && !needApproval && this.normalizePolicyFlag(policyConfig.auto_allocate_storage);
// 记录开关判定结果,便于排查自动分配快递/储位未触发的问题
this.ctx.logger.info('[DeliveryOrderService.asyncProcessOrderCreated] 自动流程开关判定', {
@ -2733,25 +2587,14 @@ class DeliveryOrderService extends Service {
orderId: context.orderId,
storeId: context.storeId,
cutoffEnabled,
allocateStartTime,
cutoffTime,
isAllocationBlocked,
isCutoffActive,
needApproval,
autoAllocateExpressFlag: policyConfig && policyConfig.auto_allocate_express,
autoAllocateStorageFlag: policyConfig && policyConfig.auto_allocate_storage,
isExpressExcludedByRemark,
excludedRemarkKeyword,
autoExpressExcludeRemarks: warehouseSubjectConfig && warehouseSubjectConfig.auto_allocate_express_exclude_remarks,
isAutoAllocateExpressEnabled,
isAutoAllocateStorageEnabled,
});
if (isExpressExcludedByRemark) {
await this.runAsyncProcessStep('appendAutoExpressSkipLog', async () => {
await this.appendAutoExpressSkipLog(context, excludedRemarkKeyword);
});
}
if (isAutoAllocateExpressEnabled) {
await this.runAsyncProcessStep('allocateExpress', async () => {
// 不再逐单直接取号:改为写入消费队列,由定时任务按仓库+货主串行批量消费,
@ -2772,7 +2615,7 @@ class DeliveryOrderService extends Service {
});
}
if (!isAllocationBlocked && !needApproval) {
if (!isCutoffActive && !needApproval) {
await this.runAsyncProcessStep('autoGrouping', async () => {
await this.runAutoGrouping(context);
});

View File

@ -787,10 +787,9 @@ class InboundDirectLogService extends Service {
* 先调用 qimenEntrySync 进行奇门/API 回传,成功后在 onSuccess 回调内开启事务写入库存。
* 同步失败则只写 FAILED 状态 + 操作日志,不写库存。
* @param {number} entryOrderId 入库单 ID
* @param {number} [noNeedNotice=0] 是否跳过入库完成通知:0 通知,1 不通知(默认 0)
* @return {Promise<Object>} code/data/message 结构
*/
async commit(entryOrderId, noNeedNotice = 0) {
async commit(entryOrderId) {
const { ctx, app } = this;
const warehouseId = ctx.user.store_id;
const entryOrderIdNum = Number(entryOrderId) || 0;
@ -994,19 +993,6 @@ class InboundDirectLogService extends Service {
await stockRecord.increment('quantity', { by: inboundQty, transaction, silent: true });
await stockRecord.reload({ transaction });
// 负库存回填:按 SW 非负增量冲销 GAP 补建行挂账(平账,拦截锁定回归真实数据)
if (beforeQuantity <= 0) {
const nonNegativeDelta = Math.max(0, Number(stockRecord.quantity) || 0) - Math.max(0, beforeQuantity);
await ctx.service.systems.storage.index.offsetGapOnInbound(stockId, inboundQty, {
transaction,
maxOffset: nonNegativeDelta,
orderNo: eo.entry_order_code || 'DIRECT_INBOUND',
orderId: eo.id,
operatorId: String(ctx.user?.employees_id || ctx.user?.id || ''),
operatorName: ctx.user?.employees_name || '',
});
}
const afterQuantity = Number(stockRecord.quantity) || 0;
const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0;
@ -1062,8 +1048,6 @@ class InboundDirectLogService extends Service {
let sAfterQty = 0;
let sBeforeLockedQty = 0;
let sAfterLockedQty = 0;
let sBeforeInterceptQty = 0;
let sAfterInterceptQty = 0;
if (sRecord) {
if (Number(sRecord.stock_id) !== Number(stockId)) {
@ -1076,8 +1060,6 @@ class InboundDirectLogService extends Service {
sAfterQty = sBeforeQty + qty;
sBeforeLockedQty = Number(sRecord.locked_quantity) || 0;
sAfterLockedQty = sBeforeLockedQty;
sBeforeInterceptQty = Number(sRecord.intercept_locked_quantity) || 0;
sAfterInterceptQty = sBeforeInterceptQty;
await ctx.model.Storage.update({
quantity: app.Sequelize.literal(`quantity + ${qty}`),
@ -1138,8 +1120,6 @@ class InboundDirectLogService extends Service {
after_quantity: sAfterQty,
before_locked_quantity: sBeforeLockedQty,
after_locked_quantity: sAfterLockedQty,
before_intercept_locked_quantity: sBeforeInterceptQty,
after_intercept_locked_quantity: sAfterInterceptQty,
batch_no: effectiveBatchNo,
inventory_type: inventoryType,
order_type: 'entry_order',
@ -1214,13 +1194,11 @@ class InboundDirectLogService extends Service {
await transaction.commit();
// 入库完成通知货主(失败不影响主流程);noNeedNotice=1 时跳过通知
if (Number(noNeedNotice) !== 1) {
try {
await this.notifyEntryOrderCompleted(eo);
} catch (noticeErr) {
ctx.logger.warn('[inbound_direct_log.commit] 入库完成通知货主失败,不影响业务', noticeErr);
}
// 入库完成通知货主(失败不影响主流程)
try {
await this.notifyEntryOrderCompleted(eo);
} catch (noticeErr) {
ctx.logger.warn('[inbound_direct_log.commit] 入库完成通知货主失败,不影响业务', noticeErr);
}
} catch (error) {
if (transaction && typeof transaction.rollback === 'function') {

View File

@ -308,46 +308,6 @@ async function buildQimenDeliveryOrderConfirmDataInternal(service, orderRow, ord
};
}
/**
* 判断货主是否开启「手工单回传通知」。
* 读取货主-仓库签约策略 policy_config.notify_manual_sync,未配置默认否。
*
* @param {object} service 服务实例。
* @param {number} warehouseId 仓库 ID。
* @param {number} storeId 货主 ID。
* @return {Promise<boolean>} true=发送通知,false=不发送通知。
*/
async function isManualSyncNoticeEnabledInternal(service, warehouseId, storeId) {
const normalizedWarehouseId = Number(warehouseId || 0);
const normalizedStoreId = Number(storeId || 0);
if (normalizedWarehouseId <= 0 || normalizedStoreId <= 0) {
return false;
}
const storeWarehouseService = service
&& service.ctx
&& service.ctx.service
&& service.ctx.service.systems
&& service.ctx.service.systems.storeWarehouse;
if (!storeWarehouseService || typeof storeWarehouseService.getContractConfig !== 'function') {
service.ctx.logger.warn('[OrderAsyncService.isManualSyncNoticeEnabled] storeWarehouse 服务不可用,按默认否处理', {
warehouseId: normalizedWarehouseId,
storeId: normalizedStoreId,
});
return false;
}
try {
const contractConfig = await storeWarehouseService.getContractConfig(normalizedWarehouseId, normalizedStoreId);
const policyConfig = contractConfig && contractConfig.policy_config;
return !!(policyConfig && Number(policyConfig.notify_manual_sync) === 1);
} catch (error) {
service.ctx.logger.warn('[OrderAsyncService.isManualSyncNoticeEnabled] 读取合约策略失败,按默认否处理: %s', String((error && error.message) || error || '').trim());
return false;
}
}
async function sendManualSyncNoticeInternal(service, syncResult = {}, context = {}) {
const rawNoticeService = service && service.ctx && service.ctx.service && service.ctx.service.systems && service.ctx.service.systems.notice;
const noticeService = rawNoticeService && typeof rawNoticeService.send === 'function'
@ -772,27 +732,7 @@ async function processManualOrderInternal(service, orderModel, orderItemsModel,
success_count: 1,
failed_count: 0,
};
const manualSyncNoticeEnabled = await isManualSyncNoticeEnabledInternal(
service,
warehouseId,
Number(orderRow && orderRow.store_id) || 0
);
let noticeResult;
if (!manualSyncNoticeEnabled) {
service.ctx.logger.info(`[OrderAsyncService.processManualOrder] 货主未开启手工单回传通知,跳过通知 orderId=${orderId}`);
noticeResult = {
success: true,
message: '货主未开启手工单回传通知,跳过通知',
data: {
mode: 'skipped',
warehouseId,
storeId: Number(orderRow && orderRow.store_id) || 0,
},
};
} else {
noticeResult = await enqueueOrderSyncNoticeInternal(service, noticeSyncResult, context);
}
const noticeResult = await enqueueOrderSyncNoticeInternal(service, noticeSyncResult, context);
if (!noticeResult || noticeResult.success !== true) {
const noticeMessage = String(noticeResult && noticeResult.message || '通知发送失败').trim() || '通知发送失败';

View File

@ -932,7 +932,7 @@ class OrderExportService extends OrderBaseService {
}
if (waveScope) {
const waveScopeCondition = this.buildWaveScopeFilterCondition(waveScope);
const waveScopeCondition = await this.buildWaveScopeWhereCondition(waveScope, warehouseId);
queryWhere = this.appendConditionToWhere(queryWhere, waveScopeCondition);
}

View File

@ -1,19 +1,8 @@
'use strict';
const crypto = require('node:crypto');
const fs = require('node:fs');
const fsp = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const ExcelJS = require('exceljs');
const Service = require('egg').Service;
const { stripWaybillSegmentSuffix, escapeLikeWildcards } = require('../../lib/waybill_code');
/** 打包任务导出主表分页拉取大小 */
const PACK_TASK_EXPORT_PAGE_SIZE = 500;
/** 打包任务导出关联数据分批拉取大小 */
const PACK_TASK_EXPORT_BATCH_SIZE = 100;
/**
* 快捷搜索运单号模糊降级的最小关键词长度。
* 运单号通常较长(如 JDX057941864338),短于该长度的输入(如单字符 "7")没有模糊搜索意义,
@ -61,31 +50,48 @@ class OrderPackingService extends Service {
}
return `http://w${warehouseId}-c${recordingComputerId}.o.gztbyc.com${videoPath}`;
}
/**
* 创建带业务错误码的异常对象。
* 打包任务列表查询(仓库侧)。
* 按仓库维度(warehouse_id)查询打包任务,支持分页、筛选、排序。
*
* @param {string} message 错误信息。
* @param {number} [code=400] 业务错误码。
* @return {Error} 包含 code 的异常对象。
* @param {Object} where 筛选条件对象
* @param {Object} [where.status] 任务状态:0=待处理 1=打包中 2=已完成 3=异常
* @param {Object} [where.pack_mode] 打包模式:1=散单 2=团购
* @param {Object} [where.waybill_code] 运单号(通过 wms_order_express 解析 order_id 后过滤;先剥离一单多件分段后缀,主体运单号等值匹配)
* @param {Object} [where.wave_no] 波次号(模糊匹配)
* @param {Object} [where.order_id] 订单ID(精确匹配)
* @param {Object} [where.workbench_id] 工作台ID(精确匹配)
* @param {Object} [where.quickWhere] 快捷搜索:支持波次号模糊匹配;运单号通过 express→order→wave 链路解析(团购按波次号查、散单按订单ID查;运单号先剥离分段后缀等值匹配,精确未命中且关键词长度≥4 时才降级模糊,短词禁止降级避免误命中)
* @param {Object} [where.start_time] 开始打包时间范围,支持 {operator:'between', value:[start,end]}
* @param {Object} [where.start_time_start] 开始打包时间起始(兼容旧写法)
* @param {Object} [where.start_time_end] 开始打包时间结束(兼容旧写法)
* @param {Object} [where.end_time] 结束打包时间范围,支持 {operator:'between', value:[start,end]}
* @param {Object} [where.create_time] 创建时间范围,支持 {operator:'between', value:[start,end]}
* @param {Object} pagination 分页参数 { page, pageSize }
* @param {Object} sort 排序参数 { sortField, sortOrder }
* @return {Promise<Object>} 打包任务列表与分页信息
*/
createBusinessError(message, code = 400) {
const error = new Error(`${message}`);
error.code = code;
return error;
}
/**
* 构建列表筛选条件(list 与 export 复用同一套语义)。
*
* @param {Object} where 筛选条件对象(与 list 入参一致)
* @param {Object} Op Sequelize Op 对象
* @param {number} warehouseId 仓库ID
* @return {Promise<Object>} Sequelize where 条件对象
*/
async _buildListWhere(where = {}, Op, warehouseId) {
async list(where = {}, pagination = {}, sort = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const page = Math.max(Number(pagination.page) || 1, 1);
const pageSize = Math.max(Number(pagination.pageSize) || 20, 1);
// 仓库上下文
const warehouseId = Number(ctx.user && ctx.user.store_id);
if (!warehouseId) {
return {
code: 400,
message: '用户未绑定仓库,无法查询打包任务',
data: {
list: [],
pagination: { page, pageSize, total: 0, totalPages: 0, hasPrevious: false, hasNext: false },
},
};
}
// 构建查询条件
const queryWhere = { warehouse_id: warehouseId };
// 状态筛选
@ -375,83 +381,23 @@ class OrderPackingService extends Service {
// 创建时间范围
applyTimeRangeFilter('create_time', where.create_time);
return queryWhere;
}
/**
* 构建列表排序(list 与 export 复用同一套语义)。
* @param {Object} sort 排序参数 { sortField, sortOrder }
* @return {Array} Sequelize order 数组
*/
_buildListOrder(sort = {}) {
// 排序
const sortField = sort.sortField || 'create_time';
const sortOrder = String(sort.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
const validSortFields = [ 'id', 'order_id', 'warehouse_id', 'workbench_id', 'wave_id', 'pack_quantity', 'pack_mode', 'status', 'start_time', 'end_time', 'create_time', 'update_time' ];
const actualSortField = validSortFields.includes(sortField) ? sortField : 'create_time';
return [[ actualSortField, sortOrder ]];
}
/**
* 打包任务列表查询(仓库侧)。
* 按仓库维度(warehouse_id)查询打包任务,支持分页、筛选、排序。
*
* @param {Object} where 筛选条件对象
* @param {Object} [where.status] 任务状态:0=待处理 1=打包中 2=已完成 3=异常
* @param {Object} [where.pack_mode] 打包模式:1=散单 2=团购
* @param {Object} [where.waybill_code] 运单号(通过 wms_order_express 解析 order_id 后过滤;先剥离一单多件分段后缀,主体运单号等值匹配)
* @param {Object} [where.wave_no] 波次号(模糊匹配)
* @param {Object} [where.order_id] 订单ID(精确匹配)
* @param {Object} [where.workbench_id] 工作台ID(精确匹配)
* @param {Object} [where.quickWhere] 快捷搜索:支持波次号模糊匹配;运单号通过 express→order→wave 链路解析(团购按波次号查、散单按订单ID查;运单号先剥离分段后缀等值匹配,精确未命中且关键词长度≥4 时才降级模糊,短词禁止降级避免误命中)
* @param {Object} [where.start_time] 开始打包时间范围,支持 {operator:'between', value:[start,end]}
* @param {Object} [where.start_time_start] 开始打包时间起始(兼容旧写法)
* @param {Object} [where.start_time_end] 开始打包时间结束(兼容旧写法)
* @param {Object} [where.end_time] 结束打包时间范围,支持 {operator:'between', value:[start,end]}
* @param {Object} [where.create_time] 创建时间范围,支持 {operator:'between', value:[start,end]}
* @param {Object} pagination 分页参数 { page, pageSize }
* @param {Object} sort 排序参数 { sortField, sortOrder }
* @return {Promise<Object>} 打包任务列表与分页信息
*/
async list(where = {}, pagination = {}, sort = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const page = Math.max(Number(pagination.page) || 1, 1);
const pageSize = Math.max(Number(pagination.pageSize) || 20, 1);
// 仓库上下文
const warehouseId = Number(ctx.user && ctx.user.store_id);
if (!warehouseId) {
return {
code: 400,
message: '用户未绑定仓库,无法查询打包任务',
data: {
list: [],
pagination: { page, pageSize, total: 0, totalPages: 0, hasPrevious: false, hasNext: false },
},
};
}
// 构建查询条件(与导出复用同一套筛选语义)
const queryWhere = await this._buildListWhere(where, Op, warehouseId);
// 排序(与导出复用同一套排序语义)
const order = this._buildListOrder(sort);
// 查询(含工作台、视频和运单关联)
// 性能优化:count 与 rows 分离。findAndCountAll 携带 hasMany include(videos/expresses)时,
// count 会生成 COUNT(DISTINCT) + 双 LEFT JOIN(生产实测 520ms),拆开后 count 走单表索引(约 44ms)。
const count = await ctx.model.PackTask.count({ where: queryWhere });
const rows = await ctx.model.PackTask.findAll({
const { count, rows } = await ctx.model.PackTask.findAndCountAll({
where: queryWhere,
order,
order: [[ actualSortField, sortOrder ]],
limit: pageSize,
offset: (page - 1) * pageSize,
include: [
{
model: ctx.model.Workbench,
as: 'workbench',
attributes: [ 'id', 'name', 'type' ],
attributes: [ 'id', 'name', 'type', 'barcode' ],
},
{
model: ctx.model.PackTaskVideo,
@ -491,6 +437,7 @@ class OrderPackingService extends Service {
deleted_at: plain.deleted_at ? appCtx.formatDate(plain.deleted_at) : null,
workbench_name: plain.workbench?.name || null,
workbench_type: plain.workbench?.type || null,
workbench_barcode: plain.workbench?.barcode || null,
has_video: rawVideos.length > 0 ? 1 : 2,
video_enable: rawVideos.some(v => v.video_url && v.status !== 'failed') ? 1 : 2,
videos: rawVideos.map(v => ({
@ -532,332 +479,6 @@ class OrderPackingService extends Service {
};
}
/**
* 导出打包任务列表(单 Sheet Excel,异步任务内部调用)。
* 复用 list 的 where/sort 语义;仓库隔离由方法层注入 warehouseId,此处再强制兜底;
* 分页拉取主表全量数据后批量关联工作台/视频/运单,流式生成 Excel 并上传。
*
* @param {Object} options 导出选项。
* @param {Object} [options.where] 标准化 where 条件(与 list 一致)。
* @param {Object} [options.sort] 排序参数(与 list 一致)。
* @param {number} [options.warehouseId] 仓库ID(由方法层从上下文注入)。
* @param {Function} [options.onProgress] 进度回调。
* @return {Promise<Object>} 上传结果与统计信息(含 url/cdnUrl/cosUrl/fileKey/current_count/total_count/sheet_count)。
*/
async exportPackTask(options = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const safeOptions = options && typeof options === 'object' && !Array.isArray(options) ? options : {};
const where = safeOptions.where && typeof safeOptions.where === 'object' ? { ...safeOptions.where } : {};
const sort = safeOptions.sort && typeof safeOptions.sort === 'object' ? { ...safeOptions.sort } : {};
const warehouseId = Number(safeOptions.warehouseId || 0);
const progressHandler = typeof safeOptions.onProgress === 'function'
? safeOptions.onProgress
: async () => {};
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
throw this.createBusinessError('缺少仓库上下文', 400);
}
// 复用 list 的 where/sort 语义,并强制仓库隔离(服务端注入,前端无需传 warehouse_id)
const queryWhere = await this._buildListWhere(where, Op, warehouseId);
const order = this._buildListOrder(sort);
const totalCount = await ctx.model.PackTask.count({ where: queryWhere });
await progressHandler({
status: 'running',
progress: totalCount > 0 ? 10 : 85,
currentCount: 0,
totalCount,
message: totalCount > 0 ? `已命中 ${totalCount} 条打包任务,开始导出` : '未命中数据,开始生成空文件',
});
// ---- 分页拉取主表全量数据 ----
const allTaskRows = [];
let page = 1;
while (allTaskRows.length < totalCount) {
const rows = await ctx.model.PackTask.findAll({
where: queryWhere,
order,
limit: PACK_TASK_EXPORT_PAGE_SIZE,
offset: (page - 1) * PACK_TASK_EXPORT_PAGE_SIZE,
raw: true,
});
if (!Array.isArray(rows) || rows.length === 0) {
break;
}
allTaskRows.push(...rows);
page += 1;
await progressHandler({
status: 'running',
progress: Math.min(30, 10 + Math.round((allTaskRows.length / Math.max(totalCount, 1)) * 20)),
currentCount: allTaskRows.length,
totalCount,
message: `正在拉取打包任务列表,已完成 ${allTaskRows.length}/${totalCount}`,
});
}
// ---- 批量拉取关联数据(工作台 / 视频 / 运单) ----
const taskIds = allTaskRows
.map(row => Number(row.id))
.filter(id => Number.isInteger(id) && id > 0);
const workbenchIds = [ ...new Set(
allTaskRows.map(row => Number(row.workbench_id || 0)).filter(id => Number.isInteger(id) && id > 0)
) ];
const orderIds = [ ...new Set(
allTaskRows.map(row => Number(row.order_id || 0)).filter(id => Number.isInteger(id) && id > 0)
) ];
/** @type {Map<number, Object>} */
const workbenchMap = new Map();
if (workbenchIds.length > 0) {
const workbenches = await ctx.model.Workbench.findAll({
where: { id: { [Op.in]: workbenchIds } },
attributes: [ 'id', 'name', 'type' ],
raw: true,
});
for (const wb of workbenches) {
workbenchMap.set(Number(wb.id), wb);
}
}
/** @type {Map<number, Array<Object>>} */
const videosMap = new Map();
if (taskIds.length > 0) {
for (let idx = 0; idx < taskIds.length; idx += PACK_TASK_EXPORT_BATCH_SIZE) {
const batchIds = taskIds.slice(idx, idx + PACK_TASK_EXPORT_BATCH_SIZE);
const videos = await ctx.model.PackTaskVideo.findAll({
where: { pack_task_id: { [Op.in]: batchIds } },
attributes: [ 'id', 'pack_task_id', 'video_url', 'camera_id', 'status' ],
raw: true,
});
for (const video of videos) {
const key = Number(video.pack_task_id);
if (!videosMap.has(key)) {
videosMap.set(key, []);
}
videosMap.get(key).push(video);
}
}
}
/** @type {Map<number, string>} */
const cameraNameMap = new Map();
const cameraIds = [ ...new Set(
Array.from(videosMap.values())
.flat()
.map(v => Number(v.camera_id || 0))
.filter(id => Number.isInteger(id) && id > 0)
) ];
if (cameraIds.length > 0) {
const cameras = await ctx.model.Camera.findAll({
where: { id: { [Op.in]: cameraIds } },
attributes: [ 'id', 'custom_name', 'channel_name' ],
raw: true,
});
for (const camera of cameras) {
cameraNameMap.set(Number(camera.id), camera.custom_name || camera.channel_name || '');
}
}
/** @type {Map<number, Array<Object>>} */
const expressesMap = new Map();
if (orderIds.length > 0) {
for (let idx = 0; idx < orderIds.length; idx += PACK_TASK_EXPORT_BATCH_SIZE) {
const batchOrderIds = orderIds.slice(idx, idx + PACK_TASK_EXPORT_BATCH_SIZE);
const expresses = await ctx.model.OrderExpress.findAll({
where: {
order_id: { [Op.in]: batchOrderIds },
warehouse_id: warehouseId,
delete_at: null,
},
attributes: [ 'id', 'order_id', 'waybill_code' ],
raw: true,
});
for (const express of expresses) {
const key = Number(express.order_id);
if (!expressesMap.has(key)) {
expressesMap.set(key, []);
}
expressesMap.get(key).push(express);
}
}
}
await progressHandler({
status: 'running',
progress: 55,
currentCount: allTaskRows.length,
totalCount,
message: '正在生成 Excel 文件...',
});
// ---- 生成 Excel(流式写入,单 Sheet) ----
const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-pack-task-export-'));
const now = new Date();
const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`;
const filename = `打包任务导出_${dateToken}.xlsx`;
const filePath = path.join(tempDir, filename);
const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({
filename: filePath,
useStyles: false,
useSharedStrings: false,
});
const normalizeCellValue = value => {
if (value === null || value === undefined) return '';
if (value instanceof Date) return app.formatDate ? app.formatDate(value) : value.toISOString();
return value;
};
const formatDateTime = value => (value ? app.formatDate(value) : '');
const PACK_MODE_TEXT = { 1: '散单', 2: '团购' };
const STATUS_TEXT = { 0: '待处理', 1: '打包中', 2: '已完成', 3: '异常' };
try {
const sheet = workbook.addWorksheet('打包任务列表');
sheet.columns = [
{ header: '任务ID', key: 'id', width: 14 },
{ header: '订单ID', key: 'order_id', width: 14 },
{ header: '波次号', key: 'wave_no', width: 18 },
{ header: '运单号', key: 'waybill_code', width: 22 },
{ header: '关联运单号', key: 'waybill_codes', width: 30 },
{ header: '打包模式', key: 'pack_mode_text', width: 10 },
{ header: '任务状态', key: 'status_text', width: 10 },
{ header: '打包数量', key: 'pack_quantity', width: 10 },
{ header: '商品总数量', key: 'item_quantity', width: 12 },
{ header: '商品种类数', key: 'sku_count', width: 12 },
{ header: '工作台', key: 'workbench_name', width: 14 },
{ header: '作业人员', key: 'operator_text', width: 20 },
{ header: '开始打包时间', key: 'start_time', width: 20 },
{ header: '结束打包时间', key: 'end_time', width: 20 },
{ header: '创建时间', key: 'create_time', width: 20 },
{ header: '视频状态', key: 'has_video_text', width: 10 },
{ header: '录像可用', key: 'video_enable_text', width: 10 },
{ header: '备注', key: 'remark', width: 30 },
];
for (const row of allTaskRows) {
const taskId = Number(row.id);
const workbench = workbenchMap.get(Number(row.workbench_id || 0));
const videos = videosMap.get(taskId) || [];
const expresses = expressesMap.get(Number(row.order_id || 0)) || [];
const waybillCodes = expresses
.map(e => e.waybill_code)
.filter(code => code && String(code).trim())
.join(', ');
const hasVideo = videos.length > 0;
const videoEnable = videos.some(v => v.video_url && v.status !== 'failed');
sheet.addRow({
id: taskId,
order_id: row.order_id,
wave_no: normalizeCellValue(row.wave_no),
waybill_code: normalizeCellValue(row.waybill_code),
waybill_codes: waybillCodes,
pack_mode_text: PACK_MODE_TEXT[Number(row.pack_mode)] || '',
status_text: STATUS_TEXT[Number(row.status)] || '',
pack_quantity: row.pack_quantity,
item_quantity: row.item_quantity,
sku_count: row.sku_count,
workbench_name: workbench ? normalizeCellValue(workbench.name) : '',
operator_text: normalizeCellValue(row.operator_text),
start_time: formatDateTime(row.start_time),
end_time: formatDateTime(row.end_time),
create_time: formatDateTime(row.create_time),
has_video_text: hasVideo ? '有视频' : '无视频',
video_enable_text: videoEnable ? '可用' : '不可用',
remark: normalizeCellValue(row.remark),
}).commit();
}
sheet.commit();
await workbook.commit();
await progressHandler({
status: 'running',
progress: 92,
currentCount: allTaskRows.length,
totalCount,
message: '正在上传文件...',
});
// ---- 上传文件 ----
const uploadService = ctx?.service?.systems?.upload;
if (!uploadService || typeof uploadService.uploadFile !== 'function') {
throw new Error('上传服务不可用');
}
const stat = await fsp.stat(filePath);
const randomToken = crypto.randomBytes(6).toString('hex');
const uploadKey = `exports/pack_task/${warehouseId}/${Date.now()}_${randomToken}.xlsx`;
const uploadStream = fs.createReadStream(filePath);
uploadStream.filename = filename;
uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
uploadStream.fileSize = stat.size;
const uploadResult = await uploadService.uploadFile(uploadStream, {
key: uploadKey,
category: 'document',
mimetype: 'xls,xlsx,csv',
});
let fileRecord = null;
if (typeof uploadService.uploadSuccessNotify === 'function') {
fileRecord = await uploadService.uploadSuccessNotify({
url: uploadResult.fileName,
fileKey: uploadResult.fileName,
fileName: filename,
fileType: 'document',
mimeType: uploadStream.mimeType,
fileSize: stat.size,
userId: ctx.userId,
description: `打包任务导出(仓库${warehouseId}),共${totalCount}条打包任务`,
});
}
// 优先取 uploadFile 返回的完整 URL,其次取 uploadSuccessNotify 落库记录(兼容 data 包裹),最后才回退 COS key
const safeUploadResult = typeof uploadResult === 'object' && uploadResult !== null ? uploadResult : {};
const resolvedFileRecord = (fileRecord && (fileRecord.data || fileRecord)) || null;
const fileUrlFromRecord = resolvedFileRecord
? (resolvedFileRecord.file_url || resolvedFileRecord.fileUrl || resolvedFileRecord.url || '')
: '';
const uploadResultUrl = safeUploadResult.url || safeUploadResult.cdnUrl || safeUploadResult.cosUrl || '';
const uploadInfo = {
filename,
fileKey: safeUploadResult.fileName || uploadKey,
url: uploadResultUrl || fileUrlFromRecord || safeUploadResult.fileName || uploadKey,
cdnUrl: safeUploadResult.cdnUrl || safeUploadResult.url || '',
cosUrl: safeUploadResult.cosUrl || '',
current_count: allTaskRows.length,
total_count: totalCount,
sheet_count: 1,
};
await progressHandler({
status: 'success',
progress: 100,
currentCount: allTaskRows.length,
totalCount,
message: '导出任务完成',
result: uploadInfo,
});
return uploadInfo;
} catch (error) {
const workbookStream = workbook.stream;
if (workbookStream && typeof workbookStream.destroy === 'function') {
workbookStream.destroy();
}
throw error;
} finally {
// 清理临时文件(不存在或删除失败均忽略)
try { await fsp.rm(tempDir, { recursive: true, force: true }); } catch (err) { /* ignore */ }
}
}
/**
* 打包任务详情查询。
* 按 id + warehouse_id 查询单条打包任务记录。
@ -885,7 +506,7 @@ class OrderPackingService extends Service {
{
model: ctx.model.Workbench,
as: 'workbench',
attributes: [ 'id', 'name', 'type' ],
attributes: [ 'id', 'name', 'type', 'barcode' ],
},
{
model: ctx.model.PackTaskVideo,
@ -927,6 +548,7 @@ class OrderPackingService extends Service {
deleted_at: plain.deleted_at ? appCtx.formatDate(plain.deleted_at) : null,
workbench_name: plain.workbench?.name || null,
workbench_type: plain.workbench?.type || null,
workbench_barcode: plain.workbench?.barcode || null,
has_video: rawVideos.length > 0 ? 1 : 2,
video_enable: rawVideos.some(v => v.video_url && v.status !== 'failed') ? 1 : 2,
videos: rawVideos.map(v => ({

View File

@ -665,11 +665,6 @@ class OrderPrintSystemService extends OrderBaseService {
normalizedWarehouseId,
validOrderWaveIds
);
const pickTaskBoxNoMap = await this.querySmallGroupBoxNoMap(
orderIds,
normalizedWarehouseId,
new Map(unlockedOrderRows.map(row => [ Number(row && row.id || 0), Number(row && row.wave_id || 0) ]))
);
const waveIdsForCount = validOrderWaveIds;
const waveTotalOrderCountMap = await this.queryWaveTotalOrderCountMap(waveIdsForCount, normalizedWarehouseId);
const templateSampleCache = new Map();
@ -689,7 +684,6 @@ class OrderPrintSystemService extends OrderBaseService {
const waveIndex = Number(waveOrderIndexInfo.wave_index || 0);
const platformsIndex = Number(waveOrderIndexInfo.platforms_index || 0);
const waveMetaRow = waveMetaMap.get(waveIdForCount) || {};
const pickTaskBoxInfo = pickTaskBoxNoMap.get(orderId) || {};
const effectiveOrderRowWithWaveIndex = {
...effectiveOrderRow,
wave_total_orders: waveTotalOrders > 0 ? waveTotalOrders : 0,
@ -697,7 +691,6 @@ class OrderPrintSystemService extends OrderBaseService {
platforms_index: platformsIndex > 0 ? platformsIndex : 0,
wave_source: Number(waveMetaRow.source || 0),
wave_type: Number(waveMetaRow.wave_type || 0),
box_no: Number(pickTaskBoxInfo.box_no || 0),
};
const storeId = Number(orderRow && orderRow.store_id || 0);
const policyConfig = policyConfigMap.get(storeId) || {};
@ -885,11 +878,6 @@ class OrderPrintSystemService extends OrderBaseService {
normalizedWarehouseId,
validOrderWaveIds
);
const pickTaskBoxNoMap = await this.querySmallGroupBoxNoMap(
orderIdsForExpress,
normalizedWarehouseId,
new Map(validOrderRows.map(row => [ Number(row && row.id || 0), Number(row && row.wave_id || 0) ]))
);
const waveIdsForCount = validOrderWaveIds;
const waveTotalOrderCountMap = await this.queryWaveTotalOrderCountMap(waveIdsForCount, normalizedWarehouseId);
const templateSampleCache = new Map();
@ -909,7 +897,6 @@ class OrderPrintSystemService extends OrderBaseService {
const waveIndex = Number(waveOrderIndexInfo.wave_index || 0);
const platformsIndex = Number(waveOrderIndexInfo.platforms_index || 0);
const waveMetaRow = waveMetaMap.get(waveIdForCount) || {};
const pickTaskBoxInfo = pickTaskBoxNoMap.get(orderId) || {};
const effectiveOrderRowWithWaveIndex = {
...effectiveOrderRow,
wave_total_orders: waveTotalOrders > 0 ? waveTotalOrders : 0,
@ -917,7 +904,6 @@ class OrderPrintSystemService extends OrderBaseService {
platforms_index: platformsIndex > 0 ? platformsIndex : 0,
wave_source: Number(waveMetaRow.source || 0),
wave_type: Number(waveMetaRow.wave_type || 0),
box_no: Number(pickTaskBoxInfo.box_no || 0),
};
const storeId = Number(orderRow && orderRow.store_id || 0);
const policyConfig = policyConfigMap.get(storeId) || {};
@ -1163,11 +1149,6 @@ class OrderPrintSystemService extends OrderBaseService {
const waveOrderIndexMap = await this.queryWaveOrderIndexMapByOrderIds(
orderIdsForIndex, normalizedWarehouseId, validOrderWaveIds
);
const pickTaskBoxNoMap = await this.querySmallGroupBoxNoMap(
orderIdsForIndex,
normalizedWarehouseId,
new Map(validOrderRows.map(row => [ Number(row && row.id || 0), Number(row && row.wave_id || 0) ]))
);
const waveTotalOrderCountMap = await this.queryWaveTotalOrderCountMap(validOrderWaveIds, normalizedWarehouseId);
const templateSampleCache = new Map();
@ -1185,7 +1166,6 @@ class OrderPrintSystemService extends OrderBaseService {
const waveIndex = Number(waveOrderIndexInfo.wave_index || 0);
const platformsIndex = Number(waveOrderIndexInfo.platforms_index || 0);
const waveMetaRow = waveMetaMap.get(waveIdForCount) || {};
const pickTaskBoxInfo = pickTaskBoxNoMap.get(orderId) || {};
const effectiveOrderRowWithWaveIndex = {
...effectiveOrderRow,
wave_total_orders: waveTotalOrders > 0 ? waveTotalOrders : 0,
@ -1193,7 +1173,6 @@ class OrderPrintSystemService extends OrderBaseService {
platforms_index: platformsIndex > 0 ? platformsIndex : 0,
wave_source: Number(waveMetaRow.source || 0),
wave_type: Number(waveMetaRow.wave_type || 0),
box_no: Number(pickTaskBoxInfo.box_no || 0),
};
const storeId = Number(orderRow.store_id || 0);
@ -2122,121 +2101,6 @@ ${waveFilterSql}
return resultMap;
}
/**
* 批量查询小团购波次(wave_type=1 且 source∈{1,2} 策略任务)的拣货篮号映射。
*
* 小团购判定由调用方根据 wms_wave_batch.wave_type/source 完成,本方法只负责取篮号。
* 篮号存在两种写入场景,均需兼容:
* - PDA 扫码创建任务(systemMethods/pick.js createWavePickTask):订单级篮号写入
* wms_wave_pick_task_order.box_no(订单所属最小篮号),订单级优先;
* - 计划创建任务(systemMethods/order/wave.js createWavePickTaskFromPlan):篮号写入
* wms_wave_pick_task_wave.box_no(每波次一篮),任务订单表不含小团购订单行,
* 按订单所属 wave_id 兜底取波次级篮号。
*
* 同一订单/波次可能命中多个任务,按 task_id DESC 取最新任务的记录。
* 查询失败时优雅降级返回空映射。
*
* @param {Array<number>} orderIds 订单ID数组。
* @param {number} warehouseId 仓库ID。
* @param {Map<number, number>} [orderWaveIdMap] 订单ID到波次ID的映射,用于波次级篮号兜底。
* @return {Promise<Map<number, {box_no:number}>>} 订单ID到拣货篮号映射。
*/
async querySmallGroupBoxNoMap(orderIds = [], warehouseId, orderWaveIdMap = null) {
const resultMap = new Map();
const normalizedOrderIds = Array.from(new Set((Array.isArray(orderIds) ? orderIds : [])
.map(id => Number(id))
.filter(id => Number.isInteger(id) && id > 0)));
if (normalizedOrderIds.length === 0) {
return resultMap;
}
const queryMethod = this.ctx.model && this.ctx.model.query;
if (typeof queryMethod !== 'function') {
return resultMap;
}
const safeOrderWaveIdMap = orderWaveIdMap instanceof Map ? orderWaveIdMap : new Map();
try {
// 1) 订单级篮号(PDA 扫码创建任务):同一订单多条时取最新任务(task_id DESC)
const orderRows = await queryMethod.call(this.ctx.model, `
SELECT order_id, box_no
FROM wms_wave_pick_task_order
WHERE warehouse_id = :warehouseId
AND order_id IN (:orderIds)
ORDER BY task_id DESC
`, {
replacements: {
warehouseId,
orderIds: normalizedOrderIds,
},
type: this.ctx.model.QueryTypes && this.ctx.model.QueryTypes.SELECT,
});
for (const row of Array.isArray(orderRows) ? orderRows : []) {
const orderId = Number(row && row.order_id || 0);
const boxNo = Number(row && row.box_no || 0);
if (orderId > 0 && boxNo > 0 && !resultMap.has(orderId)) {
resultMap.set(orderId, { box_no: boxNo });
}
}
// 2) 波次级篮号兜底(计划创建任务):未命中订单按其 wave_id 取波次篮号
const backfillWaveIds = new Set();
for (const orderId of normalizedOrderIds) {
if (resultMap.has(orderId)) {
continue;
}
const waveId = Number(safeOrderWaveIdMap.get(orderId) || 0);
if (waveId > 0) {
backfillWaveIds.add(waveId);
}
}
if (backfillWaveIds.size > 0) {
const waveRows = await queryMethod.call(this.ctx.model, `
SELECT wave_id, box_no
FROM wms_wave_pick_task_wave
WHERE warehouse_id = :warehouseId
AND wave_id IN (:waveIds)
ORDER BY task_id DESC
`, {
replacements: {
warehouseId,
waveIds: Array.from(backfillWaveIds),
},
type: this.ctx.model.QueryTypes && this.ctx.model.QueryTypes.SELECT,
});
const waveBoxNoMap = new Map();
for (const row of Array.isArray(waveRows) ? waveRows : []) {
const waveId = Number(row && row.wave_id || 0);
const boxNo = Number(row && row.box_no || 0);
if (waveId > 0 && boxNo > 0 && !waveBoxNoMap.has(waveId)) {
waveBoxNoMap.set(waveId, boxNo);
}
}
for (const orderId of normalizedOrderIds) {
if (resultMap.has(orderId)) {
continue;
}
const waveId = Number(safeOrderWaveIdMap.get(orderId) || 0);
const boxNo = waveBoxNoMap.get(waveId) || 0;
if (waveId > 0 && boxNo > 0) {
resultMap.set(orderId, { box_no: boxNo });
}
}
}
} catch (error) {
this.ctx.logger.warn(
`[orderPrint.querySmallGroupBoxNoMap] 查询失败 warehouseId=${warehouseId} message=${error.message}`
);
}
return resultMap;
}
/**
* 按波次ID批量查询波次总订单数。
*

View File

@ -242,26 +242,6 @@ function compareStorageRows(left, right) {
return toNumber(left.id, 0) - toNumber(right.id, 0);
}
/**
* 判断库存行是否属于可参与本次分配的库位。
*
* 允许存储储位(allowStorageSpace=true)时不限制库位类型;
* 否则仅库位类型同时满足「允许分配(allow_allocation=1)」且「已启用(is_active=1)」的库存行可参与分配。
*
* @param {Object} storageRow 库存行。
* @param {boolean} allowStorageSpace 是否允许存储储位参与分配。
* @return {boolean} 是否可参与分配。
*/
function isAllocatableStorageRow(storageRow, allowStorageSpace) {
if (allowStorageSpace) {
return true;
}
const locationType = storageRow && storageRow.locationType ? storageRow.locationType : {};
return toNumber(locationType.allow_allocation, 0) === 1
&& toNumber(locationType.is_active, 0) === 1;
}
/**
* 生成库位类型限制导致的缺货原因文本。
*
@ -486,9 +466,7 @@ class OrderStorageAllocationService extends MainService {
*
* 分配规则:
* - 先过滤掉已经完成储位分配的订单
* - 默认只从库位类型允许分配且启用的储位中分配(排除存储储位);
* allow_storage_location=true 或货主关闭存拣分离(storage_separation=0)时,
* 不再限制库位类型,允许存储储位参与分配
* - 允许时优先使用存储储位,再使用分拣储位
* - FIFO 先按生产日期,再按入库时间
* - 库存不足时按订单顺序尽量分配,并将不足订单标记为异常
*
@ -854,9 +832,12 @@ class OrderStorageAllocationService extends MainService {
as: 'locationType',
required: true,
attributes: [ 'id', 'type_code', 'type_name', 'allow_allocation', 'is_active' ],
// 不在 SQL 层过滤库位类型:存拣分离策略按库存(货主)维度生效,
// 无法在批量 SQL 的 include where 中按 stock_id 分组表达,
// 统一在下方按 allowStorageSpace 逐 SKU 过滤。
...(allowStorageLocation ? {} : {
where: {
allow_allocation: 1,
is_active: 1,
},
}),
},
],
},
@ -1063,7 +1044,6 @@ class OrderStorageAllocationService extends MainService {
const storageRowsForStock = storageRowsByStockId.get(stockId) || [];
const candidateStorageRows = storageRowsForStock
.slice()
.filter(storageRow => isAllocatableStorageRow(storageRow, allowStorageSpace))
.sort((left, right) => compareStorageRows(left, right));
let shortageReason = '';
@ -1080,7 +1060,7 @@ class OrderStorageAllocationService extends MainService {
});
if (candidateStorageRows.length === 0) {
shortageDiagnostics = allowStorageSpace
shortageDiagnostics = allowStorageLocation
? null
: await diagnoseStorageTypeRestriction({
ctx,
@ -1162,7 +1142,6 @@ class OrderStorageAllocationService extends MainService {
});
const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0);
const beforeInterceptLockedQuantity = toNumber(storageRow.intercept_locked_quantity, 0);
await ctx.service.systems.storage.index.lockQuantity(storageRow.id, allocationQuantity, { transaction });
@ -1187,8 +1166,6 @@ class OrderStorageAllocationService extends MainService {
after_quantity: storageRow.quantity,
before_locked_quantity: beforeLockedQuantity,
after_locked_quantity: beforeLockedQuantity + allocationQuantity,
before_intercept_locked_quantity: beforeInterceptLockedQuantity,
after_intercept_locked_quantity: beforeInterceptLockedQuantity,
batch_no: storageRow.batch_no,
inventory_type: storageRow.inventory_type,
order_type: 'PICKING_LOCK',
@ -2127,24 +2104,17 @@ class OrderStorageAllocationService extends MainService {
*
* 入参仅支持订单 ID 相关字段:
* - `order_ids` / `orderIds` / `ids` / `order_id` / `orderId` / `id`
* - `interceptMode`(可选,布尔值):拦截确认模式,默认 false。
* - false(普通取消):pending 行解除锁定(可用数量 +q)、fin 行返还实物(可用数量 +q),既有行为不变;
* - true(拦截确认):pending 行作业锁迁移为拦截锁(locked -q、intercept +q、available 不变),
* fin 行实物返还并拦截锁定(quantity +q、intercept +q、available 不变),流水 order_type 记为
* INTERCEPT_LOCK 且记录 order_id 与 before/after_intercept_locked_quantity 快照。
*
* 取消分配时仅处理当前用户仓库中已完成储位分配的订单;
* 未分配订单或非完成状态订单会进入 skipped_orders。
*
* @param {Object} data 请求体。
* @param {boolean} [data.interceptMode] 拦截确认模式开关。
* @return {Promise<Object>} 取消分配结果。
*/
async cancelAllocateStorage(data = {}) {
const { ctx, app } = this;
const { orderIds, forbiddenWarehouseKeys } = normalizeCancelStorageAllocationRequest(data);
const warehouseId = toNumber(ctx.user?.store_id ?? ctx.user?.warehouse_id, 0);
const interceptMode = normalizeBooleanFlag(data && data.interceptMode, false);
writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 规范化入参', {
warehouseId,
@ -2307,11 +2277,6 @@ class OrderStorageAllocationService extends MainService {
const pendingStorageQuantityMap = new Map();
const finStorageQuantityMap = new Map();
const storageIdSet = new Set();
// 拦截模式(interceptMode)按 (order_id, storage_id) 维度记录数量,供拦截锁迁移与按单回落使用
const interceptPendingQuantityMap = new Map();
const interceptFinQuantityMap = new Map();
// 拦截模式拣货行元信息(space_id/stock_id),供缺行补建 storage 使用
const interceptPickingMetaMap = new Map();
for (const pickingRow of Array.isArray(pickingRows) ? pickingRows : []) {
const plainPicking = toPlainRecord(pickingRow);
@ -2331,19 +2296,10 @@ class OrderStorageAllocationService extends MainService {
// 按状态分流:pending 记录解除锁定(实物不动);
// fin 记录(已拣货)返还实物数量,锁定已在拣货完成时扣减,不再重复扣除
const pickingStatus = String(plainPicking?.status || '').trim();
const interceptPairKey = `${orderId}:${storageId}`;
if (!interceptPickingMetaMap.has(interceptPairKey)) {
interceptPickingMetaMap.set(interceptPairKey, {
space_id: toNumber(plainPicking?.space_id, 0),
stock_id: toNumber(plainPicking?.stock_id, 0),
});
}
if (pickingStatus === 'fin') {
finStorageQuantityMap.set(storageId, (finStorageQuantityMap.get(storageId) || 0) + quantity);
interceptFinQuantityMap.set(interceptPairKey, (interceptFinQuantityMap.get(interceptPairKey) || 0) + quantity);
} else {
pendingStorageQuantityMap.set(storageId, (pendingStorageQuantityMap.get(storageId) || 0) + quantity);
interceptPendingQuantityMap.set(interceptPairKey, (interceptPendingQuantityMap.get(interceptPairKey) || 0) + quantity);
}
}
@ -2408,376 +2364,97 @@ class OrderStorageAllocationService extends MainService {
const storageUnlockSummary = [];
const storageReturnSummary = [];
if (interceptMode) {
// ── 拦截模式:库存不归还可用,移入拦截锁定字段(intercept_locked_quantity) ──
const interceptUnlockSummaryMap = new Map();
const interceptReturnSummaryMap = new Map();
// 按 storage 累计本批次已迁移的锁定/拦截锁定/实物数量变化,保证同库存多订单时流水快照准确
const interceptLockedDeltaMap = new Map();
const interceptLockedChangeMap = new Map();
const interceptQuantityChangeMap = new Map();
// 仓库默认库位(缺行补建时使用):优先仓库配置 default_location_id,未设置兜底 1
let fallbackDefaultSpaceId = 1;
try {
const deliveryOrderService = ctx.service && ctx.service.systems && ctx.service.systems.deliveryOrder;
const subjectConfig = deliveryOrderService && typeof deliveryOrderService.getStoreSubjectConfig === 'function'
? await deliveryOrderService.getStoreSubjectConfig(warehouseId)
: null;
const configuredLocationId = Number(subjectConfig && subjectConfig.default_location_id || 0);
if (Number.isInteger(configuredLocationId) && configuredLocationId > 0) {
fallbackDefaultSpaceId = configuredLocationId;
}
} catch (defaultSpaceErr) {
ctx.logger.warn(
`[order_storage_allocation.cancelAllocateStorage] 读取仓库默认库位失败,兜底库位 1: ${defaultSpaceErr.message}`
);
// pending 记录:解除锁定,实物库存不动
for (const [ storageId, quantity ] of pendingStorageQuantityMap.entries()) {
if (quantity <= 0) {
continue;
}
// pending 记录:作业锁迁移为拦截锁(locked -q、intercept +q、quantity 不变、available 不变)
for (const [ pairKey, quantity ] of interceptPendingQuantityMap.entries()) {
if (quantity <= 0) {
continue;
}
const [ orderId, storageId ] = pairKey.split(':').map(part => toNumber(part, 0));
if (orderId <= 0 || storageId <= 0) {
continue;
}
let storageRow = storageMap.get(storageId);
const orderRow = orderMap.get(orderId) || {};
const orderNo = String(orderRow.delivery_order_code || orderRow.pre_delivery_order_code || '').trim()
|| 'INTERCEPT_CONFIRM';
const pickingMeta = interceptPickingMetaMap.get(pairKey) || {};
if (!storageRow) {
// 拦截确认缺行补建:货物在库,直接以拦截锁定入账(quantity=q、intercept=q、available=0)
const created = await storageModel.create({
warehouse_id: warehouseId,
store_id: toNumber(orderRow.store_id, 0) || null,
space_id: toNumber(pickingMeta.space_id, 0) || fallbackDefaultSpaceId,
stock_id: toNumber(pickingMeta.stock_id, 0) || 0,
batch_no: String(orderNo).slice(0, 100),
inventory_type: 'ZP',
quantity,
locked_quantity: 0,
intercept_locked_quantity: quantity,
available_quantity: 0,
inbound_time: now,
inbound_order_no: String(orderNo).slice(0, 100),
is_enabled: 1,
created_at: now,
updated_at: now,
}, { transaction });
const plainCreated = created && typeof created.get === 'function'
? created.get({ plain: true })
: created;
storageMap.set(Number(plainCreated.id), plainCreated);
storageRow = plainCreated;
writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 拦截模式缺行补建库存行', {
orderId,
storageId,
createdStorageId: plainCreated.id,
quantity,
spaceId: toNumber(pickingMeta.space_id, 0) || fallbackDefaultSpaceId,
});
// 直接写拦截锁定流水(补建行:before=0 → after=quantity)
await ctx.model.StorageTransaction.create({
transaction_type: 'LOCK',
warehouse_id: warehouseId,
store_id: plainCreated.store_id,
stock_id: plainCreated.stock_id,
storage_id: plainCreated.id,
space_id: plainCreated.space_id,
quantity,
before_quantity: quantity,
after_quantity: quantity,
before_locked_quantity: 0,
after_locked_quantity: 0,
before_intercept_locked_quantity: 0,
after_intercept_locked_quantity: quantity,
batch_no: plainCreated.batch_no,
inventory_type: 'ZP',
order_type: 'INTERCEPT_LOCK',
order_no: orderNo,
order_id: orderId,
operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''),
operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '',
remark: '拦截确认(缺行补建并拦截锁定)',
}, { transaction });
interceptUnlockSummaryMap.set(Number(plainCreated.id), (interceptUnlockSummaryMap.get(Number(plainCreated.id)) || 0) + quantity);
continue; // 补建行已直接入账,跳过既有迁移逻辑
}
const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0)
+ (interceptLockedDeltaMap.get(storageId) || 0);
const beforeInterceptLockedQuantity = toNumber(storageRow.intercept_locked_quantity, 0)
+ (interceptLockedChangeMap.get(storageId) || 0);
await ctx.service.systems.storage.index.interceptLockQuantity(storageId, quantity, {
transaction,
});
interceptLockedDeltaMap.set(storageId, (interceptLockedDeltaMap.get(storageId) || 0) - quantity);
interceptLockedChangeMap.set(storageId, (interceptLockedChangeMap.get(storageId) || 0) + quantity);
// 写入拦截锁定流水(作业锁迁移为拦截锁,记录拦截快照)
await ctx.model.StorageTransaction.create({
transaction_type: 'LOCK',
warehouse_id: warehouseId,
store_id: storageRow.store_id,
stock_id: storageRow.stock_id,
storage_id: storageId,
space_id: storageRow.space_id,
quantity,
before_quantity: storageRow.quantity,
after_quantity: storageRow.quantity,
before_locked_quantity: beforeLockedQuantity,
after_locked_quantity: beforeLockedQuantity - quantity,
before_intercept_locked_quantity: beforeInterceptLockedQuantity,
after_intercept_locked_quantity: beforeInterceptLockedQuantity + quantity,
batch_no: storageRow.batch_no,
inventory_type: storageRow.inventory_type,
order_type: 'INTERCEPT_LOCK',
order_no: orderNo,
order_id: orderId,
operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''),
operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '',
remark: '拦截确认(作业锁迁移为拦截锁)',
}, { transaction });
interceptUnlockSummaryMap.set(storageId, (interceptUnlockSummaryMap.get(storageId) || 0) + quantity);
const storageRow = storageMap.get(storageId);
if (!storageRow) {
throw new Error(`库存记录不存在: ${storageId}`);
}
// fin 记录(已拣货):实物返还并拦截锁定(quantity +q、intercept +q、available 不变)
for (const [ pairKey, returnQuantity ] of interceptFinQuantityMap.entries()) {
if (returnQuantity <= 0) {
continue;
}
const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0);
const [ orderId, storageId ] = pairKey.split(':').map(part => toNumber(part, 0));
if (orderId <= 0 || storageId <= 0) {
continue;
}
await ctx.service.systems.storage.index.unlockQuantity(storageId, quantity, {
transaction,
});
let storageRow = storageMap.get(storageId);
const orderRow = orderMap.get(orderId) || {};
const orderNo = String(orderRow.delivery_order_code || orderRow.pre_delivery_order_code || '').trim()
|| 'INTERCEPT_CONFIRM';
const pickingMeta = interceptPickingMetaMap.get(pairKey) || {};
// 写入储位解锁流水
await ctx.model.StorageTransaction.create({
transaction_type: 'UNLOCK',
warehouse_id: warehouseId,
store_id: storageRow.store_id,
stock_id: storageRow.stock_id,
storage_id: storageId,
space_id: storageRow.space_id,
quantity,
before_quantity: storageRow.quantity,
after_quantity: storageRow.quantity,
before_locked_quantity: beforeLockedQuantity,
after_locked_quantity: beforeLockedQuantity - quantity,
batch_no: storageRow.batch_no,
inventory_type: storageRow.inventory_type,
order_type: 'PICKING_UNLOCK',
order_no: 'CANCEL_BATCH',
order_id: 0,
operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''),
operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '',
remark: '取消分配储位(库存解锁)',
}, { transaction });
if (!storageRow) {
// 拦截确认缺行补建:实物返还并拦截锁定(quantity=q、intercept=q、available=0)
const created = await storageModel.create({
warehouse_id: warehouseId,
store_id: toNumber(orderRow.store_id, 0) || null,
space_id: toNumber(pickingMeta.space_id, 0) || fallbackDefaultSpaceId,
stock_id: toNumber(pickingMeta.stock_id, 0) || 0,
batch_no: String(orderNo).slice(0, 100),
inventory_type: 'ZP',
quantity: returnQuantity,
locked_quantity: 0,
intercept_locked_quantity: returnQuantity,
available_quantity: 0,
inbound_time: now,
inbound_order_no: String(orderNo).slice(0, 100),
is_enabled: 1,
created_at: now,
updated_at: now,
}, { transaction });
const plainCreated = created && typeof created.get === 'function'
? created.get({ plain: true })
: created;
storageMap.set(Number(plainCreated.id), plainCreated);
storageRow = plainCreated;
storageUnlockSummary.push({
storage_id: storageId,
unlocked_quantity: quantity,
});
}
writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 拦截模式缺行补建库存行(fin)', {
orderId,
storageId,
createdStorageId: plainCreated.id,
returnQuantity,
});
// 直接写拦截锁定流水(补建行:before=0 → after=returnQuantity)
await ctx.model.StorageTransaction.create({
transaction_type: 'INBOUND',
warehouse_id: warehouseId,
store_id: plainCreated.store_id,
stock_id: plainCreated.stock_id,
storage_id: plainCreated.id,
space_id: plainCreated.space_id,
quantity: returnQuantity,
before_quantity: returnQuantity,
after_quantity: returnQuantity,
before_locked_quantity: 0,
after_locked_quantity: 0,
before_intercept_locked_quantity: 0,
after_intercept_locked_quantity: returnQuantity,
batch_no: plainCreated.batch_no,
inventory_type: 'ZP',
order_type: 'INTERCEPT_LOCK',
order_no: orderNo,
order_id: orderId,
operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''),
operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '',
remark: '拦截确认(缺行补建实物返还并拦截锁定)',
}, { transaction });
interceptReturnSummaryMap.set(Number(plainCreated.id), (interceptReturnSummaryMap.get(Number(plainCreated.id)) || 0) + returnQuantity);
continue; // 补建行已直接入账,跳过既有返还逻辑
}
const beforeQuantity = toNumber(storageRow.quantity, 0)
+ (interceptQuantityChangeMap.get(storageId) || 0);
const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0);
const beforeInterceptLockedQuantity = toNumber(storageRow.intercept_locked_quantity, 0)
+ (interceptLockedChangeMap.get(storageId) || 0);
await ctx.service.systems.storage.index.interceptReceiveQuantity(storageId, returnQuantity, {
transaction,
});
interceptQuantityChangeMap.set(storageId, (interceptQuantityChangeMap.get(storageId) || 0) + returnQuantity);
interceptLockedChangeMap.set(storageId, (interceptLockedChangeMap.get(storageId) || 0) + returnQuantity);
// 写入拦截锁定流水(实物返还并拦截锁定,记录拦截快照)
await ctx.model.StorageTransaction.create({
transaction_type: 'INBOUND',
warehouse_id: warehouseId,
store_id: storageRow.store_id,
stock_id: storageRow.stock_id,
storage_id: storageId,
space_id: storageRow.space_id,
quantity: returnQuantity,
before_quantity: beforeQuantity,
after_quantity: beforeQuantity + returnQuantity,
before_locked_quantity: beforeLockedQuantity,
after_locked_quantity: beforeLockedQuantity,
before_intercept_locked_quantity: beforeInterceptLockedQuantity,
after_intercept_locked_quantity: beforeInterceptLockedQuantity + returnQuantity,
batch_no: storageRow.batch_no,
inventory_type: storageRow.inventory_type,
order_type: 'INTERCEPT_LOCK',
order_no: orderNo,
order_id: orderId,
operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''),
operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '',
remark: '拦截确认(已拣货实物返还并拦截锁定)',
}, { transaction });
interceptReturnSummaryMap.set(storageId, (interceptReturnSummaryMap.get(storageId) || 0) + returnQuantity);
// fin 记录(已拣货):返还实物数量,锁定已在拣货完成时扣减,不再重复扣除
for (const [ storageId, returnQuantity ] of finStorageQuantityMap.entries()) {
if (returnQuantity <= 0) {
continue;
}
for (const [ storageId, quantity ] of interceptUnlockSummaryMap.entries()) {
storageUnlockSummary.push({ storage_id: storageId, unlocked_quantity: quantity });
}
for (const [ storageId, quantity ] of interceptReturnSummaryMap.entries()) {
storageReturnSummary.push({ storage_id: storageId, returned_quantity: quantity });
}
} else {
// ── 普通取消模式:解除锁定/返还实物,回到可用数量(既有行为不变) ──
// pending 记录:解除锁定,实物库存不动
for (const [ storageId, quantity ] of pendingStorageQuantityMap.entries()) {
if (quantity <= 0) {
continue;
}
const storageRow = storageMap.get(storageId);
if (!storageRow) {
throw new Error(`库存记录不存在: ${storageId}`);
}
const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0);
const beforeInterceptLockedQuantity = toNumber(storageRow.intercept_locked_quantity, 0);
await ctx.service.systems.storage.index.unlockQuantity(storageId, quantity, {
transaction,
});
// 写入储位解锁流水
await ctx.model.StorageTransaction.create({
transaction_type: 'UNLOCK',
warehouse_id: warehouseId,
store_id: storageRow.store_id,
stock_id: storageRow.stock_id,
storage_id: storageId,
space_id: storageRow.space_id,
quantity,
before_quantity: storageRow.quantity,
after_quantity: storageRow.quantity,
before_locked_quantity: beforeLockedQuantity,
after_locked_quantity: beforeLockedQuantity - quantity,
before_intercept_locked_quantity: beforeInterceptLockedQuantity,
after_intercept_locked_quantity: beforeInterceptLockedQuantity,
batch_no: storageRow.batch_no,
inventory_type: storageRow.inventory_type,
order_type: 'PICKING_UNLOCK',
order_no: 'CANCEL_BATCH',
order_id: 0,
operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''),
operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '',
remark: '取消分配储位(库存解锁)',
}, { transaction });
storageUnlockSummary.push({
storage_id: storageId,
unlocked_quantity: quantity,
});
const storageRow = storageMap.get(storageId);
if (!storageRow) {
throw new Error(`库存记录不存在: ${storageId}`);
}
// fin 记录(已拣货):返还实物数量,锁定已在拣货完成时扣减,不再重复扣除
for (const [ storageId, returnQuantity ] of finStorageQuantityMap.entries()) {
if (returnQuantity <= 0) {
continue;
}
const beforeQuantity = toNumber(storageRow.quantity, 0);
const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0);
const storageRow = storageMap.get(storageId);
if (!storageRow) {
throw new Error(`库存记录不存在: ${storageId}`);
}
await ctx.service.systems.storage.index.updateQuantity(storageId, returnQuantity, 0, {
transaction,
});
const beforeQuantity = toNumber(storageRow.quantity, 0);
const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0);
const beforeInterceptLockedQuantity = toNumber(storageRow.intercept_locked_quantity, 0);
// 写入库存返还流水(实物数量增加,锁定不变)
await ctx.model.StorageTransaction.create({
transaction_type: 'INBOUND',
warehouse_id: warehouseId,
store_id: storageRow.store_id,
stock_id: storageRow.stock_id,
storage_id: storageId,
space_id: storageRow.space_id,
quantity: returnQuantity,
before_quantity: beforeQuantity,
after_quantity: beforeQuantity + returnQuantity,
before_locked_quantity: beforeLockedQuantity,
after_locked_quantity: beforeLockedQuantity,
batch_no: storageRow.batch_no,
inventory_type: storageRow.inventory_type,
order_type: 'PICK_RETURN',
order_no: 'CANCEL_BATCH',
order_id: 0,
operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''),
operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '',
remark: '取消分配储位(已拣货返还库存)',
}, { transaction });
await ctx.service.systems.storage.index.updateQuantity(storageId, returnQuantity, 0, {
transaction,
});
// 写入库存返还流水(实物数量增加,锁定不变)
await ctx.model.StorageTransaction.create({
transaction_type: 'INBOUND',
warehouse_id: warehouseId,
store_id: storageRow.store_id,
stock_id: storageRow.stock_id,
storage_id: storageId,
space_id: storageRow.space_id,
quantity: returnQuantity,
before_quantity: beforeQuantity,
after_quantity: beforeQuantity + returnQuantity,
before_locked_quantity: beforeLockedQuantity,
after_locked_quantity: beforeLockedQuantity,
before_intercept_locked_quantity: beforeInterceptLockedQuantity,
after_intercept_locked_quantity: beforeInterceptLockedQuantity,
batch_no: storageRow.batch_no,
inventory_type: storageRow.inventory_type,
order_type: 'PICK_RETURN',
order_no: 'CANCEL_BATCH',
order_id: 0,
operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''),
operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '',
remark: '取消分配储位(已拣货返还库存)',
}, { transaction });
storageReturnSummary.push({
storage_id: storageId,
returned_quantity: returnQuantity,
});
}
storageReturnSummary.push({
storage_id: storageId,
returned_quantity: returnQuantity,
});
}
const cancelPickingIds = [];
@ -2884,237 +2561,6 @@ class OrderStorageAllocationService extends MainService {
throw error;
}
}
/**
* 按订单 ID 释放拦截锁定数量(拦截锁回落到可用数量)。
*
* 依据 wms_storage_transaction 中 order_type='INTERCEPT_LOCK' 与
* order_type='INTERCEPT_UNLOCK' 的流水按 (storage_id, order_id) 汇总净拦截量,
* 净量大于 0 时逐库存行调用 interceptUnlockQuantity 释放拦截锁:
* `intercept_locked_quantity -q`、`available_quantity +q`,`quantity` 与 `locked_quantity` 不变,
* 并写入 INTERCEPT_UNLOCK 流水记录拦截快照(order_id 与订单对应)。
* 释放量与流水均以订单维度记录,重复调用幂等(净量归零后不再释放)。
*
* 使用场景:
* - 批量解除拦截(batchUnintercept 后台任务);
* - 退货登记完成(return_received.create)。
*
* @param {Array<number|string>} orderIds 订单 ID 数组。
* @param {Object} [options={}] 执行上下文参数。
* @param {number|string} [options.warehouseId] 仓库 ID,缺省取当前用户仓库上下文。
* @param {Object} [options.transaction] 外部事务对象,缺省内部创建事务。
* @param {string} [options.scene='INTERCEPT_UNLOCK'] 释放场景标识(写入流水 order_no)。
* @param {string} [options.remark='解除拦截(拦截锁回落到可用数量)'] 流水备注。
* @param {string} [options.operatorId] 操作人工号 ID,缺省取当前用户上下文。
* @param {string} [options.operatorName] 操作人名称,缺省取当前用户上下文。
* @return {Promise<Object>} 释放结果,含 order_ids、released_quantity、storage_release_summary。
*/
async releaseInterceptLocksByOrderIds(orderIds = [], options = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const normalizedOrderIds = Array.from(new Set(
(Array.isArray(orderIds) ? orderIds : [])
.map(orderId => toNumber(orderId, 0))
.filter(orderId => orderId > 0)
));
if (normalizedOrderIds.length === 0) {
return {
order_ids: [],
released_quantity: 0,
storage_release_summary: [],
};
}
const warehouseId = toNumber(options.warehouseId, 0) > 0
? toNumber(options.warehouseId, 0)
: toNumber(ctx.user?.store_id ?? ctx.user?.warehouse_id, 0);
if (warehouseId <= 0) {
throw new Error('缺少仓库上下文');
}
const scene = String(options.scene || 'INTERCEPT_UNLOCK').trim() || 'INTERCEPT_UNLOCK';
const remark = String(options.remark || '解除拦截(拦截锁回落到可用数量)').trim();
const operatorId = String(options.operatorId ?? ctx.user?.employees_id ?? ctx.user?.id ?? '');
const operatorName = String(
options.operatorName ?? ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? ''
);
const externalTransaction = options.transaction || null;
const transaction = externalTransaction || await ctx.model.transaction();
try {
const groupAttributes = [
'storage_id',
'order_id',
[ app.Sequelize.fn('SUM', app.Sequelize.col('quantity')), 'total_quantity' ],
];
// 汇总本批次订单的拦截锁定流水(按 storage_id + order_id 分组)
const lockRows = await ctx.model.StorageTransaction.findAll({
attributes: groupAttributes,
where: {
warehouse_id: warehouseId,
order_type: 'INTERCEPT_LOCK',
order_id: { [Op.in]: normalizedOrderIds },
},
group: [ 'storage_id', 'order_id' ],
transaction,
raw: true,
});
const netQuantityMap = new Map();
for (const row of Array.isArray(lockRows) ? lockRows : []) {
const pairKey = `${toNumber(row.order_id, 0)}:${toNumber(row.storage_id, 0)}`;
netQuantityMap.set(pairKey, toNumber(row.total_quantity, 0));
}
if (netQuantityMap.size === 0) {
if (!externalTransaction) {
await transaction.commit();
}
return {
order_ids: normalizedOrderIds,
released_quantity: 0,
storage_release_summary: [],
};
}
const storageIdSet = new Set();
for (const pairKey of netQuantityMap.keys()) {
const storageId = toNumber(pairKey.split(':')[1], 0);
if (storageId > 0) {
storageIdSet.add(storageId);
}
}
// 汇总已释放的拦截解锁流水(同一订单维度),净量 = 锁定 - 已释放,保证幂等
const unlockRows = await ctx.model.StorageTransaction.findAll({
attributes: groupAttributes,
where: {
warehouse_id: warehouseId,
order_type: 'INTERCEPT_UNLOCK',
order_id: { [Op.in]: normalizedOrderIds },
storage_id: { [Op.in]: Array.from(storageIdSet) },
},
group: [ 'storage_id', 'order_id' ],
transaction,
raw: true,
});
for (const row of Array.isArray(unlockRows) ? unlockRows : []) {
const pairKey = `${toNumber(row.order_id, 0)}:${toNumber(row.storage_id, 0)}`;
netQuantityMap.set(pairKey, (netQuantityMap.get(pairKey) || 0) - toNumber(row.total_quantity, 0));
}
// 行锁查询库存,并维护每库存行的剩余可释放拦截量,防止多订单同库存行超释
const storageRows = await ctx.model.Storage.findAll({
where: {
id: { [Op.in]: Array.from(storageIdSet) },
warehouse_id: warehouseId,
},
transaction,
lock: transaction.LOCK.UPDATE,
raw: true,
});
const storageMap = new Map();
const remainingInterceptByStorage = new Map();
for (const row of Array.isArray(storageRows) ? storageRows : []) {
const storageId = toNumber(row.id, 0);
storageMap.set(storageId, row);
remainingInterceptByStorage.set(storageId, toNumber(row.intercept_locked_quantity, 0));
}
const storageReleaseSummary = [];
let releasedQuantity = 0;
// 已释放拦截量(按 storage 累计),保证同库存行多订单时流水 before/after 快照准确
const releasedInterceptByStorage = new Map();
for (const [ pairKey, netQuantity ] of netQuantityMap.entries()) {
if (netQuantity <= 0) {
continue;
}
const pairParts = pairKey.split(':');
const orderId = toNumber(pairParts[0], 0);
const storageId = toNumber(pairParts[1], 0);
if (orderId <= 0 || storageId <= 0) {
continue;
}
const storageRow = storageMap.get(storageId);
if (!storageRow) {
continue;
}
const storageRemaining = remainingInterceptByStorage.get(storageId) || 0;
const releaseQuantity = Math.min(netQuantity, storageRemaining);
if (releaseQuantity <= 0) {
continue;
}
const beforeQuantity = toNumber(storageRow.quantity, 0);
const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0);
const beforeInterceptLockedQuantity = toNumber(storageRow.intercept_locked_quantity, 0)
- (releasedInterceptByStorage.get(storageId) || 0);
await ctx.service.systems.storage.index.interceptUnlockQuantity(storageId, releaseQuantity, {
transaction,
});
// 写入拦截解锁流水(记录拦截快照,order_id 与订单对应)
await ctx.model.StorageTransaction.create({
transaction_type: 'UNLOCK',
warehouse_id: warehouseId,
store_id: storageRow.store_id,
stock_id: storageRow.stock_id,
storage_id: storageId,
space_id: storageRow.space_id,
quantity: releaseQuantity,
before_quantity: beforeQuantity,
after_quantity: beforeQuantity,
before_locked_quantity: beforeLockedQuantity,
after_locked_quantity: beforeLockedQuantity,
before_intercept_locked_quantity: beforeInterceptLockedQuantity,
after_intercept_locked_quantity: beforeInterceptLockedQuantity - releaseQuantity,
batch_no: storageRow.batch_no,
inventory_type: storageRow.inventory_type,
order_type: 'INTERCEPT_UNLOCK',
order_no: scene,
order_id: orderId,
operator_id: operatorId,
operator_name: operatorName,
remark,
}, { transaction });
remainingInterceptByStorage.set(storageId, storageRemaining - releaseQuantity);
releasedInterceptByStorage.set(storageId, (releasedInterceptByStorage.get(storageId) || 0) + releaseQuantity);
releasedQuantity += releaseQuantity;
storageReleaseSummary.push({
storage_id: storageId,
order_id: orderId,
released_quantity: releaseQuantity,
});
}
if (!externalTransaction) {
await transaction.commit();
}
return {
order_ids: normalizedOrderIds,
released_quantity: releasedQuantity,
storage_release_summary: storageReleaseSummary,
};
} catch (error) {
if (!externalTransaction) {
await transaction.rollback();
}
throw error;
}
}
/**
* 分拣缺货补货需求计算。
*

View File

@ -35,7 +35,7 @@ class PackTaskAutoFinishService extends MainService {
status: { [Op.lt]: PACK_TASK_FINISHED_STATUS },
start_time: { [Op.ne]: null },
},
attributes: [ 'id', 'warehouse_id', 'pack_mode', 'start_time', 'order_id', 'wave_id' ],
attributes: [ 'id', 'warehouse_id', 'pack_mode', 'start_time' ],
});
if (tasks.length === 0) {
@ -96,19 +96,6 @@ class PackTaskAutoFinishService extends MainService {
status: PACK_TASK_FINISHED_STATUS,
});
// 同步关联订单打包状态(与 workbench._finishPack 语义一致,避免任务已完成但订单停留打包中)
const workbenchService = ctx.service && ctx.service.systems && ctx.service.systems.workbench;
if (workbenchService && typeof workbenchService._updateOrderPackStatus === 'function') {
const isGroupTask = Number(task.pack_mode) === PACK_MODE_GROUP;
const taskWaveId = isGroupTask ? Number(task.wave_id || 0) : 0;
await workbenchService._updateOrderPackStatus(warehouseId, {
orderId: Number(task.order_id || 0),
waveId: taskWaveId,
packStatus: PACK_TASK_FINISHED_STATUS,
caller: 'PackTaskAutoFinish',
});
}
autoFinished += 1;
ctx.logger.info(

View File

@ -1387,8 +1387,8 @@ class PickSystemService extends Service {
picking_view: pickingView,
};
// 团购模式(小波次 pick_mode=1 / 大波次 pick_mode=5)不需要返回拣货明细,减少带宽浪费
if (pickMode !== 1 && pickMode !== 5) {
// 团购小波次不需要返回拣货明细,减少带宽浪费
if (pickMode !== 1) {
result.picking_details = pickingDetails;
}

View File

@ -927,55 +927,19 @@ class ReportDeliveryService extends Service {
return `【${reportName}】${bizDate} 数据报表已生成,点击查看:${fileUrl}`;
}
/**
* 解析计划配置的通知群(notify_group_ids → 有效群行)。
* 过滤口径与 sendNotifyIfConfigured 一致:is_blocked=0、软删自动排除、仓库维度一致。
* @param {Object} options 入参
* @param {Object} options.plan 投递计划
* @param {number} options.warehouseId 仓库ID
* @return {Promise<Array<{id: number, group_id: string, group_name: string, ext_data: Object|null}>>}
* 有效群行列表(未配置群或全部被过滤时返回空数组)
* @throws {Error} 站内信群模型不可用时抛出
*/
async resolveNotifyGroups({ plan, warehouseId }) {
const { ctx } = this;
const groupIds = this.readJsonArray(plan && plan.notify_group_ids) || [];
if (groupIds.length === 0) {
return [];
}
const inboxGroupModel = ctx.model && ctx.model.InboxGroup;
if (!inboxGroupModel || typeof inboxGroupModel.findAll !== 'function') {
throw new Error('站内信群模型 InboxGroup 不可用,无法解析通知群');
}
const { Op } = ctx.app.Sequelize;
const rows = await inboxGroupModel.findAll({
where: {
id: { [Op.in]: groupIds },
warehouse_id: Number(warehouseId) || 0,
is_blocked: 0,
},
attributes: [ 'id', 'group_id', 'group_name', 'ext_data' ],
raw: true,
});
return Array.isArray(rows) ? rows : [];
}
/**
* 按渠道投递(渠道已收敛,仅支持 inbox 站内信群推送)。
*
* 规则:
* 1. 历史计划残留 wecom/link 等已弃用渠道时,按 inbox 兜底执行并记录 warn 日志
* (不直接抛错:避免历史计划在 failed 退避循环中耗尽重试次数后永久卡死);
* 2. 群路由(缺陷 G1 修复):报表文件消息只投递到计划配置的通知群(notify_group_ids),
* 不再投递到任意「货主默认群」,避免未配置投递的群收到推送;
* 未配置通知群的历史计划保持旧行为,回退投递到货主默认站内信群(group_type=store);
* 3. 推送失败(success=false 或消息记录回写 push_status=3)时,立即复用
* 2. 推送失败(success=false 或消息记录回写 push_status=3)时,立即复用
* ctx.service.inbox.message.retry 重推一次(重置 push_status=0 异步重推,
* ext_id 幂等复用同一条消息记录,不重复写);
* 4. 重推仍失败(retry 自身抛错)时向上抛错,交由上层 failed 退避循环
* 3. 重推仍失败(retry 自身抛错)时向上抛错,交由上层 failed 退避循环
* (MAX_RETRY=3,退避 = retry_count × 60s);
* 5. 完成后按计划配置附带发送文本通知(与投递渠道独立);
* 6. 幂等键含货主维度(report:{store_id}:{report_definition_id}:{biz_date}:{time_point}),
* 4. 完成后按计划配置附带发送文本通知(与投递渠道独立);
* 5. 幂等键含货主维度(report:{store_id}:{report_definition_id}:{biz_date}:{time_point}),
* 不同货主的投递消息互不复用。
*
* @param {Object} options 入参
@ -1005,102 +969,84 @@ class ReportDeliveryService extends Service {
);
}
// inbox:站内信群推送(唯一渠道)。
// 群路由(缺陷 G1 修复):报表文件消息只投递到计划配置的通知群,不再投递到任意「货主默认群」;
// 未配置通知群的历史计划保持旧行为,回退到货主默认站内信群(group_type=store,取最早一条)。
const configuredGroupIds = this.readJsonArray(plan && plan.notify_group_ids) || [];
let targetGroups;
if (configuredGroupIds.length > 0) {
targetGroups = await this.resolveNotifyGroups({ plan, warehouseId });
if (targetGroups.length === 0) {
throw new Error(`货主 ${storeId} 配置的通知群不可达(不存在、已删除、被屏蔽或仓库不一致),无法投递`);
}
} else {
const inboxGroupModel = ctx.model && ctx.model.InboxGroup;
if (!inboxGroupModel || typeof inboxGroupModel.findOne !== 'function') {
throw new Error('站内信群模型 InboxGroup 不可用');
}
const groupRow = await inboxGroupModel.findOne({
where: {
warehouse_id: warehouseId,
store_id: storeId,
group_type: 'store',
is_blocked: 0,
},
attributes: [ 'group_id', 'group_name', 'ext_data' ],
order: [[ 'id', 'ASC' ]],
raw: true,
});
if (!groupRow || !groupRow.group_id) {
throw new Error(`货主 ${storeId} 未配置站内信群,无法投递`);
}
targetGroups = [ groupRow ];
// inbox:站内信群推送(唯一渠道)
const inboxGroupModel = ctx.model && ctx.model.InboxGroup;
if (!inboxGroupModel || typeof inboxGroupModel.findOne !== 'function') {
throw new Error('站内信群模型 InboxGroup 不可用');
}
const groupRow = await inboxGroupModel.findOne({
where: {
warehouse_id: warehouseId,
store_id: storeId,
group_type: 'store',
is_blocked: 0,
},
attributes: [ 'group_id', 'group_name', 'ext_data' ],
order: [[ 'id', 'ASC' ]],
raw: true,
});
if (!groupRow || !groupRow.group_id) {
throw new Error(`货主 ${storeId} 未配置站内信群,无法投递`);
}
const warehouseNotify = ctx.service && ctx.service.systems && ctx.service.systems.warehouseNotify;
if (!warehouseNotify || typeof warehouseNotify.pushSystemMessage !== 'function') {
throw new Error('通知推送服务 warehouseNotify.pushSystemMessage 不可用');
}
const pushResults = [];
for (const groupRow of targetGroups) {
const pushResult = await warehouseNotify.pushSystemMessage({
warehouseId,
storeId,
group: {
group_id: groupRow.group_id,
group_name: groupRow.group_name || '货主群',
ext_data: groupRow.ext_data || null,
},
content: this.buildMessageContent(definition, bizDate, fileUrl),
extId: idempotentKey,
extData: {
report_definition_id: reportDefinitionId,
biz_date: bizDate,
time_point: timePoint,
file_url: fileUrl,
},
});
pushResults.push(pushResult);
}
const pushResult = await warehouseNotify.pushSystemMessage({
warehouseId,
storeId,
group: {
group_id: groupRow.group_id,
group_name: groupRow.group_name || '货主群',
ext_data: groupRow.ext_data || null,
},
content: this.buildMessageContent(definition, bizDate, fileUrl),
extId: idempotentKey,
extData: {
report_definition_id: reportDefinitionId,
biz_date: bizDate,
time_point: timePoint,
file_url: fileUrl,
},
});
// 推送失败判定(双保险):success=false;或消息记录回写 push_status=3(推送链路异常时兜底识别)
const retryService = ctx.service && ctx.service.inbox && ctx.service.inbox.message;
for (const pushResult of pushResults) {
const messageId = (pushResult && Number(pushResult.messageId)) || 0;
let pushFailed = !pushResult || pushResult.success === false;
if (!pushFailed && messageId > 0) {
const InboxMessage = ctx.model && ctx.model.InboxMessage;
if (InboxMessage && typeof InboxMessage.findOne === 'function') {
try {
const row = await InboxMessage.findOne({
where: { id: messageId },
attributes: [ 'push_status' ],
raw: true,
});
if (row && Number(row.push_status) === 3) {
pushFailed = true;
}
} catch (statusErr) {
ctx.logger.warn(`[reportDelivery] 读取消息推送状态失败: ${statusErr.message}`);
const messageId = (pushResult && Number(pushResult.messageId)) || 0;
let pushFailed = !pushResult || pushResult.success === false;
if (!pushFailed && messageId > 0) {
const InboxMessage = ctx.model && ctx.model.InboxMessage;
if (InboxMessage && typeof InboxMessage.findOne === 'function') {
try {
const row = await InboxMessage.findOne({
where: { id: messageId },
attributes: [ 'push_status' ],
raw: true,
});
if (row && Number(row.push_status) === 3) {
pushFailed = true;
}
} catch (statusErr) {
ctx.logger.warn(`[reportDelivery] 读取消息推送状态失败: ${statusErr.message}`);
}
}
}
if (pushFailed) {
const reason = (pushResult && (pushResult.reason || pushResult.error)) || '站内信推送失败';
// 立即重推一次:复用 inbox.message.retry(重置 push_status=0 并异步重推;ext_id 幂等复用
// 同一条消息记录,不重复写)。retry 自身抛错视为重推失败,向上抛出进入 failed 退避循环
if (messageId > 0 && retryService && typeof retryService.retry === 'function') {
try {
await retryService.retry({ warehouseId, id: messageId });
ctx.logger.warn(`[reportDelivery] 站内信推送失败已受理立即重推(message_id=${messageId}): ${reason}`);
} catch (retryErr) {
const retryReason = retryErr && retryErr.message ? retryErr.message : `${retryErr}`;
throw new Error(`站内信推送失败且重推失败: ${reason} / ${retryReason}`);
}
} else {
throw new Error(reason);
if (pushFailed) {
const reason = (pushResult && (pushResult.reason || pushResult.error)) || '站内信推送失败';
// 立即重推一次:复用 inbox.message.retry(重置 push_status=0 并异步重推;ext_id 幂等复用
// 同一条消息记录,不重复写)。retry 自身抛错视为重推失败,向上抛出进入 failed 退避循环
const retryService = ctx.service && ctx.service.inbox && ctx.service.inbox.message;
if (messageId > 0 && retryService && typeof retryService.retry === 'function') {
try {
await retryService.retry({ warehouseId, id: messageId });
ctx.logger.warn(`[reportDelivery] 站内信推送失败已受理立即重推(message_id=${messageId}): ${reason}`);
} catch (retryErr) {
const retryReason = retryErr && retryErr.message ? retryErr.message : `${retryErr}`;
throw new Error(`站内信推送失败且重推失败: ${reason} / ${retryReason}`);
}
} else {
throw new Error(reason);
}
}
@ -1164,11 +1110,25 @@ class ReportDeliveryService extends Service {
bizDate,
});
// 目标解析:内部群ID → 外部群信息(is_blocked=0、软删排除、仓库维度一致),
// 复用 resolveNotifyGroups 与渠道投递保持同一解析口径
const groups = groupIds.length > 0
? await this.resolveNotifyGroups({ plan, warehouseId })
: [];
// 目标解析:内部群ID → 外部群信息(is_blocked=0、软删排除、仓库维度一致)
let groups = [];
if (groupIds.length > 0) {
const inboxGroupModel = ctx.model && ctx.model.InboxGroup;
if (!inboxGroupModel || typeof inboxGroupModel.findAll !== 'function') {
throw new Error('站内信群模型 InboxGroup 不可用,无法发送文本通知');
}
const { Op } = ctx.app.Sequelize;
const rows = await inboxGroupModel.findAll({
where: {
id: { [Op.in]: groupIds },
warehouse_id: Number(warehouseId) || 0,
is_blocked: 0,
},
attributes: [ 'id', 'group_id', 'group_name', 'ext_data' ],
raw: true,
});
groups = Array.isArray(rows) ? rows : [];
}
if (groups.length === 0 && memberIds.length === 0) {
throw new Error('文本通知目标不可达(通知群不存在、已删除、被屏蔽或未选择群/成员)');

View File

@ -1,16 +1,7 @@
'use strict';
const crypto = require('node:crypto');
const fs = require('node:fs');
const fsp = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const ExcelJS = require('exceljs');
const Service = require('egg').Service;
/** 退回收到导出分页拉取大小 */
const RETURN_RECEIVED_EXPORT_PAGE_SIZE = 500;
/**
* 退回收到模块业务逻辑层。
* 负责 wms_return_received 的增删查,以及原单反查、货主备注、30 日幂等等核心操作。
@ -31,8 +22,7 @@ class ReturnReceivedService extends Service {
/**
* 扫码登记退回包裹(30 日内同仓库同单号只写一次,以第一次为准)。
* 反查原运单判定是否原单退回,命中则回填关联字段并同步标记 is_back='Y',
* 并释放订单对应的拦截锁定库存(intercept_locked_quantity 回落到可用数量)。
* 反查原运单判定是否原单退回,命中则回填关联字段并同步标记 is_back='Y'。
*
* @param {Object} params 登记参数。
* @param {string} params.waybill_code 退回收件运单号。
@ -166,8 +156,6 @@ class ReturnReceivedService extends Service {
await this._handleInterceptAfterSale(waybillCode, warehouseId, scannerId, scannerName);
if (orderId) {
await this._updateOrderInterceptStatus(orderId, warehouseId, scannerId, scannerName);
// 注意:退货登记不释放拦截锁定数量——拦截锁的回落由退货货物后续入库处理
// (入库平账/差异对账链路)统一接管,避免登记环节直接改动库存口径。
}
}
@ -483,229 +471,6 @@ class ReturnReceivedService extends Service {
};
}
/**
* 导出退回收到登记列表(单 Sheet Excel,异步任务模式,与 returnUnpack.export 口径一致)。
* 复用 list 的 where/sort 语义;仓库隔离由方法层注入 warehouse_id,此处再强制兜底;
* 分页拉取主表全量数据后批量解析货主备注,流式生成 Excel 并上传 COS。
*
* @param {Object} options 导出选项。
* @param {Object} [options.where] 标准化 where 条件(与 list 一致)。
* @param {Object} [options.sort] 排序参数(与 list 一致)。
* @param {number} [options.warehouseId] 仓库ID(由方法层从上下文注入)。
* @param {Function} [options.onProgress] 进度回调。
* @return {Promise<Object>} 上传结果与统计信息(含 filename/fileKey/url/cdnUrl/cosUrl/current_count/total_count)。
*/
async exportList(options = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const safeOptions = options && typeof options === 'object' && !Array.isArray(options) ? options : {};
const where = safeOptions.where && typeof safeOptions.where === 'object' ? { ...safeOptions.where } : {};
const sort = safeOptions.sort && typeof safeOptions.sort === 'object' ? { ...safeOptions.sort } : {};
const warehouseId = Number(safeOptions.warehouseId || 0);
const progressHandler = typeof safeOptions.onProgress === 'function'
? safeOptions.onProgress
: async () => {};
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
throw this.createBusinessError('缺少仓库上下文', 400);
}
// 复用 list 的 where/sort 语义,并强制仓库隔离(服务端注入,前端无需传 warehouse_id)
const queryWhere = this._buildListWhere(where, Op);
queryWhere.warehouse_id = warehouseId;
const order = this._buildListOrder(sort);
const totalCount = await ctx.model.ReturnReceived.count({ where: queryWhere });
await progressHandler({
status: 'running',
progress: totalCount > 0 ? 10 : 85,
currentCount: 0,
totalCount,
message: totalCount > 0 ? `已命中 ${totalCount} 条登记记录,开始导出` : '未命中数据,开始生成空文件',
});
// ---- 分页拉取主表全量数据(复用 list 的 pageSize 口径,避免单次内存溢出)----
const pageSize = RETURN_RECEIVED_EXPORT_PAGE_SIZE;
const totalPages = Math.max(1, Math.ceil(totalCount / pageSize));
const allRows = [];
for (let page = 1; page <= totalPages; page += 1) {
if (allRows.length >= totalCount) {
break;
}
const { rows } = await ctx.model.ReturnReceived.findAndCountAll({
where: queryWhere,
order,
offset: (page - 1) * pageSize,
limit: pageSize,
raw: true,
});
for (const row of rows) {
allRows.push(row);
}
await progressHandler({
status: 'running',
progress: Math.min(55, 10 + Math.round((allRows.length / Math.max(totalCount, 1)) * 45)),
currentCount: allRows.length,
totalCount,
message: `正在拉取登记列表,已完成 ${allRows.length}/${totalCount}`,
});
// 每页之间稍作让渡,避免长时间阻塞
await new Promise(resolve => setImmediate(resolve));
}
// ---- 批量解析货主备注(避免逐行查询)----
const storeRemarkMap = await this._resolveStoreRemarkMap(allRows, warehouseId, Op);
const enrichedRows = [];
for (const row of allRows) {
enrichedRows.push(await this._enrichReturn(row, storeRemarkMap));
}
await progressHandler({
status: 'running',
progress: 60,
currentCount: allRows.length,
totalCount,
message: '正在生成 Excel 文件...',
});
const exportResult = await this._generateExportExcel(enrichedRows, warehouseId);
await progressHandler({
status: 'success',
progress: 100,
currentCount: allRows.length,
totalCount,
message: '导出任务完成',
result: exportResult,
});
return {
...exportResult,
current_count: allRows.length,
total_count: totalCount,
};
}
/**
* 生成退回收到导出 Excel(单 Sheet)并上传 COS,返回下载信息。
* 流式写入临时文件后通过 upload.uploadFile 上传,上传结果落库通知。
*
* @param {Array<Object>} rows 已组装展示字段的登记记录行。
* @param {number} warehouseId 仓库ID。
* @return {Promise<Object>} { filename, fileKey, url, cdnUrl, cosUrl }。
*/
async _generateExportExcel(rows = [], warehouseId) {
const { ctx, app } = this;
const normalizeCellValue = value => {
if (value === null || value === undefined) return '';
if (value instanceof Date) return app.formatDate ? app.formatDate(value) : value.toISOString();
return value;
};
const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-return-received-export-'));
const now = new Date();
const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`;
const filename = `退回收到导出_${dateToken}.xlsx`;
const filePath = path.join(tempDir, filename);
const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({
filename: filePath,
useStyles: false,
useSharedStrings: false,
});
try {
const worksheet = workbook.addWorksheet('退回收到登记列表');
worksheet.columns = [
{ header: '运单号', key: 'waybill_code', width: 22 },
{ header: '扫描日期', key: 'scan_date', width: 14 },
{ header: '扫描人员', key: 'scanner_name', width: 14 },
{ header: '是否原单退回', key: 'is_original_return', width: 12 },
{ header: '订单ID', key: 'order_id', width: 14 },
{ header: '货主备注', key: 'store_remark', width: 20 },
{ header: '备注', key: 'remark', width: 30 },
{ header: '登记时间', key: 'created_at', width: 20 },
{ header: '更新时间', key: 'updated_at', width: 20 },
];
for (const row of rows) {
worksheet.addRow({
waybill_code: normalizeCellValue(row.waybill_code),
scan_date: normalizeCellValue(row.scan_date),
scanner_name: normalizeCellValue(row.scanner_name),
is_original_return: row.is_original_return ? '是' : '否',
order_id: row.order_id || '',
store_remark: normalizeCellValue(row.store_remark),
remark: normalizeCellValue(row.remark),
created_at: normalizeCellValue(row.created_at),
updated_at: normalizeCellValue(row.updated_at),
}).commit();
}
worksheet.commit();
await workbook.commit();
// ---- 上传文件(与 returnUnpack 导出口径一致)----
const uploadService = ctx?.service?.systems?.upload;
if (!uploadService || typeof uploadService.uploadFile !== 'function') {
throw new Error('上传服务不可用');
}
const stat = await fsp.stat(filePath);
const randomToken = crypto.randomBytes(6).toString('hex');
const uploadKey = `exports/return_received/${warehouseId}/${Date.now()}_${randomToken}.xlsx`;
const uploadStream = fs.createReadStream(filePath);
uploadStream.filename = filename;
uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
uploadStream.fileSize = stat.size;
const uploadResult = await uploadService.uploadFile(uploadStream, {
key: uploadKey,
category: 'document',
mimetype: 'xls,xlsx,csv',
});
let fileRecord = null;
if (typeof uploadService.uploadSuccessNotify === 'function') {
fileRecord = await uploadService.uploadSuccessNotify({
url: uploadResult.fileName,
fileKey: uploadResult.fileName,
fileName: filename,
fileType: 'document',
mimeType: uploadStream.mimeType,
fileSize: stat.size,
userId: ctx.userId,
description: `退回收到登记导出(仓库${warehouseId}),共${rows.length}条登记记录`,
});
}
// 优先取 uploadFile 返回的完整 URL,其次取 uploadSuccessNotify 落库记录(兼容 data 包裹),最后才回退 COS key
const safeUploadResult = typeof uploadResult === 'object' && uploadResult !== null ? uploadResult : {};
const resolvedFileRecord = (fileRecord && (fileRecord.data || fileRecord)) || null;
const fileUrlFromRecord = resolvedFileRecord
? (resolvedFileRecord.file_url || resolvedFileRecord.fileUrl || resolvedFileRecord.url || '')
: '';
const uploadResultUrl = safeUploadResult.url || safeUploadResult.cdnUrl || safeUploadResult.cosUrl || '';
return {
filename,
fileKey: safeUploadResult.fileName || uploadKey,
url: uploadResultUrl || fileUrlFromRecord || safeUploadResult.fileName || uploadKey,
cdnUrl: safeUploadResult.cdnUrl || safeUploadResult.url || '',
cosUrl: safeUploadResult.cosUrl || '',
};
} catch (error) {
const workbookStream = workbook.stream;
if (workbookStream && typeof workbookStream.destroy === 'function') {
workbookStream.destroy();
}
throw error;
} finally {
// 清理临时文件(不存在或删除失败均忽略)
try { await fsp.rm(tempDir, { recursive: true, force: true }); } catch (err) { /* ignore */ }
}
}
/**
* 查询单条退回收到登记详情(含原运单与货主合约备注)。
*
@ -792,20 +557,13 @@ class ReturnReceivedService extends Service {
* 组装登记记录展示字段(是否原单退回、货主备注、时间格式化)。
*
* @param {Object} row 登记记录原始数据。
* @param {Map<string, string>} [remarkMap] 预解析的货主备注映射(key=store_id:warehouse_id),
* 传入时跳过逐行查询直接取映射值;不传时逐行查询。
* @return {Promise<Object>} 组装后的记录。
*/
async _enrichReturn(row, remarkMap = null) {
async _enrichReturn(row) {
const { app } = this;
const record = { ...row };
record.is_original_return = Boolean(record.order_express_id);
if (remarkMap instanceof Map) {
const remarkKey = `${Number(record.store_id || 0)}:${Number(record.warehouse_id || 0)}`;
record.store_remark = remarkMap.get(remarkKey) || '';
} else {
record.store_remark = await this._resolveStoreRemark(record);
}
record.store_remark = await this._resolveStoreRemark(record);
// 时间格式化(与 afterSale._formatAfterSaleRow 一致,直接覆盖为本地时间字符串)
record.scan_date = record.scan_date ? app.formatDate(record.scan_date, 'YYYY-MM-DD') : null;
record.created_at = record.created_at ? app.formatDate(record.created_at) : null;
@ -839,44 +597,6 @@ class ReturnReceivedService extends Service {
}
}
/**
* 批量解析货主备注映射(store_id:warehouse_id → wms_store_warehouse.store_remask)。
* 导出时一次查询全部货主合约,避免逐行查询。
*
* @param {Array<Object>} rows 登记记录行数组。
* @param {number} warehouseId 仓库ID。
* @param {Object} Op Sequelize Op 对象。
* @return {Promise<Map<string, string>>} key=store_id:warehouse_id → 货主备注映射。
*/
async _resolveStoreRemarkMap(rows = [], warehouseId, Op) {
const { ctx } = this;
const normalizedWarehouseId = Number(warehouseId || 0);
const storeIds = [ ...new Set(
(Array.isArray(rows) ? rows : [])
.map(row => Number(row && row.store_id || 0))
.filter(id => Number.isInteger(id) && id > 0)
) ];
/** @type {Map<string, string>} */
const remarkMap = new Map();
if (storeIds.length === 0 || !Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
return remarkMap;
}
try {
const contracts = await ctx.model.StoreWarehouse.findAll({
where: { store_id: { [Op.in]: storeIds }, warehouse_id: normalizedWarehouseId },
attributes: [ 'store_id', 'store_remask' ],
raw: true,
});
for (const contract of contracts) {
const key = `${Number(contract.store_id)}:${normalizedWarehouseId}`;
remarkMap.set(key, contract.store_remask ? String(contract.store_remask) : '');
}
} catch (err) {
ctx.logger.warn(`[returnReceived.export] 批量解析货主备注失败: ${err.message}`);
}
return remarkMap;
}
/**
* 根据标准化 where 条件构建 Sequelize 查询条件。
*

View File

@ -212,18 +212,7 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([
type: 'flag',
default: 1,
required: false,
description: '启用后,订单创建时间早于开始自动分配时间或超过截单时间(开始时间晚于截单时间时截单时间视为次日),不再自动分配快递和储位,不再自动加团',
}),
Object.freeze({
key: 'allocate_start_time',
name: '开始自动分配时间',
type: 'string',
default: '08:00',
required: false,
maxLength: 5,
min: '00:00',
max: '23:59',
description: '开始自动分配时间,格式 HH:mm,如 08:00;早于该时间的订单与超过截单时间行为一致,不自动分配快递和储位,不自动加团;晚于截单时间时截单时间视为次日',
description: '启用后,当天订单创建时间超过截单时间,不再自动分配快递和储位,不再自动加团',
}),
Object.freeze({
key: 'cutoff_order_time',
@ -232,7 +221,7 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([
default: '18:00',
required: false,
maxLength: 5,
min: '00:00',
min: '12:00',
max: '23:59',
description: '截单时间,格式 HH:mm,如 18:00',
}),

View File

@ -673,7 +673,7 @@ class stockStoreService extends Service {
* @param {string} [meta.remark] 备注。
* @param {string} [meta.operatorId] 操作人ID。
* @param {string} [meta.operatorName] 操作人姓名。
* @return {Promise<{success: boolean, error?: string, data?: Object}>} 修改结果,失败时携带错误信息。
* @return {Promise<{success: boolean, error?: string, data?: Object}>}
*/
async updateLockedQuantity(stockId, change, currentTransaction, meta = {}) {
const { ctx, app } = this;
@ -914,21 +914,6 @@ class stockStoreService extends Service {
const afterQuantity = Number(updatedRecord.quantity) || 0;
const afterLockedQuantity = Number(updatedRecord.locked_quantity) || 0;
// 负库存回填:按 SW 非负增量冲销 GAP 补建行挂账(平账,拦截锁定回归真实数据)
if (beforeQuantity <= 0) {
const nonNegativeDelta = Math.max(0, afterQuantity) - Math.max(0, beforeQuantity);
const offsetQty = await ctx.service.systems.storage.index.offsetGapOnInbound(storage.id, inboundQty, {
transaction: currentTransaction,
maxOffset: nonNegativeDelta,
orderNo: 'STOCK_STORE_INBOUND',
operatorId: String(ctx.user?.employees_id || ctx.user?.id || ''),
operatorName: ctx.user?.employees_name || '',
});
if (offsetQty > 0) {
app.logger.info(`[入库] 负库存回填平账,冲销 GAP 挂账 ${offsetQty} 件 stockId=${storage.id}`);
}
}
await ctx.service.systems.stockTransaction.create({
transaction_type: 'INBOUND',
warehouse_id: updatedRecord.warehouse_id || ctx.user.store_id,
@ -1616,8 +1601,8 @@ class stockStoreService extends Service {
* @param {Object} sortParams - 排序参数
* @param {string} sortParams.sortField - 排序字段,默认'create_at'
* @param {string} sortParams.sortOrder - 排序方式,默认'DESC'
* @param {number} externalWarehouseId - 外部传入的仓库ID,缺省取当前用户仓库上下文
* @param {number} externalStoreId - 外部传入的货主ID,缺省不按货主过滤
* @param externalWarehouseId
* @param externalStoreId
* @return {Promise<Object>} 返回查询结果
*/
async getWarehouseStock(where, pageParams = {}, sortParams = {}, externalWarehouseId = 0, externalStoreId = 0) {
@ -3929,7 +3914,7 @@ class stockStoreService extends Service {
where: storageWhere,
attributes: [
'id', 'stock_id', 'space_id', 'batch_no', 'inventory_type',
'quantity', 'locked_quantity', 'intercept_locked_quantity', 'available_quantity',
'quantity', 'locked_quantity', 'available_quantity',
'production_date', 'expiry_date', 'inbound_time',
'inbound_order_no', 'supplier_batch_no', 'created_at',
],
@ -3968,20 +3953,16 @@ class stockStoreService extends Service {
const existing = mergedMap.get(spaceKey);
existing.quantity += Number(s.quantity) || 0;
existing.locked_quantity += Number(s.locked_quantity) || 0;
existing.intercept_locked_quantity += Number(s.intercept_locked_quantity) || 0;
existing.available_quantity = existing.quantity - existing.locked_quantity
- existing.intercept_locked_quantity;
existing.available_quantity = existing.quantity - existing.locked_quantity;
} else {
const quantity = Number(s.quantity) || 0;
const lockedQuantity = Number(s.locked_quantity) || 0;
const interceptLockedQuantity = Number(s.intercept_locked_quantity) || 0;
mergedMap.set(spaceKey, {
space_id: s.space_id,
inventory_type: s.inventory_type,
quantity,
locked_quantity: lockedQuantity,
intercept_locked_quantity: interceptLockedQuantity,
available_quantity: quantity - lockedQuantity - interceptLockedQuantity,
available_quantity: quantity - lockedQuantity,
space: s.space,
});
}
@ -4089,7 +4070,7 @@ class stockStoreService extends Service {
where: storageWhere,
attributes: [
'id', 'space_id', 'inventory_type',
'quantity', 'locked_quantity', 'intercept_locked_quantity', 'created_at',
'quantity', 'locked_quantity', 'created_at',
],
include: [{
model: app.model.LocationSpace,
@ -4118,13 +4099,10 @@ class stockStoreService extends Service {
const existing = mergedMap.get(key);
existing.quantity += Number(plain.quantity) || 0;
existing.locked_quantity += Number(plain.locked_quantity) || 0;
existing.intercept_locked_quantity += Number(plain.intercept_locked_quantity) || 0;
existing.available_quantity = existing.quantity - existing.locked_quantity
- existing.intercept_locked_quantity;
existing.available_quantity = existing.quantity - existing.locked_quantity;
} else {
const quantity = Number(plain.quantity) || 0;
const lockedQuantity = Number(plain.locked_quantity) || 0;
const interceptLockedQuantity = Number(plain.intercept_locked_quantity) || 0;
mergedMap.set(key, {
id: plain.id,
space_id: plain.space_id,
@ -4132,8 +4110,7 @@ class stockStoreService extends Service {
inventory_type: plain.inventory_type,
quantity,
locked_quantity: lockedQuantity,
intercept_locked_quantity: interceptLockedQuantity,
available_quantity: quantity - lockedQuantity - interceptLockedQuantity,
available_quantity: quantity - lockedQuantity,
production_date: null,
expiry_date: null,
inbound_time: null,

View File

@ -193,188 +193,124 @@ class StockTransactionService extends Service {
return ctx.model.StockTransaction.create(payload, options);
}
/**
* 查询库位维度出入库流水逐条明细(wms_storage_transaction)。
* 与 stock.transaction.list 形态一致:裸 SQL 列白名单 + COUNT 分页 + 排序白名单,
* 不做聚合,仅查询当前仓库数据,并关联商品信息(stockItem)。
* @param {Object} [options] 查询选项
* @param {number} options.warehouseId 仓库ID(必填,由 method 层从当前上下文注入)
* @param {string|Date|null} [options.startTime] 开始时间(闭区间下限,created_at >= startTime)
* @param {string|Date|null} [options.endTime] 结束时间(闭区间上限,created_at <= endTime)
* @param {Array<number|string>} [options.storeIds] 货主ID数组
* @param {Array<number|string>} [options.stockIds] 商品库存ID数组
* @param {number} [options.spaceId] 库位ID
* @param {string} [options.keyword] 商品关键字(按 item_code/item_name/goods_code/barcode/SKU ID 模糊匹配)
* @param {string} [options.transactionType] 流水类型(INBOUND/OUTBOUND/TRANSFER_OUT/TRANSFER_IN/LOCK/UNLOCK)
* @param {string} [options.orderType] 单据类型
* @param {string} [options.orderNo] 单据号(模糊匹配)
* @param {string} [options.batchNo] 批次号
* @param {string} [options.inventoryType] 库存类型(ZP/CC/JS/XS/ZT/DJ/FP)
* @param {string} [options.operatorName] 操作人姓名(模糊匹配)
* @param {number} [options.orderId] 发货单ID
* @param {Object} [options.sort] 排序参数 { sortField, sortOrder }
* @param {Object} [options.pagination] 分页参数 { page, pageSize }
* @return {Promise<Object>} { list, pagination }
*/
async list(options = {}) {
async list(pageParams = {}, sortParams = {}, groupByBatch = false, keyword = '') {
const { ctx, app } = this;
const {
warehouseId,
startTime,
endTime,
storeIds: rawStoreIds,
stockIds: rawStockIds,
spaceId,
keyword,
transactionType,
orderType,
orderNo,
batchNo,
inventoryType,
operatorName,
orderId,
sort = {},
pagination = {},
} = options;
const { Op, fn, col, literal } = app.Sequelize;
if (!warehouseId) {
return {
list: [],
pagination: { page: 1, pageSize: 20, total: 0, totalPages: 0 },
};
}
const warehouseId = ctx.user.store_id;
const { page = 1, pageSize = 20 } = pageParams;
const { sortField = 'created_at', sortOrder = 'DESC' } = sortParams;
// keyword 快捷搜索:解析为 stock_id IN 条件,无匹配时直接返回空列表
let stockIds = Array.isArray(rawStockIds)
? rawStockIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)
: [];
// 基础条件:当前仓库
const baseWhere = {
[Op.and]: [
{ warehouse_id: warehouseId },
],
};
// keyword 快捷搜索:按 item_code + barcode 匹配,解析为 stock_id IN 条件
const normalizedKeyword = String(keyword || '').trim();
if (normalizedKeyword && stockIds.length === 0) {
stockIds = await this._resolveKeywordToStockIds(normalizedKeyword, 'warehouse_id', Number(warehouseId));
if (stockIds.length === 0) {
if (normalizedKeyword) {
const stockIds = await this._resolveKeywordToStockIds(normalizedKeyword, 'warehouse_id', warehouseId);
if (stockIds.length > 0) {
baseWhere[Op.and].push({ stock_id: { [Op.in]: stockIds } });
} else {
// keyword 无匹配结果,直接返回空列表
return {
list: [],
pagination: { page: 1, pageSize: 20, total: 0, totalPages: 0 },
pagination: { page, pageSize, total: 0, totalPages: 0 },
};
}
}
const { whereSQL, replacements } = this._buildStorageTransactionWhere({
warehouseId,
startTime,
endTime,
storeIds: rawStoreIds,
stockIds,
spaceId,
transactionType,
orderType,
orderNo,
batchNo,
inventoryType,
operatorName,
orderId,
});
// 动态 where 条件
const parsed = ctx.whereParsed;
if (parsed && parsed.dynamicConditions && parsed.dynamicConditions.length > 0) {
baseWhere[Op.and].push(...parsed.dynamicConditions);
}
// 排序白名单,非法字段回退默认排序(created_at DESC)
const SORT_FIELD_WHITELIST = new Set([ 'created_at', 'quantity', 'stock_id', 'store_id', 'warehouse_id', 'space_id' ]);
const sortFieldRaw = String(sort.sortField || 'created_at').trim();
const sortField = SORT_FIELD_WHITELIST.has(sortFieldRaw) ? sortFieldRaw : 'created_at';
const sortOrderRaw = String(sort.sortOrder || 'DESC').trim().toUpperCase();
const sortOrder = sortOrderRaw === 'ASC' ? 'ASC' : 'DESC';
// 分页
const page = Math.max(1, Number(pagination.page) || 1);
const pageSize = Math.min(200, Math.max(1, Number(pagination.pageSize) || 20));
const offset = (page - 1) * pageSize;
const limit = pageSize;
// 查询总数
const countResult = await ctx.model.query(
`SELECT COUNT(*) AS total FROM wms_storage_transaction t ${whereSQL}`,
{
replacements,
type: app.Sequelize.QueryTypes.SELECT,
}
);
const total = countResult && countResult[0] ? Number(countResult[0].total) : 0;
if (groupByBatch) {
// 按批次明细:保持原有逻辑
const { count: total, rows } = await ctx.model.StockTransaction.findAndCountAll({
where: baseWhere,
order: [[ sortField, sortOrder ]],
offset,
limit,
include: [
{
model: ctx.model.StockWarehouse,
as: 'stockItem',
attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit' ],
required: false,
},
],
});
// 明细白名单:显式列出列名,避免模型整行序列化引入未预期字段
const rows = await ctx.model.query(`
SELECT
t.id,
t.created_at,
t.transaction_type,
t.warehouse_id,
t.store_id,
t.stock_id,
t.storage_id,
t.space_id,
t.quantity,
t.before_quantity,
t.after_quantity,
t.before_locked_quantity,
t.after_locked_quantity,
t.before_intercept_locked_quantity,
t.after_intercept_locked_quantity,
t.batch_no,
t.inventory_type,
t.order_type,
t.order_no,
t.order_id,
t.source_order_codes,
t.operator_id,
t.operator_name,
t.remark,
sw.id AS sw_id,
sw.item_code AS sw_item_code,
sw.item_name AS sw_item_name,
sw.sku_property AS sw_sku_property,
sw.stock_unit AS sw_stock_unit
FROM wms_storage_transaction t
LEFT JOIN wms_stock_warehouse sw ON sw.id = t.stock_id
${whereSQL}
ORDER BY t.${sortField} ${sortOrder}, t.id ${sortOrder}
LIMIT :limit OFFSET :offset
`, {
replacements: { ...replacements, limit: pageSize, offset },
type: app.Sequelize.QueryTypes.SELECT,
const list = rows.map(item => {
const row = item.get({ plain: true });
row.created_at = row.created_at ? app.formatDate(row.created_at) : '';
return row;
});
return {
list,
pagination: {
page,
pageSize,
total,
totalPages: Math.ceil(total / pageSize),
},
};
}
// 不按批次:按 stock_id + transaction_type + warehouse/store + order_type 合并
const groupFields = [ 'stock_id', 'transaction_type', 'warehouse_id', 'store_id', 'order_type' ];
// 先查总数(分组后的组数)
const countResult = await ctx.model.StockTransaction.count({
where: baseWhere,
group: groupFields,
});
const total = Array.isArray(countResult) ? countResult.length : countResult;
// 查分组数据
const rows = await ctx.model.StockTransaction.findAll({
where: baseWhere,
attributes: [
'stock_id',
'transaction_type',
'warehouse_id',
'store_id',
'order_type',
[ fn('SUM', col('stock_transaction.quantity')), 'quantity' ],
[ fn('MIN', col('stock_transaction.created_at')), 'first_created_at' ],
[ fn('MAX', col('stock_transaction.created_at')), 'last_created_at' ],
[ fn('COUNT', col('stock_transaction.id')), 'record_count' ],
],
group: groupFields,
order: [[ literal('last_created_at'), sortOrder ]],
offset,
limit,
include: [
{
model: ctx.model.StockWarehouse,
as: 'stockItem',
attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit' ],
required: false,
},
],
raw: true,
nest: true,
});
const safeRows = Array.isArray(rows) ? rows : [];
const list = safeRows.map(item => ({
id: Number(item.id),
created_at: item.created_at ? app.formatDate(item.created_at) : '',
transaction_type: item.transaction_type || '',
warehouse_id: Number(item.warehouse_id) || 0,
store_id: Number(item.store_id) || 0,
stock_id: Number(item.stock_id) || 0,
storage_id: Number(item.storage_id) || 0,
space_id: Number(item.space_id) || 0,
quantity: Number(item.quantity) || 0,
before_quantity: Number(item.before_quantity) || 0,
after_quantity: Number(item.after_quantity) || 0,
before_locked_quantity: Number(item.before_locked_quantity) || 0,
after_locked_quantity: Number(item.after_locked_quantity) || 0,
before_intercept_locked_quantity: Number(item.before_intercept_locked_quantity) || 0,
after_intercept_locked_quantity: Number(item.after_intercept_locked_quantity) || 0,
batch_no: item.batch_no || '',
inventory_type: item.inventory_type || '',
order_type: item.order_type || '',
order_no: item.order_no || '',
order_id: Number(item.order_id) || 0,
source_order_codes: item.source_order_codes || '',
operator_id: item.operator_id || '',
operator_name: item.operator_name || '',
remark: item.remark || '',
stockItem: item.sw_id !== null && item.sw_id !== undefined
? {
id: Number(item.sw_id) || 0,
item_code: item.sw_item_code || '',
item_name: item.sw_item_name || '',
sku_property: item.sw_sku_property || '',
stock_unit: item.sw_stock_unit || '',
}
: null,
}));
const list = rows.map(row => {
row.first_created_at = row.first_created_at ? app.formatDate(row.first_created_at) : '';
row.last_created_at = row.last_created_at ? app.formatDate(row.last_created_at) : '';
return row;
});
return {
list,
@ -387,121 +323,6 @@ class StockTransactionService extends Service {
};
}
/**
* 组装库位维度流水查询条件白名单(wms_storage_transaction)。
* 所有条件显式拼装,避免动态 where 注入未知字段;list 与导出共用。
* @param {Object} params 归一化后的查询参数
* @param {number} params.warehouseId 仓库ID
* @param {string|Date|null} [params.startTime] 开始时间
* @param {string|Date|null} [params.endTime] 结束时间
* @param {Array<number|string>} [params.storeIds] 货主ID数组
* @param {Array<number>} [params.stockIds] 商品库存ID数组
* @param {number} [params.spaceId] 库位ID
* @param {string} [params.transactionType] 流水类型
* @param {string} [params.orderType] 单据类型
* @param {string} [params.orderNo] 单据号(模糊)
* @param {string} [params.batchNo] 批次号
* @param {string} [params.inventoryType] 库存类型
* @param {string} [params.operatorName] 操作人(模糊)
* @param {number} [params.orderId] 发货单ID
* @return {{whereSQL: string, replacements: Object}} WHERE 子句与查询参数
*/
_buildStorageTransactionWhere({
warehouseId,
startTime,
endTime,
storeIds: rawStoreIds,
stockIds,
spaceId,
transactionType,
orderType,
orderNo,
batchNo,
inventoryType,
operatorName,
orderId,
} = {}) {
const whereClauses = [ 't.warehouse_id = :warehouseId' ];
const replacements = { warehouseId: Number(warehouseId) };
if (startTime !== undefined && startTime !== null && startTime !== '') {
const startMs = new Date(startTime).getTime();
if (!Number.isNaN(startMs)) {
whereClauses.push('t.created_at >= :startTime');
replacements.startTime = startTime;
}
}
if (endTime !== undefined && endTime !== null && endTime !== '') {
const endMs = new Date(endTime).getTime();
if (!Number.isNaN(endMs)) {
whereClauses.push('t.created_at <= :endTime');
replacements.endTime = endTime;
}
}
const storeIds = Array.isArray(rawStoreIds)
? rawStoreIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)
: [];
if (storeIds.length > 0) {
whereClauses.push('t.store_id IN (:storeIds)');
replacements.storeIds = storeIds;
}
const normalizedStockIds = Array.isArray(stockIds) ? stockIds : [];
if (normalizedStockIds.length > 0) {
whereClauses.push('t.stock_id IN (:stockIds)');
replacements.stockIds = normalizedStockIds;
}
const normalizedSpaceId = Number(spaceId);
if (Number.isInteger(normalizedSpaceId) && normalizedSpaceId > 0) {
whereClauses.push('t.space_id = :spaceId');
replacements.spaceId = normalizedSpaceId;
}
if (transactionType) {
whereClauses.push('t.transaction_type = :transactionType');
replacements.transactionType = String(transactionType).trim();
}
if (orderType) {
whereClauses.push('t.order_type = :orderType');
replacements.orderType = String(orderType).trim();
}
if (orderNo) {
whereClauses.push('t.order_no LIKE :orderNo');
replacements.orderNo = `%${String(orderNo).trim()}%`;
}
if (batchNo) {
whereClauses.push('t.batch_no = :batchNo');
replacements.batchNo = String(batchNo).trim();
}
if (inventoryType) {
whereClauses.push('t.inventory_type = :inventoryType');
replacements.inventoryType = String(inventoryType).trim();
}
if (operatorName) {
whereClauses.push('t.operator_name LIKE :operatorName');
replacements.operatorName = `%${String(operatorName).trim()}%`;
}
const normalizedOrderId = Number(orderId);
if (Number.isInteger(normalizedOrderId) && normalizedOrderId > 0) {
whereClauses.push('t.order_id = :orderId');
replacements.orderId = normalizedOrderId;
}
return {
whereSQL: `WHERE ${whereClauses.join(' AND ')}`,
replacements,
};
}
/**
* 根据关键字解析匹配的 stock_id 列表。
* 支持按商品编码(item_code)、商品名称(item_name)、货物编码(goods_code)、条码(barcode)、SKU ID 模糊匹配。
@ -612,27 +433,18 @@ class StockTransactionService extends Service {
? rawStockIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)
: [];
const normalizedKeyword = String(keyword || '').trim();
let keywordResolvedEmpty = false;
if (normalizedKeyword && resolvedStockIds.length === 0) {
const isStoreMode = mode === 'store';
const primaryDimCol = isStoreMode ? 'store_id' : 'warehouse_id';
const primaryDimVal = isStoreMode ? Number(storeId) : Number(warehouseId);
if (primaryDimVal > 0) {
resolvedStockIds = await this._resolveKeywordToStockIds(normalizedKeyword, primaryDimCol, primaryDimVal);
if (resolvedStockIds.length === 0) {
// keyword 无匹配商品,避免退化为查询全部流水
keywordResolvedEmpty = true;
}
}
}
const whereClauses = [];
const replacements = {};
if (keywordResolvedEmpty) {
whereClauses.push('1 = 0');
}
// 数据范围限定:仓库侧或货主侧
if (warehouseId !== undefined && warehouseId !== null) {
whereClauses.push('t.warehouse_id = :warehouseId');
@ -874,17 +686,12 @@ class StockTransactionService extends Service {
? rawStockIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)
: [];
const normalizedKeyword = String(keyword || '').trim();
let keywordResolvedEmpty = false;
if (normalizedKeyword && resolvedStockIds.length === 0) {
const isStoreMode = mode === 'store';
const primaryDimCol = isStoreMode ? 'store_id' : 'warehouse_id';
const primaryDimVal = isStoreMode ? Number(storeId) : Number(warehouseId);
if (primaryDimVal > 0) {
resolvedStockIds = await this._resolveKeywordToStockIds(normalizedKeyword, primaryDimCol, primaryDimVal);
if (resolvedStockIds.length === 0) {
// keyword 无匹配商品,避免退化为导出全部流水
keywordResolvedEmpty = true;
}
}
}
@ -892,10 +699,6 @@ class StockTransactionService extends Service {
const whereClauses = [];
const replacements = {};
if (keywordResolvedEmpty) {
whereClauses.push('1 = 0');
}
// 数据范围限定
if (warehouseId !== undefined && warehouseId !== null) {
whereClauses.push('t.warehouse_id = :warehouseId');
@ -1111,180 +914,6 @@ class StockTransactionService extends Service {
],
});
}
/**
* 导出库位维度出入库流水明细为 Excel(wms_storage_transaction)。
* 与 list 使用相同查询条件,但不分页(导出上限 50000 条)。
* @param {Object} options 查询参数(与 list 一致,忽略 pagination)
* @return {Promise<Object>} Excel 导出结果 { url, filename }
*/
async exportStorageList(options = {}) {
const { ctx, app } = this;
const {
warehouseId,
startTime,
endTime,
storeIds: rawStoreIds,
stockIds: rawStockIds,
spaceId,
keyword,
transactionType,
orderType,
orderNo,
batchNo,
inventoryType,
operatorName,
orderId,
sort = {},
} = options;
// keyword 快捷搜索:解析为 stock_id IN 条件,无匹配时导出空表
let stockIds = Array.isArray(rawStockIds)
? rawStockIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)
: [];
const normalizedKeyword = String(keyword || '').trim();
let keywordResolvedEmpty = false;
if (normalizedKeyword && stockIds.length === 0) {
stockIds = await this._resolveKeywordToStockIds(normalizedKeyword, 'warehouse_id', Number(warehouseId));
if (stockIds.length === 0) {
keywordResolvedEmpty = true;
}
}
let whereSQL;
let replacements;
if (keywordResolvedEmpty) {
whereSQL = 'WHERE 1 = 0';
replacements = {};
} else {
({ whereSQL, replacements } = this._buildStorageTransactionWhere({
warehouseId,
startTime,
endTime,
storeIds: rawStoreIds,
stockIds,
spaceId,
transactionType,
orderType,
orderNo,
batchNo,
inventoryType,
operatorName,
orderId,
}));
}
// 排序白名单,与 list 一致
const SORT_FIELD_WHITELIST = new Set([ 'created_at', 'quantity', 'stock_id', 'store_id', 'warehouse_id', 'space_id' ]);
const sortFieldRaw = String(sort.sortField || 'created_at').trim();
const sortField = SORT_FIELD_WHITELIST.has(sortFieldRaw) ? sortFieldRaw : 'created_at';
const sortOrderRaw = String(sort.sortOrder || 'DESC').trim().toUpperCase();
const sortOrder = sortOrderRaw === 'ASC' ? 'ASC' : 'DESC';
const EXPORT_MAX = 50000;
const rows = await ctx.model.query(`
SELECT
t.id,
t.created_at,
t.transaction_type,
t.warehouse_id,
t.store_id,
t.stock_id,
t.storage_id,
t.space_id,
t.quantity,
t.before_quantity,
t.after_quantity,
t.before_locked_quantity,
t.after_locked_quantity,
t.before_intercept_locked_quantity,
t.after_intercept_locked_quantity,
t.batch_no,
t.inventory_type,
t.order_type,
t.order_no,
t.order_id,
t.source_order_codes,
t.operator_id,
t.operator_name,
t.remark
FROM wms_storage_transaction t
${whereSQL}
ORDER BY t.${sortField} ${sortOrder}, t.id ${sortOrder}
LIMIT ${EXPORT_MAX}
`, {
replacements,
type: app.Sequelize.QueryTypes.SELECT,
});
const safeRows = Array.isArray(rows) ? rows : [];
const excelRows = safeRows.map((item, index) => ({
序号: index + 1,
创建时间: item.created_at ? app.formatDate(item.created_at) : '',
流水类型: item.transaction_type || '',
仓库ID: Number(item.warehouse_id) || 0,
货主ID: Number(item.store_id) || 0,
商品ID: Number(item.stock_id) || 0,
库位库存ID: Number(item.storage_id) || 0,
库位ID: Number(item.space_id) || 0,
库存变动量: Number(item.quantity) || 0,
库存变更前: Number(item.before_quantity) || 0,
库存变更后: Number(item.after_quantity) || 0,
锁定变更前: Number(item.before_locked_quantity) || 0,
锁定变更后: Number(item.after_locked_quantity) || 0,
拦截锁定变更前: Number(item.before_intercept_locked_quantity) || 0,
拦截锁定变更后: Number(item.after_intercept_locked_quantity) || 0,
批次号: item.batch_no || '',
库存类型: item.inventory_type || '',
单据类型: item.order_type || '',
单据号: item.order_no || '',
发货单ID: Number(item.order_id) || 0,
来源订单号: item.source_order_codes || '',
操作人ID: item.operator_id || '',
操作人: item.operator_name || '',
备注: item.remark || '',
}));
const warehouseIdForPath = Number(warehouseId) || 'unknown';
return await ctx.service.systems.excel.generateAndUpload({
filename: `库位流水_${warehouseIdForPath}_${Date.now()}.xlsx`,
dir: `exports/storage/transaction/${warehouseIdForPath}`,
category: 'document',
sheets: [
{
name: '库位流水',
columns: [
{ header: '序号', key: '序号' },
{ header: '创建时间', key: '创建时间' },
{ header: '流水类型', key: '流水类型' },
{ header: '仓库ID', key: '仓库ID' },
{ header: '货主ID', key: '货主ID' },
{ header: '商品ID', key: '商品ID' },
{ header: '库位库存ID', key: '库位库存ID' },
{ header: '库位ID', key: '库位ID' },
{ header: '库存变动量', key: '库存变动量' },
{ header: '库存变更前', key: '库存变更前' },
{ header: '库存变更后', key: '库存变更后' },
{ header: '锁定变更前', key: '锁定变更前' },
{ header: '锁定变更后', key: '锁定变更后' },
{ header: '拦截锁定变更前', key: '拦截锁定变更前' },
{ header: '拦截锁定变更后', key: '拦截锁定变更后' },
{ header: '批次号', key: '批次号' },
{ header: '库存类型', key: '库存类型' },
{ header: '单据类型', key: '单据类型' },
{ header: '单据号', key: '单据号' },
{ header: '发货单ID', key: '发货单ID' },
{ header: '来源订单号', key: '来源订单号' },
{ header: '操作人ID', key: '操作人ID' },
{ header: '操作人', key: '操作人' },
{ header: '备注', key: '备注' },
],
rows: excelRows,
},
],
});
}
}
module.exports = StockTransactionService;

View File

@ -9,10 +9,6 @@ const Service = require('egg').Service;
const STOCK_DETAIL_CACHE_KEY_PREFIX = 'cache:stock_detail';
/** 仓库商品详情缓存默认 TTL(秒) */
const DEFAULT_STOCK_DETAIL_CACHE_TTL = 300;
/** 缓存读取并发批大小 */
const CACHE_READ_BATCH_SIZE = 200;
/** 缓存写入并发批大小 */
const CACHE_WRITE_BATCH_SIZE = 100;
class StockWarehouseService extends Service {
/**
@ -51,25 +47,19 @@ class StockWarehouseService extends Service {
const cacheHits = new Map();
const missedStockIds = [];
// 第一步:分批并发查缓存(避免逐个串行 await 叠加 N 次 Redis 往返延迟)
for (let i = 0; i < uniqueStockIds.length; i += CACHE_READ_BATCH_SIZE) {
const batch = uniqueStockIds.slice(i, i + CACHE_READ_BATCH_SIZE);
const batchResults = await Promise.all(batch.map(async stockId => {
const cacheKey = this._buildStockDetailCacheKey(warehouseId, stockId);
try {
const cached = await app.getCacheAsync(cacheKey);
return { stockId, cached, hit: cached !== null && cached !== undefined };
} catch {
// 缓存读取异常时降级为查数据库
return { stockId, cached: null, hit: false };
}
}));
for (const item of batchResults) {
if (item.hit) {
cacheHits.set(item.stockId, item.cached);
// 第一步:逐个查缓存
for (const stockId of uniqueStockIds) {
const cacheKey = this._buildStockDetailCacheKey(warehouseId, stockId);
try {
const cached = await app.getCacheAsync(cacheKey);
if (cached !== null && cached !== undefined) {
cacheHits.set(stockId, cached);
} else {
missedStockIds.push(item.stockId);
missedStockIds.push(stockId);
}
} catch {
// 缓存读取异常时降级为查数据库
missedStockIds.push(stockId);
}
}
@ -141,8 +131,7 @@ class StockWarehouseService extends Service {
}
}
// 组装每个 stock 的完整详情,并收集缓存写入任务
const cacheWriteTasks = [];
// 组装每个 stock 的完整详情
for (const row of stockRows) {
const detail = {
id: row.id,
@ -163,31 +152,27 @@ class StockWarehouseService extends Service {
};
dbResults.set(row.id, detail);
// 第三步:写入缓存(收集任务,稍后统一分批并发执行)
cacheWriteTasks.push({
key: this._buildStockDetailCacheKey(warehouseId, row.id),
value: detail,
ttl: cacheTTL,
});
// 第三步:写入缓存
const cacheKey = this._buildStockDetailCacheKey(warehouseId, row.id);
try {
await app.setCacheAsync(cacheKey, detail, cacheTTL);
} catch {
// 缓存写入失败不影响主流程
}
}
// 对于数据库中也不存在的 stockId,写入空标记防止缓存穿透
for (const stockId of missedStockIds) {
if (!dbResults.has(stockId)) {
cacheWriteTasks.push({
key: this._buildStockDetailCacheKey(warehouseId, stockId),
value: null,
const cacheKey = this._buildStockDetailCacheKey(warehouseId, stockId);
try {
// 用较短的 TTL 缓存空结果,避免缓存穿透
ttl: Math.min(cacheTTL, 60),
});
await app.setCacheAsync(cacheKey, null, Math.min(cacheTTL, 60));
} catch {
// 忽略缓存写入失败
}
}
}
// 分批并发写缓存(缓存写入失败不影响主流程)
for (let i = 0; i < cacheWriteTasks.length; i += CACHE_WRITE_BATCH_SIZE) {
const batch = cacheWriteTasks.slice(i, i + CACHE_WRITE_BATCH_SIZE);
await Promise.all(batch.map(task => app.setCacheAsync(task.key, task.value, task.ttl).catch(() => {})));
}
}
// 第四步:合并缓存命中 + 数据库结果,保持原始 stockIds 顺序

View File

@ -1521,13 +1521,11 @@ class EntryService extends Service {
* 采用"先同步后写库"两段式:① 先发奇门/OpenAPI 回传,② 回传成功后再开启事务写库存。
* @param {Object} data 请求体
* @param {number} data.id 入库单ID
* @param {number} [data.noNeedNotice=0] 是否跳过入库完成通知:0 通知,1 不通知(默认 0)
* @return {Promise<Object>} code/data/message 结构
*/
async quickInbound(data = {}) {
const { ctx, app } = this;
const orderId = Number(data.id || 0);
const noNeedNotice = Number(data.noNeedNotice) || 0;
if (!orderId) {
return {
@ -1720,19 +1718,6 @@ class EntryService extends Service {
await stockRecord.increment('quantity', { by: planQty, transaction, silent: true });
await stockRecord.reload({ transaction });
// 负库存回填:按 SW 非负增量冲销 GAP 补建行挂账(平账,拦截锁定回归真实数据)
if (beforeQuantity <= 0) {
const nonNegativeDelta = Math.max(0, Number(stockRecord.quantity) || 0) - Math.max(0, beforeQuantity);
await ctx.service.systems.storage.index.offsetGapOnInbound(stockId, planQty, {
transaction,
maxOffset: nonNegativeDelta,
orderNo: eo.entry_order_code || 'QUICK_INBOUND',
orderId: eo.id,
operatorId: String(ctx.user?.employees_id || ctx.user?.id || ''),
operatorName: ctx.user?.employees_name || '',
});
}
const afterQuantity = Number(stockRecord.quantity) || 0;
const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0;
@ -1774,16 +1759,12 @@ class EntryService extends Service {
let storageAfterQty = 0;
let storageBeforeLockedQty = 0;
let storageAfterLockedQty = 0;
let storageBeforeInterceptQty = 0;
let storageAfterInterceptQty = 0;
if (storageRecord) {
storageBeforeQty = Number(storageRecord.quantity) || 0;
storageAfterQty = storageBeforeQty + planQty;
storageBeforeLockedQty = Number(storageRecord.locked_quantity) || 0;
storageAfterLockedQty = storageBeforeLockedQty;
storageBeforeInterceptQty = Number(storageRecord.intercept_locked_quantity) || 0;
storageAfterInterceptQty = storageBeforeInterceptQty;
await ctx.model.Storage.update({
quantity: app.Sequelize.literal(`quantity + ${planQty}`),
@ -1839,8 +1820,6 @@ class EntryService extends Service {
after_quantity: storageAfterQty,
before_locked_quantity: storageBeforeLockedQty,
after_locked_quantity: storageAfterLockedQty,
before_intercept_locked_quantity: storageBeforeInterceptQty,
after_intercept_locked_quantity: storageAfterInterceptQty,
batch_no: batchNo,
inventory_type: inventoryType,
order_type: 'entry_order',
@ -1894,13 +1873,11 @@ class EntryService extends Service {
await transaction.commit();
// 入库完成通知货主(失败不影响主流程);noNeedNotice=1 时跳过通知
if (noNeedNotice !== 1) {
try {
await ctx.service.systems.inboundDirectLog.notifyEntryOrderCompleted(eo);
} catch (noticeErr) {
ctx.logger.warn('[storage.entry.quickInbound] 入库完成通知货主失败,不影响业务', noticeErr);
}
// 入库完成通知货主(失败不影响主流程)
try {
await ctx.service.systems.inboundDirectLog.notifyEntryOrderCompleted(eo);
} catch (noticeErr) {
ctx.logger.warn('[storage.entry.quickInbound] 入库完成通知货主失败,不影响业务', noticeErr);
}
} catch (error) {
if (transaction && typeof transaction.rollback === 'function') {

View File

@ -113,24 +113,8 @@ class IndexService extends Service {
});
}
/**
* 更新库存数量、锁定数量与拦截锁定数量,并按统一口径重算可用数量。
*
* 可用数量统一口径:
* `available_quantity = quantity - locked_quantity - intercept_locked_quantity`。
*
* @param {number} id 库存记录 ID。
* @param {number} quantityChange 库存数量变化量(正数为增加,负数为减少)。
* @param {number} [lockedChange=0] 锁定数量变化量。
* @param {Object} [options={}] 执行上下文与事务参数。
* @param {Object} [options.transaction] Sequelize 事务对象。
* @param {number} [options.interceptLockedChange=0] 拦截锁定数量变化量(正数为拦截锁定,负数为释放;
* 允许结果为负值:差异对账场景下 storage 比 stock 少的差异以负拦截锁定入账,可用数量等量回补)。
* @return {Promise<Object>} 更新后的库存记录。
*/
async updateQuantity(id, quantityChange, lockedChange = 0, options = {}) {
const { ctx } = this;
const interceptLockedChange = Number((options && options.interceptLockedChange) || 0);
const applyUpdate = async transaction => {
const storage = await ctx.model.Storage.findByPk(id, {
transaction,
@ -143,35 +127,19 @@ class IndexService extends Service {
const newQuantity = storage.quantity + quantityChange;
const newLocked = storage.locked_quantity + lockedChange;
const newInterceptLocked = Number(storage.intercept_locked_quantity || 0) + interceptLockedChange;
if (newQuantity < 0) {
throw new Error('库存数量不能为负数');
}
if (newLocked < 0) {
if (newLocked < 0 || newLocked > newQuantity) {
throw new Error('锁定数量无效');
}
// 拦截锁定允许为负(差异对账:storage 比 stock 少的差异以负值入账,可用数量回补);
// 上界仍禁止超过库存数量;锁定数量仍禁止为负
if (newInterceptLocked > newQuantity) {
throw new Error('拦截锁定数量无效');
}
// 总和上界:锁定与拦截锁定之和不能超过库存数量;
// 等价于锁定后可用不为负(available ≥ 0)。
// 负拦截锁(差异对账补回)时锁定量可超过 quantity,但总和上限口径不变,
// 保证补回的可用数量可真实被锁定使用。
if (newLocked + newInterceptLocked > newQuantity) {
throw new Error('锁定数量与拦截锁定数量之和不能超过库存数量');
}
const updateData = {
quantity: newQuantity,
locked_quantity: newLocked,
intercept_locked_quantity: newInterceptLocked,
available_quantity: newQuantity - newLocked - newInterceptLocked,
available_quantity: newQuantity - newLocked,
updated_at: new Date(),
};
@ -207,28 +175,10 @@ class IndexService extends Service {
return await this.updateQuantity(id, 0, quantity, options);
}
/**
* 解除指定库存记录的锁定数量(锁定数量减少,可用数量等量增加)。
*
* @param {number} id 库存记录 ID。
* @param {number} quantity 需要解除锁定的数量。
* @param {Object} [options={}] 执行上下文与事务参数。
* @param {Object} [options.transaction] Sequelize 事务对象。
* @return {Promise<Object>} 更新后的库存记录。
*/
async unlockQuantity(id, quantity, options = {}) {
return await this.updateQuantity(id, 0, -quantity, options);
}
/**
* 从可用数量中分配锁定指定数量(锁定数量增加,可用数量等量减少)。
*
* @param {number} id 库存记录 ID。
* @param {number} quantity 需要分配锁定的数量。
* @param {Object} [options={}] 执行上下文与事务参数。
* @param {Object} [options.transaction] Sequelize 事务对象。
* @return {Promise<Object>} 更新后的库存记录。
*/
async allocateQuantity(id, quantity, options = {}) {
const { ctx } = this;
const storage = await ctx.model.Storage.findByPk(id, {
@ -246,180 +196,6 @@ class IndexService extends Service {
return await this.updateQuantity(id, 0, quantity, options);
}
/**
* 将作业锁定数量迁移为拦截锁定数量(拦截确认专用,pending 拣货行)。
*
* 库存总量与可用数量均不变,仅将锁定类型从 `locked_quantity` 迁移到 `intercept_locked_quantity`:
* `locked_quantity -q`、`intercept_locked_quantity +q`、`quantity` 与 `available_quantity` 不变。
*
* @param {number} id 库存记录 ID。
* @param {number} quantity 需要迁移为拦截锁定的数量。
* @param {Object} [options={}] 执行上下文与事务参数。
* @param {Object} [options.transaction] Sequelize 事务对象。
* @return {Promise<Object>} 更新后的库存记录。
*/
async interceptLockQuantity(id, quantity, options = {}) {
return await this.updateQuantity(id, 0, -quantity, {
...options,
interceptLockedChange: quantity,
});
}
/**
* 实物返还并拦截锁定(拦截确认专用,fin 已拣货行)。
*
* 库存总量与拦截锁定数量等量增加,可用数量不变:
* `quantity +q`、`intercept_locked_quantity +q`、`locked_quantity` 与 `available_quantity` 不变。
*
* @param {number} id 库存记录 ID。
* @param {number} quantity 需要返还并拦截锁定的数量。
* @param {Object} [options={}] 执行上下文与事务参数。
* @param {Object} [options.transaction] Sequelize 事务对象。
* @return {Promise<Object>} 更新后的库存记录。
*/
async interceptReceiveQuantity(id, quantity, options = {}) {
return await this.updateQuantity(id, quantity, 0, {
...options,
interceptLockedChange: quantity,
});
}
/**
* 释放拦截锁定数量,使其回落到可用数量(解除拦截/退货登记专用)。
*
* 库存总量与作业锁定数量不变,拦截锁定数量减少、可用数量等量增加:
* `intercept_locked_quantity -q`、`available_quantity +q`、`quantity` 与 `locked_quantity` 不变。
*
* @param {number} id 库存记录 ID。
* @param {number} quantity 需要释放的拦截锁定数量。
* @param {Object} [options={}] 执行上下文与事务参数。
* @param {Object} [options.transaction] Sequelize 事务对象。
* @return {Promise<Object>} 更新后的库存记录。
*/
async interceptUnlockQuantity(id, quantity, options = {}) {
return await this.updateQuantity(id, 0, 0, {
...options,
interceptLockedChange: -quantity,
});
}
/**
* 入库回填平账:负库存入库时,按入库量冲销该商品的 GAP 补建行挂账。
*
* 背景:差异对账(INTERCEPT_GAP)对无行/截断差异会补建 GAP- 前缀库存行承载拦截锁定;
* 当负库存商品真实入库回填时,将补建行挂账按入库量冲销(quantity/intercept 同减),
* 账归真实入库数据,避免补建挂账与真实入库叠加造成虚账。
*
* 冲销口径:每行冲销量 m = min(入库量, 行 quantity, 行 intercept_locked_quantity);
* available 按统一口径重算(quantity 与 intercept 同减,available 不变);
* 写 INTERCEPT_GAP(UNLOCK 方向)冲销流水,保留快照可追溯。
*
* 冲销上限:差异基准为 max(SW.quantity, 0),只有 SW 在非负区间的增量才会收窄差异;
* SW 在负数区间回填(如 -10→0)不改变基准,不冲销。因此调用方应传入
* options.maxOffset = max(0, 入库后SW) - max(0, 入库前SW),缺省时按入库量冲销(兼容)。
*
* @param {number} stockId 商品SKU ID(wms_stock_warehouse.id)。
* @param {number} qty 本次入库数量。
* @param {Object} [options={}] 执行上下文与事务参数。
* @param {Object} [options.transaction] Sequelize 事务对象。
* @param {number} [options.maxOffset] 冲销上限(推荐传 SW 非负区间增量,缺省=入库量)。
* @param {string} [options.orderNo] 入库单号/来源标识(流水追溯)。
* @param {number} [options.orderId] 关联订单/入库单 ID。
* @param {string} [options.operatorId] 操作人 ID。
* @param {string} [options.operatorName] 操作人名。
* @return {Promise<number>} 实际冲销量。
*/
async offsetGapOnInbound(stockId, qty, options = {}) {
const { ctx, app } = this;
const inboundQty = Number(qty) || 0;
if (!stockId || inboundQty <= 0) return 0;
const maxOffset = options.maxOffset !== undefined && options.maxOffset !== null
? Math.max(0, Number(options.maxOffset) || 0)
: inboundQty;
if (maxOffset <= 0) return 0;
const apply = async transaction => {
const gapRows = await ctx.model.Storage.findAll({
where: {
stock_id: stockId,
is_enabled: 1,
delete_at: null,
[app.Sequelize.Op.or]: [
{ batch_no: { [app.Sequelize.Op.like]: 'GAP-%' } },
{ inbound_order_no: { [app.Sequelize.Op.like]: 'GAP-%' } },
],
},
order: [[ 'id', 'ASC' ]],
lock: transaction ? transaction.LOCK.UPDATE : undefined,
transaction,
});
let remain = inboundQty;
let offsetTotal = 0;
let offsetBudget = maxOffset;
for (const row of gapRows) {
if (remain <= 0 || offsetBudget <= 0) break;
const gapQty = Number(row.quantity) || 0;
const gapIntercept = Number(row.intercept_locked_quantity) || 0;
const offsetQty = Math.min(remain, offsetBudget, Math.min(gapQty, gapIntercept));
if (offsetQty <= 0) continue;
const newQty = gapQty - offsetQty;
const newIntercept = gapIntercept - offsetQty;
const lockedQty = Number(row.locked_quantity) || 0;
await row.update({
quantity: newQty,
intercept_locked_quantity: newIntercept,
available_quantity: newQty - lockedQty - newIntercept,
updated_at: new Date(),
}, { transaction });
// 冲销流水(UNLOCK 方向,快照守恒:after = before - offsetQty)
await ctx.model.StorageTransaction.create({
transaction_type: 'UNLOCK',
warehouse_id: row.warehouse_id,
store_id: row.store_id,
stock_id: stockId,
storage_id: row.id,
space_id: row.space_id,
quantity: offsetQty,
before_quantity: gapQty,
after_quantity: newQty,
before_locked_quantity: lockedQty,
after_locked_quantity: lockedQty,
before_intercept_locked_quantity: gapIntercept,
after_intercept_locked_quantity: newIntercept,
batch_no: row.batch_no,
inventory_type: row.inventory_type,
order_type: 'INTERCEPT_GAP',
order_no: String(options.orderNo || 'INBOUND_GAP_OFFSET').slice(0, 255),
order_id: Number(options.orderId || 0) || null,
operator_id: options.operatorId || null,
operator_name: options.operatorName || '',
remark: '入库回填平账(冲销差异挂账)',
created_at: new Date(),
}, { transaction });
remain -= offsetQty;
offsetBudget -= offsetQty;
offsetTotal += offsetQty;
}
return offsetTotal;
};
if (options.transaction) {
return await apply(options.transaction);
}
return await ctx.model.transaction(async transaction => {
return await apply(transaction);
});
}
async getStockSummary(warehouseId) {
const { ctx, app } = this;

View File

@ -272,8 +272,6 @@ class InventoryService extends Service {
const totalSnapshotQuantity = Number(data.totalSnapshotQuantity) || 0;
const totalSnapshotLockedQuantity = Number(data.totalSnapshotLockedQuantity) || 0;
// 拦截锁定快照:wms_stock_warehouse 层无该字段,取源库位行值(移库不动拦截锁,before=after)
const sourceInterceptLockedQuantity = Number(data.srcRecord?.intercept_locked_quantity) || 0;
await ctx.model.StorageTransaction.create({
transaction_type: 'TRANSFER_OUT',
@ -295,8 +293,6 @@ class InventoryService extends Service {
after_quantity: totalSnapshotQuantity,
before_locked_quantity: totalSnapshotLockedQuantity,
after_locked_quantity: totalSnapshotLockedQuantity,
before_intercept_locked_quantity: sourceInterceptLockedQuantity,
after_intercept_locked_quantity: sourceInterceptLockedQuantity,
source_order_codes: null,
created_at: new Date(),
}, {
@ -323,8 +319,6 @@ class InventoryService extends Service {
after_quantity: totalSnapshotQuantity,
before_locked_quantity: totalSnapshotLockedQuantity,
after_locked_quantity: totalSnapshotLockedQuantity,
before_intercept_locked_quantity: sourceInterceptLockedQuantity,
after_intercept_locked_quantity: sourceInterceptLockedQuantity,
source_order_codes: null,
created_at: new Date(),
}, {
@ -1229,7 +1223,7 @@ class InventoryService extends Service {
* @param {string} [sortParams.sortField='created_at'] 排序字段(明细模式支持 wms_storage 真实列;汇总模式仅支持 quantity/locked_quantity/available_quantity/batch_count/first_inbound_time/last_inbound_time/production_date/expiry_date,其余回退 last_inbound_time)
* @param {string} [sortParams.sortOrder='DESC'] 排序方向
* @param {boolean} [groupByBatch=false] 是否按批次明细返回
* @param {string|string[]} [stockQuery=''] 商品快捷搜索关键字(来自 where.stock_query,按商品编码/名称/货物编码/条码/SKU ID 模糊匹配,解析为 stock_id 过滤;支持数组,多关键字取并集)
* @param {string} [stockQuery=''] 商品快捷搜索关键字(来自 where.stock_query,按商品编码/名称/货物编码/条码/SKU ID 模糊匹配,解析为 stock_id 过滤)
* @return {Promise<{list: Object[], pagination: {page: number, pageSize: number, total: number, totalPages: number}}>} 库存列表结果
*/
async getInventoryList(pageParams = {}, sortParams = {}, groupByBatch = false, stockQuery = '') {
@ -1265,20 +1259,11 @@ class InventoryService extends Service {
}
// stock_query 快捷搜索:按商品编码/名称/货物编码/条码/SKU ID 解析为 stock_id IN 条件
// 兼容单关键字(字符串)与多关键字(数组):多关键字逐项解析后取 stock_id 并集
const stockQueryKeywords = (Array.isArray(stockQuery) ? stockQuery : [ stockQuery ])
.map(keyword => String(keyword || '').trim())
.filter(Boolean);
if (stockQueryKeywords.length > 0) {
const stockIdSet = new Set();
for (const keyword of stockQueryKeywords) {
const matchedStockIds = await this.resolveStockQueryToStockIds(keyword, warehouseId);
for (const stockId of matchedStockIds) {
stockIdSet.add(stockId);
}
}
if (stockIdSet.size > 0) {
baseWhere[Op.and].push({ stock_id: { [Op.in]: [ ...stockIdSet ] } });
const normalizedKeyword = String(stockQuery || '').trim();
if (normalizedKeyword) {
const stockIds = await this.resolveStockQueryToStockIds(normalizedKeyword, warehouseId);
if (stockIds.length > 0) {
baseWhere[Op.and].push({ stock_id: { [Op.in]: stockIds } });
} else {
// stock_query 无匹配结果,直接返回空列表
return {
@ -2266,8 +2251,6 @@ class InventoryService extends Service {
let sAfterQty = 0;
let sBeforeLockedQty = 0;
let sAfterLockedQty = 0;
let sBeforeInterceptQty = 0;
let sAfterInterceptQty = 0;
if (sRecord) {
if (Number(sRecord.stock_id) !== Number(sid)) {
@ -2280,8 +2263,6 @@ class InventoryService extends Service {
sAfterQty = sBeforeQty + qty;
sBeforeLockedQty = Number(sRecord.locked_quantity) || 0;
sAfterLockedQty = sBeforeLockedQty;
sBeforeInterceptQty = Number(sRecord.intercept_locked_quantity) || 0;
sAfterInterceptQty = sBeforeInterceptQty;
await ctx.model.Storage.update({
quantity: app.Sequelize.literal(`quantity + ${qty}`),
@ -2341,8 +2322,6 @@ class InventoryService extends Service {
after_quantity: sAfterQty,
before_locked_quantity: sBeforeLockedQty,
after_locked_quantity: sAfterLockedQty,
before_intercept_locked_quantity: sBeforeInterceptQty,
after_intercept_locked_quantity: sAfterInterceptQty,
batch_no: batchNo,
inventory_type: inventoryType,
order_type: 'entry_order',

View File

@ -368,12 +368,6 @@ class ReceivingService extends Service {
});
}
// 补充货主名称:合约表 store_remask 优先、公司全称兜底(快照 store_name 可能缺失或过期)
const storeNameMap = await this._resolveReceivingStoreNameMap(
data.map(item => item.store_id),
ctx.user.store_id
);
const processedData = data.map(item => {
// 注意:wms_receiving 表中没有 locked_quantity 字段,total_quantity 为商品总数量
const availableQuantity = Math.max(0, item.total_quantity || 0);
@ -383,8 +377,6 @@ class ReceivingService extends Service {
.map(row => row.file.file_url);
return {
...item,
// 货主名称:实时解析优先(货主备注 → 公司全称),缺失时回退主表快照
store_name: storeNameMap.get(Number(item.store_id)) || item.store_name || '',
images: itemImages,
available_quantity: availableQuantity,
lock_rate: parseFloat(lockRate),
@ -512,49 +504,6 @@ class ReceivingService extends Service {
return [ ...new Set(detailRows.map(row => row.receiving_id)) ];
}
/**
* 批量解析收货单货主名称映射。
* 货主名称优先取合约表 wms_store_warehouse.store_remask(货主备注名称,按 store_id + warehouse_id 维度),
* 无合约或备注为空时回退 wms_store.company_name(公司全称)。
* @param {Array<number|string>} storeIds 货主ID列表
* @param {number} warehouseId 仓库ID
* @return {Promise<Map<number, string>>} store_id → 货主名称
*/
async _resolveReceivingStoreNameMap(storeIds, warehouseId) {
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const normalizedIds = [ ...new Set((storeIds || []).map(v => Number(v)).filter(v => v > 0)) ];
const resultMap = new Map();
if (normalizedIds.length === 0) return resultMap;
// 1. 合约表货主备注名称
const contractRows = await ctx.model.StoreWarehouse.findAll({
where: {
store_id: { [Op.in]: normalizedIds },
warehouse_id: warehouseId,
},
attributes: [ 'store_id', 'store_remask' ],
raw: true,
});
for (const row of contractRows) {
resultMap.set(Number(row.store_id), row.store_remask || '');
}
// 2. 货主公司全称兜底
const storeRows = await ctx.model.Store.findAll({
where: { id: { [Op.in]: normalizedIds } },
attributes: [ 'id', 'company_name' ],
raw: true,
});
for (const row of storeRows) {
if (!resultMap.get(Number(row.id))) {
resultMap.set(Number(row.id), row.company_name || '');
}
}
return resultMap;
}
/**
* 货主侧收货单列表查询。
* 以 store_id 为维度查询收货单,支持分页、多条件筛选与排序。
@ -772,8 +721,7 @@ class ReceivingService extends Service {
* @param {Object} data 请求体
* @param {number} data.id 收货单ID
* @param {Object} data.pagination 分页参数
* @return {Promise<Object>} 详情数据,明细中的 space_id 会优先展示自定义库位名称,其次展示库位编码,
* 并补充 space_id_raw 兼容原始ID;每个明细项同时返回 stock_id(商品/库存ID,语义与 system_product_id 一致,缺失时为 null)
* @return {Promise<Object>} 详情数据,明细中的 space_id 会优先展示自定义库位名称,其次展示库位编码,并补充 space_id_raw 兼容原始ID
*/
async getReceivingDetail(data) {
const { id, pagination } = data;
@ -791,17 +739,6 @@ class ReceivingService extends Service {
if (!receiving) {
return { code: 0, message: '无记录或无权访问', data: {} };
}
// 补充货主名称:合约表 store_remask 优先、公司全称兜底(快照 store_name 可能缺失或过期)
if (Number(receiving.store_id || 0) > 0) {
const detailStoreNameMap = await this._resolveReceivingStoreNameMap(
[ receiving.store_id ],
Number(receiving.warehouse_id || warehouseId)
);
const resolvedStoreName = detailStoreNameMap.get(Number(receiving.store_id));
if (resolvedStoreName) {
receiving.store_name = resolvedStoreName;
}
}
// 2. 查询收货单明细,按分页
const receivingItems = await app.model.ReceivingDetail.findAll({
where: { receiving_id: id },
@ -861,8 +798,6 @@ class ReceivingService extends Service {
const spaceName = receivingSpace?.custom_name || receivingSpace?.space_code || null;
return {
...detailBase,
// 商品/库存ID,语义与 system_product_id 一致,缺失时兜底为 null
stock_id: detailBase.system_product_id ?? null,
space_id_raw: detailBase.space_id ?? null,
space_name: spaceName,
custom_space_name: receivingSpace?.custom_name ?? null,
@ -3098,25 +3033,8 @@ class ReceivingService extends Service {
if (barcodes.length > 0) {
updateData.barcode = barcodes.join(';');
}
// 毛重处理:stock_warehouse 有毛重时以商品毛重为准;
// 毛重为 0 时,用收货明细的重量回写覆盖 stock_warehouse 的毛重
const swGrossWeight = Number(stockWarehouse.gross_weight) || 0;
const detailWeight = Number(receivingDetail.weight) || 0;
if (swGrossWeight > 0) {
updateData.weight = swGrossWeight;
} else if (detailWeight > 0) {
try {
await app.model.StockWarehouse.update({
gross_weight: detailWeight,
updated_at: new Date(),
}, {
where: { id: systemProductId },
});
updateData.weight = detailWeight;
} catch (weightErr) {
// 毛重回写失败仅记录日志,不阻断绑定业务
ctx.logger.warn('[receiving.bindDetailProduct] 回写商品毛重失败,不影响业务', weightErr);
}
if (stockWarehouse.gross_weight !== undefined && stockWarehouse.gross_weight !== null) {
updateData.weight = stockWarehouse.gross_weight;
}
if (stockWarehouse.enable_box_spec) {
updateData.boxes_per_pallet = stockWarehouse.quantity_per_box || receivingDetail.boxes_per_pallet || 0;
@ -3531,7 +3449,7 @@ class ReceivingService extends Service {
* 删除收货单明细并回算统计。
* @param {Object} data 请求体
* @param {number} data.detail_id 明细ID
* @return {Promise<Object>} 删除结果,data.details 为删除后剩余明细列表(字段与 getReceivingDetail 明细项保持一致,含 stock_id)
* @return {Promise<Object>} 删除结果
*/
async deleteDetail(data) {
const ctx = this.ctx;
@ -3611,9 +3529,6 @@ class ReceivingService extends Service {
}
}
// 商品/库存ID,与 getReceivingDetail 明细项字段保持一致,缺失时兜底为 null
detailData.stock_id = detailData.system_product_id ?? null;
return detailData;
});

View File

@ -134,15 +134,12 @@ function formatTransactionType(transactionType) {
return rawType;
}
const SORT_FIELD_WHITE_LIST = new Set([ 'stock_id', 'item_code', 'item_name', 'begin_total', 'inbound_total', 'outbound_total', 'end_total' ]);
/** 字符串排序字段集合(按字典序比较),其余白名单字段按数值比较 */
const STRING_SORT_FIELD_SET = new Set([ 'item_code', 'item_name' ]);
const SORT_FIELD_WHITE_LIST = new Set([ 'begin_total', 'inbound_total', 'outbound_total', 'end_total' ]);
/**
* 归一化排序参数。
* @param {Object|null|undefined} sort 排序入参
* @param {string} [sort.sortField] 排序字段(白名单:stock_id、item_code、item_name、begin_total、inbound_total、outbound_total、end_total)
* @param {string} [sort.sortField] 排序字段
* @param {string} [sort.sortOrder] 排序顺序
* @return {{sortField: string, sortOrder: 'ASC'|'DESC'}|null} 合法排序参数
*/
@ -205,19 +202,12 @@ function sortReportList(list, isBySpace, sort) {
const { sortField, sortOrder } = normalizedSort;
const direction = sortOrder === 'DESC' ? -1 : 1;
const isStringSort = STRING_SORT_FIELD_SET.has(sortField);
return list.sort((a, b) => {
let cmp;
if (isStringSort) {
cmp = String(a[sortField] || '').localeCompare(String(b[sortField] || ''));
} else {
const aValue = toNumber(a[sortField]);
const bValue = toNumber(b[sortField]);
cmp = aValue === bValue ? 0 : aValue - bValue;
}
if (cmp !== 0) {
return cmp * direction;
const aValue = toNumber(a[sortField]);
const bValue = toNumber(b[sortField]);
if (aValue !== bValue) {
return (aValue - bValue) * direction;
}
return compareByDefaultOrder(a, b, isBySpace);
});
@ -306,56 +296,6 @@ function buildPreStartAfterMap(rows, resolveKey) {
return snapshotMap;
}
/**
* 将 SQL WHERE 子句数组中的表别名 t. 重绑定为指定别名,便于在派生表子查询中复用同一组条件。
* @param {string[]} clauses WHERE 子句数组
* @param {string} alias 目标表别名
* @return {string[]} 重绑定后的子句数组
*/
function rebindTableAlias(clauses, alias) {
return clauses.map(clause => String(clause).replace(/\bt\./g, `${alias}.`));
}
/** 默认分页每页条数 */
const DEFAULT_PAGE_SIZE = 20;
/** 导出全量分页大小(导出必须全量,避免默认分页截断汇总与明细) */
const EXPORT_FULL_PAGE_SIZE = 1000000;
/**
* 对已排序的结果列表做内存分页切片。
* 分页参数未传或非法时回退默认分页:page=1、pageSize=20。
* @param {Object[]} list 已排序列表
* @param {Object|null|undefined} pagination 分页参数 { page, pageSize }(兼容 page_size)
* @return {{items: Object[], meta: {page: number, pageSize: number, total: number, totalPages: number, hasPrevious: boolean, hasNext: boolean}}} 分页结果
*/
function paginateList(list, pagination) {
const hasPagination = pagination && typeof pagination === 'object';
const rawPage = hasPagination ? Number(pagination.page) : NaN;
const rawPageSize = hasPagination
? Number(pagination.pageSize !== undefined ? pagination.pageSize : pagination.page_size)
: NaN;
const page = Number.isInteger(rawPage) && rawPage >= 1 ? rawPage : 1;
const pageSize = Number.isInteger(rawPageSize) && rawPageSize >= 1 ? rawPageSize : DEFAULT_PAGE_SIZE;
const total = Array.isArray(list) ? list.length : 0;
const totalPages = Math.ceil(total / pageSize) || 1;
const offset = (page - 1) * pageSize;
const items = list.slice(offset, offset + pageSize);
return {
items,
meta: {
page,
pageSize,
total,
totalPages,
hasPrevious: page > 1,
hasNext: page < totalPages,
},
};
}
/**
* 获取报表流水数据源配置。
* @param {boolean} isBySpace 是否按库位维度统计
@ -586,8 +526,7 @@ class StorageReportService extends Service {
async export(startTime, endTime, bySpace = false, storeIds = [], sort = null, exportMode = '', searchMode = 'warehouse', stockIds = null, keyword = '') {
const { ctx, app } = this;
const isStoreMode = searchMode === 'store';
// 导出必须全量:显式传大分页,避免默认分页(pageSize=20)截断汇总与明细白名单
const searchResult = await this.search(startTime, endTime, bySpace, storeIds, sort, searchMode, stockIds, keyword, { page: 1, pageSize: EXPORT_FULL_PAGE_SIZE });
const searchResult = await this.search(startTime, endTime, bySpace, storeIds, sort, searchMode, stockIds, keyword);
if (!searchResult || searchResult.code !== 200) {
return searchResult;
}
@ -638,17 +577,6 @@ class StorageReportService extends Service {
replacements.excludeLockType = 'LOCK';
}
// 明细商品范围与汇总对齐:keyword/stock_ids 过滤后的汇总 stock 白名单同步作用于明细,
// 避免导出与汇总无关商品的变更记录
const summaryStockIds = [ ...new Set(summaryList.map(item => Number(item.stock_id)).filter(item => Number.isInteger(item) && item > 0)) ];
if (summaryStockIds.length === 0) {
// 汇总无数据时明细也不应导出任何流水
whereClauses.push('0 = 1');
} else {
whereClauses.push('t.stock_id IN (:detailStockIds)');
replacements.detailStockIds = summaryStockIds;
}
const detailTransactionTable = isBySpace ? 'wms_storage_transaction' : 'wms_stock_transaction';
const detailSpaceSelectSql = isBySpace ? 'COALESCE(t.space_id, 0) AS space_id' : '0 AS space_id';
const detailInventoryTypeSelectSql = isBySpace ? 't.inventory_type' : '\'\' AS inventory_type';
@ -692,6 +620,7 @@ class StorageReportService extends Service {
const detailEntryOrderIds = [ ...new Set(safeDetailRows.map(item => Number(item.entry_order_id)).filter(item => Number.isInteger(item) && item > 0)) ];
const detailOrderIds = [ ...new Set(safeDetailRows.map(item => Number(item.order_id)).filter(item => Number.isInteger(item) && item > 0)) ];
const summaryStockIds = [ ...new Set(summaryList.map(item => Number(item.stock_id)).filter(item => Number.isInteger(item) && item > 0)) ];
const summaryStoreIds = [ ...new Set(summaryList.map(item => Number(item.store_id)).filter(item => Number.isInteger(item) && item > 0)) ];
const summarySpaceIds = isBySpace
? [ ...new Set(summaryList.map(item => Number(item.space_id)).filter(item => Number.isInteger(item) && item > 0)) ]
@ -920,7 +849,7 @@ class StorageReportService extends Service {
* 1) 期初优先取 start_time 之前最后一条流水的 after_quantity。
* 2) 若 start_time 之前无流水,期初回退到区间内首条流水的 before_quantity。
* 3) 期末取区间内末条流水的 after_quantity。
* 4) 若维度键在区间内无流水,期末回退到期初(库存未变动,保持“期末 = 期初 + 入库 - 出库”恒等)。
* 4) 若维度键在区间内仍无流水,期初/期末统一回退为 0。
* 5) by_space=false 时按 stock_id+store_id 维度输出;by_space=true 时按 stock_id+space_id+store_id 维度输出。
*
* @param {string|Date|null} startTime 开始时间(闭区间下限)
@ -933,10 +862,9 @@ class StorageReportService extends Service {
* @param {string} [searchMode='warehouse'] 查询维度:'warehouse' 按仓库维度(默认),'store' 按货主维度
* @param {number[]} [stockIds=null] 商品库存ID列表(精确过滤),与 keyword 互斥
* @param {string} [keyword=''] 商品关键字(按 item_code/item_name/goods_code/barcode 模糊匹配),与 stockIds 互斥
* @param {Object|null} [pagination=null] 分页参数 { page, pageSize }(兼容 page_size);未传或非法时默认 page=1、pageSize=20,仅对当前页行加载名称信息
* @return {Promise<Object>} code/data/message 结构
*/
async search(startTime, endTime, bySpace = false, storeIds = [], sort = null, searchMode = 'warehouse', stockIds = null, keyword = '', pagination = null) {
async search(startTime, endTime, bySpace = false, storeIds = [], sort = null, searchMode = 'warehouse', stockIds = null, keyword = '') {
const { ctx, app } = this;
const isStoreMode = searchMode === 'store';
const rawPrimaryId = Number(ctx.user && ctx.user.store_id);
@ -1006,11 +934,11 @@ class StorageReportService extends Service {
return {
code: 200,
message: '查询成功',
data: { list: [], pagination: paginateList([], pagination).meta },
data: { list: [] },
};
}
} else if (stockIds !== null && stockIds !== undefined) {
const rawIds = Array.isArray(stockIds) ? stockIds.flat() : [ stockIds ];
const rawIds = Array.isArray(stockIds) ? stockIds : [ stockIds ];
resolvedStockIds = [ ...new Set(
rawIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)
) ];
@ -1018,7 +946,7 @@ class StorageReportService extends Service {
return {
code: 200,
message: '查询成功',
data: { list: [], pagination: paginateList([], pagination).meta },
data: { list: [] },
};
}
}
@ -1041,9 +969,7 @@ class StorageReportService extends Service {
sw.id AS stock_id,
sw.store_id,
sw.warehouse_id,
sw.quantity,
sw.item_code,
sw.item_name
sw.quantity
FROM wms_stock_warehouse sw
WHERE ${baseWhereClauses.join(' AND ')}
`, {
@ -1061,7 +987,7 @@ class StorageReportService extends Service {
return {
code: 200,
message: '查询成功',
data: { list: [], pagination: paginateList([], pagination).meta },
data: { list: [] },
};
}
} else {
@ -1081,11 +1007,8 @@ class StorageReportService extends Service {
COALESCE(s.space_id, 0) AS space_id,
s.store_id,
s.warehouse_id,
SUM(s.quantity) AS quantity,
MAX(sw.item_code) AS item_code,
MAX(sw.item_name) AS item_name
SUM(s.quantity) AS quantity
FROM wms_storage s
LEFT JOIN wms_stock_warehouse sw ON sw.id = s.stock_id
WHERE ${baseWhereClauses.join(' AND ')}
GROUP BY s.stock_id, COALESCE(s.space_id, 0), s.store_id, s.warehouse_id
`, {
@ -1130,7 +1053,7 @@ class StorageReportService extends Service {
return {
code: 200,
message: '查询成功',
data: { list: [], pagination: paginateList([], pagination).meta },
data: { list: [] },
};
}
@ -1159,43 +1082,18 @@ class StorageReportService extends Service {
const safeRangeRows = Array.isArray(rangeRows) ? rangeRows : [];
// 区间内首/末条快照:在 SQL 端按维度键聚合取极值行,每组仅返回 1 行
// (before_quantity 取首条、after_quantity 取末条),避免把区间内全部流水明细拉回 Node 内存归并。
// 兼容 MySQL 5.7:不使用窗口函数,采用派生表聚合 MIN/MAX(created_at) + 标量子查询取极值 id 回表。
const intervalEdgeRows = await ctx.model.query(`
SELECT
g.stock_id,
g.space_id,
g.store_id,
ft.before_quantity,
lt.after_quantity,
ft.created_at
FROM (
SELECT
t.stock_id,
${transactionSource.spaceSelectSql},
t.store_id,
MIN(t.created_at) AS _min_ct,
MAX(t.created_at) AS _max_ct
FROM ${transactionSource.tableName} t
WHERE ${rangeWhereClauses.join(' AND ')}
GROUP BY t.stock_id${transactionSource.spaceGroupSql}, t.store_id
) g
LEFT JOIN ${transactionSource.tableName} ft
ON ft.id = (
SELECT MIN(t2.id)
FROM ${transactionSource.tableName} t2
WHERE ${rebindTableAlias(rangeWhereClauses, 't2').join(' AND ')}${isBySpace ? ' AND COALESCE(t2.space_id, 0) = g.space_id' : ''}
AND t2.created_at = g._min_ct
)
LEFT JOIN ${transactionSource.tableName} lt
ON lt.id = (
SELECT MAX(t3.id)
FROM ${transactionSource.tableName} t3
WHERE ${rebindTableAlias(rangeWhereClauses, 't3').join(' AND ')}${isBySpace ? ' AND COALESCE(t3.space_id, 0) = g.space_id' : ''}
AND t3.created_at = g._max_ct
)
ORDER BY g.stock_id ASC, g.space_id ASC, g.store_id ASC, g._min_ct ASC, g._max_ct ASC
t.id,
t.stock_id,
${transactionSource.spaceSelectSql},
t.store_id,
t.before_quantity,
t.after_quantity,
t.created_at
FROM ${transactionSource.tableName} t
WHERE ${rangeWhereClauses.join(' AND ')}
ORDER BY t.stock_id ASC${transactionSource.spaceOrderSql}, t.store_id ASC, t.created_at ASC, t.id ASC
`, {
replacements: rangeReplacements,
type: app.Sequelize.QueryTypes.SELECT,
@ -1222,33 +1120,17 @@ class StorageReportService extends Service {
preStartReplacements.baseStockIds = rangeReplacements.baseStockIds;
}
// start_time 之前的期初快照:SQL 端按维度键聚合取最新一条流水,每组仅返回 1 行,
// 避免把全部历史流水明细拉回 Node 内存归并。兼容 MySQL 5.7(聚合 + 标量子查询取极值 id 回表)。
preStartSnapshotRows = await ctx.model.query(`
SELECT
g.stock_id,
g.space_id,
g.store_id,
lt.after_quantity,
lt.created_at
FROM (
SELECT
t.stock_id,
${transactionSource.spaceSelectSql},
t.store_id,
MAX(t.created_at) AS _max_ct
FROM ${transactionSource.tableName} t
WHERE ${preStartWhereClauses.join(' AND ')}
GROUP BY t.stock_id${transactionSource.spaceGroupSql}, t.store_id
) g
LEFT JOIN ${transactionSource.tableName} lt
ON lt.id = (
SELECT MAX(t3.id)
FROM ${transactionSource.tableName} t3
WHERE ${rebindTableAlias(preStartWhereClauses, 't3').join(' AND ')}${isBySpace ? ' AND COALESCE(t3.space_id, 0) = g.space_id' : ''}
AND t3.created_at = g._max_ct
)
ORDER BY g.stock_id ASC, g.space_id ASC, g.store_id ASC, g._max_ct DESC
t.id,
t.stock_id,
${transactionSource.spaceSelectSql},
t.store_id,
t.after_quantity,
t.created_at
FROM ${transactionSource.tableName} t
WHERE ${preStartWhereClauses.join(' AND ')}
ORDER BY t.stock_id ASC${transactionSource.spaceOrderSql}, t.store_id ASC, t.created_at DESC, t.id DESC
`, {
replacements: preStartReplacements,
type: app.Sequelize.QueryTypes.SELECT,
@ -1310,8 +1192,7 @@ class StorageReportService extends Service {
beginTotal = toNumber(snapshot && snapshot.begin_total);
}
// 区间内无流水时,期末回退到期初,保证“期末 = 期初 + 入库 - 出库”恒等
const endTotal = hasSnapshot ? toNumber(snapshot && snapshot.end_total) : beginTotal;
const endTotal = hasSnapshot ? toNumber(snapshot && snapshot.end_total) : 0;
return {
start_time: startTime || null,
@ -1325,24 +1206,16 @@ class StorageReportService extends Service {
outbound_total: toNumber(rangeSum && rangeSum.outbound_total),
store_name: '',
warehouse_name: '',
// item_code/item_name 取快照查询结果,供按 item_code/item_name 排序使用;
// 最终展示值以 getStockDetails 为准(本字段作为回退)
item_name: row.item_name || '',
item_name: '',
barcode: '',
item_code: row.item_code || '',
item_code: '',
};
})
.filter(item => item.stock_id > 0 && item.store_id > 0);
// 先按最终规则排序,再做分页切片:仅对当前页行填充名称信息,
// 避免全量 SKU 的商品详情缓存/DB 查询(大数据量下为耗时大头)。
sortReportList(groupedList, false, sort);
const pageResult = paginateList(groupedList, pagination);
const pageItems = pageResult.items;
const groupedStockIds = [ ...new Set(pageItems.map(item => item.stock_id).filter(Boolean)) ];
const storeIdList = [ ...new Set(pageItems.map(item => item.store_id).filter(Boolean)) ];
const warehouseIdList = [ ...new Set(pageItems.map(item => item.warehouse_id).filter(Boolean)) ];
const groupedStockIds = [ ...new Set(groupedList.map(item => item.stock_id).filter(Boolean)) ];
const storeIdList = [ ...new Set(groupedList.map(item => item.store_id).filter(Boolean)) ];
const warehouseIdList = [ ...new Set(groupedList.map(item => item.warehouse_id).filter(Boolean)) ];
// 复用 getStockDetails 获取商品名称和条码
// store 模式下不传 warehouseId,避免用 store_id 误当 warehouse_id 过滤导致查不到商品
@ -1399,7 +1272,7 @@ class StorageReportService extends Service {
const warehouseMap = new Map(warehouseRows.map(item => [ Number(item.id), item ]));
const list = pageItems
const list = groupedList
.map(item => {
const stock = stockMap.get(item.stock_id) || {};
const store = storeMap.get(item.store_id) || {};
@ -1410,16 +1283,20 @@ class StorageReportService extends Service {
...item,
store_name: store.company_name || '',
warehouse_name: warehouse.company_name || '',
item_name: stock.item_name || item.item_name || '',
item_code: stock.item_code || item.item_code || '',
item_name: stock.item_name || '',
item_code: stock.item_code || '',
barcode: barcodeSet ? [ ...barcodeSet ].join(',') : '',
};
});
sortReportList(list, false, sort);
return {
code: 200,
message: '查询成功',
data: { list, pagination: pageResult.meta },
data: {
list,
},
};
}
@ -1440,8 +1317,6 @@ class StorageReportService extends Service {
store_id: storeId,
warehouse_id: whId,
quantity: toNumber(row.quantity),
item_code: row.item_code || '',
item_name: row.item_name || '',
});
}
@ -1462,8 +1337,6 @@ class StorageReportService extends Service {
store_id: storeId,
warehouse_id: whId,
quantity: 0,
item_code: '',
item_name: '',
});
}
}
@ -1473,7 +1346,7 @@ class StorageReportService extends Service {
return {
code: 200,
message: '查询成功',
data: { list: [], pagination: paginateList([], pagination).meta },
data: { list: [] },
};
}
@ -1546,10 +1419,9 @@ class StorageReportService extends Service {
outbound_total: 0,
store_name: '',
warehouse_name: '',
// item_code/item_name 取库存快照查询结果,供按 item_code/item_name 排序使用
item_name: row.item_name || '',
item_name: '',
barcode: '',
item_code: row.item_code || '',
item_code: '',
space_name: '',
});
}
@ -1560,8 +1432,7 @@ class StorageReportService extends Service {
: snapshot.has_snapshot
? toNumber(snapshot.begin_total)
: 0;
// 区间内无流水时,期末回退到期初,保证“期末 = 期初 + 入库 - 出库”恒等
const endTotal = snapshot.has_snapshot ? toNumber(snapshot.end_total) : beginTotal;
const endTotal = snapshot.has_snapshot ? toNumber(snapshot.end_total) : 0;
current.begin_total += beginTotal;
current.end_total += endTotal;
current.inbound_total += toNumber(rangeSum.inbound_total);
@ -1569,17 +1440,11 @@ class StorageReportService extends Service {
}
const groupedList = [ ...groupedMap.values() ];
// 先按最终规则排序,再做分页切片:仅对当前页行填充名称信息,避免全量 SKU 详情查询
sortReportList(groupedList, isBySpace, sort);
const pageResult = paginateList(groupedList, pagination);
const pageItems = pageResult.items;
const groupedStockIds = [ ...new Set(pageItems.map(item => item.stock_id).filter(Boolean)) ];
const storeIdList = [ ...new Set(pageItems.map(item => item.store_id).filter(Boolean)) ];
const warehouseIdList = [ ...new Set(pageItems.map(item => item.warehouse_id).filter(Boolean)) ];
const groupedStockIds = [ ...new Set(groupedList.map(item => item.stock_id).filter(Boolean)) ];
const storeIdList = [ ...new Set(groupedList.map(item => item.store_id).filter(Boolean)) ];
const warehouseIdList = [ ...new Set(groupedList.map(item => item.warehouse_id).filter(Boolean)) ];
const spaceIds = isBySpace
? [ ...new Set(pageItems.map(item => item.space_id).filter(id => Number(id) > 0)) ]
? [ ...new Set(groupedList.map(item => item.space_id).filter(id => Number(id) > 0)) ]
: [];
// 复用 getStockDetails 获取商品名称和条码
@ -1647,7 +1512,7 @@ class StorageReportService extends Service {
const spaceMap = new Map(spaceRows.map(item => [ Number(item.id), item ]));
const warehouseMap = new Map(warehouseRows.map(item => [ Number(item.id), item ]));
const list = pageItems
const list = groupedList
.map(item => {
const stock = stockMap.get(item.stock_id) || {};
const store = storeMap.get(item.store_id) || {};
@ -1659,8 +1524,8 @@ class StorageReportService extends Service {
...item,
store_name: store.company_name || '',
warehouse_name: warehouse.company_name || '',
item_name: stock.item_name || item.item_name || '',
item_code: stock.item_code || item.item_code || '',
item_name: stock.item_name || '',
item_code: stock.item_code || '',
barcode: barcodeSet ? [ ...barcodeSet ].join(',') : '',
};
@ -1671,10 +1536,14 @@ class StorageReportService extends Service {
return merged;
});
sortReportList(list, isBySpace, sort);
return {
code: 200,
message: '查询成功',
data: { list, pagination: pageResult.meta },
data: {
list,
},
};
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,75 +0,0 @@
'use strict';
/**
* 打印迁移阶段对应的数据库连接上下文信息。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {'up'|'down'} phase 迁移阶段。
* @param {string} table 迁移目标表名。
* @return {Promise<void>} 无返回值。
*/
const logMigrationDbContext = async (queryInterface, phase, table) => {
try {
const [ rows ] = await queryInterface.sequelize.query(
'SELECT DATABASE() AS db_name, @@hostname AS db_host, @@port AS db_port, CURRENT_USER() AS db_user'
);
const dbContext = Array.isArray(rows) && rows.length > 0 ? rows[0] : {};
console.log(
`[Migration DB Context] phase=${phase}; table=${table}; db_name=${dbContext.db_name || 'unknown'}; db_host=${dbContext.db_host || 'unknown'}; db_port=${dbContext.db_port || 'unknown'}; db_user=${dbContext.db_user || 'unknown'}`
);
} catch (error) {
console.warn(
`[Migration DB Context] 获取连接信息失败: phase=${phase}; table=${table}; reason=${error.message}`
);
}
};
/**
* Migration: add intercept_locked_quantity to wms_storage
* - intercept_locked_quantity: INT(12) NOT NULL DEFAULT 0 COMMENT '拦截锁定数量'
*
* Idempotent: uses queryInterface.describeTable to only add if missing.
*
* Raw SQL (MySQL 8+ supports IF NOT EXISTS):
* ALTER TABLE `wms_storage`
* ADD COLUMN IF NOT EXISTS `intercept_locked_quantity` INT(12) NOT NULL DEFAULT 0 COMMENT '拦截锁定数量';
*
* If MySQL < 8 (no IF NOT EXISTS), use INFORMATION_SCHEMA checks before ALTER.
*/
module.exports = {
/**
* 执行正向迁移,按需新增库存拦截锁定数量字段。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {Promise<void>} 无返回值。
*/
up: async (queryInterface, Sequelize) => {
const table = 'wms_storage';
await logMigrationDbContext(queryInterface, 'up', table);
const columns = await queryInterface.describeTable(table);
if (!columns.intercept_locked_quantity) {
await queryInterface.addColumn(table, 'intercept_locked_quantity', {
type: Sequelize.INTEGER(12),
allowNull: false,
defaultValue: 0,
comment: '拦截锁定数量',
});
}
},
/**
* 执行回滚迁移,按需删除库存拦截锁定数量字段。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
down: async queryInterface => {
const table = 'wms_storage';
await logMigrationDbContext(queryInterface, 'down', table);
const columns = await queryInterface.describeTable(table);
if (columns.intercept_locked_quantity) {
await queryInterface.removeColumn(table, 'intercept_locked_quantity');
}
},
};

View File

@ -1,84 +0,0 @@
'use strict';
/**
* 打印迁移阶段对应的数据库连接上下文信息。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {'up'|'down'} phase 迁移阶段。
* @param {string} table 迁移目标表名。
* @return {Promise<void>} 无返回值。
*/
const logMigrationDbContext = async (queryInterface, phase, table) => {
try {
const [ rows ] = await queryInterface.sequelize.query(
'SELECT DATABASE() AS db_name, @@hostname AS db_host, @@port AS db_port, CURRENT_USER() AS db_user'
);
const dbContext = Array.isArray(rows) && rows.length > 0 ? rows[0] : {};
console.log(
`[Migration DB Context] phase=${phase}; table=${table}; db_name=${dbContext.db_name || 'unknown'}; db_host=${dbContext.db_host || 'unknown'}; db_port=${dbContext.db_port || 'unknown'}; db_user=${dbContext.db_user || 'unknown'}`
);
} catch (error) {
console.warn(
`[Migration DB Context] 获取连接信息失败: phase=${phase}; table=${table}; reason=${error.message}`
);
}
};
/**
* Migration: add intercept locked quantity snapshots to wms_storage_transaction
* - before_intercept_locked_quantity: INT NULL COMMENT '变更前拦截锁定数量'
* - after_intercept_locked_quantity: INT NULL COMMENT '变更后拦截锁定数量'
*
* 与既有 before/after_locked_quantity 快照字段保持一致:
* 可空(NULL)、无默认值,由写入逻辑维护。
*
* Idempotent: uses queryInterface.describeTable to only add if missing.
*/
module.exports = {
/**
* 执行正向迁移,按需新增拦截锁定数量快照字段。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {Promise<void>} 无返回值。
*/
up: async (queryInterface, Sequelize) => {
const table = 'wms_storage_transaction';
await logMigrationDbContext(queryInterface, 'up', table);
const columns = await queryInterface.describeTable(table);
if (!columns.before_intercept_locked_quantity) {
await queryInterface.addColumn(table, 'before_intercept_locked_quantity', {
type: Sequelize.INTEGER,
allowNull: true,
comment: '变更前拦截锁定数量',
});
}
if (!columns.after_intercept_locked_quantity) {
await queryInterface.addColumn(table, 'after_intercept_locked_quantity', {
type: Sequelize.INTEGER,
allowNull: true,
comment: '变更后拦截锁定数量',
});
}
},
/**
* 执行回滚迁移,按需删除拦截锁定数量快照字段。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
down: async queryInterface => {
const table = 'wms_storage_transaction';
await logMigrationDbContext(queryInterface, 'down', table);
const columns = await queryInterface.describeTable(table);
if (columns.before_intercept_locked_quantity) {
await queryInterface.removeColumn(table, 'before_intercept_locked_quantity');
}
if (columns.after_intercept_locked_quantity) {
await queryInterface.removeColumn(table, 'after_intercept_locked_quantity');
}
},
};

View File

@ -1,19 +0,0 @@
'use strict';
/**
* order.packing.list 慢查询优化配套索引。
* 列表默认按 create_time DESC 排序(_buildListOrder),原 idx_warehouse_id 单列索引
* 命中后需 filesort 全仓库行数(生产实测 33722 行),新增 (warehouse_id, create_time)
* 复合索引消除 filesort,加速默认列表与导出查询。
*/
module.exports = {
async up(queryInterface) {
await queryInterface.addIndex('wms_pack_task', [ 'warehouse_id', 'create_time' ], {
name: 'idx_warehouse_create_time',
});
},
async down(queryInterface) {
await queryInterface.removeIndex('wms_pack_task', 'idx_warehouse_create_time');
},
};

View File

@ -1,89 +0,0 @@
'use strict';
const TABLE_NAME = 'wms_workbench';
async function indexExists(queryInterface, tableName, indexName) {
const indexes = await queryInterface.showIndex(tableName);
return (indexes || []).some(i => (typeof i === 'string' ? i : i.name) === indexName);
}
async function addIndexIfNotExists(queryInterface, tableName, indexName, options = {}) {
if (await indexExists(queryInterface, tableName, indexName)) {
console.log(`[idx] ${tableName}.${indexName} 已存在,跳过`);
return;
}
await queryInterface.addIndex(tableName, options.fields, {
name: indexName,
unique: !!options.unique,
});
console.log(`[idx] ${tableName}.${indexName} 已创建`);
}
async function dropIndexIfExists(queryInterface, tableName, indexName) {
if (await indexExists(queryInterface, tableName, indexName)) {
await queryInterface.removeIndex(tableName, indexName);
console.log(`[idx] ${tableName}.${indexName} 已删除`);
}
}
/**
* Migration: add login_code / token to wms_workbench
* - login_code: VARCHAR(64) NULL COMMENT '工作台登录码(前缀+随机,64位,全局唯一)'
* - token: VARCHAR(64) NULL COMMENT '工作台令牌(随机64位,绑定后生成)'
*
* Idempotent: 通过 describeTable / showIndex 判断后仅补齐缺失部分。
*/
module.exports = {
/**
* 执行正向迁移:新增 login_code、token 两列与 uk_login_code、idx_token 索引。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {Promise<void>} 无返回值。
*/
up: async (queryInterface, Sequelize) => {
const columns = await queryInterface.describeTable(TABLE_NAME);
if (!columns.login_code) {
await queryInterface.addColumn(TABLE_NAME, 'login_code', {
type: Sequelize.STRING(64),
allowNull: true,
comment: '工作台登录码(前缀+随机,64位,全局唯一)',
});
}
if (!columns.token) {
await queryInterface.addColumn(TABLE_NAME, 'token', {
type: Sequelize.STRING(64),
allowNull: true,
comment: '工作台令牌(随机64位,绑定后生成)',
});
}
await addIndexIfNotExists(queryInterface, TABLE_NAME, 'uk_login_code', {
fields: [ 'login_code' ],
unique: true,
});
await addIndexIfNotExists(queryInterface, TABLE_NAME, 'idx_token', {
fields: [ 'token' ],
});
},
/**
* 执行回滚迁移:删除索引与新增列。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
down: async queryInterface => {
await dropIndexIfExists(queryInterface, TABLE_NAME, 'uk_login_code');
await dropIndexIfExists(queryInterface, TABLE_NAME, 'idx_token');
const columns = await queryInterface.describeTable(TABLE_NAME);
if (columns.login_code) {
await queryInterface.removeColumn(TABLE_NAME, 'login_code');
}
if (columns.token) {
await queryInterface.removeColumn(TABLE_NAME, 'token');
}
},
};

View File

@ -1,86 +0,0 @@
'use strict';
const TABLE_NAME = 'wms_workbench_member';
/**
* Migration: create wms_workbench_member(工作台成员/用户登录副表)
* - user_id 允许为空:非系统账号用户(如未注册 wms_account 的硬件操作员)以 NULL 记录,名称存 user_name 快照。
* - 软删除(deleted_at),移除成员通过 workbench.removeMember 完成。
*
* Idempotent: 表已存在时跳过创建。
*/
module.exports = {
/**
* 执行正向迁移:创建工作台成员副表与索引。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {Promise<void>} 无返回值。
*/
up: async (queryInterface, Sequelize) => {
const tables = await queryInterface.showAllTables();
const exists = tables.some(t => (typeof t === 'string' ? t : (t.tableName || t.name)) === TABLE_NAME);
if (exists) return;
await queryInterface.createTable(TABLE_NAME, {
id: {
type: Sequelize.BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键ID',
},
workbench_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: false,
comment: '工作台ID,关联 wms_workbench.id',
},
user_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
comment: '账号ID,关联 wms_account.id;非系统账号用户为 NULL',
},
user_name: {
type: Sequelize.STRING(128),
allowNull: true,
comment: '成员名称快照(非系统账号用户显示名)',
},
created_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
updated_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
comment: '更新时间',
},
deleted_at: {
type: Sequelize.DATE,
allowNull: true,
comment: '软删除时间',
},
});
// 按工作台查询成员
await queryInterface.addIndex(TABLE_NAME, [ 'workbench_id' ], {
name: 'idx_workbench_id',
});
// 按账号反查成员
await queryInterface.addIndex(TABLE_NAME, [ 'user_id' ], {
name: 'idx_user_id',
});
},
/**
* 执行回滚迁移:删除工作台成员副表。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
down: async queryInterface => {
await queryInterface.dropTable(TABLE_NAME);
},
};

View File

@ -1,77 +0,0 @@
'use strict';
const TABLE_NAME = 'wms_workbench';
async function indexExists(queryInterface, tableName, indexName) {
const indexes = await queryInterface.showIndex(tableName);
return (indexes || []).some(i => (typeof i === 'string' ? i : i.name) === indexName);
}
async function dropIndexIfExists(queryInterface, tableName, indexName) {
if (await indexExists(queryInterface, tableName, indexName)) {
await queryInterface.removeIndex(tableName, indexName);
console.log(`[idx] ${tableName}.${indexName} 已删除`);
}
}
async function addIndexIfNotExists(queryInterface, tableName, indexName, options = {}) {
if (await indexExists(queryInterface, tableName, indexName)) {
console.log(`[idx] ${tableName}.${indexName} 已存在,跳过`);
return;
}
await queryInterface.addIndex(tableName, options.fields, {
name: indexName,
unique: !!options.unique,
});
console.log(`[idx] ${tableName}.${indexName} 已创建`);
}
/**
* Migration: remove barcode from wms_workbench(工作台条码字段未使用,下线)
* - 删除列 barcode VARCHAR(100)
* - 删除索引 idx_barcode、uk_warehouse_barcode(仓库级唯一条码索引)
*
* Idempotent: 通过 describeTable / showIndex 判断后仅删除存在部分。
*/
module.exports = {
/**
* 执行正向迁移:先删索引,再删 barcode 列。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
up: async queryInterface => {
await dropIndexIfExists(queryInterface, TABLE_NAME, 'uk_warehouse_barcode');
await dropIndexIfExists(queryInterface, TABLE_NAME, 'idx_barcode');
const columns = await queryInterface.describeTable(TABLE_NAME);
if (columns.barcode) {
await queryInterface.removeColumn(TABLE_NAME, 'barcode');
}
},
/**
* 执行回滚迁移:恢复 barcode 列与索引。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {Promise<void>} 无返回值。
*/
down: async (queryInterface, Sequelize) => {
const columns = await queryInterface.describeTable(TABLE_NAME);
if (!columns.barcode) {
await queryInterface.addColumn(TABLE_NAME, 'barcode', {
type: Sequelize.STRING(100),
allowNull: true,
comment: '工作台条码(用户自定义,仓库内唯一)',
});
}
await addIndexIfNotExists(queryInterface, TABLE_NAME, 'idx_barcode', {
fields: [ 'barcode' ],
});
await addIndexIfNotExists(queryInterface, TABLE_NAME, 'uk_warehouse_barcode', {
fields: [ 'warehouse_id', 'barcode', 'deleted_at' ],
unique: true,
});
},
};

View File

@ -1,62 +0,0 @@
'use strict';
/**
* 为拣货任务表 wms_wave_pick_task 增加 batch_no_array 字段。
*
* 背景:
* 一个拣货任务可能涉及多个波次,此前任务主表未冗余波次号,
* 统计/查询需要关联 wms_wave_pick_task_wave,不便。
*
* 变更:
* 1. wms_wave_pick_task 新增 batch_no_array:TEXT,可空,
* 存储逗号分隔的波次号列表,如 'WAVE202401001,WAVE202401002',
* 便于 FIND_IN_SET / LIKE 等统计与查询。
*/
/**
* 获取表字段定义。
*
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} tableName 表名。
* @return {Promise<Object>} 字段定义对象。
*/
const getTableColumns = async (queryInterface, tableName) => {
return queryInterface.describeTable(tableName);
};
module.exports = {
/**
* 正向迁移:为拣货任务表补充 batch_no_array 字段。
*
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。
* @return {Promise<void>} 无返回值。
*/
up: async (queryInterface, Sequelize) => {
const tableName = 'wms_wave_pick_task';
const columnsBefore = await getTableColumns(queryInterface, tableName);
if (!columnsBefore.batch_no_array) {
await queryInterface.addColumn(tableName, 'batch_no_array', {
type: Sequelize.TEXT,
allowNull: true,
comment: '波次号列表(逗号分隔),方便统计和查询',
});
}
},
/**
* 回滚迁移:若 batch_no_array 字段存在则删除。
*
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
down: async queryInterface => {
const tableName = 'wms_wave_pick_task';
const columnsBefore = await getTableColumns(queryInterface, tableName);
if (columnsBefore.batch_no_array) {
await queryInterface.removeColumn(tableName, 'batch_no_array');
}
},
};

View File

@ -1,74 +0,0 @@
'use strict';
/**
* 为波次表 wms_wave_batch 增加领料人字段。
*
* 背景:
* 整波领单(pick.waveClaimScan)是波次级操作,此前仅写入订单操作日志
* (ORDER_WAVE_CLAIM),波次表无领料人记录,不便于核对领料人与领料时间。
*
* 变更:
* 1. wms_wave_batch 新增 claim_operator:VARCHAR(50),可空,领料人姓名。
* 2. wms_wave_batch 新增 claim_time:DATETIME,可空,领料时间。
* 3. 模型定义同步更新(app/model/wave_batch.js)。
*/
const TABLE_NAME = 'wms_wave_batch';
/**
* 获取表字段定义。
*
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} tableName 表名。
* @return {Promise<Object>} 字段定义对象。
*/
const getTableColumns = async (queryInterface, tableName) => {
return queryInterface.describeTable(tableName);
};
module.exports = {
/**
* 正向迁移:为波次表补充领料人、领料时间字段。
*
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。
* @return {Promise<void>} 无返回值。
*/
up: async (queryInterface, Sequelize) => {
const columnsBefore = await getTableColumns(queryInterface, TABLE_NAME);
if (!columnsBefore.claim_operator) {
await queryInterface.addColumn(TABLE_NAME, 'claim_operator', {
type: Sequelize.STRING(50),
allowNull: true,
comment: '领料人',
});
}
if (!columnsBefore.claim_time) {
await queryInterface.addColumn(TABLE_NAME, 'claim_time', {
type: Sequelize.DATE,
allowNull: true,
comment: '领料时间',
});
}
},
/**
* 回滚迁移:若领料字段存在则删除。
*
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
down: async queryInterface => {
const columnsBefore = await getTableColumns(queryInterface, TABLE_NAME);
if (columnsBefore.claim_time) {
await queryInterface.removeColumn(TABLE_NAME, 'claim_time');
}
if (columnsBefore.claim_operator) {
await queryInterface.removeColumn(TABLE_NAME, 'claim_operator');
}
},
};

View File

@ -1,73 +0,0 @@
'use strict';
/**
* 为拣货任务表 wms_wave_pick_task 增加领料人字段。
*
* 背景:
* 整波领单(pick.waveClaimScan)会回写订单表 claim_operator_id/claim_operator;
* 拣货任务创建时需从订单冗余领料人,便于任务列表追溯领料人。
*
* 变更:
* 1. wms_wave_pick_task 新增 claim_operator_id:BIGINT,可空,领料人工号ID。
* 2. wms_wave_pick_task 新增 claim_operator:VARCHAR(50),可空,领料人姓名。
*/
const TABLE_NAME = 'wms_wave_pick_task';
/**
* 获取表字段定义。
*
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} tableName 表名。
* @return {Promise<Object>} 字段定义对象。
*/
const getTableColumns = async (queryInterface, tableName) => {
return queryInterface.describeTable(tableName);
};
module.exports = {
/**
* 正向迁移:为拣货任务表补充领料人工号与姓名字段。
*
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {typeof import('sequelize')} Sequelize Sequelize 类型集合。
* @return {Promise<void>} 无返回值。
*/
up: async (queryInterface, Sequelize) => {
const columnsBefore = await getTableColumns(queryInterface, TABLE_NAME);
if (!columnsBefore.claim_operator_id) {
await queryInterface.addColumn(TABLE_NAME, 'claim_operator_id', {
type: Sequelize.BIGINT,
allowNull: true,
comment: '领料人工号ID',
});
}
if (!columnsBefore.claim_operator) {
await queryInterface.addColumn(TABLE_NAME, 'claim_operator', {
type: Sequelize.STRING(50),
allowNull: true,
comment: '领料人',
});
}
},
/**
* 回滚迁移:若领料字段存在则删除。
*
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
down: async queryInterface => {
const columnsBefore = await getTableColumns(queryInterface, TABLE_NAME);
if (columnsBefore.claim_operator) {
await queryInterface.removeColumn(TABLE_NAME, 'claim_operator');
}
if (columnsBefore.claim_operator_id) {
await queryInterface.removeColumn(TABLE_NAME, 'claim_operator_id');
}
},
};

View File

@ -1,105 +0,0 @@
'use strict';
/**
* 订单表增加 wave_scope(波次范围)字段。
*
* 取值约定(与 order 工作台虚拟筛选 wave_scope 一致):
* - 0 = 未分配波次
* - 1 = 团购
* - 2 = 散单
* 默认 0。
*
* 覆盖范围:
* - 基表 wms_order_delivery;
* - 全部仓库分表 wms_order_delivery_{wh}(current)及
* _{wh}_history / _{wh}_dispatch / _{wh}_outsourced。
*
* 幂等:列已存在则跳过。分表模型由 app/model/order_delivery_factory.js
* 运行时 drift 同步兜底,本迁移提前补齐避免运行时 ALTER。
*/
const BASE_TABLE = 'wms_order_delivery';
const SHARD_PATTERN = /^wms_order_delivery_(\d+)(?:_(history|dispatch|outsourced))?$/;
const COLUMN_NAME = 'wave_scope';
/**
* 列举库内全部订单分表。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<string[]>} 分表名列表。
*/
async function listOrderShards(queryInterface) {
const [ rows ] = await queryInterface.sequelize.query(
'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES '
+ 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE \'wms_order_delivery\\_%\' '
+ 'ORDER BY TABLE_NAME'
);
return (rows || [])
.map(row => String(row.tableName || row.TABLE_NAME || ''))
.filter(name => SHARD_PATTERN.test(name));
}
/**
* 判断列是否已存在。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} tableName 表名。
* @param {string} columnName 列名。
* @return {Promise<boolean>} 是否存在。
*/
async function columnExists(queryInterface, tableName, columnName) {
const described = await queryInterface.describeTable(tableName);
return Boolean(described && described[columnName]);
}
module.exports = {
/**
* 执行迁移:为基表与全部分表增加 wave_scope 列。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 构造器。
* @return {Promise<void>} 无返回值。
*/
async up(queryInterface, Sequelize) {
const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ];
const results = [];
for (const tableName of tables) {
if (await columnExists(queryInterface, tableName, COLUMN_NAME)) {
results.push({ tableName, action: 'skip', reason: 'exists' });
continue;
}
await queryInterface.addColumn(tableName, COLUMN_NAME, {
type: Sequelize.TINYINT(4),
allowNull: false,
defaultValue: 0,
comment: '波次范围:0未分配波次 1团购 2散单',
});
results.push({ tableName, action: 'added' });
}
console.log('[20260905100000-add-wave-scope-to-order-delivery] up results:', JSON.stringify(results));
},
/**
* 回滚迁移:移除 base 与全部分表的 wave_scope 列。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
async down(queryInterface) {
const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ];
const results = [];
for (const tableName of tables) {
if (!await columnExists(queryInterface, tableName, COLUMN_NAME)) {
results.push({ tableName, action: 'skip', reason: 'missing' });
continue;
}
await queryInterface.removeColumn(tableName, COLUMN_NAME);
results.push({ tableName, action: 'removed' });
}
console.log('[20260905100000-add-wave-scope-to-order-delivery] down results:', JSON.stringify(results));
},
};

View File

@ -1,102 +0,0 @@
'use strict';
/**
* 存量订单回填 wave_scope(波次范围)字段。
*
* 口径(与波次生成写入逻辑 resolveWaveScopeByWaveMeta 一致):
* - 0 = 未分配波次(wave_id = 0,默认值无需更新);
* - 1 = 大团购:wms_wave_batch.wave_type = 1 且 source = 0;
* - 3 = 小团购:wms_wave_batch.wave_type = 1 且 source = 2;
* - 2 = 散单:其余有波次的订单(wave_type = 2,或 wave_type = 1 且 source = 1,
* 或 wave_id 指向的波次已不存在)。
*
* 覆盖范围:基表 wms_order_delivery 与全部仓库分表
* (current/history/dispatch/outsourced)。
*
* 幂等:按 CASE 规则全量覆盖写入,重复执行结果一致。
*/
const BASE_TABLE = 'wms_order_delivery';
const SHARD_PATTERN = /^wms_order_delivery_(\d+)(?:_(history|dispatch|outsourced))?$/;
/**
* 列举库内全部订单分表。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<string[]>} 分表名列表。
*/
async function listOrderShards(queryInterface) {
const [ rows ] = await queryInterface.sequelize.query(
'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES '
+ 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE \'wms_order_delivery\\_%\' '
+ 'ORDER BY TABLE_NAME'
);
return (rows || [])
.map(row => String(row.tableName || row.TABLE_NAME || ''))
.filter(name => SHARD_PATTERN.test(name));
}
/**
* 提取受影响行数。
* @param {*} updateResult query 返回结果。
* @return {number} 受影响行数。
*/
function extractAffectedRows(updateResult) {
if (Array.isArray(updateResult)) {
const meta = updateResult[1];
return Number(meta && (meta.affectedRows || meta.affectedCount || meta.rowCount) || 0);
}
if (updateResult && typeof updateResult === 'object') {
return Number(updateResult.affectedRows || updateResult.affectedCount || updateResult.rowCount || 0);
}
return 0;
}
module.exports = {
/**
* 执行迁移:按波次类型/来源回填 wave_scope。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
async up(queryInterface) {
const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ];
const results = [];
for (const tableName of tables) {
const updateResult = await queryInterface.sequelize.query(`
UPDATE \`${tableName}\` o
LEFT JOIN wms_wave_batch wb ON wb.wave_id = o.wave_id
SET o.wave_scope = CASE
WHEN wb.wave_type = 1 AND wb.source = 0 THEN 1
WHEN wb.wave_type = 1 AND wb.source = 2 THEN 3
ELSE 2
END
WHERE o.wave_id > 0
`);
results.push({ tableName, affectedRows: extractAffectedRows(updateResult) });
}
console.log('[20260905130000-backfill-order-wave-scope] up results:', JSON.stringify(results));
},
/**
* 回滚迁移:将已分配波次订单的 wave_scope 重置为 0(未回填状态)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
async down(queryInterface) {
const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ];
const results = [];
for (const tableName of tables) {
const updateResult = await queryInterface.sequelize.query(`
UPDATE \`${tableName}\`
SET wave_scope = 0
WHERE wave_id > 0
`);
results.push({ tableName, affectedRows: extractAffectedRows(updateResult) });
}
console.log('[20260905130000-backfill-order-wave-scope] down results:', JSON.stringify(results));
},
};

View File

@ -164,12 +164,6 @@ report.generate(method 层,异步任务,入参 report_id)
修复前不含 `store_id`,不同货主的投递/通知消息会互相复用、串扰。
- **货主维度强校验**(2026-08-31):`processOne` 对 `store_id`/`report_definition_id` 强校验,
任一无效直接抛错「投递计划维度非法(…),拒绝生成报表」,绝不生成跨货主报表。
- **文件消息投递目标与群路由口径**(2026-09-01 修复 G1 缺陷):报表文件消息(inbox 渠道)
**只投递到计划配置的通知群 `notify_group_ids`**,不再投递任意「货主默认群」;
未配置通知群的历史计划保持旧行为,回退投递到货主默认站内信群(`group_type='store'`,按 id ASC 取最早一条)。
配置了群但全部不可达(不存在/已删除/被屏蔽/仓库不一致)时直接抛错「配置的通知群不可达…无法投递」
进入 `failed` 退避重试(`MAX_RETRY=3`,退避 `retry_count × 60s`),不再静默回退到未配置群。
投递与文本通知共用 `resolveNotifyGroups` 解析口径(过滤 `is_blocked=1`、软删、仓库维度一致)。
- **失败自动重推**:inbox 推送失败(`success=false` 或消息回写 `push_status=3`)时,立即复用
`inbox.message.retry` **重推一次**(`ext_id` 幂等复用同一条消息记录,不重复写);重推仍失败进入
`failed` 退避重试:`MAX_RETRY=3`,退避 `retry_count × 60s`;重试扫描条件
@ -201,10 +195,6 @@ report.generate(method 层,异步任务,入参 report_id)
- 元素为 `wms_inbox_group.id`(内部群 ID),**正整数**、自动去重并升序,最多 **20** 个。
- 保存时校验存在性:软删(已删除)的群报错并**列出缺失 ID**;被屏蔽(`is_blocked=1`)的群仍可选中,
屏蔽属于发送时过滤维度。
- **同时为报表文件消息的投递目标**:计划配置了 `notify_group_ids` 时,文件消息(inbox 渠道)
**仅逐群投递到这些配置群**,不再投递任意「货主默认群」;未配置通知群的历史计划回退投递到
货主默认站内信群(`group_type='store'`,取最早一条);配置的群全部不可达
(不存在/已删除/被屏蔽/仓库不一致)时投递抛错进入 `failed` 退避重试。
- 发送时逐群推送(群维度协议字段 `group_id`/`group_name` 为单值),并再次过滤
`is_blocked=1`、软删、仓库维度不一致的群;此类群不发送且不进入投递记录快照。

View File

@ -1,372 +1,4 @@
[
{
"version": "2026.09.05-storageTransaction-list-detail",
"date": "2026-09-05",
"summary": "storage.transaction.list 实现纠正:原实现错误查询 wms_stock_transaction 并按商品+单据类型聚合(合并模式),现改为查询 wms_storage_transaction 的逐条流水明细(与 stock.transaction.list 形态一致:裸 SQL 列白名单 + COUNT 分页 + 排序白名单)。聚合查询移除后,生产单仓库 160 万行聚合慢查询(约 9s)不复存在;明细查询实测 COUNT 约 0.2s。",
"methods": [
"storage.transaction.list"
],
"notes": [
"代码变更:systems/stock_transaction.js list() 由 ORM 聚合查询重写为 wms_storage_transaction 裸 SQL 逐条明细(列白名单含 storage_id/space_id/inventory_type/source_order_codes/before/after_intercept_locked_quantity,LEFT JOIN wms_stock_warehouse 返回 stockItem);systemMethods/storage/transaction.js 解构 whereValue 逐字段传参,warehouse_id 由服务端从 ctx.user.store_id 注入。",
"行为变更:group_by_batch 参数废弃,恒返回逐条明细;原合并模式响应(quantity 合计/first_created_at/last_created_at/record_count)不再返回。",
"where 支持字段:transaction_type、stock_id/stock_ids、space_id、store_id/store_ids、order_type、order_no(模糊)、batch_no、inventory_type、operator_name(模糊)、order_id、created_at(between)与 start_time/end_time;keyword 支持顶层或 where 内。",
"排序白名单:created_at、quantity、stock_id、store_id、warehouse_id、space_id,非法回退 created_at DESC;pageSize 上限 200。",
"前端调用方需按逐条明细结构适配(原合并模式渲染逻辑作废)。"
]
},
{
"version": "2026.09.04-storage.entry.quickInbound-noneed-notice",
"date": "2026-09-04",
"type": "enhanced",
"summary": "storage.entry.quickInbound 新增参数 noNeedNotice(默认 0):0 时快捷直入完成后通知货主,1 时跳过通知,通知失败仍不影响入库主流程。",
"methods": [
"storage.entry.quickInbound"
],
"notes": [
"app/service/systemMethods/storage/entry.js:quickInbound 解析 data.noNeedNotice(默认 0)并透传底层 quickInbound({ id, noNeedNotice })",
"app/service/systems/storage/entry.js:quickInbound(data) 解析 data.noNeedNotice(Number 归一化),事务提交后仅当 noNeedNotice !== 1 时调用 notifyEntryOrderCompleted",
"methods/system.json:storage.entry.quickInbound 新增 noNeedNotice 参数说明与 description 补充;版本 0.3.83 -> 0.3.84(docMeta.version),updatedAt 保持 2026-09-04",
"无数据库 schema 变更,未执行任何写库操作"
],
"module": "storage.entry"
},
{
"version": "2026.09.04-storage.entry.commit-noneed-notice",
"date": "2026-09-04",
"type": "enhanced",
"summary": "storage.entry.commit 新增参数 noNeedNotice(默认 0):0 时入库完成后通知货主,1 时跳过通知,通知失败仍不影响入库主流程。",
"methods": [
"storage.entry.commit"
],
"notes": [
"app/service/systemMethods/storage/entry.js:commit 解析 data.noNeedNotice(默认 0)并透传底层 inboundDirectLog.commit(entry_order_id, noNeedNotice)",
"app/service/systems/inbound_direct_log.js:commit(entryOrderId, noNeedNotice = 0),事务提交后仅当 Number(noNeedNotice) !== 1 时调用 notifyEntryOrderCompleted(字符串 '1' 也兼容)",
"methods/system.json:storage.entry.commit 新增 noNeedNotice 参数说明与 description 补充;版本 0.3.82 -> 0.3.83(docMeta.version),updatedAt 保持 2026-09-04",
"无数据库 schema 变更,未执行任何写库操作"
],
"module": "storage.entry"
},
{
"version": "2026.09.04-stock.report.export-stock-id-fix",
"date": "2026-09-04",
"type": "fixed",
"summary": "修复 stock.report.export(含 search/searchStore/exportStore)where.stock_id 传数组时导出空白的问题:单数 stock_id 现兼容数组,避免被再包裹一层导致嵌套数组归一化为 NaN 全量过滤;同时修复默认分页上线后导出内部 search 被截断为第一页 20 条导致汇总/明细缺数据的回归。",
"methods": [
"stock.report.search",
"stock.report.searchStore",
"stock.report.export",
"stock.report.exportStore"
],
"notes": [
"根因:where.stock_id 传数组时 systemMethods 层 [ stockIdRaw ] 再包一层形成嵌套数组,systems 层 Number(嵌套数组)=NaN 被全部过滤 → 汇总空 → 导出空白",
"app/service/systemMethods/stock/report.js:search/searchStore/export/exportStore 四处 stock_id 解析兼容数组(Array.isArray ? 原样 : 包单元素)",
"app/service/systems/storage/report.js:search 中 stockIds 归一化改用 flat() 防御嵌套;export 内部调用 search 显式传全量分页 { page: 1, pageSize: 1000000 }(新增常量 EXPORT_FULL_PAGE_SIZE),避免默认分页截断",
"methods/system.json:search/searchStore 的 stock_id 描述补充“兼容数组”;export/exportStore 的 where 描述补充 stock_id/stock_ids/keyword,export 新增 export_mode 参数说明;版本 0.3.81 -> 0.3.82(docMeta.version),updatedAt 保持 2026-09-04",
"验证:开发库 where.stock_id 传 20 个 ID 的 search 返回 20 行;export 同条件任务成功并产出 832KB Excel(非空白);无数据库 schema 变更,未执行任何写库操作"
],
"module": "stock.report"
},
{
"version": "2026.09.04-stock.report.search-sort-fields",
"date": "2026-09-04",
"type": "enhanced",
"summary": "stock.report.search 排序白名单扩充:新增 stock_id、item_code、item_name(与 begin_total、inbound_total、outbound_total、end_total 共 7 个字段),item_code/item_name 按字典序、其余按数值排序,与其他列表页面的 sort.sortField/sortOrder 用法保持一致。",
"methods": [
"stock.report.search",
"stock.report.searchStore",
"stock.report.export",
"stock.report.exportStore"
],
"notes": [
"app/service/systems/storage/report.js:SORT_FIELD_WHITE_LIST 扩充为 7 字段;新增 STRING_SORT_FIELD_SET(item_code/item_name 字典序比较,localeCompare),其余字段数值比较;by_space=false 分支 baseStockRows 查询新增 sw.item_code/sw.item_name,groupedList 行携带(供排序与展示回退);by_space=true 分支 baseStorageRows LEFT JOIN wms_stock_warehouse sw ON sw.id=s.stock_id 取 MAX(sw.item_code)/MAX(sw.item_name);两分支最终 item_name/item_code 展示优先 getStockDetails,回退快照值",
"app/service/systemMethods/stock/report.js:search JSDoc 同步白名单",
"methods/system.json:search/searchStore/export/exportStore 的 sort 参数描述同步新白名单;版本 0.3.80 -> 0.3.81(docMeta.version),updatedAt 更新为 2026-09-04",
"无数据库 schema 变更,未执行任何写库操作"
],
"module": "stock.report"
},
{
"version": "2026.09.03-stock.report.search-default-pagination",
"date": "2026-09-03",
"type": "updated",
"summary": "stock.report.search 分页改为默认生效:不传 data.pagination 或传非法分页时,默认按 page=1、pageSize=20 返回第一页,响应始终携带 data.pagination 分页信息(原为未传时全量返回)。分页参数同时支持顶层 page/pageSize/page_size(与其他 list 接口一致,顶层值优先)。",
"methods": [
"stock.report.search"
],
"notes": [
"app/service/systems/storage/report.js:paginateList 改为默认分页语义(未传/非法回退 page=1、pageSize=20,新增模块常量 DEFAULT_PAGE_SIZE=20);两个输出分支(by_space=false/true)响应 data.pagination 恒返回;200 空列表 early return 同步携带 pagination 元信息(total=0)",
"app/service/systemMethods/stock/report.js:search 分页参数解析与其他 list 一致——data.pagination 优先,兼容顶层 data.page 与 data.pageSize / data.page_size(顶层值覆盖 pagination 对象);searchStore(货主侧)暂不支持分页,行为不变",
"methods/system.json:pagination 参数与 data.list/data.pagination 响应描述更新为默认分页语义,data.pagination required 改为 true,新增 page/pageSize 顶层兼容参数条目;版本 0.3.78 -> 0.3.80(docMeta.version),updatedAt 保持 2026-09-03",
"无数据库 schema 变更,未执行任何写库操作"
],
"module": "stock.report"
},
{
"version": "2026.09.03-stock.report.search-pagination",
"date": "2026-09-03",
"type": "enhanced",
"summary": "stock.report.search 新增分页支持:请求体 data.pagination = { page, pageSize } 时,先按现有排序规则排序再切片,仅对当前页行加载名称信息,响应 data.pagination 返回分页元信息;未传或非法分页保持全量返回(向后兼容)。",
"methods": [
"stock.report.search"
],
"notes": [
"app/service/systems/storage/report.js:新增模块函数 paginateList(归一化 page/pageSize,非法/未传返回 null 表示不分页);search 方法新增 pagination 入参,两个输出分支(by_space=false/true)均改为 sortReportList 先排序 → paginateList 切片 → 仅对 pageItems 加载名称信息(getStockDetails/Store/LocationSpace 只查当前页),分页时响应 data.pagination = { page, pageSize, total, totalPages, hasPrevious, hasNext }",
"app/service/systemMethods/stock/report.js:search 透传 data.pagination(JSDoc 同步);searchStore(货主侧)暂不支持分页",
"性能背景:生产实测全仓 33353 SKU 无分页约 4.6~8.8s,其中 getStockDetails 名称加载为耗时大头;分页后仅当前页触发缓存/DB 查询",
"methods/system.json:stock.report.search 新增 pagination/pagination.page/pagination.pageSize 参数与 data.pagination 响应字段;版本 0.3.77 -> 0.3.78(docMeta.version),updatedAt 保持 2026-09-03",
"无数据库 schema 变更,未执行任何写库操作"
],
"module": "stock.report"
},
{
"version": "2026.09.03-workbench-barcode-removed",
"date": "2026-09-03",
"type": "removed",
"summary": "下线工作台条码 barcode 相关字段(未使用):wms_workbench 删除 barcode 列及 idx_barcode、uk_warehouse_barcode 索引;workbench.list 移除 barcode 筛选与列表项、workbench.create/update 不再接收 barcode;workbench.checkBarcode 接口整体移除(方法、权限白名单、文档条目同步删除);order.packing.list / order.packing.detail 响应移除 workbench_barcode 字段(源列已删,恒为 null 无意义)。",
"methods": [
"workbench.list",
"workbench.create",
"workbench.update",
"workbench.getWorkbenchInfo",
"workbench.checkBarcode",
"order.packing.list",
"order.packing.detail"
],
"notes": [
"database/migrations/20260903180000-remove-barcode-from-wms-workbench.js:先删 uk_warehouse_barcode、idx_barcode 索引再删 barcode 列(幂等 describeTable/showIndex 判断),up/down 对称(down 恢复列与索引),已在开发库执行并验证(wms_workbench 现为 12 列)",
"app/model/workbench.js:移除 barcode 字段定义与 idx_barcode、uk_warehouse_barcode 索引声明",
"app/service/systems/workbench.js:list 移除 where.barcode 筛选;create/update 移除 barcode 处理;删除 checkBarcodeExists;formatWorkbenchTokenInfo 移除 barcode 输出",
"app/service/systemMethods/workbench.js:删除 checkBarcode 方法,systemInit 免权限/免日志/免鉴权白名单移除 checkBarcode",
"app/service/systems/order_packing.js:list/detail 扁平化输出移除 workbench_barcode 字段",
"methods/system.json:工作台模块删除 workbench.checkBarcode 条目、list/create/update/getWorkbenchInfo 条目按无 barcode 形态重写;订单打包模块 order.packing.list / order.packing.detail description 移除 workbench_barcode 说明;版本 0.3.76 -> 0.3.77(docMeta.version),updatedAt 保持 2026-09-03",
"本次未执行任何直接 DDL/写库操作;仅通过迁移文件在开发库(127.0.0.1:3307)执行 schema 变更并验证;生产库迁移需发布时按标准流程执行"
],
"module": "workbench"
},
{
"version": "2026.09.03-workbench-member-bind",
"date": "2026-09-03",
"type": "enhanced",
"summary": "新增接口 workbench.bindMember(免登录、免鉴权):入参用户ID(可为空,兼容非系统账号用户)+ 姓名(必填非空)+ 工作台 token,按 token 解析工作台后在 wms_workbench_member 副表新增成员行(user_id 空时仅存 user_name 姓名快照),返回新建成员行(id/workbench_id/user_id/user_name);token 无效返回失败 code=403。与已上线的 workbench.removeMember 构成成员增删闭环。",
"methods": [
"workbench.bindMember"
],
"notes": [
"app/service/systems/workbench.js:新增 bindWorkbenchMember(token 校验 → 姓名必填校验 → 用户ID归一化(空/非正整数处理)→ resolveWorkbenchByToken 解析工作台 → WorkbenchMember.create),复用既有 resolveWorkbenchByToken 缓存优先逻辑",
"app/service/systemMethods/workbench.js:新增 bindMember 薄出口,systemInit 免登录/免权限/免日志/免鉴权声明补充 bindMember",
"methods/system.json:工作台模块新增 workbench.bindMember 条目;版本 0.3.75 -> 0.3.76(docMeta.version),updatedAt 保持 2026-09-03",
"无数据库 schema 变更(复用 wms_workbench_member 表),未执行任何写库操作"
],
"module": "workbench"
},
{
"version": "2026.09.03-workbench-member-remove",
"date": "2026-09-03",
"type": "enhanced",
"summary": "工作台新增成员/用户登录副表 wms_workbench_member(id/workbench_id/user_id/user_name/created_at/updated_at/deleted_at,user_id 允许为空以兼容非系统账号用户,user_name 存名称快照;索引 idx_workbench_id/idx_user_id)。新增接口 workbench.removeMember(免登录、免鉴权):入参成员行 ids 与工作台 token,按 token 解析工作台后仅软删除归属于该工作台的成员行,返回 removed 数量与 ids 列表;token 无效返回失败 code=403,无可移除成员返回 code=404。",
"methods": [
"workbench.removeMember"
],
"notes": [
"database/migrations/20260903150000-create-wms-workbench-member.js:创建 wms_workbench_member 表(幂等 showAllTables 判断)+ idx_workbench_id/idx_user_id 索引,up/down 对称,已在开发库执行并验证(user_id 列 IS_NULLABLE=YES)",
"app/model/workbench_member.js:新增 WorkbenchMember 模型(paranoid 软删除),associate 声明 belongsTo Workbench(as workbench)与 belongsTo Account(as user)",
"app/model/workbench.js:associate 新增 Workbench.hasMany(WorkbenchMember, as members)",
"app/service/systems/workbench.js:新增 resolveWorkbenchByToken(缓存 workbench:token:{token} 优先、查库兜底并回填缓存)、normalizeWorkbenchMemberIds(数组/单值/逗号串,去重仅正整数)、removeWorkbenchMember(token 解析工作台后软删除归属成员行)",
"app/service/systemMethods/workbench.js:新增 removeMember 薄出口,systemInit 免登录/免权限/免日志/免鉴权声明补充 removeMember",
"methods/system.json:工作台模块新增 workbench.removeMember 条目;版本 0.3.74 -> 0.3.75(docMeta.version),updatedAt 保持 2026-09-03",
"本次未执行任何直接 DDL/写库操作;仅通过迁移文件在开发库(127.0.0.1:3307)执行 schema 变更并验证表结构;生产库迁移需发布时按标准流程执行"
],
"module": "workbench"
},
{
"version": "2026.09.03-workbench-login-code-token",
"date": "2026-09-03",
"type": "enhanced",
"summary": "工作台登录码/令牌与绑定登录能力:wms_workbench 新增 token、login_code 两个字段(VARCHAR(64),login_code 前缀 wblc + 随机段共 64 位、全局唯一;token 随机 64 位)。新增 5 个接口:index.getWorkbenchBindCode(免登录免鉴权,参考 user.getLoginWechatCode:返回 client_code 并在缓存生成绑定码,传入 client_code 时长轮询等待绑定完成返回 token,超时/缓存失效重新生成绑定码后才返回数据)、workbench.bind(需登录需权限:校验缓存绑定码 + 工作台ID 关联绑定,成功后写入随机 token,旧 workbench:token:{token} 缓存删除)、workbench.getWorkbenchInfo(免登录免鉴权:token 查缓存 workbench:token:{token},未命中查库,无信息返回失败 code=403)、index.LoginWorkbenchByCode(免登录免鉴权:wms_workbench.login_code 入参换取 token,无匹配返回失败 code=403)、workbench.resetLoginCode(需登录需权限:随机重置 login_code)。workbench.list 返回 login_code(不返回 token),workbench.update 不受理 login_code 传入,workbench.create 自动创建 login_code。",
"methods": [
"index.getWorkbenchBindCode",
"index.LoginWorkbenchByCode",
"workbench.bind",
"workbench.getWorkbenchInfo",
"workbench.resetLoginCode",
"workbench.list",
"workbench.create",
"workbench.update"
],
"notes": [
"database/migrations/20260903100000-add-login-code-token-to-wms-workbench.js:新增 login_code/token 两列(幂等 describeTable 判断)+ uk_login_code 唯一索引 + idx_token 索引,up/down 对称,已在开发库执行并验证",
"app/model/workbench.js:新增 login_code/token 字段定义与 uk_login_code/idx_token 索引声明",
"app/service/systems/workbench.js:新增绑定码/令牌能力(getWorkbenchBindCode/bindWorkbench/getWorkbenchInfoByToken/loginWorkbenchByCode/resetLoginCode 与配套缓存/生成/轮询辅助方法);list/detail 排除 token;create 自动生成唯一 login_code;update 白名单不含 login_code/token(传入不受理);缓存 key:workbench:bind:client:{clientCode}、workbench:bind:code:{code}(TTL 120s)、workbench:token:{token}(TTL 300s);长轮询 60s、每秒轮询缓存状态",
"app/service/systemMethods/workbench.js:新增 bind/getWorkbenchInfo/resetLoginCode 薄出口,systemInit 免登录/免权限/免鉴权/免日志声明补充 getWorkbenchInfo(bind/resetLoginCode 走默认需登录需权限)",
"app/service/systemMethods/index.js:新增 getWorkbenchBindCode/LoginWorkbenchByCode 薄出口,systemInit 免登录/免权限/免鉴权声明补充两方法(_noNeedLog 本就为 *)",
"403 口径:/system 网关不支持方法内设置 HTTP 状态码,按现有惯例(stock/warehouse.js 同款)返回 flag=failure、code=403 业务失败",
"methods/system.json:工作台模块新增 workbench.bind / workbench.getWorkbenchInfo / workbench.resetLoginCode 条目并更新 list/create/update 条目(list 响应补 login_code);基础模块新增 index.getWorkbenchBindCode / index.LoginWorkbenchByCode 条目;版本 0.3.73 -> 0.3.74(docMeta.version),updatedAt 保持 2026-09-03",
"本次未执行任何直接 DDL/写库操作;仅通过迁移文件在开发库(127.0.0.1:3307)执行 schema 变更并验证列与索引;生产库迁移需发布时按标准流程执行"
],
"module": "workbench"
},
{
"version": "2026.09.03-receiving-store-name-enrich",
"date": "2026-09-03",
"type": "changed",
"summary": "storage.receiving.getReceivingList / getReceivingDetail 货主名称实时解析:列表每项与详情主单的 store_name 不再只依赖主表快照(约 26% 历史数据快照为空),改为优先取合约表 wms_store_warehouse.store_remask(货主备注名称,按 store_id + warehouse_id 维度),无合约或备注为空时回退 wms_store.company_name(公司全称),均无时保留主表快照(可能为空字符串)。",
"methods": [
"storage.receiving.getReceivingList",
"storage.receiving.getReceivingDetail"
],
"notes": [
"app/service/systems/storage/receiving.js 新增 _resolveReceivingStoreNameMap(storeIds, warehouseId):批量解析货主名称映射——先查 wms_store_warehouse(store_id IN + warehouse_id)取 store_remask,再查 wms_store 取 company_name 兑底,返回 Map<store_id, 货主名称>;口径与 afterSale._enrichListStoreNames / inventory.store_name 一致(store_remask 优先、company_name 兑底)",
"app/service/systems/storage/receiving.js getReceivingList:拉取列表后批量调用 _resolveReceivingStoreNameMap,processedData 每项 store_name = 实时解析值 || 主表快照 || ''(实时值优先,兼容未绑定货主的存量数据)",
"app/service/systems/storage/receiving.js getReceivingDetail:查到主单后按 receiving.store_id + receiving.warehouse_id 实时解析货主名称,解析有值时覆盖 receiving.store_name(否则保留快照)",
"methods/system.json 收货单模块(module=storage_receiving):getReceivingList description 补充列表项 store_name 实时解析口径;getReceivingDetail 响应新增 receiving.store_name 字段描述;版本 0.3.72 -> 0.3.73(docMeta.version),updatedAt 保持 2026-09-03",
"AI_METHOD_ROUTING.md / AI_TOOLBOX.md 本次未同步:两者仅登记服务方法名清单,不含字段级描述,无需改动",
"本次仅查询验证(wms_receiving 共 1238 条、store_name 为空 319 条、store_id 为空 317 条;抽检 store_id=1000000 可经 store_remask='测试货主' 解析),未执行任何数据库写操作/DDL/Redis 操作;业务代码已通过 ESLint"
],
"module": "storage.receiving"
},
{
"version": "2026.09.03-policy-allocate-start-time-cross-day",
"date": "2026-09-03",
"type": "enhanced",
"summary": "货主策略与仓库级设置新增「开始自动分配时间」allocate_start_time(默认 08:00),支持跨天窗口:截单时间作为最后允许时间,开始时间晚于截单时间时截单时间视为次日;当前时间早于开始自动分配时间与超过截单时间行为一致(不自动分配快递/储位、不自动加团)。保存时开始时间等于截单时间(自动分配窗口为空)报 400。",
"methods": [
"storeWarehouse.store.getPolicyConfigFields",
"storeWarehouse.store.savePolicyConfig",
"setting.warehouse.getSettings",
"setting.warehouse.saveSettings"
],
"notes": [
"app/model/store_warehouse.js POLICY_CONFIG_FIELDS 新增 allocate_start_time(名称:开始自动分配时间,type string,default 08:00,min 00:00,max 23:59,maxLength 5);cutoff_order_time 的 min 从 12:00 放开为 00:00(支持凌晨截单/跨天窗口);cutoff_order_enabled/cutoff_order_time 描述补充跨天语义;normalizePolicyConfig 保存路径(sanitizeOnly=false)新增跨字段校验:allocate_start_time 与 cutoff_order_time 相同时抛错「policy_config.allocate_start_time 不能等于 policy_config.cutoff_order_time(自动分配窗口为空)」(400),读取路径(sanitizeOnly=true)不校验",
"app/model/store.js DEFAULT_SUBJECT_CONFIG 新增 allocate_start_time: '08:00';CUTOFF_ORDER_TIME_MIN 放开为 00:00;normalizeSubjectConfig 新增 HH:mm 格式校验(非法抛「subject_config.allocate_start_time 格式必须为 HH:mm(如 08:00)」)与相等校验(显式同时提交两个时间字段且相等时抛错),旧数据读取自动补默认 08:00",
"app/service/systems/setting/warehouse.js WAREHOUSE_SETTING_FIELDS 新增 allocate_start_time 字段元信息(default 08:00,min 00:00,max 23:59);cutoff_order_time 的 min 放开为 00:00;getFieldMeta 自动返回新字段元信息",
"app/service/systems/delivery_order.js resolveCutoffOrderConfig 返回值新增 allocateStartTime(默认 08:00,货主-仓库级优先、仓库级兜底);新增 isAllocationWindowClosed(allocateStartTimeStr, cutoffTimeStr, nowDate):同天窗口(start<cutoff)now<start 或 now>=cutoff 禁止;跨天窗口(start>cutoff,截单视为次日)now in [cutoff,start) 禁止;start==cutoff 防御性全天禁止;asyncProcessOrderCreated 用 isAllocationBlocked 替换 isCutoffActive 控制自动分配快递/储位/自动加团,日志补充 allocateStartTime/cutoffTime",
"methods/system.json:storeWarehouse.store.getPolicyConfigFields response 从空数组补充字段元信息说明(data[]、data[].allocate_start_time、data[].cutoff_order_time、data[].cutoff_order_enabled);storeWarehouse.store.savePolicyConfig params 补充 policy_config.cutoff_order_enabled/cutoff_order_time/allocate_start_time 字段文档与 400 错误说明,response 补充 data.policy_config.allocate_start_time;setting.warehouse.getSettings response 与 setting.warehouse.saveSettings params 补充 subject_config.allocate_start_time/subject_config.cutoff_order_time 字段文档(getFieldMeta 为通用字段元信息结构,无逐字段清单,无需改动);版本 0.3.71 -> 0.3.72(docMeta.version),updatedAt 更新为 2026-09-03",
"本次仅文档同步(业务代码由 wms-dev-agent 完成:新增字段、跨天窗口判定、保存校验,并已通过 ESLint 与单元测试),未修改 app/ 下任何代码,未执行数据库/Redis 操作"
],
"module": "storeWarehouse.store"
},
{
"version": "2026.09.02-order-packing-list-perf-export",
"date": "2026-09-02",
"type": "changed",
"summary": "order.packing.list 慢查询优化 + 新增导出与进度查询接口:list 查询将 findAndCountAll 拆分为 count(不带 include)+ findAll(带 include),避免 count 生成 COUNT(DISTINCT)+双 LEFT JOIN(生产实测 520ms,拆分后 count 走单表索引约 44ms);筛选/排序逻辑提取为 _buildListWhere/_buildListOrder 供列表与导出复用。新增 order.packing.export(提交异步导出任务,入参 where/sort 语义与 list 一致,warehouse_id 由服务端注入;后台生成单 Sheet Excel「打包任务列表」并上传 COS)与 order.packing.exportTaskProgress(按 task_id 查询进度与下载链接)。两接口免权限免日志免鉴权(与 order.export 口径一致,无 wms_permission 记录),需登录。",
"methods": [
"order.packing.list",
"order.packing.export",
"order.packing.exportTaskProgress"
],
"notes": [
"app/service/systems/order_packing.js:list 查询拆分——findAndCountAll 改为 count({where})(不带 include)+ findAll({where, include, limit, offset}),修复 hasMany include(videos/expresses)导致 count 生成 COUNT(DISTINCT)+双 LEFT JOIN 的慢查询(生产实测 520ms → 44ms);where 构建逻辑(status/pack_mode/waybill_code/wave_no/order_id/workbench_id/quickWhere/has_video/video_enable/时间范围)原样提取为 _buildListWhere(list/export 共用),排序提取为 _buildListOrder(list/export 共用);新增 createBusinessError 与 exportPackTask",
"app/service/systems/order_packing.js exportPackTask:复用 _buildListWhere/_buildListOrder 并强制 warehouse_id(缺失抛 400 缺少仓库上下文);主表全量分页拉取(每页 500,无行数上限);批量关联工作台(wms_workbench)、视频(wms_pack_task_video,含 camera 名称)、运单(wms_order_express,按 order_id 分批 100);ExcelJS 流式单 Sheet「打包任务列表」18 列(任务ID/订单ID/波次号/运单号/关联运单号/打包模式/任务状态/打包数量/商品总数量/商品种类数/工作台/作业人员/开始打包时间/结束打包时间/创建时间/视频状态/录像可用/备注),经 systems.upload.uploadFile 上传(key=exports/pack_task/{warehouseId}/{timestamp}_{token}.xlsx,mimetype xlsx,category=document),结果含 filename/fileKey/url/cdnUrl/cosUrl/current_count/total_count/sheet_count",
"app/service/systemMethods/order/packing.js:新增 export/exportTaskProgress 与任务缓存辅助方法(generateExportTaskId/normalizeExportTaskId/getExportTaskCacheKey/setExportTaskProgress/getExportTaskProgress):缓存键前缀 packing_export_task_,Redis TTL 1800 秒;export 提交后 setImmediate 异步执行并逐阶段回写进度(submitted(0) → running(5) → 数据拉取 10~30(未命中数据时 85)→ 关联拉取 30~55 → Excel 55~90 → 上传 92 → success(100),失败 failed + error);exportTaskProgress 入参兼容 task_id/taskId,download_url 从 result.url/cdnUrl/cosUrl/fileKey 兜底取,未命中返回 status=not_found(正常响应非报错)",
"systemInit 权限声明:_noNeedRight/_noNeedLog/_noNeedAuth 由 'list,get' 扩展为 'list,get,export,exportTaskProgress'(导出异步任务免权限免日志免鉴权,与 order.export 口径一致);_noNeedLogin 不变",
"methods/system.json order.packing 模块:新增 order.packing.export 与 order.packing.exportTaskProgress 两个 method 条目(追加于 order.packing.list 之后),版本 0.3.70 -> 0.3.71(docMeta.version),updatedAt 更新为 2026-09-02",
"本次未修改 wms_pack_task 表结构,未执行数据库写操作/Redis 操作;未运行测试"
],
"module": "order.packing"
},
{
"version": "2026.09.01-report-delivery-notify-group-routing-fix",
"date": "2026-09-01",
"type": "changed",
"summary": "修复「补货预警报表定时投递群路由」缺陷(G1):生产上 3 条投递计划发出 5 条消息——报表文件消息被投递到投递计划未配置的「货主默认站内信群」(如 store-1000156 的收货群、store-1000159 的对接群被误发)。根因:deliverByChannel 未按计划配置解析群目标,按 group_type='store' 取任意货主默认群(与 notify_group_ids 配置无关)。修复:新增 resolveNotifyGroups 统一解析(过滤 is_blocked=1、软删、仓库维度一致)供投递与通知两路共用;配置了 notify_group_ids 的计划文件消息仅逐群投递到配置群,全部不可达(不存在/已删除/被屏蔽/仓库不一致)时抛错进入 failed 退避重试、不再回退未配置群;未配置通知群的历史计划保持旧行为回退货主默认站内信群;sendNotifyIfConfigured 复用 resolveNotifyGroups 删除重复查询逻辑。响应结构不变,仅群路由语义变更。",
"methods": [
"report.deliveryPlan.save",
"report.deliveryPlan.list",
"report.deliveryPlan.copy"
],
"notes": [
"app/service/systems/reportDelivery.js 新增 resolveNotifyGroups({plan, warehouseId}):notify_group_ids → 有效群行统一解析(is_blocked=0、软删自动排除、warehouse_id 维度一致),投递(deliverByChannel)与文本通知(sendNotifyIfConfigured)两路共用,保证口径一致;未配置群或全部被过滤时返回空数组,InboxGroup 模型不可用时抛错",
"app/service/systems/reportDelivery.js deliverByChannel 群路由改造:计划配置 notify_group_ids 时报表文件消息只逐群投递到配置群,不再投递任意「货主默认群」(旧逻辑为 group_type='store' 按 id ASC 取最早一条,与计划配置无关);配置了群但全部不可达(不存在/已删除/被屏蔽/仓库不一致)时抛「货主 <store_id> 配置的通知群不可达…无法投递」进入 failed 退避重试(MAX_RETRY=3,退避 retry_count × 60s),不再静默回退到未配置群;未配置通知群的历史计划保持旧行为回退到货主默认站内信群(group_type='store',取最早一条)兼容存量计划",
"app/service/systems/reportDelivery.js sendNotifyIfConfigured 复用 resolveNotifyGroups 解析通知群,删除重复查询逻辑,投递与通知共用同一解析口径",
"methods/system.json 通用报表模块(module=report):report.deliveryPlan.save description 与 params/response 的 notify_group_ids 描述补充群路由口径(文件消息仅投递计划配置群、未配置回退货主默认站内信群、配置群全部不可达失败退避);report.deliveryPlan.list description 与 response 的 notify_group_ids 描述同步;report.deliveryPlan.copy description 补充复制计划通知群置空后投递回退目标货主默认站内信群语义;请求/响应结构、headers、errors 均不变;版本 0.3.69 -> 0.3.70(docMeta.version),updatedAt 保持 2026-09-01",
"docs/report-config-guide.md 第 5 节补充文件消息投递目标/群路由口径(配置群定向投递、未配置回退默认群、全部不可达失败退避),第 5.1.2 节 notify_group_ids 补充同时作为文件消息投递目标的说明",
"测试回归:140 测试全过(业务代码由开发任务完成并测试通过);本次仅文档同步,未修改 app/ 下任何代码,未执行数据库/Redis 操作,未运行测试"
],
"module": "report"
},
{
"version": "2026.09.01-returnReceived.export",
"date": "2026-09-01",
"type": "added",
"summary": "退回收到模块新增导出与进度查询接口:returnReceived.export(提交异步导出任务,入参 where/sort 语义与 returnReceived.list 一致,warehouse_id 由服务端注入 ctx.user.store_id;后台生成单 Sheet Excel「退回收到登记列表」并上传 COS)与 returnReceived.exportTaskProgress(按 task_id 查询任务进度与下载链接,未命中返回 status=not_found)。任务缓存 Redis TTL 30 分钟,全量分页拉取 500/页;两接口默认走 API 权限校验(需 wms_permission 存在类型为 api 的记录),需登录。",
"methods": [
"returnReceived.export",
"returnReceived.exportTaskProgress"
],
"notes": [
"app/service/systemMethods/returnReceived.js 新增 export/exportTaskProgress 与任务缓存辅助方法(generateExportTaskId/normalizeExportTaskId/getExportTaskCacheKey/setExportTaskProgress/getExportTaskProgress):缓存键前缀 return_received_export_task_,Redis TTL 1800 秒(30 分钟);export 提交后 setImmediate 异步执行并逐阶段回写进度(submitted(0) → running(5) → 数据拉取 10~55(未命中数据时 85)→ Excel 生成 60 → success(100),失败 failed + error);exportTaskProgress 入参兼容 task_id/taskId,download_url 从 result.url/cdnUrl/cosUrl/fileKey 兜底取;task_id 为空或缓存未命中返回 status=not_found(正常响应非报错)",
"systemInit 权限声明:_noNeedRight 仅 detail(export/exportTaskProgress 未加入免权限列表,默认走 API 权限校验,需 wms_permission 存在 returnReceived.export / returnReceived.exportTaskProgress 类型为 api 的记录);_noNeedLogin 为空(两接口均需登录,isNeedAuth=true、isNeedLogin=true);_noNeedLog 为空(记录操作日志);_noNeedAuth 为空(走仓库有效期检查)",
"app/service/systems/return_received.js 新增 exportList/_generateExportExcel/_resolveStoreRemarkMap:复用 _buildListWhere/_buildListOrder(与 list 语义一致)并强制 warehouse_id=注入值(缺失抛 400 缺少仓库上下文);主表全量分页拉取(每页 500,无行数上限);货主备注批量解析(wms_store_warehouse.store_remask,失败降级空字符串不阻断导出)",
"导出 Excel:单 Sheet「退回收到登记列表」,列=运单号/扫描日期/扫描人员/是否原单退回(是/否)/订单ID/货主备注/备注/登记时间/更新时间;ExcelJS 流式写入临时文件后经 systems.upload.uploadFile 上传(key=exports/return_received/{warehouseId}/{timestamp}_{token}.xlsx,mimetype xlsx,category=document),结果含 filename/fileKey/url/cdnUrl/cosUrl/current_count/total_count",
"methods/system.json 退回收到模块(module=returnReceived)新增 returnReceived.export 与 returnReceived.exportTaskProgress 两个 method 条目(追加于 returnReceived.delete 之后),版本 0.3.68 -> 0.3.69(docMeta.version),updatedAt 保持 2026-09-01",
"AI_METHOD_ROUTING.md 同步:app/service/systemMethods/returnReceived.js 方法计数 (5) -> (7),方法清单补充 export/exportTaskProgress;AI_TOOLBOX.md 未涉及 returnReceived 清单,无需改动",
"本次仅文档同步(业务代码由开发任务完成),未修改 app/ 下任何代码,未执行数据库/Redis 操作,未运行测试"
],
"module": "returnReceived"
},
{
"version": "2026.09.01-intercept-locked-quantity-rework",
"date": "2026-09-01",
"type": "changed",
"summary": "库内拦截确认时库存不再归还可用、改移入拦截锁定字段的改造落地:wms_storage_transaction 新增 before_intercept_locked_quantity / after_intercept_locked_quantity 两个拦截锁定快照字段(migration 20260901000200,尚未上线);wms_storage 可用数量统一口径 available_quantity = quantity - locked_quantity - intercept_locked_quantity;拦截相关流水新增 order_type=INTERCEPT_LOCK(拦截锁迁移/实物返还并拦截锁定)与 INTERCEPT_UNLOCK(拦截锁释放回落可用);stock.warehouse.search(with_stock)与 stock.warehouse.getStockDetail 按库位合并明细响应新增 intercept_locked_quantity 字段(向后兼容);order.recheckOrder.confirmIntercept / interceptScan 确认拦截时以拦截模式释放储位分配(interceptMode=true,库存不归还可用、移入拦截锁定)。",
"methods": [
"stock.warehouse.getStockDetail",
"stock.warehouse.search",
"order.recheckOrder.confirmIntercept",
"order.recheckOrder.interceptScan"
],
"notes": [
"database/migrations/20260901000200-add-intercept-locked-snapshots-to-wms-storage-transaction.js:describeTable 幂等检测,新增 before_intercept_locked_quantity / after_intercept_locked_quantity(INT NULL,comment 变更前/后拦截锁定数量,与既有 before/after_locked_quantity 风格一致、可空无默认值、由写入逻辑维护);该 migration 尚未上线",
"app/model/storage_transaction.js:在 after_locked_quantity 之后新增 before_intercept_locked_quantity / after_intercept_locked_quantity 字段定义(INTEGER(12)/allowNull=true,comment 变更前/变更后拦截锁定数量)",
"app/service/systems/storage/index.js updateQuantity:新增 options.interceptLockedChange 变化量参数,统一重算 available_quantity = quantity - locked_quantity - intercept_locked_quantity,并校验拦截锁定数量非负、不超过库存数量、与锁定数量之和不超过库存数量;新增 interceptLockQuantity(作业锁迁移为拦截锁:locked -q、intercept +q、available 不变)/ interceptReceiveQuantity(实物返还并拦截锁定:quantity +q、intercept +q、available 不变)/ interceptUnlockQuantity(拦截锁释放回落可用:intercept -q、available +q)三个专用方法",
"app/service/systems/order_storage_allocation.js cancelAllocateStorage:新增 interceptMode 开关——拦截确认模式下 pending 行执行作业锁迁移(locked -q、intercept +q、available 不变)、fin 行实物返还并拦截锁定(quantity +q、intercept +q、available 不变),流水 order_type 记为 INTERCEPT_LOCK 并记录 order_id 与 before/after_intercept_locked_quantity 快照;普通取消模式行为不变;新增 releaseInterceptLocksByOrderIds:按 INTERCEPT_LOCK 与 INTERCEPT_UNLOCK 流水按 (storage_id, order_id) 汇总净拦截量,净量大于 0 时逐库存行调用 interceptUnlockQuantity 释放拦截锁(intercept -q、available +q),写入 order_type=INTERCEPT_UNLOCK 流水并记录快照,重复调用幂等(净量归零后不再释放)",
"app/service/systemMethods/order/recheckOrder.js confirmIntercept/interceptScan:释放储位分配改走 cancelAllocateStorage({ order_ids, interceptMode: true }),确认拦截时库存不再归还可用而是移入拦截锁定字段 intercept_locked_quantity;运单标记、订单状态、订单锁、工单、日志等其余口径不变",
"app/service/systemMethods/order/pendingOrder.js runBatchUninterceptTask:解除拦截不操作拦截锁定数量字段(业务上拦截→取消拦截均不动库存口径,拦截锁定数量仅在库内拦截确定时占用,回落由后续特定入库处理链路接管)",
"app/service/systems/return_received.js create:退货登记不释放拦截锁定库存(拦截锁回落由退货货物后续入库处理接管)",
"app/service/systems/stock_store.js search(with_stock)与 getStockDetail:storage 查询 attributes 显式加入 intercept_locked_quantity,按库位合并模式累加拦截锁定数量并按统一口径重算 available_quantity;合并明细响应新增 intercept_locked_quantity(向后兼容,默认 0)",
"methods/system.json 同步:stock.warehouse.getStockDetail response storageList 描述补充 intercept_locked_quantity 与 available_quantity 统一口径;stock.warehouse.search response storage 字段的库位分组汇总(children_grouped)与批次明细(children_batch)字段清单均新增 intercept_locked_quantity、available_quantity 口径说明更新为 quantity - locked_quantity - intercept_locked_quantity;order.recheckOrder.confirmIntercept / interceptScan 描述更新为拦截模式释放储位分配(库存不归还可用、移入拦截锁定);版本 0.3.67 -> 0.3.68(docMeta.version),updatedAt 保持 2026-09-01",
"核查结论:methods/qimen.json 与 methods/openapi.json 无涉及本改造的接口(openapi.json 仅 order.cancel 描述中出现 intercept_status 字面量,与本改造无关),未同步;stock.transaction.list / stock.transaction.storeList / stock.transaction.export 使用显式 SQL 列白名单(不含拦截锁定快照字段),响应不受影响,文档无需同步;storage.transaction.list(group_by_batch=true)明细模式因模型整行序列化隐含新增 before/after_intercept_locked_quantity,但其 response 文档为对象结构(更新脚本要求数组格式,与既有处理一致),本次未改写,其 list_detail 示例本非全量字段清单",
"本次仅文档同步,未修改 app/ 与 database/ 下任何代码与 migration,未执行数据库/Redis 操作,未运行测试"
],
"module": "storage"
},
{
"version": "2026.09.01-receiving-detail-stock-id",
"date": "2026-09-01",
"type": "changed",
"summary": "storage.receiving.getReceivingDetail 与 deleteDetail 明细项新增 stock_id 字段(与 system_product_id 语义一致,向后兼容)",
"methods": [
"storage.receiving.getReceivingDetail",
"storage.receiving.deleteDetail"
],
"notes": [
"app/service/systems/storage/receiving.js getReceivingDetail:明细组装时新增 stock_id: detailBase.system_product_id ?? null(商品/库存ID,语义与 system_product_id 一致,缺失时为 null),system_product_id 保留向后兼容",
"app/service/systems/storage/receiving.js deleteDetail:删除后剩余明细 formattedDetails 每项同步新增 stock_id = detailData.system_product_id ?? null,与 getReceivingDetail 明细项字段保持一致",
"methods/system.json 收货单模块(module=storage_receiving):getReceivingDetail 响应新增 receiving.details.*.stock_id(number|null,语义与 system_product_id 一致,取 system_product_id、缺失为 null,system_product_id 保留向后兼容);deleteDetail 响应 data.details 描述补充 stock_id 说明;deleteDetail 按更新脚本规范补齐 response 各字段 required、errors 的 description 归一化为 message(语义不变);版本 0.3.66 -> 0.3.67(docMeta.version),updatedAt 保持 2026-09-01",
"AI_METHOD_ROUTING.md / AI_TOOLBOX.md 本次未同步:两者仅登记服务方法名清单,不含 getReceivingDetail/deleteDetail 的字段级描述,无需改动",
"本次仅文档同步(业务代码由 wms-dev-agent 完成),未修改 app/ 下任何代码,未执行数据库/Redis 操作,未运行测试"
],
"module": "storage.receiving"
},
{
"version": "2026.09.01-wms-storage-intercept-locked-quantity",
"date": "2026-09-01",
"type": "changed",
"summary": "wms_storage 库存表新增「拦截锁定数量」字段 intercept_locked_quantity(INTEGER(12) NOT NULL DEFAULT 0,comment 拦截锁定数量),用于拦截场景数量锁定、与 locked_quantity 区分;纯数据模型变更:无接口入参/错误码/鉴权变化,现有写入点由模型默认值 0 兜底;明细模式接口响应因模型整行序列化隐含新增该字段(当前恒为 0,暂无业务读写)。",
"methods": [
"storage.inventory.listByStockId"
],
"notes": [
"database/migrations/20260901000000-add-intercept-locked-quantity-to-wms-storage.js:describeTable 幂等检测,缺省时 ALTER TABLE wms_storage ADD COLUMN intercept_locked_quantity INT(12) NOT NULL DEFAULT 0 COMMENT '拦截锁定数量';down 删除该字段",
"app/model/storage.js:在 locked_quantity 之后新增 intercept_locked_quantity 字段定义(INTEGER(12)/allowNull=false/defaultValue=0/comment 拦截锁定数量);现有写入点(quickPutaway/directPutaway/commit 等)不显式传该字段,依赖模型默认值 0 兜底",
"methods/system.json storage.inventory.listByStockId:data.list 明细行字段清单补充 intercept_locked_quantity(拦截锁定数量,默认 0);group_by_space=true 汇总行与 params/errors/isNeedAuth/isNeedLogin 均不变;版本 0.3.65 -> 0.3.66(docMeta.version),updatedAt 更新为 2026-09-01",
"storage.inventory.list(group_by_batch=true 明细模式)响应同样隐含新增该字段,但其 response 文档为对象结构(脚本校验要求数组格式),本次未改写;其 list_detail 示例本非全量字段清单(未列 is_enabled/delete_at/supplier_id 等),不构成文档缺口",
"storage.inventory.export(明细/汇总导出)、stock.warehouse.getStockDetail、库存报表 stockFlow 等查询均使用显式 attributes 白名单,不受该字段影响,文档无需同步",
"本次仅文档同步,未修改 app/ 与 database/ 下任何代码,未执行数据库/Redis 操作,未运行测试"
],
"module": "storage"
},
{
"version": "2026.08.31-report-stockflow-export-columns-restructure",
"date": "2026-08-31",

File diff suppressed because it is too large Load Diff

View File

@ -58,9 +58,6 @@
"deploy:verify": "node ./script/deploy-ops.cjs production verify",
"deploy:cleanup-backups": "node ./script/deploy-ops.cjs production cleanup-backups",
"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",
"ops:clean-root-logs:apply": "node ./script/check-root-logs.cjs production --clean --apply",
"version:record": "node ./script/version-record.cjs",
"version:history": "node ./script/version-history.cjs --limit=50",
"deploy": "npm run deploy:prod",

View File

@ -1,91 +0,0 @@
'use strict';
/**
* 回填 wms_wave_pick_task.batch_no_array。
*
* 从 wms_wave_pick_task_wave 按 task_id 聚合 wave_no(逗号分隔,按 id 升序),
* 只更新 batch_no_array 为空的记录,幂等可重复执行。
*
* 用法:
* 开发:node script/backfill-batch-no-array.cjs
* 生产:$env:NODE_ENV='production'; node script/backfill-batch-no-array.cjs
*/
const dbConfig = require('../database/config.js');
const Sequelize = require('sequelize');
(async () => {
const cfg = dbConfig.production;
const s = new Sequelize(cfg.database, cfg.username, cfg.password, {
host: cfg.host,
port: cfg.port,
dialect: cfg.dialect || 'mysql',
logging: false,
});
// 放大 GROUP_CONCAT 上限(任务最多 20 波次,避免截断)
await s.query('SET SESSION group_concat_max_len = 1048576');
const [ updateResult ] = await s.query(`
UPDATE wms_wave_pick_task t
JOIN (
SELECT
tw.task_id,
GROUP_CONCAT(tw.wave_no ORDER BY tw.id ASC SEPARATOR ',') AS wave_nos
FROM wms_wave_pick_task_wave tw
WHERE tw.wave_no IS NOT NULL AND tw.wave_no <> ''
GROUP BY tw.task_id
) w ON w.task_id = t.id
SET t.batch_no_array = w.wave_nos,
t.update_time = NOW()
WHERE t.batch_no_array IS NULL OR t.batch_no_array = ''
`);
console.log('1) task_wave 聚合回填行数:', JSON.stringify(updateResult && updateResult.affectedRows !== undefined
? updateResult.affectedRows
: null));
// 回退 2:task_wave 无记录的任务,用主表 wave_id 关联 wms_wave_batch.wave_no
const [ updateResult2 ] = await s.query(`
UPDATE wms_wave_pick_task t
JOIN wms_wave_batch wb ON wb.wave_id = t.wave_id
SET t.batch_no_array = wb.wave_no,
t.update_time = NOW()
WHERE (t.batch_no_array IS NULL OR t.batch_no_array = '')
AND t.wave_id > 0
AND wb.wave_no IS NOT NULL AND wb.wave_no <> ''
`);
console.log('2) wave_id→wms_wave_batch 回填行数:', JSON.stringify(updateResult2 && updateResult2.affectedRows !== undefined
? updateResult2.affectedRows
: null));
// 回退 3:仍为空的散单老数据,用主表 batch_no 兜底
const [ updateResult3 ] = await s.query(`
UPDATE wms_wave_pick_task t
SET t.batch_no_array = t.batch_no,
t.update_time = NOW()
WHERE (t.batch_no_array IS NULL OR t.batch_no_array = '')
AND t.batch_no IS NOT NULL AND t.batch_no <> ''
`);
console.log('3) batch_no 兜底回填行数:', JSON.stringify(updateResult3 && updateResult3.affectedRows !== undefined
? updateResult3.affectedRows
: null));
const [ remaining ] = await s.query(
"SELECT COUNT(*) AS c FROM wms_wave_pick_task WHERE batch_no_array IS NULL OR batch_no_array = ''"
);
console.log('回填后仍为空的任务数:', JSON.stringify(remaining));
const [ sample ] = await s.query(
"SELECT id, task_no, batch_no_array FROM wms_wave_pick_task "
+ "WHERE id IN (259, 258, 251, 249) ORDER BY id DESC"
);
console.log('抽样核验:', JSON.stringify(sample, null, 2));
await s.close();
})().catch(e => {
console.error('ERROR:', e.message);
process.exit(1);
});

View File

@ -1,386 +0,0 @@
'use strict';
const path = require('node:path');
const {
ensureCommandAvailable,
loadDeployConfig,
quoteForBash,
runSsh,
} = require('./deploy-lib.cjs');
const DEFAULT_ENV = 'production';
const LOGS_DIR = '/root/logs/wms';
/** 正在写入的活跃日志文件名(不带日期后缀),绝对不允许删除 */
const ACTIVE_LOG_NAME = 'wms-web.log';
/** egg logrotator 按日期轮转后的历史日志文件名模式:wms-web.log.YYYY-MM-DD */
const ROTATED_LOG_PATTERN = /^wms-web\.log\.\d{4}-\d{2}-\d{2}$/;
/** 触发清理的目录总大小阈值:4 GiB */
const CLEAN_THRESHOLD_BYTES = 4 * 1024 * 1024 * 1024;
/** 清理目标水位:目录总大小降到 2 GiB 以下 */
const CLEAN_TARGET_BYTES = 2 * 1024 * 1024 * 1024;
/** 清理后至少保留的历史轮转文件数量 */
const MIN_KEEP_COUNT = 3;
/**
* 构建只读的远端日志目录检测脚本
* 仅使用 du / ls / df 等只读命令,不包含任何删除、清理或写入操作
*
* @return {string} 远端 bash 脚本内容
*/
function buildRemoteScript() {
const logsDir = quoteForBash(LOGS_DIR);
return [
'set -euo pipefail',
`LOGS_DIR=${logsDir}`,
'printf "===WMS_LOGS_SIZE===\\n"',
'if [ -d "$LOGS_DIR" ]; then',
' du -sh "$LOGS_DIR" 2>&1 | head -5 || true',
'else',
' echo "DIR_NOT_FOUND: $LOGS_DIR"',
'fi',
'printf "===TOP_LARGE_FILES===\\n"',
'if [ -d "$LOGS_DIR" ]; then',
' ls -lhS "$LOGS_DIR" 2>&1 | head -20 || true',
'else',
' echo "SKIP: $LOGS_DIR 不存在"',
'fi',
'printf "===TOP_LARGE_ITEMS===\\n"',
'if [ -d "$LOGS_DIR" ]; then',
' du -sh "$LOGS_DIR"/* 2>&1 | sort -rh | head -20 || true',
'else',
' echo "SKIP: $LOGS_DIR 不存在"',
'fi',
'printf "===ROOT_PARTITION===\\n"',
'df -h / 2>&1 || true',
].join('\n');
}
/**
* 通过 SSH 执行只读检测,返回远端输出
*
* @param {object} config - 部署配置对象
* @return {string} 远端日志目录检测结果
*/
function checkRootLogs(config) {
const remoteScript = buildRemoteScript();
return runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
}
/**
* 将字节数格式化为人类可读的大小字符串
*
* @param {number} bytes - 字节数
* @return {string} 人类可读的大小,如 "3.2 GiB"
*/
function formatBytes(bytes) {
if (!Number.isFinite(bytes) || bytes < 0) {
return 'N/A';
}
const units = [ 'B', 'KiB', 'MiB', 'GiB', 'TiB' ];
let value = bytes;
let unitIndex = 0;
while (value >= 1024 && unitIndex < units.length - 1) {
value /= 1024;
unitIndex += 1;
}
const digits = unitIndex === 0 ? 0 : 1;
return `${value.toFixed(digits)} ${units[unitIndex]}`;
}
/**
* 将 epoch 秒数格式化为 ISO 时间字符串,便于人工核对 mtime
*
* @param {number} mtimeSeconds - Unix 时间戳(秒,支持小数)
* @return {string} ISO 格式时间字符串,无效时返回 UNKNOWN
*/
function formatMtime(mtimeSeconds) {
const date = new Date(Number(mtimeSeconds) * 1000);
if (Number.isNaN(date.getTime())) {
return 'UNKNOWN';
}
return date.toISOString();
}
/**
* 构建远端只读探测脚本:计算目录总大小并按 mtime 升序列出全部文件
* 仅使用 du / find / sort 等只读命令,不包含任何删除操作;
* 目录不存在或无法计算大小时输出 NO_CLEANUP_NEEDED 并以 0 正常退出
*
* @return {string} 远端 bash 脚本内容
*/
function buildCleanProbeScript() {
const logsDir = quoteForBash(LOGS_DIR);
return [
'set -euo pipefail',
`LOGS_DIR=${logsDir}`,
'if [ ! -d "$LOGS_DIR" ]; then',
' echo "NO_CLEANUP_NEEDED: DIR_NOT_FOUND: $LOGS_DIR"',
' exit 0',
'fi',
'TOTAL_BYTES=$(du -sb "$LOGS_DIR" | awk \'{print $1}\')',
'if [ -z "${TOTAL_BYTES}" ]; then',
' echo "NO_CLEANUP_NEEDED: EMPTY_DIR_SIZE"',
' exit 0',
'fi',
'echo "PROBE_TOTAL_BYTES=${TOTAL_BYTES}"',
'find "$LOGS_DIR" -maxdepth 1 -type f -printf \'%T@\\t%s\\t%p\\n\' | sort -k1,1n',
].join('\n');
}
/**
* 解析远端只读探测脚本的标准输出
* 识别 NO_CLEANUP_NEEDED 提示与 PROBE_TOTAL_BYTES 总大小标记,
* 并把每行文件清单解析为 mtime / size / filePath 三元组
*
* @param {string} output - 远端探测脚本的标准输出
* @return {object} 解析结果:
* - noCleanup: {string|null} NO_CLEANUP_NEEDED 提示(无需清理时非空)
* - totalBytes: {number} 目录总字节数
* - files: {Array<{mtime:number,size:number,filePath:string}>} 文件清单
*/
function parseCleanProbe(output) {
const lines = String(output || '').split(/\r?\n/)
.map(line => line.trim())
.filter(Boolean);
const noCleanup = lines.find(line => line.startsWith('NO_CLEANUP_NEEDED'));
if (noCleanup) {
return { noCleanup, totalBytes: 0, files: [] };
}
const totalLine = lines.find(line => line.startsWith('PROBE_TOTAL_BYTES='));
if (!totalLine) {
throw new Error('远端探测输出缺少 PROBE_TOTAL_BYTES 标记,无法确定目录总大小。');
}
const totalBytes = Number(totalLine.slice('PROBE_TOTAL_BYTES='.length));
if (!Number.isFinite(totalBytes)) {
throw new Error(`远端探测输出的总大小非法: ${totalLine}`);
}
const files = [];
for (const line of lines) {
if (line.startsWith('PROBE_TOTAL_BYTES=')) {
continue;
}
const parts = line.split('\t');
if (parts.length < 3) {
continue;
}
const mtime = Number(parts[0]);
const size = Number(parts[1]);
const filePath = parts.slice(2).join('\t');
if (!Number.isFinite(mtime) || !Number.isFinite(size) || !filePath) {
continue;
}
files.push({ mtime, size, filePath });
}
return { noCleanup: null, totalBytes, files };
}
/**
* 从远端文件清单中筛选出允许删除的历史轮转日志文件
* 安全边界:仅保留 basename 严格匹配轮转命名模式的文件,
* 明确排除正在写入的活跃日志,并按 mtime 从旧到新排序
*
* @param {Array<{mtime:number,size:number,filePath:string}>} files - 远端文件清单
* @return {Array<{mtime:number,size:number,filePath:string}>} 候选删除文件(mtime 升序)
*/
function collectCleanCandidates(files) {
return files
.filter(item => {
const baseName = path.posix.basename(item.filePath);
if (baseName === ACTIVE_LOG_NAME) {
return false;
}
return ROTATED_LOG_PATTERN.test(baseName);
})
.sort((left, right) => left.mtime - right.mtime);
}
/**
* 按阈值 / 目标水位 / 最小保留数量计算删除计划
* 从最旧的候选文件开始逐个删除,直到预计总大小降到目标水位以下;
* 候选数量不足 MIN_KEEP_COUNT 时停止,避免误删近期日志
*
* @param {Array<{mtime:number,size:number,filePath:string}>} candidates - 候选删除文件(mtime 升序)
* @param {number} totalBytes - 当前目录总字节数
* @return {object} 删除计划:
* - deleteFiles: {Array} 计划删除的文件列表
* - keepFiles: {Array} 计划保留的文件列表
* - totalBytes: {number} 删除前总字节数
* - estimatedAfterBytes: {number} 删除后预计总字节数
* - limitedByMinKeep: {boolean} 是否因最小保留数量限制未能降到目标水位
*/
function buildCleanPlan(candidates, totalBytes) {
const pool = [ ...candidates ];
const deleteFiles = [];
let remaining = totalBytes;
while (pool.length > MIN_KEEP_COUNT && remaining > CLEAN_TARGET_BYTES) {
const oldest = pool.shift();
deleteFiles.push(oldest);
remaining -= oldest.size;
}
return {
deleteFiles,
keepFiles: pool,
totalBytes,
estimatedAfterBytes: remaining,
limitedByMinKeep: remaining > CLEAN_TARGET_BYTES && pool.length <= MIN_KEEP_COUNT,
};
}
/**
* 构建远端实际删除脚本(仅 --apply 模式使用)
* 删除清单通过 quoted here-doc 逐行传入,逐条校验路径必须严格位于
* ${LOGS_DIR}/ 下且 basename 匹配轮转命名模式,再用 `rm -f -- 完整路径` 删除;
* 不使用 rm -rf、不使用任何通配符;删除完成后重新计算并输出目录总大小
*
* @param {Array<string>} filePaths - 计划删除的完整路径列表
* @return {string} 远端 bash 脚本内容
*/
function buildCleanApplyScript(filePaths) {
const logsDir = quoteForBash(LOGS_DIR);
const lines = [
'set -euo pipefail',
`LOGS_DIR=${logsDir}`,
'if [ ! -d "$LOGS_DIR" ]; then',
' echo "NO_CLEANUP_NEEDED: DIR_NOT_FOUND: $LOGS_DIR"',
' exit 0',
'fi',
'while IFS= read -r FILE_PATH; do',
' [ -n "$FILE_PATH" ] || continue',
' case "$FILE_PATH" in',
' "$LOGS_DIR"/wms-web.log.[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]) ;;',
' *)',
' echo "CLEAN_FAIL: 拒绝删除不匹配轮转命名模式的文件: $FILE_PATH" >&2',
' exit 1',
' ;;',
' esac',
' rm -f -- "$FILE_PATH"',
' echo "REMOVED $FILE_PATH"',
'done <<\'CLEAN_FILE_LIST\'',
...filePaths,
'CLEAN_FILE_LIST',
'AFTER_BYTES=$(du -sb "$LOGS_DIR" | awk \'{print $1}\')',
'echo "CLEAN_AFTER_BYTES=${AFTER_BYTES:-0}"',
];
return lines.join('\n');
}
/**
* 执行日志目录清理流程(dry-run 或 apply)
* 1. 通过 SSH 只读探测目录总大小与文件清单
* 2. 目录不存在或大小未超阈值时输出 NO_CLEANUP_NEEDED 并正常退出
* 3. dry-run 输出 WOULD_REMOVE 删除计划与删除前后总大小,不执行任何删除;
* apply 才真正执行删除并输出 REMOVED 清单与 CLEAN_AFTER_BYTES
*
* @param {object} config - 部署配置对象
* @param {object} options - 选项对象
* @param {boolean} options.apply - true 表示真正执行删除;false(默认)为 dry-run
* @return {void}
*/
function runClean(config, options = {}) {
const apply = Boolean(options.apply);
const modeText = apply ? 'apply' : 'dry-run';
console.log(`[CLEAN_ROOT_LOGS] env=${config.envName} host=${config.username}@${config.host}:${config.port} dir=${LOGS_DIR} mode=${modeText}`);
const probe = parseCleanProbe(runSsh(config, buildCleanProbeScript(), { stdio: 'pipe' }).trim());
if (probe.noCleanup) {
console.log(`NO_CLEANUP_NEEDED: ${probe.noCleanup}`);
console.log('CLEAN_SKIPPED');
return;
}
console.log(`TOTAL_BEFORE=${probe.totalBytes} bytes (${formatBytes(probe.totalBytes)}) threshold=${formatBytes(CLEAN_THRESHOLD_BYTES)} target=${formatBytes(CLEAN_TARGET_BYTES)}`);
if (probe.totalBytes <= CLEAN_THRESHOLD_BYTES) {
console.log(`NO_CLEANUP_NEEDED: 目录总大小未超过 ${formatBytes(CLEAN_THRESHOLD_BYTES)} 阈值,无需清理`);
console.log('CLEAN_SKIPPED');
return;
}
const candidates = collectCleanCandidates(probe.files);
if (candidates.length === 0) {
console.log('NO_CLEANUP_NEEDED: 未找到符合轮转命名模式的历史日志文件,不做任何删除');
console.log('CLEAN_SKIPPED');
return;
}
const plan = buildCleanPlan(candidates, probe.totalBytes);
if (plan.deleteFiles.length === 0) {
console.log(`NO_CLEANUP_NEEDED: 需保留最近 ${MIN_KEEP_COUNT} 个历史文件,无可安全删除的文件`);
console.log('CLEAN_SKIPPED');
return;
}
console.log(`CANDIDATES=${candidates.length} PLAN_DELETE=${plan.deleteFiles.length} KEEP_RECENT=${plan.keepFiles.length}`);
if (apply) {
console.log(runSsh(config, buildCleanApplyScript(plan.deleteFiles.map(file => file.filePath)), { stdio: 'pipe' }).trim());
} else {
for (const file of plan.deleteFiles) {
console.log(`WOULD_REMOVE ${file.filePath} ${file.size} bytes (${formatBytes(file.size)}) mtime=${formatMtime(file.mtime)}`);
}
console.log(`TOTAL_AFTER=${plan.estimatedAfterBytes} bytes (${formatBytes(plan.estimatedAfterBytes)}) (预计)`);
}
if (plan.limitedByMinKeep) {
console.log(`CLEAN_LIMITED: 受"保留最近 ${MIN_KEEP_COUNT} 个历史文件"限制,清理后目录可能仍高于目标水位 ${formatBytes(CLEAN_TARGET_BYTES)}`);
}
console.log(apply ? 'CLEAN_OK' : 'CLEAN_DRY_RUN_OK');
}
/**
* 解析命令行参数
* 用法:node script/check-root-logs.cjs [env] [--clean] [--apply]
* 不带 --clean 时保持原有只读检测行为;--clean 默认 dry-run 输出删除计划;
* --apply 必须与 --clean 一起使用才真正执行删除
*
* @param {Array<string>} argv - process.argv.slice(2)
* @return {object} 解析结果:{ envName: {string}, clean: {boolean}, apply: {boolean} }
*/
function parseArgs(argv) {
const result = { envName: DEFAULT_ENV, clean: false, apply: false };
for (const arg of argv) {
if (arg === '--clean') {
result.clean = true;
} else if (arg === '--apply') {
result.apply = true;
} else if (arg.startsWith('--')) {
throw new Error(`未知参数: ${arg}`);
} else {
result.envName = arg;
}
}
if (result.apply && !result.clean) {
throw new Error('--apply 必须与 --clean 一起使用;请先使用 --clean(默认 dry-run)预览删除计划。');
}
return result;
}
/**
* 脚本入口:加载部署配置并执行只读日志目录检测
* 无 --clean 时沿用原有只读检测流程;有 --clean 时执行日志目录清理(默认 dry-run,仅 --apply 真正删除);配置缺失或 SSH 失败时输出错误信息并以非零退出码结束
*
* @return {void}
*/
function main() {
const rawArgs = process.argv.slice(2);
const isCleanFlow = rawArgs.includes('--clean') || rawArgs.includes('--apply');
try {
ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。');
const options = parseArgs(rawArgs);
const config = loadDeployConfig(options.envName);
if (options.clean) {
runClean(config, { apply: options.apply });
return;
}
console.log(`[CHECK_ROOT_LOGS] env=${options.envName} host=${config.username}@${config.host}:${config.port} dir=${LOGS_DIR}`);
console.log(checkRootLogs(config));
console.log('CHECK_ROOT_LOGS_OK');
} catch (error) {
const message = String(error && error.message ? error.message : error);
const failTag = isCleanFlow ? 'CLEAN_FAIL' : 'CHECK_ROOT_LOGS_FAIL';
console.error(`${failTag}: ${message}`);
process.exit(1);
}
}
main();

View File

@ -1,78 +0,0 @@
'use strict';
/**
* 幂等补齐订单分表的 claim_operator_id / claim_operator 列。
*
* 背景:这两列由订单模型(app/model/order_delivery.js)定义,分表工厂
* (order_delivery_factory.js)在首次访问某张分表时自动同步;history /
* outsourced 等长期不被访问的表可能滞后,可用本脚本提前补齐。
*
* 用法:
* 开发:node script/fix-order-claim-operator-column.cjs
* 生产:PowerShell 中 $env:NODE_ENV='production'; node script/fix-order-claim-operator-column.cjs
*
* 安全:只 ADD 缺失列(与模型定义一致),不触碰 id / AUTO_INCREMENT,
* 不修改已有列,可重复执行。
*/
(async () => {
try {
const configs = require('../database/config.js');
const env = process.env.NODE_ENV || 'development';
const cfg = configs[env];
if (!cfg) {
console.error('NO_CONFIG_FOR_ENV');
process.exit(2);
}
const mysql = require('mysql2/promise');
const conn = await mysql.createConnection({
host: cfg.host,
port: cfg.port || 3306,
user: cfg.username,
password: cfg.password,
database: cfg.database,
});
const [ tables ] = await conn.query(
`SELECT TABLE_NAME FROM information_schema.TABLES
WHERE TABLE_SCHEMA = ? AND TABLE_NAME LIKE 'wms_order_delivery\\_%'
ORDER BY TABLE_NAME`,
[ cfg.database ]
);
console.log(`环境: ${env}, 库: ${cfg.host}:${cfg.port}/${cfg.database}`);
console.log(`订单分表数量: ${tables.length}\n`);
const targetColumns = [
{ name: 'claim_operator_id', sql: "ADD COLUMN claim_operator_id BIGINT(20) NULL COMMENT '领料人工号ID'" },
{ name: 'claim_operator', sql: "ADD COLUMN claim_operator VARCHAR(50) NULL COMMENT '领料人'" },
];
let added = 0;
let ok = 0;
for (const row of tables) {
const tableName = row.TABLE_NAME || row.table_name;
for (const column of targetColumns) {
const [ columns ] = await conn.query(
`SELECT COLUMN_NAME FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = ?`,
[ cfg.database, tableName, column.name ]
);
if (columns.length === 0) {
await conn.query(`ALTER TABLE \`${tableName}\` ${column.sql}`);
console.log(`[ADD] ${tableName}.${column.name}`);
added += 1;
} else {
ok += 1;
}
}
}
console.log(`\n完成: 已存在 ${ok} 列, 新增 ${added} 列`);
await conn.end();
process.exit(0);
} catch (err) {
console.error('ERROR', err.message);
process.exit(3);
}
})();

View File

@ -1,78 +0,0 @@
'use strict';
/**
* 幂等补齐订单分表的 grab_operator_id / grab_operator 列。
*
* 背景:这两列由订单模型(app/model/order_delivery.js)定义,分表工厂
* (order_delivery_factory.js)在首次访问某张分表时自动同步;history /
* outsourced 等长期不被访问的表可能滞后,可用本脚本提前补齐。
*
* 用法:
* 开发:node script/fix-order-grab-operator-column.cjs
* 生产:PowerShell 中 $env:NODE_ENV='production'; node script/fix-order-grab-operator-column.cjs
*
* 安全:只 ADD 缺失列(与模型定义一致),不触碰 id / AUTO_INCREMENT,
* 不修改已有列,可重复执行。
*/
(async () => {
try {
const configs = require('../database/config.js');
const env = process.env.NODE_ENV || 'development';
const cfg = configs[env];
if (!cfg) {
console.error('NO_CONFIG_FOR_ENV');
process.exit(2);
}
const mysql = require('mysql2/promise');
const conn = await mysql.createConnection({
host: cfg.host,
port: cfg.port || 3306,
user: cfg.username,
password: cfg.password,
database: cfg.database,
});
const [ tables ] = await conn.query(
`SELECT TABLE_NAME FROM information_schema.TABLES
WHERE TABLE_SCHEMA = ? AND TABLE_NAME LIKE 'wms_order_delivery\\_%'
ORDER BY TABLE_NAME`,
[ cfg.database ]
);
console.log(`环境: ${env}, 库: ${cfg.host}:${cfg.port}/${cfg.database}`);
console.log(`订单分表数量: ${tables.length}\n`);
const targetColumns = [
{ name: 'grab_operator_id', sql: "ADD COLUMN grab_operator_id BIGINT(20) NULL COMMENT '抓取人工号ID'" },
{ name: 'grab_operator', sql: "ADD COLUMN grab_operator VARCHAR(50) NULL COMMENT '抓取人'" },
];
let added = 0;
let ok = 0;
for (const row of tables) {
const tableName = row.TABLE_NAME || row.table_name;
for (const column of targetColumns) {
const [ columns ] = await conn.query(
`SELECT COLUMN_NAME FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = ?`,
[ cfg.database, tableName, column.name ]
);
if (columns.length === 0) {
await conn.query(`ALTER TABLE \`${tableName}\` ${column.sql}`);
console.log(`[ADD] ${tableName}.${column.name}`);
added += 1;
} else {
ok += 1;
}
}
}
console.log(`\n完成: 已存在 ${ok} 列, 新增 ${added} 列`);
await conn.end();
process.exit(0);
} catch (err) {
console.error('ERROR', err.message);
process.exit(3);
}
})();

View File

@ -1,51 +0,0 @@
'use strict';
/**
* 回填 wms_wave_pick_task.batch_no_array(生产只读预检)。
*
* 从 wms_wave_pick_task_wave 按 task_id 聚合 wave_no(逗号分隔,按 id 升序),
* 只更新 batch_no_array IS NULL 的任务,幂等可重复执行。
*/
const dbConfig = require('../database/config.js');
const Sequelize = require('sequelize');
(async () => {
const cfg = dbConfig.production;
const s = new Sequelize(cfg.database, cfg.username, cfg.password, {
host: cfg.host,
port: cfg.port,
dialect: cfg.dialect || 'mysql',
logging: false,
});
const q = async (sql, repl) => {
const rows = await s.query(sql, { replacements: repl, type: Sequelize.QueryTypes.SELECT });
return Array.isArray(rows) ? rows : [];
};
const total = await q('SELECT COUNT(*) AS c FROM wms_wave_pick_task');
console.log('A. 任务总数:', JSON.stringify(total));
const nullable = await q("SELECT COUNT(*) AS c FROM wms_wave_pick_task WHERE batch_no_array IS NULL OR batch_no_array = ''");
console.log('B. batch_no_array 为空的任务数:', JSON.stringify(nullable));
const backfillable = await q(
"SELECT COUNT(DISTINCT tw.task_id) AS c FROM wms_wave_pick_task_wave tw "
+ "INNER JOIN wms_wave_pick_task t ON t.id = tw.task_id "
+ "WHERE tw.wave_no IS NOT NULL AND tw.wave_no <> '' "
+ "AND (t.batch_no_array IS NULL OR t.batch_no_array = '')"
);
console.log('C. 可回填的任务数(有 wave 记录且 batch_no_array 为空):', JSON.stringify(backfillable));
const byWaveRows = await q(
"SELECT task_id, COUNT(*) AS c FROM wms_wave_pick_task_wave "
+ "WHERE wave_no IS NOT NULL AND wave_no <> '' GROUP BY task_id ORDER BY c DESC LIMIT 5"
);
console.log('D. 单任务最多波次记录数样例:', JSON.stringify(byWaveRows));
await s.close();
})().catch(e => {
console.error('ERROR:', e.message);
process.exit(1);
});

View File

@ -1,55 +0,0 @@
'use strict';
/**
* 临时核验脚本:核实生产库历史任务的领料人回填来源。
* 1) wms_wave_batch 波次表 claim 字段现状;
* 2) order_operation_log 中 ORDER_WAVE_CLAIM 领料日志数量与样例。
*/
const dbConfig = require('../database/config.js');
const Sequelize = require('sequelize');
(async () => {
const cfg = dbConfig.production;
const s = new Sequelize(cfg.database, cfg.username, cfg.password, {
host: cfg.host,
port: cfg.port,
dialect: cfg.dialect || 'mysql',
logging: false,
});
const q = async sql => {
const rows = await s.query(sql, { type: Sequelize.QueryTypes.SELECT });
return Array.isArray(rows) ? rows : [];
};
const waveClaim = await q(
"SELECT wave_id, wave_no, claim_operator, claim_time FROM wms_wave_batch "
+ "WHERE wave_no IN ('B2026081500040','B2026081500038','B2026081500084','B2026081500075','B2026081500023','B2026081500022','B2026081500085') "
+ "ORDER BY wave_id DESC"
);
console.log('A. 波次表 claim 现状:', JSON.stringify(waveClaim, null, 2));
const claimLogTotal = await q(
"SELECT COUNT(*) AS c FROM order_operation_log WHERE operation_code = 'ORDER_WAVE_CLAIM'"
);
console.log('B. 领料日志总数:', JSON.stringify(claimLogTotal));
const claimLogSample = await q(
"SELECT id, business_id, operation_code, operator_id, operator_name, message, create_time "
+ "FROM order_operation_log WHERE operation_code = 'ORDER_WAVE_CLAIM' "
+ "ORDER BY id DESC LIMIT 10"
);
console.log('C. 领料日志最近10条:', JSON.stringify(claimLogSample, null, 2));
const taskClaim = await q(
"SELECT id, task_no, pick_mode, source, claim_operator_id, claim_operator FROM wms_wave_pick_task "
+ "WHERE id IN (259, 251, 229) ORDER BY id DESC"
);
console.log('D. 任务表 claim 现状:', JSON.stringify(taskClaim, null, 2));
await s.close();
})().catch(e => {
console.error('ERROR:', e.message);
process.exit(1);
});

View File

@ -1,48 +0,0 @@
'use strict';
/**
* 临时核验脚本 v2:核实生产库历史领料人回填来源(wms_operation_log)。
*/
const dbConfig = require('../database/config.js');
const Sequelize = require('sequelize');
(async () => {
const cfg = dbConfig.production;
const s = new Sequelize(cfg.database, cfg.username, cfg.password, {
host: cfg.host,
port: cfg.port,
dialect: cfg.dialect || 'mysql',
logging: false,
});
const q = async sql => {
const rows = await s.query(sql, { type: Sequelize.QueryTypes.SELECT });
return Array.isArray(rows) ? rows : [];
};
const claimLogTotal = await q(
"SELECT COUNT(*) AS c, COUNT(DISTINCT warehouse_id) AS wh "
+ "FROM wms_operation_log WHERE operation_code = 'ORDER_WAVE_CLAIM'"
);
console.log('A. 领料日志总数/仓库数:', JSON.stringify(claimLogTotal));
const claimLogSample = await q(
"SELECT id, business_type, business_id, operation_code, operator_id, operator_name, message, warehouse_id, created_at "
+ "FROM wms_operation_log WHERE operation_code = 'ORDER_WAVE_CLAIM' "
+ "ORDER BY id DESC LIMIT 5"
);
console.log('B. 领料日志最近5条:', JSON.stringify(claimLogSample, null, 2));
const claimLogByOperator = await q(
"SELECT operator_id, operator_name, COUNT(*) AS c FROM wms_operation_log "
+ "WHERE operation_code = 'ORDER_WAVE_CLAIM' GROUP BY operator_id, operator_name "
+ "ORDER BY c DESC LIMIT 10"
);
console.log('C. 领料日志按操作人分布:', JSON.stringify(claimLogByOperator, null, 2));
await s.close();
})().catch(e => {
console.error('ERROR:', e.message);
process.exit(1);
});

View File

@ -1,64 +0,0 @@
'use strict';
/**
* 临时脚本:影响范围确认(只读)——
* wms_wave_pick_task WHERE pick_mode = 1 AND source = 2 的回填范围。
*/
const dbConfig = require('../database/config.js');
const Sequelize = require('sequelize');
(async () => {
const cfg = dbConfig.production;
const s = new Sequelize(cfg.database, cfg.username, cfg.password, {
host: cfg.host,
port: cfg.port,
dialect: cfg.dialect || 'mysql',
logging: false,
});
const q = async sql => {
const rows = await s.query(sql, { type: Sequelize.QueryTypes.SELECT });
return Array.isArray(rows) ? rows : [];
};
const total = await q(
"SELECT COUNT(*) AS c FROM wms_wave_pick_task WHERE pick_mode = 1 AND source = 2"
);
console.log('A. 目标行数 (pick_mode=1 AND source=2):', JSON.stringify(total));
const byStatus = await q(
'SELECT status, COUNT(*) AS cnt FROM wms_wave_pick_task WHERE pick_mode = 1 AND source = 2 GROUP BY status ORDER BY status'
);
console.log('B. 按任务状态分布:', JSON.stringify(byStatus));
const byWaveCount = await q(
'SELECT wave_count, COUNT(*) AS cnt FROM wms_wave_pick_task WHERE pick_mode = 1 AND source = 2 GROUP BY wave_count ORDER BY wave_count'
);
console.log('C. 按 wave_count 分布(确认单波次):', JSON.stringify(byWaveCount));
const byTaskNoPrefix = await q(
"SELECT LEFT(task_no, 2) AS prefix, COUNT(*) AS cnt FROM wms_wave_pick_task "
+ "WHERE pick_mode = 1 AND source = 2 GROUP BY prefix"
);
console.log('D. task_no 前缀分布(PK=拣货创建):', JSON.stringify(byTaskNoPrefix));
const waveRel = await q(
'SELECT COUNT(*) AS c FROM wms_wave_pick_task t '
+ 'INNER JOIN wms_wave_pick_task_wave tw ON tw.task_id = t.id '
+ 'WHERE t.pick_mode = 1 AND t.source = 2'
);
console.log('E. 目标任务中已有波次关联记录的任务数:', JSON.stringify(waveRel));
const noWaveRel = await q(
'SELECT COUNT(*) AS c FROM wms_wave_pick_task t '
+ 'LEFT JOIN wms_wave_pick_task_wave tw ON tw.task_id = t.id '
+ 'WHERE t.pick_mode = 1 AND t.source = 2 AND tw.task_id IS NULL'
);
console.log('F. 目标任务中无波次关联记录的任务数:', JSON.stringify(noWaveRel));
await s.close();
})().catch(e => {
console.error('ERROR:', e.message);
process.exit(1);
});

View File

@ -1,75 +0,0 @@
'use strict';
/**
* 临时核验脚本:核实生产库 wms_wave_pick_task 的 pick_mode / source / wave_count /
* batch_no 写入情况,以及团购任务(pick_mode=1/5)是否单波次。
*/
const dbConfig = require('../database/config.js');
const Sequelize = require('sequelize');
(async () => {
const cfg = dbConfig.production;
const s = new Sequelize(cfg.database, cfg.username, cfg.password, {
host: cfg.host,
port: cfg.port,
dialect: cfg.dialect || 'mysql',
logging: false,
});
console.log('=== 1) 主表按 source/pick_mode 统计(batch_no / batch_no_array 非空数、wave_count 分布) ===');
const [ rows1 ] = await s.query(`
SELECT t.source,
t.pick_mode,
COUNT(*) AS cnt,
SUM(t.batch_no IS NOT NULL AND t.batch_no <> '') AS with_batch_no,
SUM(t.batch_no_array IS NOT NULL AND t.batch_no_array <> '') AS with_batch_no_array,
MIN(t.wave_count) AS min_wave_count,
MAX(t.wave_count) AS max_wave_count
FROM wms_wave_pick_task t
GROUP BY t.source, t.pick_mode
ORDER BY t.source, t.pick_mode
`, { type: Sequelize.QueryTypes.SELECT });
console.table(rows1);
console.log('=== 2) 团购任务(pick_mode IN (1,5))与波次关联表记录数分布(判断单波次/多波次) ===');
const [ rows2 ] = await s.query(`
SELECT t.source,
t.pick_mode,
t.wave_count,
COUNT(*) AS cnt
FROM wms_wave_pick_task t
WHERE t.pick_mode IN (1, 5)
GROUP BY t.source, t.pick_mode, t.wave_count
ORDER BY t.source, t.pick_mode, t.wave_count
`, { type: Sequelize.QueryTypes.SELECT });
console.table(rows2);
console.log('=== 3) 团购任务主表 wave_id 非空占比与 wave_count 实际值(抽样) ===');
const [ rows3 ] = await s.query(`
SELECT t.id, t.task_no, t.source, t.pick_mode, t.wave_id, t.wave_count, t.batch_no, t.batch_no_array,
(SELECT COUNT(*) FROM wms_wave_pick_task_wave tw WHERE tw.task_id = t.id) AS task_wave_rows
FROM wms_wave_pick_task t
WHERE t.pick_mode IN (1, 5)
ORDER BY t.id DESC
LIMIT 20
`, { type: Sequelize.QueryTypes.SELECT });
console.table(rows3);
console.log('=== 4) wms_wave_pick_task_wave 中单任务波次数 > 1 的任务(按 task_id 分组) ===');
const [ rows4 ] = await s.query(`
SELECT tw.task_id, t.source, t.pick_mode, t.wave_count, COUNT(*) AS task_wave_rows
FROM wms_wave_pick_task_wave tw
INNER JOIN wms_wave_pick_task t ON t.id = tw.task_id
GROUP BY tw.task_id, t.source, t.pick_mode, t.wave_count
HAVING COUNT(*) > 1
ORDER BY tw.task_id DESC
LIMIT 20
`, { type: Sequelize.QueryTypes.SELECT });
console.table(rows4);
await s.close();
})().catch(e => {
console.error('ERROR:', e.message);
process.exit(1);
});

View File

@ -1,68 +0,0 @@
'use strict';
/**
* 临时核验脚本(v2):JSON 输出核实生产库 wms_wave_pick_task 的
* pick_mode/source 分布与团购任务波次数。
*/
const dbConfig = require('../database/config.js');
const Sequelize = require('sequelize');
(async () => {
const cfg = dbConfig.production;
const s = new Sequelize(cfg.database, cfg.username, cfg.password, {
host: cfg.host,
port: cfg.port,
dialect: cfg.dialect || 'mysql',
logging: false,
});
const [ total ] = await s.query('SELECT COUNT(*) AS c FROM wms_wave_pick_task', { type: Sequelize.QueryTypes.SELECT });
console.log('A. 主表总数:', JSON.stringify(total));
const [ byMode ] = await s.query(
'SELECT pick_mode, source, COUNT(*) AS cnt FROM wms_wave_pick_task GROUP BY pick_mode, source ORDER BY pick_mode, source',
{ type: Sequelize.QueryTypes.SELECT }
);
console.log('B. pick_mode/source 分布:', JSON.stringify(byMode));
const [ byWaveCount ] = await s.query(
'SELECT pick_mode, wave_count, COUNT(*) AS cnt FROM wms_wave_pick_task WHERE pick_mode IN (1, 5) GROUP BY pick_mode, wave_count ORDER BY pick_mode, wave_count',
{ type: Sequelize.QueryTypes.SELECT }
);
console.log('C. 团购任务 wave_count 分布:', JSON.stringify(byWaveCount));
const [ multiWave ] = await s.query(
'SELECT tw.task_id, t.pick_mode, t.source, t.wave_count, COUNT(*) AS task_wave_rows '
+ 'FROM wms_wave_pick_task_wave tw '
+ 'INNER JOIN wms_wave_pick_task t ON t.id = tw.task_id '
+ 'GROUP BY tw.task_id, t.pick_mode, t.source, t.wave_count '
+ 'ORDER BY tw.task_id DESC LIMIT 10',
{ type: Sequelize.QueryTypes.SELECT }
);
console.log('D. 任务-波次关联(最近10条):', JSON.stringify(multiWave));
const [ taskWaveTotal ] = await s.query('SELECT COUNT(*) AS c FROM wms_wave_pick_task_wave', { type: Sequelize.QueryTypes.SELECT });
console.log('E. 波次关联表总数:', JSON.stringify(taskWaveTotal));
const [ sampleGroup ] = await s.query(
"SELECT id, task_no, source, pick_mode, wave_id, wave_count, batch_no, "
+ "(SELECT COUNT(*) FROM wms_wave_pick_task_wave tw WHERE tw.task_id = t.id) AS task_wave_rows "
+ "FROM wms_wave_pick_task t WHERE pick_mode = 1 ORDER BY id DESC LIMIT 10",
{ type: Sequelize.QueryTypes.SELECT }
);
console.log('F. 团购任务最近10条:', JSON.stringify(sampleGroup));
const [ sampleScatter ] = await s.query(
"SELECT id, task_no, source, pick_mode, wave_id, wave_count, batch_no, "
+ "(SELECT COUNT(*) FROM wms_wave_pick_task_wave tw WHERE tw.task_id = t.id) AS task_wave_rows "
+ "FROM wms_wave_pick_task t WHERE pick_mode IN (2, 3, 4) ORDER BY id DESC LIMIT 10",
{ type: Sequelize.QueryTypes.SELECT }
);
console.log('G. 散单任务最近10条:', JSON.stringify(sampleScatter));
await s.close();
})().catch(e => {
console.error('ERROR:', e.message);
process.exit(1);
});

View File

@ -1,76 +0,0 @@
'use strict';
/**
* 临时核验脚本(v3):修正 SELECT 结果解构,JSON 输出核实生产库
* wms_wave_pick_task 的 pick_mode/source 分布与团购任务波次数。
*/
const dbConfig = require('../database/config.js');
const Sequelize = require('sequelize');
(async () => {
const cfg = dbConfig.production;
const s = new Sequelize(cfg.database, cfg.username, cfg.password, {
host: cfg.host,
port: cfg.port,
dialect: cfg.dialect || 'mysql',
logging: false,
});
const q = async sql => {
const rows = await s.query(sql, { type: Sequelize.QueryTypes.SELECT });
return Array.isArray(rows) ? rows : [];
};
const total = await q('SELECT COUNT(*) AS c FROM wms_wave_pick_task');
console.log('A. 主表总数:', JSON.stringify(total));
const byMode = await q(
'SELECT pick_mode, source, COUNT(*) AS cnt FROM wms_wave_pick_task GROUP BY pick_mode, source ORDER BY pick_mode, source'
);
console.log('B. pick_mode/source 分布:', JSON.stringify(byMode));
const byWaveCount = await q(
'SELECT pick_mode, wave_count, COUNT(*) AS cnt FROM wms_wave_pick_task WHERE pick_mode IN (1, 5) GROUP BY pick_mode, wave_count ORDER BY pick_mode, wave_count'
);
console.log('C. 团购任务 wave_count 分布:', JSON.stringify(byWaveCount));
const multiWave = await q(
'SELECT tw.task_id, t.pick_mode, t.source, t.wave_count, COUNT(*) AS task_wave_rows '
+ 'FROM wms_wave_pick_task_wave tw '
+ 'INNER JOIN wms_wave_pick_task t ON t.id = tw.task_id '
+ 'GROUP BY tw.task_id, t.pick_mode, t.source, t.wave_count '
+ 'HAVING COUNT(*) > 1 '
+ 'ORDER BY tw.task_id DESC LIMIT 10'
);
console.log('D. 多波次任务样例:', JSON.stringify(multiWave));
const singleWave = await q(
'SELECT tw.task_id, t.pick_mode, t.source, t.wave_count, COUNT(*) AS task_wave_rows '
+ 'FROM wms_wave_pick_task_wave tw '
+ 'INNER JOIN wms_wave_pick_task t ON t.id = tw.task_id '
+ 'GROUP BY tw.task_id, t.pick_mode, t.source, t.wave_count '
+ 'HAVING COUNT(*) = 1 '
+ 'ORDER BY tw.task_id DESC LIMIT 10'
);
console.log('E. 单波次任务样例:', JSON.stringify(singleWave));
const sampleGroup = await q(
'SELECT id, task_no, source, pick_mode, wave_id, wave_count, batch_no, '
+ '(SELECT COUNT(*) FROM wms_wave_pick_task_wave tw WHERE tw.task_id = t.id) AS task_wave_rows '
+ 'FROM wms_wave_pick_task t WHERE pick_mode = 1 ORDER BY id DESC LIMIT 10'
);
console.log('F. 团购任务最近10条:', JSON.stringify(sampleGroup));
const sampleScatter = await q(
'SELECT id, task_no, source, pick_mode, wave_id, wave_count, batch_no, '
+ '(SELECT COUNT(*) FROM wms_wave_pick_task_wave tw WHERE tw.task_id = t.id) AS task_wave_rows '
+ 'FROM wms_wave_pick_task t WHERE pick_mode IN (2, 3, 4) ORDER BY id DESC LIMIT 10'
);
console.log('G. 散单任务最近10条:', JSON.stringify(sampleScatter));
await s.close();
})().catch(e => {
console.error('ERROR:', e.message);
process.exit(1);
});

View File

@ -1,60 +0,0 @@
'use strict';
/**
* 本地自测桩:模拟远端只读探测输出,验证 check-root-logs.cjs 的
* --clean dry-run 删除计划逻辑(不连接任何真实服务器)。
*
* 用法:node script/tmp-test-clean-plan.cjs --clean
*/
const path = require('node:path');
const deployLibPath = require.resolve('./deploy-lib.cjs');
/**
* 构造模拟的远端探测输出:
* 总大小约 6.37 GiB(超过 4 GiB 阈值),包含活跃日志、7 个轮转日志、
* 其他命名模式的日志与 .gz 文件,用于验证排除规则与删除计划
*
* @return {string} 模拟的远端探测标准输出
*/
function buildFakeProbeOutput() {
const files = [
// 正在写入的活跃日志(无日期后缀),必须被排除
{ mtime: 1757780000, size: 1181116006, filePath: '/root/logs/wms/wms-web.log' },
// 历史轮转日志(mtime 升序,最旧的 4 个较大)
{ mtime: 1756150000, size: 1288490188, filePath: '/root/logs/wms/wms-web.log.2026-08-24' },
{ mtime: 1756236400, size: 1288490188, filePath: '/root/logs/wms/wms-web.log.2026-08-25' },
{ mtime: 1756322800, size: 1288490188, filePath: '/root/logs/wms/wms-web.log.2026-08-26' },
{ mtime: 1756409200, size: 1288490188, filePath: '/root/logs/wms/wms-web.log.2026-08-27' },
{ mtime: 1756495600, size: 214748365, filePath: '/root/logs/wms/wms-web.log.2026-08-28' },
{ mtime: 1756582000, size: 107374182, filePath: '/root/logs/wms/wms-web.log.2026-08-29' },
{ mtime: 1756668400, size: 107374182, filePath: '/root/logs/wms/wms-web.log.2026-08-30' },
// 非 wms-web 轮转命名模式的文件,必须被排除
{ mtime: 1756583000, size: 29360128, filePath: '/root/logs/wms/common-error.log.2026-08-29' },
{ mtime: 1756720000, size: 12582912, filePath: '/root/logs/wms/egg-schedule.log.2026-08-31' },
// .gz 后缀文件不符合严格命名模式,必须被排除
{ mtime: 1756730000, size: 31457280, filePath: '/root/logs/wms/wms-web.log.2026-08-31.gz' },
];
const totalBytes = files.reduce((sum, item) => sum + item.size, 0);
return [
`PROBE_TOTAL_BYTES=${totalBytes}`,
...files.map(item => `${item.mtime}\t${item.size}\t${item.filePath}`),
].join('\n');
}
// 将 deploy-lib.cjs 替换为本地桩,避免真实 SSH 连接
require.cache[deployLibPath] = {
id: deployLibPath,
filename: deployLibPath,
loaded: true,
exports: {
ensureCommandAvailable() {},
loadDeployConfig: () => ({ envName: 'production', username: 'root', host: '127.0.0.1', port: 22 }),
quoteForBash: value => `'${String(value)}'`,
runSsh: () => buildFakeProbeOutput(),
},
};
// 加载被测脚本(其 main() 会读取当前进程参数,即 --clean)
require(path.resolve(__dirname, 'check-root-logs.cjs'));

View File

@ -1,37 +0,0 @@
'use strict';
/**
* 临时核验脚本:查询生产库 wms_wave_pick_task.batch_no_array 字段是否已添加。
*/
const dbConfig = require('../database/config.js');
const Sequelize = require('sequelize');
(async () => {
const cfg = dbConfig.production;
const s = new Sequelize(cfg.database, cfg.username, cfg.password, {
host: cfg.host,
port: cfg.port,
dialect: cfg.dialect || 'mysql',
logging: false,
});
const [ rows ] = await s.query(
"SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_COMMENT "
+ "FROM INFORMATION_SCHEMA.COLUMNS "
+ "WHERE TABLE_SCHEMA = DATABASE() "
+ "AND TABLE_NAME = 'wms_wave_pick_task' "
+ "AND COLUMN_NAME = 'batch_no_array'"
);
console.log(JSON.stringify(rows, null, 2));
const [ meta ] = await s.query(
"SELECT name FROM SequelizeMeta WHERE name = '20260904120000-add-batch-no-array-to-wms-wave-pick-task.js'"
);
console.log('SequelizeMeta 记录:', JSON.stringify(meta));
await s.close();
})().catch(e => {
console.error('ERROR:', e.message);
process.exit(1);
});

View File

@ -1,39 +0,0 @@
'use strict';
/**
* 临时核验脚本:查询生产库 wms_wave_batch 领料字段与 SequelizeMeta 记录。
*/
const dbConfig = require('../database/config.js');
const Sequelize = require('sequelize');
(async () => {
const cfg = dbConfig.production;
const s = new Sequelize(cfg.database, cfg.username, cfg.password, {
host: cfg.host,
port: cfg.port,
dialect: cfg.dialect || 'mysql',
logging: false,
});
const rows = await s.query(
"SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_COMMENT "
+ "FROM INFORMATION_SCHEMA.COLUMNS "
+ "WHERE TABLE_SCHEMA = DATABASE() "
+ "AND TABLE_NAME = 'wms_wave_batch' "
+ "AND COLUMN_NAME IN ('claim_operator', 'claim_time')",
{ type: Sequelize.QueryTypes.SELECT }
);
console.log('字段:', JSON.stringify(rows));
const meta = await s.query(
"SELECT name FROM SequelizeMeta WHERE name = '20260904130000-add-claim-operator-to-wms-wave-batch.js'",
{ type: Sequelize.QueryTypes.SELECT }
);
console.log('Meta:', JSON.stringify(meta));
await s.close();
})().catch(e => {
console.error('ERROR:', e.message);
process.exit(1);
});

View File

@ -1,39 +0,0 @@
'use strict';
/**
* 临时核验脚本:查询生产库 wms_wave_pick_task 领料字段与 SequelizeMeta 记录。
*/
const dbConfig = require('../database/config.js');
const Sequelize = require('sequelize');
(async () => {
const cfg = dbConfig.production;
const s = new Sequelize(cfg.database, cfg.username, cfg.password, {
host: cfg.host,
port: cfg.port,
dialect: cfg.dialect || 'mysql',
logging: false,
});
const rows = await s.query(
"SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_COMMENT "
+ "FROM INFORMATION_SCHEMA.COLUMNS "
+ "WHERE TABLE_SCHEMA = DATABASE() "
+ "AND TABLE_NAME = 'wms_wave_pick_task' "
+ "AND COLUMN_NAME IN ('claim_operator_id', 'claim_operator')",
{ type: Sequelize.QueryTypes.SELECT }
);
console.log('字段:', JSON.stringify(rows));
const meta = await s.query(
"SELECT name FROM SequelizeMeta WHERE name = '20260904140000-add-claim-operator-to-wms-wave-pick-task.js'",
{ type: Sequelize.QueryTypes.SELECT }
);
console.log('Meta:', JSON.stringify(meta));
await s.close();
})().catch(e => {
console.error('ERROR:', e.message);
process.exit(1);
});

View File

@ -1,341 +0,0 @@
/**
* 临时验证脚本:对比 stock.report.search 改造后的 SQL(聚合极值)与旧 SQL(全量明细+JS归并)在开发库的结果等价性。
* 用法:node script/tmp-verify-report-edge-sql.cjs
* 验证完成后可删除。
*/
'use strict';
const path = require('path');
const { createRequire } = require('module');
const projectRoot = path.resolve(__dirname, '..');
const projectRequire = createRequire(path.join(projectRoot, 'package.json'));
const mysql = projectRequire('mysql2/promise');
function buildOldEdgeMap(rows, keyFn) {
const map = new Map();
for (const row of rows) {
const key = keyFn(row);
if (!map.has(key)) {
map.set(key, {
first_before: row.before_quantity,
last_after: row.after_quantity,
});
} else {
map.get(key).last_after = row.after_quantity;
}
}
return map;
}
function buildOldPreStartMap(rows, keyFn) {
const latest = new Map();
for (const row of rows) {
const key = keyFn(row);
if (!key) continue;
const ct = new Date(row.created_at).getTime();
const id = Number(row.id);
const cur = latest.get(key);
if (!cur || ct > cur.ct || (ct === cur.ct && id > cur.id)) {
latest.set(key, { after_quantity: row.after_quantity, ct, id });
}
}
const map = new Map();
for (const [ key, v ] of latest.entries()) {
map.set(key, v.after_quantity);
}
return map;
}
function diffMaps(label, oldMap, newMap) {
const keys = new Set([ ...oldMap.keys(), ...newMap.keys() ]);
const diffs = [];
for (const key of keys) {
const a = oldMap.get(key);
const b = newMap.get(key);
const isScalarOld = a === null || typeof a !== 'object';
const isScalarNew = b === null || typeof b !== 'object';
if (isScalarOld || isScalarNew) {
const av = Number(a === undefined || a === null ? 0 : a);
const bv = Number(b === undefined || b === null ? 0 : b);
if (av !== bv) {
diffs.push(`${key}: old=${JSON.stringify(a)} new=${JSON.stringify(b)}`);
}
continue;
}
const aFirst = a.first_before === undefined ? null : a.first_before;
const aLast = a.last_after === undefined ? null : a.last_after;
const bFirst = b.first_before === undefined ? null : b.first_before;
const bLast = b.last_after === undefined ? null : b.last_after;
if (Number(aFirst) !== Number(bFirst) || Number(aLast) !== Number(bLast)) {
diffs.push(`${key}: old=(${aFirst},${aLast}) new=(${bFirst},${bLast})`);
}
}
console.log(`[${label}] old keys=${oldMap.size}, new keys=${newMap.size}, diffs=${diffs.length}`);
diffs.slice(0, 10).forEach(d => console.log(' DIFF ' + d));
return diffs.length === 0;
}
(async () => {
const configFactory = require(path.join(projectRoot, 'config', 'config.local.js'));
const config = typeof configFactory === 'function' ? configFactory({ name: 'wms-debug' }) : configFactory;
const client = config.mysql.clients.wms;
const connection = await mysql.createConnection({
host: client.host,
port: Number(client.port),
user: client.user,
password: client.password,
database: client.database,
charset: 'utf8mb4',
});
try {
const startTime = '2026-08-01 00:00:00';
const endTime = '2026-08-31 23:59:59';
// by_space=false 分支用更宽区间(覆盖区间内有流水的场景)
const wideStart = '2026-05-01 00:00:00';
const wideEnd = '2026-09-03 00:00:00';
// ============ by_space=false(wms_stock_transaction) ============
const warehouseId = 1000028;
const oldRangeParams = [ warehouseId, wideStart, wideEnd ];
const oldIntervalRows = (await connection.query(
`SELECT t.id, t.stock_id, t.store_id, t.before_quantity, t.after_quantity, t.created_at
FROM wms_stock_transaction t
WHERE t.warehouse_id = ? AND t.created_at >= ? AND t.created_at <= ?
ORDER BY t.stock_id ASC, t.store_id ASC, t.created_at ASC, t.id ASC`,
oldRangeParams
))[0];
const newIntervalRows = (await connection.query(
`SELECT
g.stock_id,
g.space_id,
g.store_id,
ft.before_quantity,
lt.after_quantity,
ft.created_at
FROM (
SELECT
t.stock_id,
0 AS space_id,
t.store_id,
MIN(t.created_at) AS _min_ct,
MAX(t.created_at) AS _max_ct
FROM wms_stock_transaction t
WHERE t.warehouse_id = ? AND t.created_at >= ? AND t.created_at <= ?
GROUP BY t.stock_id, t.store_id
) g
LEFT JOIN wms_stock_transaction ft
ON ft.id = (
SELECT MIN(t2.id)
FROM wms_stock_transaction t2
WHERE t2.warehouse_id = ? AND t2.created_at >= ? AND t2.created_at <= ?
AND t2.stock_id = g.stock_id AND t2.store_id = g.store_id
AND t2.created_at = g._min_ct
)
LEFT JOIN wms_stock_transaction lt
ON lt.id = (
SELECT MAX(t3.id)
FROM wms_stock_transaction t3
WHERE t3.warehouse_id = ? AND t3.created_at >= ? AND t3.created_at <= ?
AND t3.stock_id = g.stock_id AND t3.store_id = g.store_id
AND t3.created_at = g._max_ct
)
ORDER BY g.stock_id ASC, g.space_id ASC, g.store_id ASC, g._min_ct ASC, g._max_ct ASC`,
[ warehouseId, wideStart, wideEnd, warehouseId, wideStart, wideEnd, warehouseId, wideStart, wideEnd ]
))[0];
const oldEdge = buildOldEdgeMap(oldIntervalRows, r => `${r.stock_id}_${r.store_id}`);
const newEdge = new Map(newIntervalRows.map(r => [
`${r.stock_id}_${r.store_id}`,
{ first_before: r.before_quantity, last_after: r.after_quantity },
]));
const edgeOk = diffMaps('edge by_space=false', oldEdge, newEdge);
// 旧 preStart(全量历史 + JS 归并)
const oldPreRows = (await connection.query(
`SELECT t.id, t.stock_id, t.store_id, t.after_quantity, t.created_at
FROM wms_stock_transaction t
WHERE t.warehouse_id = ? AND t.created_at < ?
ORDER BY t.stock_id ASC, t.store_id ASC, t.created_at DESC, t.id DESC`,
[ warehouseId, startTime ]
))[0];
const newPreRows = (await connection.query(
`SELECT
g.stock_id,
g.space_id,
g.store_id,
lt.after_quantity,
lt.created_at
FROM (
SELECT
t.stock_id,
0 AS space_id,
t.store_id,
MAX(t.created_at) AS _max_ct
FROM wms_stock_transaction t
WHERE t.warehouse_id = ? AND t.created_at < ?
GROUP BY t.stock_id, t.store_id
) g
LEFT JOIN wms_stock_transaction lt
ON lt.id = (
SELECT MAX(t3.id)
FROM wms_stock_transaction t3
WHERE t3.warehouse_id = ? AND t3.created_at < ?
AND t3.stock_id = g.stock_id AND t3.store_id = g.store_id
AND t3.created_at = g._max_ct
)
ORDER BY g.stock_id ASC, g.space_id ASC, g.store_id ASC, g._max_ct DESC`,
[ warehouseId, startTime, warehouseId, startTime ]
))[0];
const oldPre = buildOldPreStartMap(oldPreRows, r => `${r.stock_id}_${r.store_id}`);
const newPre = new Map(newPreRows.map(r => [ `${r.stock_id}_${r.store_id}`, r.after_quantity ]));
const preOk = diffMaps('preStart by_space=false', oldPre, newPre);
// ============ by_space=true(wms_storage_transaction) ============
const whRows = (await connection.query(
'SELECT warehouse_id, COUNT(*) AS cnt FROM wms_storage_transaction GROUP BY warehouse_id ORDER BY cnt DESC LIMIT 1'
))[0];
const storageWh = Number(whRows[0] && whRows[0].warehouse_id) || 0;
console.log(`storage_transaction max warehouse_id=${storageWh}`);
const oldSpaceRows = (await connection.query(
`SELECT t.id, t.stock_id, COALESCE(t.space_id, 0) AS space_id, t.store_id, t.before_quantity, t.after_quantity, t.created_at
FROM wms_storage_transaction t
WHERE t.warehouse_id = ? AND t.created_at >= ? AND t.created_at <= ?
ORDER BY t.stock_id ASC, COALESCE(t.space_id, 0) ASC, t.store_id ASC, t.created_at ASC, t.id ASC`,
[ storageWh, startTime, endTime ]
))[0];
const newSpaceRows = (await connection.query(
`SELECT
g.stock_id,
g.space_id,
g.store_id,
ft.before_quantity,
lt.after_quantity,
ft.created_at
FROM (
SELECT
t.stock_id,
COALESCE(t.space_id, 0) AS space_id,
t.store_id,
MIN(t.created_at) AS _min_ct,
MAX(t.created_at) AS _max_ct
FROM wms_storage_transaction t
WHERE t.warehouse_id = ? AND t.created_at >= ? AND t.created_at <= ?
GROUP BY t.stock_id, COALESCE(t.space_id, 0), t.store_id
) g
LEFT JOIN wms_storage_transaction ft
ON ft.id = (
SELECT MIN(t2.id)
FROM wms_storage_transaction t2
WHERE t2.warehouse_id = ? AND t2.created_at >= ? AND t2.created_at <= ?
AND t2.stock_id = g.stock_id AND COALESCE(t2.space_id, 0) = g.space_id AND t2.store_id = g.store_id
AND t2.created_at = g._min_ct
)
LEFT JOIN wms_storage_transaction lt
ON lt.id = (
SELECT MAX(t3.id)
FROM wms_storage_transaction t3
WHERE t3.warehouse_id = ? AND t3.created_at >= ? AND t3.created_at <= ?
AND t3.stock_id = g.stock_id AND COALESCE(t3.space_id, 0) = g.space_id AND t3.store_id = g.store_id
AND t3.created_at = g._max_ct
)
ORDER BY g.stock_id ASC, g.space_id ASC, g.store_id ASC, g._min_ct ASC, g._max_ct ASC`,
[ storageWh, startTime, endTime, storageWh, startTime, endTime, storageWh, startTime, endTime ]
))[0];
const oldSpaceEdge = buildOldEdgeMap(oldSpaceRows, r => `${r.stock_id}_${r.space_id}_${r.store_id}`);
const newSpaceEdge = new Map(newSpaceRows.map(r => [
`${r.stock_id}_${r.space_id}_${r.store_id}`,
{ first_before: r.before_quantity, last_after: r.after_quantity },
]));
const spaceEdgeOk = diffMaps('edge by_space=true', oldSpaceEdge, newSpaceEdge);
const oldSpacePreRows = (await connection.query(
`SELECT t.id, t.stock_id, COALESCE(t.space_id, 0) AS space_id, t.store_id, t.after_quantity, t.created_at
FROM wms_storage_transaction t
WHERE t.warehouse_id = ? AND t.created_at < ?
ORDER BY t.stock_id ASC, COALESCE(t.space_id, 0) ASC, t.store_id ASC, t.created_at DESC, t.id DESC`,
[ storageWh, startTime ]
))[0];
const newSpacePreRows = (await connection.query(
`SELECT
g.stock_id,
g.space_id,
g.store_id,
lt.after_quantity,
lt.created_at
FROM (
SELECT
t.stock_id,
COALESCE(t.space_id, 0) AS space_id,
t.store_id,
MAX(t.created_at) AS _max_ct
FROM wms_storage_transaction t
WHERE t.warehouse_id = ? AND t.created_at < ?
GROUP BY t.stock_id, COALESCE(t.space_id, 0), t.store_id
) g
LEFT JOIN wms_storage_transaction lt
ON lt.id = (
SELECT MAX(t3.id)
FROM wms_storage_transaction t3
WHERE t3.warehouse_id = ? AND t3.created_at < ?
AND t3.stock_id = g.stock_id AND COALESCE(t3.space_id, 0) = g.space_id AND t3.store_id = g.store_id
AND t3.created_at = g._max_ct
)
ORDER BY g.stock_id ASC, g.space_id ASC, g.store_id ASC, g._max_ct DESC`,
[ storageWh, startTime, storageWh, startTime ]
))[0];
const oldSpacePre = buildOldPreStartMap(oldSpacePreRows, r => `${r.stock_id}_${r.space_id}_${r.store_id}`);
const newSpacePre = new Map(newSpacePreRows.map(r => [ `${r.stock_id}_${r.space_id}_${r.store_id}`, r.after_quantity ]));
const spacePreOk = diffMaps('preStart by_space=true', oldSpacePre, newSpacePre);
// ============ EXPLAIN 新 intervalEdge SQL ============
const explainRows = (await connection.query(
`EXPLAIN
SELECT
g.stock_id, g.space_id, g.store_id, ft.before_quantity, lt.after_quantity, ft.created_at
FROM (
SELECT t.stock_id, 0 AS space_id, t.store_id, MIN(t.created_at) AS _min_ct, MAX(t.created_at) AS _max_ct
FROM wms_stock_transaction t
WHERE t.warehouse_id = ? AND t.created_at >= ? AND t.created_at <= ?
GROUP BY t.stock_id, t.store_id
) g
LEFT JOIN wms_stock_transaction ft
ON ft.id = (
SELECT MIN(t2.id) FROM wms_stock_transaction t2
WHERE t2.warehouse_id = ? AND t2.created_at >= ? AND t2.created_at <= ?
AND t2.stock_id = g.stock_id AND t2.store_id = g.store_id
AND t2.created_at = g._min_ct
)
LEFT JOIN wms_stock_transaction lt
ON lt.id = (
SELECT MAX(t3.id) FROM wms_stock_transaction t3
WHERE t3.warehouse_id = ? AND t3.created_at >= ? AND t3.created_at <= ?
AND t3.stock_id = g.stock_id AND t3.store_id = g.store_id
AND t3.created_at = g._max_ct
)`,
[ warehouseId, startTime, endTime, warehouseId, startTime, endTime, warehouseId, startTime, endTime ]
))[0];
console.log('--- EXPLAIN new intervalEdge ---');
explainRows.forEach(r => console.log(` ${r.id} | ${r.select_type} | ${r.table} | type=${r.type} | possible_keys=${r.possible_keys} | key=${r.key} | rows=${r.rows}`));
const allOk = edgeOk && preOk && spaceEdgeOk && spacePreOk;
console.log(allOk ? '\n=== ALL PASS ===' : '\n=== FAIL ===');
process.exit(allOk ? 0 : 1);
} finally {
await connection.end();
}
})().catch(err => {
console.error(err);
process.exit(1);
});

View File

@ -170,47 +170,4 @@ describe('test/app/model/store.test.js', () => {
/subject_config\.inventory_warning_rules\[0\]\.key 不能为空/
);
});
it('should default allocate_start_time to "08:00" and backfill legacy config', () => {
const Store = require('../../../app/model/store')(createApp());
const fromNull = Store.normalizeSubjectConfig(null);
const fromLegacy = Store.normalizeSubjectConfig({ cutoff_order_time: '16:00' });
assert.equal(fromNull.allocate_start_time, '08:00');
assert.equal(fromLegacy.allocate_start_time, '08:00');
});
it('should normalize valid allocate_start_time and allow cross-day window', () => {
const Store = require('../../../app/model/store')(createApp());
const normalized = Store.normalizeSubjectConfig({
allocate_start_time: '20:00',
cutoff_order_time: '06:00',
});
assert.equal(normalized.allocate_start_time, '20:00');
assert.equal(normalized.cutoff_order_time, '06:00');
});
it('should throw for invalid allocate_start_time format', () => {
const Store = require('../../../app/model/store')(createApp());
assert.throws(
() => Store.normalizeSubjectConfig({ allocate_start_time: '8:00' }),
/subject_config\.allocate_start_time 格式必须为 HH:mm(如 08:00)/
);
});
it('should reject allocate_start_time equal to cutoff_order_time', () => {
const Store = require('../../../app/model/store')(createApp());
assert.throws(
() => Store.normalizeSubjectConfig({
allocate_start_time: '09:00',
cutoff_order_time: '09:00',
}),
/subject_config\.allocate_start_time 不能等于 subject_config\.cutoff_order_time/
);
});
});

View File

@ -17,9 +17,6 @@ function createHarness(storeId = 100321) {
},
},
},
model: {
Picking: undefined,
},
logger: {
warn() {},
},
@ -42,26 +39,6 @@ function createHarness(storeId = 100321) {
};
},
},
stockWarehouse: {
async getStockDetails() {
return [
{
id: 7,
item_code: 'ITEM-7',
item_name: '测试商品',
sku_property: '',
quantity: 10,
locked_quantity: 0,
is_batch_mgmt: 'N',
is_shelf_life_mgmt: 'N',
is_images: 'N',
store_id: storeId,
packing_requirements: '',
stock_unit: '',
},
];
},
},
},
},
};
@ -81,7 +58,7 @@ function createHarness(storeId = 100321) {
service.getOrderItemsModelByTableType = async () => ({
async findAll(args) {
calls.findOrderItemsArgs = args;
return [{ id: 1, order_id: 99, stock_id: 7 }];
return [{ id: 1, order_id: 99 }];
},
});

View File

@ -79,7 +79,7 @@ function createHarness() {
describe('test/app/service/systems/delivery_order.asyncProcessOrderCreated.test.js', () => {
it('should execute async flow in order: express -> storage -> autoGrouping', async () => {
const { service, calls, ctx } = createHarness();
const { service, calls } = createHarness();
service.buildAsyncProcessContext = async () => ({
orderId: 101,
@ -97,17 +97,12 @@ describe('test/app/service/systems/delivery_order.asyncProcessOrderCreated.test.
service.getStoreWarehousePolicyConfig = async () => ({
auto_allocate_express: 1,
auto_allocate_storage: 1,
need_order_approval: 0,
});
service.enqueueAutoWaybillAllocation = async () => {
calls.sequence.push('allocateExpress');
};
service.buildExpressAllocateRequest = () => ({ orders: [{ order_id: 101 }] });
service.buildStorageAllocateRequest = () => ({ order_ids: [ 101 ], warehouse_id: 100000 });
service.buildStorageAllocateRequest = () => ({ order_ids: [ 101 ], allow_storage_location: true });
service.runAutoGrouping = async () => {
calls.sequence.push('autoGrouping');
};
ctx.service.systemMethods.order.wave.submitWaveStrategyQuickScanForWarehouse = async () => null;
await service.asyncProcessOrderCreated(101, {
warehouseId: 100000,
@ -134,10 +129,9 @@ describe('test/app/service/systems/delivery_order.asyncProcessOrderCreated.test.
service.getStoreWarehousePolicyConfig = async () => ({
auto_allocate_express: 1,
auto_allocate_storage: 1,
need_order_approval: 0,
});
service.enqueueAutoWaybillAllocation = async () => {
ctx.service.systemMethods.order.pendingOrder.allocateExpressCode = async () => {
calls.sequence.push('allocateExpress');
throw new Error('分配快递异常');
};
@ -148,7 +142,6 @@ describe('test/app/service/systems/delivery_order.asyncProcessOrderCreated.test.
service.runAutoGrouping = async () => {
calls.sequence.push('autoGrouping');
};
ctx.service.systemMethods.order.wave.submitWaveStrategyQuickScanForWarehouse = async () => null;
await service.asyncProcessOrderCreated(102, {
warehouseId: 100000,
@ -159,131 +152,6 @@ describe('test/app/service/systems/delivery_order.asyncProcessOrderCreated.test.
assert.equal(calls.warns.length >= 1, true);
});
it('should skip auto express allocation when order remark matches exclude keywords', async () => {
const { service, calls, ctx } = createHarness();
const skipLogs = [];
service.buildAsyncProcessContext = async () => ({
orderId: 301,
warehouseId: 100000,
storeId: 200000,
order: {
id: 301,
store_id: 200000,
warehouse_id: 100000,
remark: '买家要求:请勿自动分配快递,联系客服',
},
orderItemRows: [],
});
service.getStoreWarehousePolicyConfig = async () => ({
auto_allocate_express: 1,
auto_allocate_storage: 1,
need_order_approval: 0,
});
service.getStoreSubjectConfig = async () => ({
auto_allocate_express_exclude_remarks: [ '请勿自动分配快递' ],
});
service.enqueueAutoWaybillAllocation = async () => {
calls.sequence.push('allocateExpress');
};
service.runAutoGrouping = async () => {
calls.sequence.push('autoGrouping');
};
ctx.service.systemMethods.order.wave.submitWaveStrategyQuickScanForWarehouse = async () => null;
ctx.service.systems.operationLog = {
createOperationLogs: async payloads => {
skipLogs.push(...payloads);
},
};
await service.asyncProcessOrderCreated(301, {
warehouseId: 100000,
storeId: 200000,
}, 'API');
assert.deepEqual(calls.sequence, [ 'allocateStorage', 'autoGrouping' ]);
assert.equal(skipLogs.length, 1);
assert.equal(skipLogs[0].businessType, 'order');
assert.equal(skipLogs[0].businessId, '301');
assert.equal(skipLogs[0].operationCode, 'ORDER_AUTO_EXPRESS_SKIP');
assert.equal(skipLogs[0].operator.name, 'system');
assert.match(skipLogs[0].extras.message, /请勿自动分配快递/);
});
it('should keep auto express allocation when order remark does not match exclude keywords', async () => {
const { service, calls, ctx } = createHarness();
const skipLogs = [];
service.buildAsyncProcessContext = async () => ({
orderId: 302,
warehouseId: 100000,
storeId: 200000,
order: {
id: 302,
store_id: 200000,
warehouse_id: 100000,
remark: '正常订单,尽快发货',
},
orderItemRows: [],
});
service.getStoreWarehousePolicyConfig = async () => ({
auto_allocate_express: 1,
auto_allocate_storage: 1,
need_order_approval: 0,
});
service.getStoreSubjectConfig = async () => ({
auto_allocate_express_exclude_remarks: [ '请勿自动分配快递' ],
});
service.enqueueAutoWaybillAllocation = async () => {
calls.sequence.push('allocateExpress');
};
service.runAutoGrouping = async () => {
calls.sequence.push('autoGrouping');
};
ctx.service.systemMethods.order.wave.submitWaveStrategyQuickScanForWarehouse = async () => null;
ctx.service.systems.operationLog = {
createOperationLogs: async payloads => {
skipLogs.push(...payloads);
},
};
await service.asyncProcessOrderCreated(302, {
warehouseId: 100000,
storeId: 200000,
}, 'API');
assert.deepEqual(calls.sequence, [ 'allocateExpress', 'allocateStorage', 'autoGrouping' ]);
assert.equal(skipLogs.length, 0);
});
it('should treat buyer_message and seller_message as remark source for exclusion', async () => {
const { service } = createHarness();
const config = {
auto_allocate_express_exclude_remarks: [ '勿发圆通', '', '中通' ],
};
assert.equal(service.findAutoExpressExcludedRemark({ remark: '正常备注' }, config), '');
assert.equal(service.findAutoExpressExcludedRemark({ remark: '勿发圆通' }, config), '勿发圆通');
assert.equal(service.findAutoExpressExcludedRemark({ buyer_message: '请用中通' }, config), '中通');
assert.equal(service.findAutoExpressExcludedRemark({ seller_message: '备注圆通' }, config), '');
assert.equal(service.findAutoExpressExcludedRemark({}, null), '');
assert.equal(service.findAutoExpressExcludedRemark({}, { auto_allocate_express_exclude_remarks: [] }), '');
});
it('should not pass allow_storage_location for auto storage allocation', () => {
const { service } = createHarness();
const request = service.buildStorageAllocateRequest({
orderId: 99,
warehouseId: 100000,
});
assert.deepEqual(request, {
order_ids: [ 99 ],
warehouse_id: 100000,
});
});
it('should skip auto grouping when switch is disabled', async () => {
const { service } = createHarness();
let triggered = false;

View File

@ -32,10 +32,6 @@ function matchesWhere(row, where) {
return Array.isArray(condition[Sequelize.Op.in]) && condition[Sequelize.Op.in].includes(row[fieldName]);
}
if (Object.prototype.hasOwnProperty.call(condition, Sequelize.Op.notIn)) {
return Array.isArray(condition[Sequelize.Op.notIn]) && !condition[Sequelize.Op.notIn].includes(row[fieldName]);
}
if (Object.prototype.hasOwnProperty.call(condition, Sequelize.Op.ne)) {
return row[fieldName] !== condition[Sequelize.Op.ne];
}
@ -538,8 +534,7 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
assert.equal(captures.pickingRows[0].space_id, 501);
assert.equal(captures.pickingRows[0].space_name, '存储位A');
assert.equal(captures.pickingRows[0].status, 'pending');
// 当前实现仅在 wms_storage 维度维护锁定量,wms_stock_warehouse.locked_quantity 由建单链路维护
assert.equal(stockRows[0].locked_quantity, 0);
assert.equal(stockRows[0].locked_quantity, 2);
assert.equal(storageRows[0].locked_quantity, 2);
assert.equal(storageRows[0].available_quantity, 0);
assert.deepEqual(captures.reversePendingExceptionRequest, { ids: [ 2 ] });
@ -622,38 +617,14 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
available_quantity: 1,
quantity: 1,
locked_quantity: 0,
production_date: '2026-04-01 08:00:00',
production_date: null,
inbound_time: '2026-04-15 08:00:00',
space_id: 90502,
space: {
id: 90502,
space_code: 'ST-902',
custom_name: '受限存储位902',
custom_name: '存储位902',
is_preferred_pick: false,
locationType: {
id: 9,
allow_allocation: 0,
is_active: 0,
},
},
},
{
id: 90202,
warehouse_id: 100000,
stock_id: 9021,
is_enabled: 1,
delete_at: null,
available_quantity: 1,
quantity: 1,
locked_quantity: 0,
production_date: '2026-04-02 08:00:00',
inbound_time: '2026-04-15 09:00:00',
space_id: 90503,
space: {
id: 90503,
space_code: 'PK-902',
custom_name: '分拣位902',
is_preferred_pick: true,
locationType: {
id: 1,
allow_allocation: 1,
@ -670,100 +641,16 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
});
assert.equal(result.code, 200);
assert.equal(result.data.allocated_order_ids.length, 1);
assert.equal(captures.pickingRows.length, 1);
assert.equal(captures.pickingRows[0].storage_id, 90202);
assert.equal(captures.pickingRows[0].space_id, 90503);
const locationTypeInclude = captures.storageFindAllInclude
&& captures.storageFindAllInclude[0]
&& captures.storageFindAllInclude[0].include
&& captures.storageFindAllInclude[0].include[0];
assert.ok(locationTypeInclude, 'locationType include 应存在');
assert.equal(Object.prototype.hasOwnProperty.call(locationTypeInclude, 'where'), false);
});
it('should allow restricted storage locations when storage separation is disabled even if request flag is false', async () => {
const { service, captures } = createHarness({
orders: [
{ id: 903, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 },
],
orderItems: [
{ id: 9031, order_id: 903, stock_id: 9031, plan_qty: 1, order_line_no: '1' },
],
stockRows: [
{ id: 9031, item_code: 'SKU-9031', item_name: '测试商品9031', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 },
],
storageRows: [
{
id: 90301,
warehouse_id: 100000,
stock_id: 9031,
is_enabled: 1,
delete_at: null,
available_quantity: 1,
quantity: 1,
locked_quantity: 0,
production_date: '2026-04-01 08:00:00',
inbound_time: '2026-04-15 08:00:00',
space_id: 90504,
space: {
id: 90504,
space_code: 'ST-903',
custom_name: '受限存储位903',
is_preferred_pick: false,
locationType: {
id: 9,
allow_allocation: 0,
is_active: 0,
},
},
},
{
id: 90302,
warehouse_id: 100000,
stock_id: 9031,
is_enabled: 1,
delete_at: null,
available_quantity: 1,
quantity: 1,
locked_quantity: 0,
production_date: '2026-04-02 08:00:00',
inbound_time: '2026-04-15 09:00:00',
space_id: 90505,
space: {
id: 90505,
space_code: 'PK-903',
custom_name: '分拣位903',
is_preferred_pick: true,
locationType: {
id: 1,
allow_allocation: 1,
is_active: 1,
},
},
},
],
policies: {
9031: {
policyConfig: {
storage_separation: 0,
},
allowOversell: false,
},
},
assert.deepEqual(locationTypeInclude.where, {
allow_allocation: 1,
is_active: 1,
});
const result = await service.allocateStorage({
allow_storage_location: false,
order_ids: [ 903 ],
});
assert.equal(result.code, 200);
assert.equal(result.data.allocated_order_ids.length, 1);
assert.equal(captures.pickingRows.length, 1);
assert.equal(captures.pickingRows[0].storage_id, 90301);
assert.equal(captures.pickingRows[0].space_id, 90504);
});
it('should skip cancelled orders when allocating storage', async () => {
@ -846,8 +733,7 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
assert.deepEqual(result.data.create_channel_groups[0].order_ids, [ 1 ]);
assert.deepEqual(result.data.create_channel_groups[1].order_ids, [ 2 ]);
assert.deepEqual(result.data.create_channel_groups[2].order_ids, [ 3 ]);
// 实现查询已排除 sync_status='fin' 与已取消订单,被排除订单按 not_found 跳过
assert.deepEqual(result.data.skipped_orders.map(item => item.skipped_reason), [ 'not_found', 'not_found' ]);
assert.deepEqual(result.data.skipped_orders.map(item => item.skipped_reason), [ 'already_synced', 'not_found' ]);
assert.equal(result.data.failed_count, 0);
assert.deepEqual(result.data.failed_orders, []);
assert.equal(captures.qm.groupedOrder.create_channel, 'QM');
@ -871,7 +757,7 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
});
assert.equal(result.code, 200);
assert.equal(result.message, '同步失败:存在不允许批量回传的订单');
assert.equal(result.message, '同步失败:存在快递状态未分配订单');
assert.deepEqual(result.data.pending_order_ids, []);
assert.equal(result.data.dispatch_count, 0);
assert.equal(result.data.failed_count, 1);
@ -895,21 +781,21 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
assert.equal(orders[0].order_flag, '快递状态未分配,禁止同步');
});
it('should prefer explicit warehouse id from request', async () => {
it('should always use the current user warehouse context and ignore request warehouse ids', async () => {
const { service, captures } = createHarness({
orders: [
{ id: 9, warehouse_id: 200000, storage_status: 'none', order_flag: '', step: 2 },
{ id: 9, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 },
],
orderItems: [
{ id: 91, order_id: 9, stock_id: 901, plan_qty: 1, order_line_no: '1' },
],
stockRows: [
{ id: 901, item_code: 'SKU-901', item_name: '测试商品901', warehouse_id: 200000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 },
{ id: 901, item_code: 'SKU-901', item_name: '测试商品901', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 },
],
storageRows: [
{
id: 9001,
warehouse_id: 200000,
warehouse_id: 100000,
stock_id: 901,
is_enabled: 1,
delete_at: null,
@ -941,9 +827,9 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
});
assert.equal(result.code, 200);
assert.equal(captures.order.findAllWhere.warehouse_id, 200000);
assert.equal(captures.stockFindAllWhere.warehouse_id, 200000);
assert.equal(captures.storageFindAllWhere.warehouse_id, 200000);
assert.equal(captures.order.findAllWhere.warehouse_id, 100000);
assert.equal(captures.stockFindAllWhere.warehouse_id, 100000);
assert.equal(captures.storageFindAllWhere.warehouse_id, 100000);
});
it('should allow storage locations when storage separation is disabled even if the request flag is false', async () => {
@ -1033,7 +919,7 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
});
it('should allocate partially and mark shortage orders with exception text', async () => {
const { service, captures, orders, stockRows, storageRows } = createHarness({
const { service, captures, orders, stockRows } = createHarness({
orders: [
{ id: 4, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 },
],
@ -1085,20 +971,19 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
});
assert.equal(result.code, 200);
assert.deepEqual(result.data.shortage_order_ids, [ 4 ]);
assert.equal(result.data.shortage_order_ids.length, 1);
assert.equal(result.data.orders.find(item => item.order_id === 4).storage_status, 'error');
assert.equal(result.data.orders.find(item => item.order_id === 4).status, 'error');
assert.match(result.data.shortage_messages[0], /库存不足:sku\(301\),数量:3,库位数量:2/);
// 单订单原子性分配:缺货时回滚已锁定库存、不写 picking
assert.equal(result.data.picking_count, 0);
assert.equal(captures.pickingRows, null);
assert.equal(captures.storageLocks.length, 1);
assert.equal(captures.storageUnlocks.length, 1);
assert.equal(stockRows[0].locked_quantity, 0);
assert.equal(storageRows[0].locked_quantity, 0);
assert.equal(storageRows[0].available_quantity, 2);
assert.equal(captures.pickingRows.length, 1);
assert.equal(captures.pickingRows[0].order_id, 4);
assert.equal(captures.pickingRows[0].order_item_id, 41);
assert.equal(captures.pickingRows[0].storage_id, 3001);
assert.equal(captures.pickingRows[0].quantity, 2);
assert.equal(captures.pickingRows[0].space_name, '分拣位C');
assert.equal(stockRows[0].locked_quantity, 2);
assert.equal(orders[0].storage_status, 'error');
assert.equal(orders[0].order_flag, '库存不足:sku(301),数量:3,库位数量:2,原因:库存不足');
assert.equal(orders[0].order_flag, '库存不足:sku(301),数量:3,库位数量:2');
assert.equal(captures.committed, true);
});
@ -1135,7 +1020,6 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
id: 501,
order_id: 21,
order_item_id: 2101,
warehouse_id: 100000,
storage_id: 7001,
quantity: 2,
space_id: 9001,
@ -1194,8 +1078,7 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
});
assert.equal(storageRows[0].available_quantity, 2);
assert.equal(storageRows[0].locked_quantity, 0);
// 当前实现不在取消分配链路更新 wms_stock_warehouse 维度锁定量
assert.equal(stockRows[0].locked_quantity, 2);
assert.equal(stockRows[0].locked_quantity, 0);
assert.deepEqual(pickingRows, []);
assert.deepEqual(captures.pickingDestroyIds, [ 501 ]);
assert.equal(orders[0].storage_status, 'none');
@ -1418,23 +1301,24 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
const { service, captures, orders, storageRows, pickingRows } = harness;
// === 第 1 次分配:缺货 → 原子回滚,不写 picking ===
// === 第 1 次分配:部分成功 → error ===
const result1 = await service.allocateStorage({ allow_storage_location: true, order_ids: [ 200 ] });
assert.equal(result1.code, 200);
assert.equal(orders[0].storage_status, 'error');
assert.equal(captures.storageLocks.length, 1);
assert.deepEqual(captures.storageLocks[0], { storageId: 6001, quantity: 2 });
// 单订单原子性:缺货时回滚已锁定库存、不写 picking
assert.equal(captures.pickingRows, null);
assert.equal(pickingRows.length, 0);
assert.equal(captures.storageUnlocks.length, 1);
assert.deepEqual(captures.storageUnlocks[0], { storageId: 6001, quantity: 2 });
assert.equal(storageRows[0].available_quantity, 2);
assert.equal(storageRows[0].locked_quantity, 0);
assert.equal(captures.pickingRows.length, 1);
assert.equal(pickingRows.length, 1);
assert.equal(pickingRows[0].order_id, 200);
assert.equal(pickingRows[0].storage_id, 6001);
assert.equal(pickingRows[0].quantity, 2);
assert.equal(pickingRows[0].status, 'pending');
assert.equal(storageRows[0].available_quantity, 0);
assert.equal(storageRows[0].locked_quantity, 2);
const unlockCountAfterCall1 = captures.storageUnlocks.length;
// 补货 — 追加新库存(仍不够:2+1=3 < 5)
// 补货 — 追加新库存(仍不够:1 < 3)
storageRows.push({
id: 6002,
warehouse_id: 100000,
@ -1450,19 +1334,20 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
space: { id: 11, space_code: 'LOC-11', custom_name: '库位11', is_preferred_pick: false, locationType: { id: 1, allow_allocation: 1, is_active: 1 } },
});
// === 第 2 次分配:仍缺货 → 同样原子回滚 ===
// === 第 2 次分配:仍然缺货 → error ===
const result2 = await service.allocateStorage({ allow_storage_location: true, order_ids: [ 200 ] });
assert.equal(result2.code, 200);
assert.equal(orders[0].storage_status, 'error');
// 第 2 次锁定 6001(2)+6002(1) 后全部回滚(从未写 picking,无旧数据可清理)
// 验证第 2 次调用清理了第 1 次的旧数据
const newUnlocks = captures.storageUnlocks.slice(unlockCountAfterCall1);
assert.equal(newUnlocks.length, 2, '第2次调用应回滚2条锁定');
assert.equal(newUnlocks.length, 1, '第2次调用应释放第1次的1条锁定');
assert.deepEqual(newUnlocks[0], { storageId: 6001, quantity: 2 });
assert.deepEqual(newUnlocks[1], { storageId: 6002, quantity: 1 });
assert.equal(captures.pickingRows, null);
assert.equal(pickingRows.length, 0);
assert.equal(storageRows.find(r => r.id === 6002).locked_quantity, 0, '6002 回滚后锁定应清零');
// picking 表只有新记录(旧的已被 destroy),无重复
assert.equal(pickingRows.length, 1, 'picking表应只有1条记录(旧的已删除)');
assert.equal(pickingRows[0].storage_id, 6002);
assert.equal(pickingRows[0].quantity, 1);
const unlockCountAfterCall2 = captures.storageUnlocks.length;
@ -1487,33 +1372,35 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
assert.equal(result3.code, 200);
assert.equal(orders[0].storage_status, 'fin');
// 前两次均原子回滚且未写 picking,第 3 次无旧数据可清理,不新增解锁
assert.equal(captures.storageUnlocks.length, unlockCountAfterCall2, '第3次调用不应新增解锁');
// 验证第 3 次调用清理了第 2 次的旧数据
const finalUnlocks = captures.storageUnlocks.slice(unlockCountAfterCall2);
assert.equal(finalUnlocks.length, 1, '第3次调用应释放第2次的1条锁定');
assert.deepEqual(finalUnlocks[0], { storageId: 6002, quantity: 1 });
// 候选库存 FIFO:6001(2) + 6002(1) + 6003(2) = 5 → 3 条 picking
assert.equal(captures.pickingRows.length, 3, 'picking应有3条(6001/6002/6003)');
const picking6001 = captures.pickingRows.find(r => r.storage_id === 6001);
const picking6002 = captures.pickingRows.find(r => r.storage_id === 6002);
const picking6003 = captures.pickingRows.find(r => r.storage_id === 6003);
// 注意:第3次分配的 Storage.findAll 查询时,6001 已被第2次清理释放(available=2),
// 6003 是新增的(available=10),6002 在查询时 available=0 被过滤。
// 所以分配结果:6001(qty=2) + 6003(qty=3) = 5 → 2 条 picking
assert.equal(pickingRows.length, 2, 'picking应有2条(6001和6003各一条)');
// 验证每条 picking 的分配数量
const picking6001 = pickingRows.find(r => r.storage_id === 6001);
const picking6003 = pickingRows.find(r => r.storage_id === 6003);
assert.ok(picking6001, '应存在 storage_id=6001 的 picking');
assert.equal(picking6001.quantity, 2);
assert.ok(picking6002, '应存在 storage_id=6002 的 picking');
assert.equal(picking6002.quantity, 1);
assert.ok(picking6003, '应存在 storage_id=6003 的 picking');
assert.equal(picking6003.quantity, 2);
assert.equal(picking6003.quantity, 3);
// 总分配数量 = 5
const totalAllocated = captures.pickingRows.reduce((sum, r) => sum + Number(r.quantity), 0);
const totalAllocated = pickingRows.reduce((sum, r) => sum + Number(r.quantity), 0);
assert.equal(totalAllocated, 5, '总分配数量应为5');
// 所有 picking 的 (order_item_id, space_name) 无重复
const itemSpacePairs = captures.pickingRows.map(r => `${r.order_item_id}_${r.space_name}`);
assert.equal(new Set(itemSpacePairs).size, captures.pickingRows.length, '不应存在重复的 (order_item_id, space_name)');
const itemSpacePairs = pickingRows.map(r => `${r.order_item_id}_${r.space_name}`);
assert.equal(new Set(itemSpacePairs).size, pickingRows.length, '不应存在重复的 (order_item_id, space_name)');
// 锁定无泄漏
assert.equal(storageRows.find(r => r.id === 6001).locked_quantity, 2, '6001 应锁定 2');
assert.equal(storageRows.find(r => r.id === 6002).locked_quantity, 1, '6002 应锁定 1');
assert.equal(storageRows.find(r => r.id === 6003).locked_quantity, 2, '6003 应锁定 2');
// 库存锁定没有泄漏:6002 在清理后被释放锁定,且本轮未被重新分配(因为 findAll 查询时其 available=0)
// 6001 被重新锁定 2,6003 被锁定 3
assert.equal(storageRows.find(r => r.id === 6002).locked_quantity, 0, '6002锁定应已清零');
});
// ============================================================
@ -1715,7 +1602,7 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
assert.deepEqual(unlocksAfterCleanup[0], { storageId: 8001, quantity: 1 });
});
it('should mark QM dispatch failed without writing operation log in service layer', async () => {
it('should write error message in operation log when QM sync fails', async () => {
const { service, captures } = createHarness({
orders: [
{ id: 51, warehouse_id: 100000, express_code: 'WB-051', post_status: 'padding', sync_status: 'padding', create_channel: 'QM' },
@ -1752,11 +1639,23 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
assert.equal(result.data.dispatch_failed_count, 1);
assert.equal(result.data.dispatch_results[0].status, 'failed');
// 操作日志已移至 pendingOrder.syncOrderIds 层统一写入,本层不再写日志
assert.equal(captures.operationLogs, null, 'service 层不应写操作日志');
// 验证操作日志包含了失败信息
assert.ok(Array.isArray(captures.operationLogs), '应有操作日志');
assert.equal(captures.operationLogs.length, 1, '应有 1 条日志');
assert.ok(
captures.operationLogs[0].extras.message.includes('失败'),
`日志消息应包含"失败",实际: ${captures.operationLogs[0].extras.message}`
);
assert.ok(
captures.operationLogs[0].extras.message.includes('parse error'),
`日志消息应包含具体错误原因,实际: ${captures.operationLogs[0].extras.message}`
);
assert.equal(captures.operationLogs[0].extras.warehouseId, 100000);
assert.equal(captures.operationLogs[0].businessType, 'order');
assert.equal(captures.operationLogs[0].operationCode, 'ORDER_SYNC');
});
it('should complete QM sync without writing operation log in service layer', async () => {
it('should write success message in operation log when QM sync succeeds', async () => {
const { service, captures } = createHarness({
orders: [
{ id: 52, warehouse_id: 100000, express_code: 'WB-052', post_status: 'padding', sync_status: 'padding', create_channel: 'QM' },
@ -1769,11 +1668,14 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
assert.equal(result.code, 200);
// 操作日志已移至 pendingOrder.syncOrderIds 层统一写入,本层不再写日志
assert.equal(captures.operationLogs, null, 'service 层不应写操作日志');
// 验证操作日志包含了成功信息
assert.ok(Array.isArray(captures.operationLogs), '应有操作日志');
const qmLog = captures.operationLogs.find(log => log.businessId === '52');
assert.ok(qmLog, '应有订单 52 的日志');
assert.equal(qmLog.extras.message, '同步到QM渠道');
});
it('should skip already synced orders without writing operation log in service layer', async () => {
it('should write skip message for already synced orders', async () => {
const { service, captures } = createHarness({
orders: [
{ id: 53, warehouse_id: 100000, express_code: 'WB-053', post_status: 'padding', sync_status: 'fin', create_channel: 'QM' },
@ -1787,8 +1689,11 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
assert.equal(result.code, 200);
assert.equal(result.data.skipped_count, 1);
// 操作日志已移至 pendingOrder.syncOrderIds 层统一写入,本层不再写日志
assert.equal(captures.operationLogs, null, 'service 层不应写操作日志');
// 验证操作日志
assert.ok(Array.isArray(captures.operationLogs), '应有操作日志');
const skipLog = captures.operationLogs.find(log => log.businessId === '53');
assert.ok(skipLog, '应有订单 53 的日志');
assert.ok(skipLog.extras.message.includes('跳过'), `跳过订单应含"跳过",实际: ${skipLog.extras.message}`);
});
// ============================================================
@ -2019,7 +1924,7 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
// ============================================================
// 场景 A:正常分配锁定 → StockWarehouse.locked_quantity 同步增加
it('场景A:正常分配锁定后 storage 锁定与锁定流水应正确写入', async () => {
it('场景A:正常分配锁定后 StockWarehouse.increment 应被正确调用', async () => {
const { service, captures, stockRows } = createHarness({
orders: [
{ id: 701, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 },
@ -2066,27 +1971,25 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
assert.equal(result.code, 200);
assert.equal(result.data.orders[0].storage_status, 'fin');
// 核心断言:wms_storage 维度锁定调用 1 次,锁定数量 3
assert.equal(captures.storageLocks.length, 1, 'lockQuantity 应被调用1次');
assert.equal(captures.storageLocks[0].storageId, 11001);
assert.equal(captures.storageLocks[0].quantity, 3, '锁定数量应为 allocationQuantity=3');
// 锁定流水写入 1 条 PICKING_LOCK,且在事务内
const lockTransactions = captures.storageTransactionCreates.filter(
item => item.data.transaction_type === 'LOCK' && item.data.order_type === 'PICKING_LOCK'
// 核心断言:StockWarehouse.increment 被调用了 1 次
assert.equal(
captures.stockWarehouseIncrements.length,
1,
`StockWarehouse.increment 应被调用1次,实际: ${captures.stockWarehouseIncrements.length}`
);
assert.equal(lockTransactions.length, 1, '应写入1条 PICKING_LOCK 流水');
assert.equal(lockTransactions[0].data.storage_id, 11001);
assert.equal(lockTransactions[0].data.quantity, 3);
assert.equal(lockTransactions[0].hasTransaction, true);
// 当前实现不更新 wms_stock_warehouse 维度锁定量(由建单链路维护)
assert.equal(captures.stockWarehouseIncrements.length, 0, '分配链路不应调用 StockWarehouse.increment');
assert.equal(stockRows[0].locked_quantity, 0, 'stockRows 的 locked_quantity 保持不变');
// 验证 increment 参数
const incrementCall = captures.stockWarehouseIncrements[0];
assert.equal(incrementCall.field, 'locked_quantity', 'increment 的字段应为 locked_quantity');
assert.equal(incrementCall.by, 3, 'increment 的数量应为 allocationQuantity=3');
assert.deepEqual(incrementCall.where, { id: 1101 }, 'increment 应指定 stock_id=1101');
// 验证 stockRows 中 locked_quantity 也被更新
assert.equal(stockRows[0].locked_quantity, 3, 'stockRows 的 locked_quantity 应增加 3');
});
// 场景 B:库位无效回滚 → StockWarehouse.locked_quantity 同步减少
it('场景B:库位无效回滚时 storage 锁应被释放', async () => {
it('场景B:库位无效回滚时 StockWarehouse.decrement 应被正确调用', async () => {
const { service, captures } = createHarness({
orders: [
{ id: 702, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 },
@ -2149,7 +2052,18 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
assert.equal(result.code, 200);
assert.equal(result.data.orders[0].storage_status, 'fin');
// 验证 unlockQuantity 被调用(无效库存的 storage 锁被释放)
// 核心断言:StockWarehouse.decrement 被调用了 1 次(针对无效库位A)
const decrementsForBadSpace = captures.stockWarehouseDecrements.filter(
call => call.where && call.where.id === 1102 && call.by === 4
);
assert.equal(
decrementsForBadSpace.length,
1,
`应有一次 StockWarehouse.decrement 针对 stock_id=1102 by=4(无效库位回退),实际: ${decrementsForBadSpace.length}`
);
assert.equal(decrementsForBadSpace[0].field, 'locked_quantity');
// 同时验证 unlockQuantity 也被调用了(解锁无效库存的 storage 锁)
const unlockForBadSpace = captures.storageUnlocks.find(
item => item.storageId === 11002
);
@ -2162,14 +2076,10 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
);
assert.ok(lockForGoodSpace, '有效库位B应被锁定');
assert.equal(lockForGoodSpace.quantity, 10);
// 当前实现不更新 wms_stock_warehouse 维度锁定量
assert.equal(captures.stockWarehouseIncrements.length, 0, '分配链路不应调用 StockWarehouse.increment');
assert.equal(captures.stockWarehouseDecrements.length, 0, '分配链路不应调用 StockWarehouse.decrement');
});
// 场景 C:取消分配 → StockWarehouse.locked_quantity 同步减少
it('场景C:取消分配时仅解除 wms_storage 锁', async () => {
it('场景C:取消分配时 StockWarehouse.decrement 应被正确调用', async () => {
const { service, captures, stockRows } = createHarness({
orders: [
{ id: 703, warehouse_id: 100000, storage_status: 'fin', order_flag: '', step: 2 },
@ -2217,13 +2127,21 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
assert.equal(result.code, 200);
assert.equal(result.data.cancellable_order_ids.length, 1);
// 当前实现不更新 wms_stock_warehouse 维度锁定量(由建单链路维护)
// 核心断言:StockWarehouse.decrement 被调用
// cancelAllocateStorage 中 unlockQuantity 成功后应有 decrement 调用
assert.equal(
captures.stockWarehouseDecrements.length,
0,
'取消分配不应调用 StockWarehouse.decrement'
1,
`StockWarehouse.decrement 应被调用1次,实际: ${captures.stockWarehouseDecrements.length}`
);
assert.equal(stockRows[0].locked_quantity, 5, '取消后 stockRows locked_quantity 保持不变');
const decrementCall = captures.stockWarehouseDecrements[0];
assert.equal(decrementCall.field, 'locked_quantity', 'decrement 的字段应为 locked_quantity');
assert.equal(decrementCall.by, 5, 'decrement 的数量应为 5');
assert.deepEqual(decrementCall.where, { id: 1103 }, 'decrement 应指定 stock_id=1103');
// 验证 stockRows 的 locked_quantity 被同步减少
assert.equal(stockRows[0].locked_quantity, 0, '取消后 stockRows locked_quantity 应为 0');
// 验证 unlockQuantity 也被调用
assert.equal(captures.storageUnlocks.length, 1);
@ -2231,7 +2149,7 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
});
// 场景 D:StockWarehouse.increment 失败时事务回滚
it('场景D:正常分配时锁定成功并提交事务', async () => {
it('场景D:StockWarehouse.increment 失败时 lockQuantity 的锁应被回滚', async () => {
const { service, captures } = createHarness({
orders: [
{ id: 704, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 },
@ -2279,10 +2197,14 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
// 验证 lockQuantity 被调用
assert.equal(captures.storageLocks.length, 1);
assert.equal(captures.storageLocks[0].quantity, 3);
// 当前实现不调用 StockWarehouse.increment
assert.equal(captures.stockWarehouseIncrements.length, 0, '分配链路不应调用 StockWarehouse.increment');
// 验证 StockWarehouse.increment 被调用
assert.equal(
captures.stockWarehouseIncrements.length,
1,
'正常流程中 StockWarehouse.increment 应被调用1次'
);
assert.equal(captures.stockWarehouseIncrements[0].by, 3);
// 验证事务提交
assert.equal(captures.committed, true);
@ -2290,7 +2212,7 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
});
// 场景 E:同一事务内操作原子性 — lockQuantity + StockWarehouse.increment
it('场景E:lockQuantity 与锁定流水应在同一事务内完成', async () => {
it('场景E:lockQuantity 和 StockWarehouse.increment 应在同一事务内调用', async () => {
const { service, captures } = createHarness({
orders: [
{ id: 705, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 },
@ -2337,29 +2259,39 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
assert.equal(result.code, 200);
assert.equal(result.data.orders[0].storage_status, 'fin');
// 核心断言:lockQuantity 与锁定流水均在同一事务内完成
// 核心断言:lockQuantity 和 StockWarehouse.increment 都被调用
assert.equal(
captures.storageLocks.length,
1,
'lockQuantity 应被调用1次'
);
const lockTransactions = captures.storageTransactionCreates.filter(
call => call.data.transaction_type === 'LOCK' && call.data.order_type === 'PICKING_LOCK'
);
assert.equal(lockTransactions.length, 1, '应写入 1 条 PICKING_LOCK 流水');
assert.equal(
lockTransactions[0].data.quantity,
captures.storageLocks[0].quantity,
`流水 quantity(${lockTransactions[0].data.quantity}) 应与锁定 quantity(${captures.storageLocks[0].quantity}) 一致`
captures.stockWarehouseIncrements.length,
1,
'StockWarehouse.increment 应被调用1次'
);
// 验证两者的数量一致
assert.equal(
captures.storageLocks[0].quantity,
captures.stockWarehouseIncrements[0].by,
`lockQuantity 的 quantity(${captures.storageLocks[0].quantity}) 应与 increment by(${captures.stockWarehouseIncrements[0].by}) 一致`
);
assert.equal(lockTransactions[0].hasTransaction, true, '流水应在事务内写入');
// 验证事务提交 — 两者在同一个事务中完成
assert.equal(captures.committed, true, '事务应成功提交');
assert.equal(captures.rolledBack, undefined, '事务不应回滚');
// 当前实现不更新 wms_stock_warehouse 维度锁定量
assert.equal(captures.stockWarehouseIncrements.length, 0, '分配链路不应调用 StockWarehouse.increment');
// 验证 storageTransaction 流水已写入(lockQuantity 后应有 LOCK 流水)
const lockTransactions = captures.storageTransactionCreates.filter(
call => call.data.transaction_type === 'LOCK'
);
assert.equal(lockTransactions.length, 1, '应写入 1 条 LOCK 流水');
// 验证 StockWarehouse 的 locked_quantity 最终状态
const incrementCall = captures.stockWarehouseIncrements[0];
assert.equal(incrementCall.field, 'locked_quantity');
assert.equal(incrementCall.by, 2);
assert.deepEqual(incrementCall.where, { id: 1105 });
});
});

View File

@ -140,109 +140,4 @@ describe('test/app/service/systems/storage.receiving.getDetail.test.js', () => {
assert.equal(details[1].custom_space_name, null);
assert.equal(Number(details[1].space_id_raw), 3002);
});
it('should resolve store_name from contract store_remask with company_name fallback', async () => {
const receivingRow = {
id: 123,
warehouse_id: 100000,
store_id: 77,
store_name: '',
receiving_number: 'RCV202605060001',
dataValues: {},
};
const detailRows = [];
const model = {
Receiving: {
async findOne() {
return receivingRow;
},
},
ReceivingDetail: {
async findAll() {
return detailRows;
},
async count() {
return 0;
},
},
FileReference: {
async findAll() {
return [];
},
},
File: {},
StoreWarehouse: {
async findAll() {
return [];
},
},
Store: {
async findAll() {
return [{ id: 77, company_name: '货主公司全称' }];
},
},
};
const ctx = {
user: {
store_id: 100000,
},
app: {
Sequelize: {
Op: {
in: 'in',
},
},
model,
},
model,
};
const service = new ReceivingService(ctx);
const result = await service.getReceivingDetail({
id: 123,
pagination: {
page: 1,
pageSize: 10,
},
});
assert.equal(result.code, 200);
assert.equal(result.data.receiving.store_name, '货主公司全称');
});
it('should resolve store_name remask first over company_name', async () => {
const model = {
StoreWarehouse: {
async findAll({ where }) {
if (where.store_id.in.includes(1)) {
return [{ store_id: 1, store_remask: '货主备注A' }];
}
return [];
},
},
Store: {
async findAll({ where }) {
return where.id.in.map(id => ({ id, company_name: id === 1 ? '公司A' : '公司B' }));
},
},
};
const ctx = {
app: {
Sequelize: {
Op: {
in: 'in',
},
},
},
model,
};
const service = new ReceivingService(ctx);
const map = await service._resolveReceivingStoreNameMap([ 1, 2 ], 100000);
assert.equal(map.get(1), '货主备注A');
assert.equal(map.get(2), '公司B');
});
});