Compare commits
32 Commits
731bc8e9fb
...
e9e39eafa7
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e9e39eafa7 | ||
|
|
fdec622f2d | ||
|
|
e602d205b2 | ||
|
|
16134e88c6 | ||
|
|
938e46e04c | ||
|
|
3171ce4fab | ||
|
|
b1ac685b84 | ||
|
|
eb4ce994ba | ||
|
|
ef933bc353 | ||
|
|
75333b2eb6 | ||
|
|
b62d3247ac | ||
|
|
8d86eb361b | ||
|
|
9928acacb2 | ||
|
|
d02690cc4d | ||
|
|
2f842c1a4b | ||
|
|
2c0ae6e089 | ||
|
|
a67e9c3955 | ||
|
|
4ae9ae852f | ||
|
|
c3896bc68a | ||
|
|
06a2126e2e | ||
|
|
5f2daf4e35 | ||
|
|
a49a878b5f | ||
|
|
7238621025 | ||
|
|
2c9f656ac9 | ||
|
|
d3e8421bdc | ||
|
|
a22e788706 | ||
|
|
2452cef4f1 | ||
|
|
606928194f | ||
|
|
bf1f2b3fad | ||
|
|
c3f97279da | ||
|
|
4ca6af82b0 | ||
|
|
4b8e17c139 |
@ -621,8 +621,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods
|
||||
- buildOperationLogData, buildBusinessLogWhere, formatOperationLogRows, createOperationLog, createOperationLogs, queryLogsByBusinessType, queryStockLogs, queryOrderLogs, queryAllOrderLogs, queryAllLogsByBusinessType, queryReceivingLogs, queryEntryOrderLogs, queryStockoutLogs, getMessageDetail
|
||||
- app/service/systems/order_async.js (9)
|
||||
- finalizeSuccessfulQimenSync, syncQmOrders, syncManualOrders, flushDeferredOrderSyncNotices, syncApiOrders, syncStockoutOrders, buildStockoutConfirmRequest, notifyStockoutExternal, resolveOpenApiAppByStore
|
||||
- app/service/systems/order_auto_outbound.js (11)
|
||||
- getEnabledAutoOutboundWarehouses, normalizeSubjectConfigForAutoOutbound, buildAutoOutboundWhere, findAutoOutboundOrders, buildSameDayOutboundCutoffUtc, resolveSameDayTime, resolveSameDayReleaseTime, buildSameDayReleaseUtc, findOrderIdsWithWeigh, processWarehouseAutoOutbound, executeAutoOutbound
|
||||
- app/service/systems/order_auto_outbound.js (17)
|
||||
- getEnabledAutoOutboundWarehouses, isAutoOutboundEnabled, resolveAutoOutboundRules, normalizeSubjectConfigForAutoOutbound, buildAutoOutboundWhere, findAutoOutboundOrderIds, resolveSameDayTime, resolveSameDayDeadlineTime, resolveSameDayReleaseTime, buildBeijingDayStartUtc, buildSameDayOutboundHoldWindows, buildSameDayOutboundRecheckCondition, findOrderIdsWithWeigh, processWarehouseAutoOutbound, writeAutoOutboundOperationLogs, buildAutoOutboundRuleSummary, executeAutoOutbound
|
||||
- app/service/systems/order_delivery_archive.js (16)
|
||||
- getArchiveDefaults, buildArchiveOptions, buildArchiveThresholds, normalizeWarehouseIds, listDispatchWarehouseIds, getArchiveModels, buildCandidateWhere, buildQueryOptions, buildHistoryOrderRow, buildHistoryItemRow, getArchiveErrorInfo, rollbackQuietly, archiveDispatchBatch, archiveDispatchOrdersForWarehouse, resolveFailureCursor, archiveDispatchOrdersToHistory
|
||||
- app/service/systems/order_delivery_migration.js (15)
|
||||
|
||||
@ -1,9 +1,15 @@
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const XLSX = require('xlsx');
|
||||
const {
|
||||
Controller,
|
||||
} = require('egg');
|
||||
const { toSuccess, toFailure } = require('../lib/api_response');
|
||||
|
||||
// 扫描记录 Excel 追加串行队列(临时联调用,避免并发读写冲突)
|
||||
let scanExcelWriteQueue = Promise.resolve();
|
||||
|
||||
class HomeController extends Controller {
|
||||
/**
|
||||
* 规范化平台编码。
|
||||
@ -257,6 +263,157 @@ class HomeController extends Controller {
|
||||
this.ctx.body = 'ok';
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取原始请求报文文本。
|
||||
*
|
||||
* 优先取 koa-bodyparser 已解析的 rawBody;若上游未携带可识别的
|
||||
* Content-Type(bodyParser 未消费请求流),则直接从请求流中读取。
|
||||
* @return {Promise<string>} 报文文本,读取失败时返回空字符串。
|
||||
*/
|
||||
async readRawRequestText() {
|
||||
const { ctx } = this;
|
||||
const rawBody = ctx.request.rawBody;
|
||||
|
||||
if (rawBody !== undefined && rawBody !== null) {
|
||||
return Buffer.isBuffer(rawBody) ? rawBody.toString('utf8') : String(rawBody);
|
||||
}
|
||||
|
||||
const chunks = [];
|
||||
|
||||
try {
|
||||
for await (const chunk of ctx.req) {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
} catch (err) {
|
||||
ctx.logger.error('[scan] 读取请求流失败', err && err.message || String(err));
|
||||
}
|
||||
|
||||
return Buffer.concat(chunks.map(chunk => (Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)))).toString('utf8');
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成格式化的当前时间字符串。
|
||||
* @param {Date} date 时间对象。
|
||||
* @return {string} YYYY-MM-DD HH:mm:ss。
|
||||
*/
|
||||
formatScanRecordTime(date = new Date()) {
|
||||
const pad = value => String(value).padStart(2, '0');
|
||||
|
||||
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` +
|
||||
`${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将一次扫描记录(时间 + 条码)追加写入项目根目录的 scan_records.xlsx。
|
||||
*
|
||||
* 临时联调用途:文件不存在则新建(含表头),存在则读取全部已有行后追加。
|
||||
* 写入复用 ExcelService 的原子写(临时文件 + rename),避免写坏文件。
|
||||
*
|
||||
* @param {string} barcode 扫描到的条码内容。
|
||||
* @return {Promise<{filePath: string, timeText: string, barcode: string, totalRows: number}>} 追加结果。
|
||||
*/
|
||||
async appendScanRecordToExcel(barcode) {
|
||||
const filePath = path.join(this.app.baseDir, 'scan_records.xlsx');
|
||||
const timeText = this.formatScanRecordTime();
|
||||
const headerRow = [ '时间', '条码' ];
|
||||
let rows = [ headerRow ];
|
||||
|
||||
if (fs.existsSync(filePath)) {
|
||||
try {
|
||||
const workbook = XLSX.readFile(filePath);
|
||||
const firstSheetName = workbook.SheetNames && workbook.SheetNames[0];
|
||||
|
||||
if (firstSheetName) {
|
||||
const sheet = workbook.Sheets[firstSheetName];
|
||||
const parsedRows = XLSX.utils.sheet_to_json(sheet, { header: 1, raw: false });
|
||||
const existingRows = parsedRows.filter(row => Array.isArray(row) && row.length);
|
||||
|
||||
if (existingRows.length) {
|
||||
rows = existingRows;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
this.ctx.logger.error('[scan] 读取根目录 scan_records.xlsx 失败,将重建文件', error && error.message || String(error));
|
||||
rows = [ headerRow ];
|
||||
}
|
||||
}
|
||||
|
||||
rows.push([ timeText, barcode ]);
|
||||
|
||||
const workbook = XLSX.utils.book_new();
|
||||
const sheet = XLSX.utils.aoa_to_sheet(rows);
|
||||
XLSX.utils.book_append_sheet(workbook, sheet, 'scan_records');
|
||||
|
||||
const buffer = XLSX.write(workbook, { type: 'buffer', bookType: 'xlsx' });
|
||||
await this.ctx.service.systems.excel.writeAtomicBufferFile(filePath, Buffer.from(buffer));
|
||||
|
||||
return {
|
||||
filePath,
|
||||
timeText,
|
||||
barcode,
|
||||
totalRows: rows.length - 1,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 扫描报文接收入口(POST /scan)。
|
||||
*
|
||||
* 联调阶段:接收上游报文并原样打日志、回显,同时把扫描到的条码与时间
|
||||
* 追加写入项目根目录 scan_records.xlsx。
|
||||
*/
|
||||
async scan() {
|
||||
const { ctx } = this;
|
||||
const rawBody = await this.readRawRequestText();
|
||||
const barcode = rawBody ? rawBody.trim() : '';
|
||||
let body = null;
|
||||
let parseError = '';
|
||||
let excelRecord = null;
|
||||
|
||||
if (rawBody) {
|
||||
const trimmed = rawBody.trim();
|
||||
|
||||
if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
|
||||
try {
|
||||
body = JSON.parse(trimmed);
|
||||
} catch (err) {
|
||||
parseError = err && err.message || String(err);
|
||||
body = rawBody;
|
||||
}
|
||||
} else {
|
||||
body = rawBody;
|
||||
}
|
||||
}
|
||||
|
||||
if (barcode) {
|
||||
excelRecord = await (scanExcelWriteQueue = scanExcelWriteQueue
|
||||
.catch(() => {})
|
||||
.then(() => this.appendScanRecordToExcel(barcode)));
|
||||
}
|
||||
|
||||
ctx.logger.info('[scan] 收到请求报文', {
|
||||
method: ctx.method,
|
||||
url: ctx.url,
|
||||
contentType: ctx.get('content-type'),
|
||||
query: ctx.query,
|
||||
headers: ctx.headers,
|
||||
rawBody,
|
||||
rawBodyHex: rawBody ? Buffer.from(rawBody, 'utf8').toString('hex') : '',
|
||||
body,
|
||||
parseError,
|
||||
barcode,
|
||||
excelRecord,
|
||||
});
|
||||
|
||||
ctx.body = toSuccess({
|
||||
contentType: ctx.get('content-type'),
|
||||
rawBody,
|
||||
body,
|
||||
parseError,
|
||||
barcode,
|
||||
excelRecord,
|
||||
});
|
||||
}
|
||||
|
||||
async index() {
|
||||
const {
|
||||
ctx,
|
||||
|
||||
@ -4,6 +4,38 @@ const Controller = require('egg').Controller;
|
||||
const wechatOpenCrypt = require('../lib/wechat_open_crypt');
|
||||
const WechatOpenClient = require('../lib/wechat_open_client');
|
||||
|
||||
/**
|
||||
* 微信全网发布检测专用测试号(官方文档 5 组随机分配),用于日志标注公众号/小程序场景。
|
||||
* 步骤2=公众号被动回复;步骤3=公众号客服消息;步骤4=小程序客服消息。
|
||||
*/
|
||||
const WECHAT_TEST_ACCOUNTS = {
|
||||
mp: new Set([
|
||||
'wx570bc396a51b8ff8', 'wx9252c5e0bb1836fc', 'wx8e1097c5bc82cde9',
|
||||
'wx14550af28c71a144', 'wxa35b9c23cfe664eb',
|
||||
]),
|
||||
mini: new Set([
|
||||
'wxd101a85aa106f53e', 'wxc39235c15087f6f3', 'wx7720d01d4b2a4500',
|
||||
'wx05d483572dcd5d8b', 'wx5910277cae6fd970',
|
||||
]),
|
||||
};
|
||||
|
||||
/**
|
||||
* 判断 appid 属于公众号/小程序测试号(用于日志标注,未知账号不影响处理)。
|
||||
* @param {string} appid 授权方 AppID。
|
||||
* @return {string} '公众号' | '小程序' | '未知账号'。
|
||||
*/
|
||||
function detectAccountType(appid) {
|
||||
if (WECHAT_TEST_ACCOUNTS.mp.has(appid)) return '公众号';
|
||||
if (WECHAT_TEST_ACCOUNTS.mini.has(appid)) return '小程序';
|
||||
return '未知账号';
|
||||
}
|
||||
|
||||
/**
|
||||
* autoReply 返回该值表示「显式不回复,响应体回空串」:
|
||||
* 官方检测步骤3要求 5 秒内返回空串表明暂时不回复(不能回 success)。
|
||||
*/
|
||||
const EMPTY_REPLY = '__EMPTY_REPLY__';
|
||||
|
||||
/**
|
||||
* 微信开放平台第三方平台回调 Controller。
|
||||
* 接收微信服务器推送的授权事件(组件票据/授权成功/授权更新/取消授权),
|
||||
@ -158,6 +190,8 @@ class WechatOpenController extends Controller {
|
||||
await existing.update(fields);
|
||||
} else {
|
||||
await app.model.WechatApp.create({ appid: authorizerAppid, ...fields });
|
||||
// 首次授权:写入系统默认用户须知作为第一版(幂等)
|
||||
await ctx.service.systems.wechat.ensureDefaultAgreementVersion(authorizerAppid);
|
||||
}
|
||||
|
||||
// 令牌写入 Redis 缓存(不落库)
|
||||
@ -232,8 +266,18 @@ class WechatOpenController extends Controller {
|
||||
// 暂存授权码(供后续换取令牌使用)
|
||||
await client.saveAuthorizationCode(authorizerAppid, authorizationCode);
|
||||
|
||||
// 用授权码换取授权方令牌与权限集合
|
||||
const authorizationInfo = await client.queryAuth(authorizationCode);
|
||||
// 用授权码换取授权方令牌与权限集合。
|
||||
// 注意:同一 authorization_code 只能 queryAuth 成功一次。微信全网发布检测时,
|
||||
// authorized 事件与 QUERY_AUTH_CODE 文本消息几乎同时推送(实测仅差 1 秒),
|
||||
// 文本分支也会用同一 code 调 queryAuth——谁先到谁消费。此处失败不抛错重试,
|
||||
// 令牌可由文本分支/授权回跳链路换得,保证「授权成功」检测项始终响应 success。
|
||||
let authorizationInfo = null;
|
||||
try {
|
||||
authorizationInfo = await client.queryAuth(authorizationCode);
|
||||
} catch (e) {
|
||||
ctx.logger.warn(`[wechatOpen] ${infoType} 换取授权方令牌失败(可能已被 QUERY_AUTH_CODE 文本消费): ${e.message}`);
|
||||
return;
|
||||
}
|
||||
const nowSec = Math.floor(Date.now() / 1000);
|
||||
const fields = {
|
||||
authorizer_refresh_token: authorizationInfo.authorizer_refresh_token || null,
|
||||
@ -276,6 +320,8 @@ class WechatOpenController extends Controller {
|
||||
ctx.logger.info(`[wechatOpen] 已更新授权记录 appid=${authorizerAppid}`);
|
||||
} else {
|
||||
await app.model.WechatApp.create({ appid: authorizerAppid, ...fields });
|
||||
// 首次授权:写入系统默认用户须知作为第一版(幂等)
|
||||
await ctx.service.systems.wechat.ensureDefaultAgreementVersion(authorizerAppid);
|
||||
ctx.logger.info(`[wechatOpen] 已新增授权记录 appid=${authorizerAppid}`);
|
||||
}
|
||||
break;
|
||||
@ -333,6 +379,376 @@ class WechatOpenController extends Controller {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 授权方(小程序/公众号)消息与事件推收入口,参考 PHP /index/index/events/appid/$APPID$。
|
||||
* GET=服务器地址 URL 有效性验证(echostr),POST=消息/事件推送(组件密钥加密)。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async events() {
|
||||
const { ctx, app } = this;
|
||||
const { params } = ctx;
|
||||
const appid = String((params && params.appid) || '').trim();
|
||||
const config = app.config.wechatOpen || {};
|
||||
|
||||
if (!appid) {
|
||||
ctx.logger.error('[wechatOpen.events] 缺少 appid 参数');
|
||||
ctx.body = 'success';
|
||||
return;
|
||||
}
|
||||
|
||||
const signature = String(ctx.query.signature || '');
|
||||
const timestamp = String(ctx.query.timestamp || '');
|
||||
const nonce = String(ctx.query.nonce || '');
|
||||
const echostr = String(ctx.query.echostr || '');
|
||||
const msgSignature = String(ctx.query.msg_signature || '');
|
||||
|
||||
// ─── URL 有效性验证(首次配置服务器地址时) ───────────────
|
||||
if (echostr) {
|
||||
ctx.body = await this.verifyEventUrl(appid, signature, timestamp, nonce, echostr);
|
||||
return;
|
||||
}
|
||||
|
||||
// ─── 消息/事件推送 ───────────────────────────────────────
|
||||
try {
|
||||
const rawBody = await this.readRawBody();
|
||||
if (!rawBody || !rawBody.trim()) {
|
||||
ctx.logger.error(`[wechatOpen.events] 事件推送数据为空 appid=${appid}`);
|
||||
ctx.body = 'success';
|
||||
return;
|
||||
}
|
||||
|
||||
const decryptResult = wechatOpenCrypt.decryptMsg({
|
||||
token: config.token,
|
||||
encodingAesKey: config.encoding_aes_key,
|
||||
componentAppid: config.component_appid,
|
||||
msgSignature,
|
||||
timestamp,
|
||||
nonce,
|
||||
encryptedXml: rawBody,
|
||||
});
|
||||
|
||||
if (decryptResult.code !== wechatOpenCrypt.ERROR_CODES.OK) {
|
||||
ctx.logger.error(`[wechatOpen.events] 消息解密失败 appid=${appid} code=${decryptResult.code} msg=${decryptResult.msg}`);
|
||||
ctx.body = 'success';
|
||||
return;
|
||||
}
|
||||
|
||||
const data = wechatOpenCrypt.parseXml(decryptResult.msg);
|
||||
ctx.logger.info(`[wechatOpen.events] 事件推送 appid=${appid}: ${decryptResult.msg}`);
|
||||
|
||||
const msgType = String(data.MsgType || '');
|
||||
const event = String(data.Event || '');
|
||||
|
||||
// 文本消息全量落盘(WARN 级):生产日志只落 WARN+,用于检测场景定位回复问题
|
||||
if (msgType === 'text') {
|
||||
ctx.logger.warn(`[wechatOpen.events] 收到文本消息 appid=${appid} type=${detectAccountType(appid)} openid=${data.FromUserName} content=${JSON.stringify(String(data.Content || ''))}`);
|
||||
}
|
||||
|
||||
switch (msgType) {
|
||||
case 'event':
|
||||
await this.handlePushEvent(appid, event, data);
|
||||
break;
|
||||
|
||||
case 'text': {
|
||||
// 记录文本消息并自动回复(被动回复返回加密 XML;客服消息场景返回空串)
|
||||
const reply = await this.autoReply(appid, data, nonce);
|
||||
if (reply === EMPTY_REPLY) {
|
||||
// 官方检测步骤3/4:5 秒内返回空串表明暂时不回复,客服消息在后台异步发送
|
||||
ctx.logger.warn(`[wechatOpen.events] 返回空串响应(客服消息后台发送中) appid=${appid} type=${detectAccountType(appid)}`);
|
||||
ctx.body = '';
|
||||
return;
|
||||
}
|
||||
if (reply) {
|
||||
ctx.logger.warn(`[wechatOpen.events] 被动回复已返回 appid=${appid} type=${detectAccountType(appid)} openid=${data.FromUserName} length=${reply.length}`);
|
||||
ctx.type = 'application/xml';
|
||||
ctx.body = reply;
|
||||
return;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'image':
|
||||
await this.recordUserAction(appid, data, 'image');
|
||||
break;
|
||||
|
||||
default:
|
||||
ctx.logger.info(`[wechatOpen.events] 未处理的消息类型 appid=${appid} MsgType=${msgType}`);
|
||||
break;
|
||||
}
|
||||
|
||||
// 微信要求回显 success 表示处理成功
|
||||
ctx.body = 'success';
|
||||
} catch (e) {
|
||||
ctx.logger.error(`[wechatOpen.events] 处理异常 appid=${appid}: ${e.message}`, e);
|
||||
ctx.body = 'success';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证事件推送服务器 URL(参考 PHP verifyEventUrl)。
|
||||
* 签名使用第三方平台(组件)Token 校验(与 /Authorization 的 URL 验证一致)。
|
||||
* appid 记录不存在时不阻断验证:首次配置服务器地址、微信全网发布检测等场景下,
|
||||
* 微信会先发 echostr 验证 URL,此时可能尚无授权记录,仍按组件 Token 验签回显。
|
||||
* @param {string} appid 授权方 AppID。
|
||||
* @param {string} signature 微信回传签名。
|
||||
* @param {string} timestamp 时间戳。
|
||||
* @param {string} nonce 随机串。
|
||||
* @param {string} echostr 回显串。
|
||||
* @return {Promise<string>} 验证通过返回 echostr,否则返回错误提示。
|
||||
*/
|
||||
async verifyEventUrl(appid, signature, timestamp, nonce, echostr) {
|
||||
const { ctx, app } = this;
|
||||
|
||||
// 对应小程序应已授权登记;未登记仅告警,不阻断 URL 验证
|
||||
const record = await app.model.WechatApp.findOne({ where: { appid } });
|
||||
if (!record) {
|
||||
ctx.logger.warn(`[wechatOpen.events] URL 验证:appid 尚无授权记录(首次配置或检测场景),仍按组件 Token 验签 appid=${appid}`);
|
||||
}
|
||||
|
||||
const config = app.config.wechatOpen || {};
|
||||
const valid = wechatOpenCrypt.verifyUrlSignature(config.token, signature, timestamp, nonce);
|
||||
ctx.logger.info(`[wechatOpen.events] URL 验证 appid=${appid} ${valid ? '通过' : '失败'}`);
|
||||
return valid ? echostr : '验证失败';
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理事件类型推送(MsgType=event,参考 PHP handleEvent)。
|
||||
* @param {string} appid 授权方 AppID。
|
||||
* @param {string} event 事件类型(subscribe/unsubscribe/SCAN/CLICK/VIEW/TEMPLATESENDJOBFINISH)。
|
||||
* @param {object} data 解密后的消息对象。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async handlePushEvent(appid, event, data) {
|
||||
const { ctx } = this;
|
||||
const openid = String(data.FromUserName || '');
|
||||
|
||||
switch (event) {
|
||||
case 'subscribe':
|
||||
// 关注事件:记录行为并发送欢迎消息(客服消息,非被动回复)
|
||||
await this.recordUserAction(appid, data, 'subscribe');
|
||||
await this.sendWelcomeMessage(appid, openid);
|
||||
break;
|
||||
|
||||
case 'unsubscribe':
|
||||
await this.recordUserAction(appid, data, 'unsubscribe');
|
||||
break;
|
||||
|
||||
case 'SCAN':
|
||||
case 'CLICK':
|
||||
case 'VIEW':
|
||||
case 'TEMPLATESENDJOBFINISH':
|
||||
await this.recordUserAction(appid, data, event);
|
||||
break;
|
||||
|
||||
default:
|
||||
ctx.logger.info(`[wechatOpen.events] 未处理的事件类型 appid=${appid} Event=${event}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 文本消息自动回复(参考 PHP autoReply):先记录用户行为,
|
||||
* 关键词命中生成被动回复并加密;QUERY_AUTH_CODE 场景改为客服消息直发、不被动回复。
|
||||
* @param {string} appid 授权方 AppID。
|
||||
* @param {object} data 解密后的消息对象。
|
||||
* @param {string} nonce 微信回传随机串(用于回复签名)。
|
||||
* @return {Promise<string>} 加密回复 XML;无需被动回复时返回空串。
|
||||
*/
|
||||
async autoReply(appid, data, nonce) {
|
||||
const { ctx, app } = this;
|
||||
const config = app.config.wechatOpen || {};
|
||||
|
||||
const openid = String(data.FromUserName || '');
|
||||
const appName = String(data.ToUserName || '');
|
||||
const content = String(data.Content || '');
|
||||
|
||||
// 记录用户文本消息
|
||||
await this.recordUserAction(appid, data, 'text');
|
||||
|
||||
try {
|
||||
const lowerContent = content.toLowerCase();
|
||||
let replyContent = '';
|
||||
|
||||
// 关键词回复(与参考实现保持一致)
|
||||
if (content.includes('你好') || lowerContent.includes('hello')) {
|
||||
replyContent = '你好!有什么可以帮您的吗?';
|
||||
} else if (content.includes('帮助') || lowerContent.includes('help')) {
|
||||
replyContent = '输入以下关键词获取帮助:\n1. 功能 - 查看功能列表\n2. 关于 - 了解更多信息';
|
||||
} else if (content.includes('TESTCOMPONENT_MSG_TYPE_TEXT')) {
|
||||
replyContent = 'TESTCOMPONENT_MSG_TYPE_TEXT_callback';
|
||||
ctx.logger.warn(`[wechatOpen.events] 命中官方检测步骤2-公众号被动回复 appid=${appid} type=${detectAccountType(appid)}`);
|
||||
} else if (content.includes('QUERY_AUTH_CODE')) {
|
||||
// 微信全网发布检测场景(官方步骤3=公众号客服/步骤4=小程序客服):文本携带授权码
|
||||
// (QUERY_AUTH_CODE:<code>)。处理:响应体直接回空串(官方要求「5 秒内返回空串
|
||||
// 表明暂时不回复」),客服消息由后台异步发送(含前缀/去前缀双发)。
|
||||
const authCode = content.replace('QUERY_AUTH_CODE:', '').trim();
|
||||
const accountType = detectAccountType(appid);
|
||||
ctx.logger.warn(`[wechatOpen.events] 命中官方检测步骤3/4-客服消息回复 appid=${appid} type=${accountType} code=${authCode}`);
|
||||
|
||||
// 官方要求:不被动回复,响应体回空串;客服消息流程放入后台异步执行
|
||||
ctx.runInBackground(async () => {
|
||||
const client = new WechatOpenClient(ctx);
|
||||
let refreshToken = null;
|
||||
let tokenSource = '';
|
||||
|
||||
// 1) 优先使用已存储的 refresh_token(authorized 事件已换取):Redis → DB。
|
||||
// 真实业务中用户消息不带 code,只能依赖存储的令牌(与 PHP 参考实现一致)。
|
||||
refreshToken = await client.cacheGet(`App:${appid}:authorizer_refresh_token`);
|
||||
if (refreshToken) {
|
||||
tokenSource = 'redis';
|
||||
} else {
|
||||
try {
|
||||
const record = await app.model.WechatApp.findOne({ where: { appid } });
|
||||
if (record && record.authorizer_refresh_token) {
|
||||
refreshToken = String(record.authorizer_refresh_token);
|
||||
tokenSource = 'db';
|
||||
}
|
||||
} catch (e) {
|
||||
ctx.logger.warn(`[wechatOpen.events] 读取授权记录失败: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 2) 存储令牌不存在(文本消息先于 authorized 事件到达),用文本携带的授权码换取(官方检测意图)
|
||||
if (!refreshToken && authCode) {
|
||||
try {
|
||||
const authorizationInfo = await client.queryAuth(authCode);
|
||||
refreshToken = authorizationInfo.authorizer_refresh_token || null;
|
||||
if (refreshToken) {
|
||||
tokenSource = 'query_auth';
|
||||
await client.cacheSet(`App:${appid}:authorizer_refresh_token`, refreshToken, 30 * 24 * 3600);
|
||||
if (authorizationInfo.authorizer_access_token) {
|
||||
await client.cacheSet(
|
||||
`App:${appid}:AuthorizerAccessToken`,
|
||||
authorizationInfo.authorizer_access_token,
|
||||
Math.max((authorizationInfo.expires_in || 7200) - 300, 60)
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
ctx.logger.warn(`[wechatOpen.events] QUERY_AUTH_CODE 换取令牌失败: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
ctx.logger.warn(`[wechatOpen.events] 客服回复令牌来源 source=${tokenSource || 'none'} appid=${appid} has_token=${!!refreshToken}`);
|
||||
|
||||
// 客服消息双发兼容:官方文档字面要求回复 <queryauthcode@@@code>_from_api;
|
||||
// 检测脚本可能按「去掉 queryauthcode@@@ 标记前缀的真实 code」核对,两条都发确保命中。
|
||||
const codeValue = authCode.trim();
|
||||
const pureCode = codeValue.startsWith('queryauthcode@@@')
|
||||
? codeValue.slice('queryauthcode@@@'.length)
|
||||
: codeValue;
|
||||
try {
|
||||
await this.sendMessage(appid, openid, `${codeValue}_from_api`, refreshToken);
|
||||
if (pureCode && pureCode !== codeValue) {
|
||||
await this.sendMessage(appid, openid, `${pureCode}_from_api`, refreshToken);
|
||||
}
|
||||
} catch (e) {
|
||||
ctx.logger.error(`[wechatOpen.events] 客服消息发送异常: ${e.message}`);
|
||||
}
|
||||
});
|
||||
|
||||
// 响应体回空串(不被动回复,与 PHP 参考实现一致)
|
||||
return EMPTY_REPLY;
|
||||
} else {
|
||||
replyContent = `收到您的消息:${content}\n我会尽快回复您!`;
|
||||
}
|
||||
|
||||
// 组装明文回复 XML(ToUserName=用户 openid,FromUserName=公众号原始 ID)
|
||||
const plainXml = '<xml>'
|
||||
+ `<ToUserName><![CDATA[${openid}]]></ToUserName>`
|
||||
+ `<FromUserName><![CDATA[${appName}]]></FromUserName>`
|
||||
+ `<CreateTime>${Math.floor(Date.now() / 1000)}</CreateTime>`
|
||||
+ '<MsgType><![CDATA[text]]></MsgType>'
|
||||
+ `<Content><![CDATA[${replyContent}]]></Content>`
|
||||
+ '</xml>';
|
||||
|
||||
const encryptResult = wechatOpenCrypt.encryptMsg({
|
||||
token: config.token,
|
||||
encodingAesKey: config.encoding_aes_key,
|
||||
componentAppid: config.component_appid,
|
||||
plainXml,
|
||||
nonce,
|
||||
});
|
||||
|
||||
if (encryptResult.code !== wechatOpenCrypt.ERROR_CODES.OK) {
|
||||
ctx.logger.error(`[wechatOpen.events] 回复消息加密失败 code=${encryptResult.code}`);
|
||||
return '';
|
||||
}
|
||||
return encryptResult.encryptedXml;
|
||||
} catch (e) {
|
||||
ctx.logger.error(`[wechatOpen.events] 自动回复失败: ${e.message}`);
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录用户行为到 Redis(参考 PHP recordUserAction)。
|
||||
* @param {string} appid 授权方 AppID。
|
||||
* @param {object} data 解密后的消息对象。
|
||||
* @param {string} action 行为类型(subscribe/unsubscribe/SCAN/CLICK/VIEW/text/image 等)。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async recordUserAction(appid, data, action) {
|
||||
const { ctx } = this;
|
||||
const client = new WechatOpenClient(ctx);
|
||||
const openid = String(data.FromUserName || '');
|
||||
if (!openid) return;
|
||||
|
||||
const nowSec = Math.floor(Date.now() / 1000);
|
||||
const key = `UserAction:${appid}:${openid}:${nowSec}`;
|
||||
await client.cacheSet(key, JSON.stringify({
|
||||
appid,
|
||||
openid,
|
||||
action,
|
||||
data,
|
||||
time: nowSec,
|
||||
}), 86400);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送客服文本消息(refreshToken 优先,其次从 DB 兜底读取,避免 Redis 丢失导致失败)。
|
||||
* @param {string} appid 授权方 AppID。
|
||||
* @param {string} openid 用户 openid。
|
||||
* @param {string} content 文本内容。
|
||||
* @param {string} [refreshToken] 授权方刷新令牌(调用方已获取时传入)。
|
||||
* @return {Promise<object>} 微信原始响应。
|
||||
*/
|
||||
async sendMessage(appid, openid, content, refreshToken) {
|
||||
const { ctx, app } = this;
|
||||
const client = new WechatOpenClient(ctx);
|
||||
|
||||
// Redis 中的 refresh token 可能丢失,从 wms_wechat_app 兜底读取
|
||||
let token = refreshToken || null;
|
||||
try {
|
||||
const record = await app.model.WechatApp.findOne({ where: { appid } });
|
||||
if (record && record.authorizer_refresh_token) {
|
||||
token = String(record.authorizer_refresh_token);
|
||||
}
|
||||
} catch (e) {
|
||||
ctx.logger.warn(`[wechatOpen.events] 读取授权记录失败 appid=${appid}: ${e.message}`);
|
||||
}
|
||||
|
||||
ctx.logger.warn(`[wechatOpen.events] 发送客服消息 appid=${appid} openid=${openid} content=${JSON.stringify(content)} has_token=${!!token}`);
|
||||
const result = await client.sendCustomMessage(appid, openid, content, token);
|
||||
ctx.logger.warn(`[wechatOpen.events] 客服消息发送结果: ${JSON.stringify(result)}`);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送关注欢迎消息(失败仅记录日志,不阻断事件处理)。
|
||||
* @param {string} appid 授权方 AppID。
|
||||
* @param {string} openid 用户 openid。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async sendWelcomeMessage(appid, openid) {
|
||||
const { ctx } = this;
|
||||
try {
|
||||
await this.sendMessage(appid, openid, '欢迎关注!感谢您的支持!');
|
||||
} catch (e) {
|
||||
ctx.logger.error(`[wechatOpen.events] 发送欢迎消息失败: ${e.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WechatOpenController;
|
||||
|
||||
@ -96,6 +96,7 @@ module.exports = {
|
||||
ORDER_RETURN_RECEIVED: '退回收到',
|
||||
ORDER_LOCK: '订单锁定',
|
||||
ORDER_UNLOCK: '订单解锁',
|
||||
ORDER_AUTO_OUTBOUND: '自动出库',
|
||||
|
||||
// 库存管理
|
||||
STORAGE_TRANSFER_LOCATION: '库位调拨',
|
||||
|
||||
@ -677,6 +677,48 @@ class WechatOpenClient {
|
||||
async clearAuthState(state) {
|
||||
await this.cacheDel(`wechat_auth_state:${state}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送客服文本消息(POST cgi-bin/message/custom/send,使用 authorizer_access_token
|
||||
* 代授权方调用,用于用户关注欢迎语、关键词自动回复等场景)。
|
||||
*
|
||||
* @param {string} appid 授权方(小程序/公众号)AppID。
|
||||
* @param {string} touser 用户 openid。
|
||||
* @param {string} content 文本内容。
|
||||
* @param {string} [refreshToken] 授权方刷新令牌(缺省从缓存/DB 读)。
|
||||
* @return {Promise<object>} 微信原始响应(errcode/errmsg)。
|
||||
*/
|
||||
async sendCustomMessage(appid, touser, content, refreshToken) {
|
||||
const request = async () => {
|
||||
const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken);
|
||||
const base = this.config.api_base || DEFAULT_API_BASE;
|
||||
const url = `${base.replace(/\/$/, '')}/cgi-bin/message/custom/send`
|
||||
+ `?access_token=${encodeURIComponent(authorizerAccessToken)}`;
|
||||
const response = await this.ctx.curl(url, {
|
||||
method: 'POST',
|
||||
dataType: 'json',
|
||||
timeout: 30000,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
data: {
|
||||
touser,
|
||||
msgtype: 'text',
|
||||
text: { content },
|
||||
},
|
||||
});
|
||||
return response && response.data !== undefined ? response.data : response;
|
||||
};
|
||||
|
||||
let result = await request();
|
||||
// authorizer_access_token 失效(40001/40014)时清缓存重试一次
|
||||
if (result && [ 40001, 40014 ].includes(Number(result.errcode))) {
|
||||
if (this.ctx && this.ctx.logger) {
|
||||
this.ctx.logger.warn(`[wechatOpen] message/custom/send token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`);
|
||||
}
|
||||
await this.cacheDel(`App:${appid}:AuthorizerAccessToken`);
|
||||
result = await request();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WechatOpenClient;
|
||||
|
||||
@ -98,6 +98,20 @@ function pkcs7Decode(buf) {
|
||||
return buf;
|
||||
}
|
||||
|
||||
/**
|
||||
* PKCS#7 填充(微信 AES 块大小为 32 字节)。
|
||||
* @param {Buffer} buf 原始 buffer。
|
||||
* @return {Buffer} 填充后的 buffer。
|
||||
*/
|
||||
function pkcs7Encode(buf) {
|
||||
const blockSize = 32;
|
||||
const pad = blockSize - (buf.length % blockSize);
|
||||
const result = Buffer.alloc(buf.length + pad);
|
||||
buf.copy(result);
|
||||
result.fill(pad, buf.length);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* AES-256-CBC 解密微信密文。
|
||||
* @param {string} encrypted base64 密文。
|
||||
@ -212,6 +226,72 @@ function parseXml(xml) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 加密被动回复消息(完整流程:明文组装 → PKCS#7 → AES-256-CBC → base64 → 签名 → 组装 XML)。
|
||||
* 用于第三方平台模式下回复授权方(小程序/公众号)用户消息:
|
||||
* 16 字节随机串 + 4 字节大端消息长度 + 明文 XML + component_appid,密钥与推送解密共用组件密钥。
|
||||
* @param {object} opts 参数。
|
||||
* @param {string} opts.token 第三方平台消息校验 Token。
|
||||
* @param {string} opts.encodingAesKey 第三方平台消息加解密 Key(43 位)。
|
||||
* @param {string} opts.componentAppid 第三方平台 AppID。
|
||||
* @param {string} opts.plainXml 明文回复 XML。
|
||||
* @param {string} opts.nonce 微信回传的随机串(用于回复签名)。
|
||||
* @return {{ code: number, encryptedXml: string }} code=0 时 encryptedXml 为加密回复 XML。
|
||||
*/
|
||||
function encryptMsg(opts) {
|
||||
const {
|
||||
token,
|
||||
encodingAesKey,
|
||||
componentAppid,
|
||||
plainXml,
|
||||
nonce,
|
||||
} = opts || {};
|
||||
|
||||
if (!token || !encodingAesKey || !componentAppid || !plainXml) {
|
||||
return { code: ERROR_CODES.ILLEGAL_BUFFER, encryptedXml: '' };
|
||||
}
|
||||
|
||||
// 1. AES Key(encodingAesKey 43 位补 '=' 后 base64 解码为 32 字节)
|
||||
let aesKey;
|
||||
try {
|
||||
aesKey = Buffer.from(String(encodingAesKey) + '=', 'base64');
|
||||
} catch (e) {
|
||||
return { code: ERROR_CODES.ILLEGAL_AES_KEY, encryptedXml: '' };
|
||||
}
|
||||
if (aesKey.length !== 32) {
|
||||
return { code: ERROR_CODES.ILLEGAL_AES_KEY, encryptedXml: '' };
|
||||
}
|
||||
|
||||
// 2. 组装明文:16 字节随机串 + 4 字节大端长度 + 明文 XML + component_appid
|
||||
const random = crypto.randomBytes(16);
|
||||
const plainBuf = Buffer.from(String(plainXml), 'utf8');
|
||||
const lenBuf = Buffer.alloc(4);
|
||||
lenBuf.writeUInt32BE(plainBuf.length, 0);
|
||||
const appidBuf = Buffer.from(String(componentAppid), 'utf8');
|
||||
const padded = pkcs7Encode(Buffer.concat([ random, lenBuf, plainBuf, appidBuf ]));
|
||||
|
||||
// 3. AES-256-CBC 加密(iv = key 前 16 字节,手动填充)
|
||||
let encrypt;
|
||||
try {
|
||||
const iv = aesKey.subarray(0, 16);
|
||||
const cipher = crypto.createCipheriv('aes-256-cbc', aesKey, iv);
|
||||
cipher.setAutoPadding(false);
|
||||
encrypt = Buffer.concat([ cipher.update(padded), cipher.final() ]).toString('base64');
|
||||
} catch (e) {
|
||||
return { code: ERROR_CODES.DECRYPT_AES_ERROR, encryptedXml: '' };
|
||||
}
|
||||
|
||||
// 4. 签名与组装回复 XML
|
||||
const timestamp = Math.floor(Date.now() / 1000);
|
||||
const signature = getSignature(token, timestamp, nonce, encrypt);
|
||||
const encryptedXml = `<xml><Encrypt><![CDATA[${encrypt}]]></Encrypt>`
|
||||
+ `<MsgSignature><![CDATA[${signature}]]></MsgSignature>`
|
||||
+ `<TimeStamp>${timestamp}</TimeStamp>`
|
||||
+ `<Nonce><![CDATA[${String(nonce)}]]></Nonce></xml>`;
|
||||
|
||||
return { code: ERROR_CODES.OK, encryptedXml };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
ERROR_CODES,
|
||||
sha1,
|
||||
@ -220,4 +300,5 @@ module.exports = {
|
||||
extractEncrypt,
|
||||
decryptMsg,
|
||||
parseXml,
|
||||
encryptMsg,
|
||||
};
|
||||
|
||||
81
app/model/container.js
Normal file
81
app/model/container.js
Normal file
@ -0,0 +1,81 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 容器(篮筐)资产登记表 Model。
|
||||
*
|
||||
* 对应数据库表 `wms_container`,登记仓库的物理容器(篮筐)资产:
|
||||
* 容器编号、使用状态、是否损坏、损坏说明、备注等。
|
||||
* 同一仓库内容器编号唯一,通过 warehouse_id 做数据隔离维度。
|
||||
* 后续散单拣货把购物车商品临时转移到容器时,通过 status 标记占用/空闲。
|
||||
* @param {import('egg').Application} app - Egg 应用实例
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, ENUM } = app.Sequelize;
|
||||
|
||||
const Container = app.model.define('wms_container', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '仓库ID(数据隔离维度)',
|
||||
},
|
||||
container_no: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '容器编号(篮筐编号)',
|
||||
},
|
||||
status: {
|
||||
type: ENUM('idle', 'in_use'),
|
||||
allowNull: false,
|
||||
defaultValue: 'idle',
|
||||
comment: '使用状态:idle=空闲 in_use=占用(散单商品临时转移)',
|
||||
},
|
||||
is_damaged: {
|
||||
type: ENUM('Y', 'N'),
|
||||
allowNull: false,
|
||||
defaultValue: 'N',
|
||||
comment: '是否损坏:Y=损坏 N=正常',
|
||||
},
|
||||
damage_remark: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '损坏说明',
|
||||
},
|
||||
remark: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '备注',
|
||||
},
|
||||
creator_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '登记人账户ID',
|
||||
},
|
||||
creator_name: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '登记人名称快照',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_container',
|
||||
comment: '容器(篮筐)资产登记表',
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
paranoid: false,
|
||||
indexes: [
|
||||
{ name: 'uk_warehouse_container_no', unique: true, fields: [ 'warehouse_id', 'container_no' ] },
|
||||
{ name: 'idx_warehouse_id', fields: [ 'warehouse_id' ] },
|
||||
{ name: 'idx_status', fields: [ 'status' ] },
|
||||
{ name: 'idx_is_damaged', fields: [ 'is_damaged' ] },
|
||||
],
|
||||
});
|
||||
|
||||
return Container;
|
||||
};
|
||||
@ -610,6 +610,15 @@ function buildIndexOptions(warehouseId, type) {
|
||||
dispatchLaneIndex,
|
||||
...inheritedIndexes,
|
||||
...buildListSortIndexes(warehouseId, modelType),
|
||||
// 大屏面板计数索引:面板 count 不携带 warehouse_id 条件(分表名已隐含仓库),
|
||||
// 列表排序索引的前缀 warehouse_id+dispatch_lane 无法使用;且全表 dispatch_lane
|
||||
// 仅有 m4 一个值,无选择性。以 delivery_time 作为前导列做范围裁剪(一个业务日
|
||||
// 窗口约 1.6 万行 vs 全表 106 万行),outbound_status 作为第二列由 ICP 在索引
|
||||
// 内过滤(所有阶段卡片均带 outbound_status='fin')。
|
||||
{
|
||||
name: `idx_dispatch_${warehouseId}_panel_fulfillment`,
|
||||
fields: [ 'delivery_time', 'outbound_status' ],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@ -130,6 +130,7 @@ module.exports = app => {
|
||||
indexes: [
|
||||
{ name: 'uk_unpack_no', unique: true, fields: [ 'unpack_no' ] },
|
||||
{ name: 'idx_warehouse_unpack_date', fields: [ 'warehouse_id', 'unpack_date' ] },
|
||||
{ name: 'idx_warehouse_created_at', fields: [ 'warehouse_id', 'created_at' ] },
|
||||
{ name: 'idx_return_received_id', fields: [ 'return_received_id' ] },
|
||||
{ name: 'idx_waybill_code', fields: [ 'waybill_code' ] },
|
||||
{ name: 'idx_order_express_id', fields: [ 'order_express_id' ] },
|
||||
|
||||
@ -31,18 +31,17 @@ module.exports = app => {
|
||||
const DEFAULT_SAME_DAY_OUTBOUND_DEADLINE_TIME = '06:00';
|
||||
const DEFAULT_SAME_DAY_OUTBOUND_RELEASE_TIME = '22:00';
|
||||
|
||||
const DEFAULT_AUTO_OUTBOUND_RULES = Object.freeze({
|
||||
enabled: false,
|
||||
require_recheck: true,
|
||||
require_pack: true,
|
||||
require_weigh: true,
|
||||
require_sync: true,
|
||||
require_print: true,
|
||||
require_pick: true,
|
||||
exclude_same_day_outbound: true,
|
||||
same_day_outbound_deadline_time: '06:00',
|
||||
same_day_outbound_release_time: '22:00',
|
||||
});
|
||||
// 自动出库开关:独立字段,默认关闭
|
||||
const DEFAULT_AUTO_OUTBOUND_ENABLED = false;
|
||||
// 自动出库规则:数组,默认空数组(空数组 = 不出库任何订单);每项规则独立判断,任一命中即出库
|
||||
const DEFAULT_AUTO_OUTBOUND_RULES = Object.freeze([]);
|
||||
|
||||
/**
|
||||
* 获取自动出库规则默认值(新数组,避免共享冻结数组引用)。
|
||||
*
|
||||
* @return {Array<Object>} 默认自动出库规则数组。
|
||||
*/
|
||||
const getDefaultAutoOutboundRules = () => [];
|
||||
|
||||
const DEFAULT_CUTOFF_ORDER_TIME = '18:00';
|
||||
const CUTOFF_ORDER_TIME_MIN = '00:00';
|
||||
@ -50,6 +49,10 @@ module.exports = app => {
|
||||
const DEFAULT_ALLOCATE_START_TIME = '08:00';
|
||||
const ALLOCATE_START_TIME_MIN = '00:00';
|
||||
const ALLOCATE_START_TIME_MAX = '23:59';
|
||||
// 自然日开始时间(业务日分界点):今日统计窗口 = [该时间点, 次日该时间点)
|
||||
const DEFAULT_DAY_START_TIME = '06:00';
|
||||
const DAY_START_TIME_MIN = '00:00';
|
||||
const DAY_START_TIME_MAX = '23:59';
|
||||
|
||||
// 收货未入库提醒:默认关闭,开启后每天按 notice_time 扫描超时未入库的收货单
|
||||
const DEFAULT_PENDING_RECEIVING_NOTICE_TIME = '08:30';
|
||||
@ -103,10 +106,12 @@ module.exports = app => {
|
||||
stock_static_hours: 168,
|
||||
return_unpack_max_record_minutes: 5,
|
||||
inventory_warning_rules: DEFAULT_INVENTORY_WARNING_RULES,
|
||||
auto_outbound_enabled: DEFAULT_AUTO_OUTBOUND_ENABLED,
|
||||
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,
|
||||
day_start_time: DEFAULT_DAY_START_TIME,
|
||||
receiving_pending_inbound_notice: DEFAULT_RECEIVING_PENDING_INBOUND_NOTICE,
|
||||
inbox_push_retry: DEFAULT_INBOX_PUSH_RETRY,
|
||||
});
|
||||
@ -188,61 +193,106 @@ module.exports = app => {
|
||||
};
|
||||
|
||||
/**
|
||||
* 规范化 HH:mm 时间文本。
|
||||
* 缺省或格式非法时回退指定默认值。
|
||||
* 规范化 HH:mm 时间文本(支持跨天:小时最大 maxHour)。
|
||||
* 缺省或格式非法(含超出 maxHour)时回退指定默认值。
|
||||
*
|
||||
* @param {string|undefined|null} value 原始时间文本。
|
||||
* @param {string} defaultValue 默认 HH:mm。
|
||||
* @param {number} [maxHour=23] 允许的最大小时(放开时间用 47,表示可跨到次日)。
|
||||
* @return {string} 规范化后的 HH:mm 文本。
|
||||
*/
|
||||
const normalizeHourMinuteTime = (value, defaultValue) => {
|
||||
const normalizeHourMinuteTime = (value, defaultValue, maxHour = 23) => {
|
||||
if (value === undefined || value === null || value === '') {
|
||||
return defaultValue;
|
||||
}
|
||||
const text = String(value).trim();
|
||||
return /^([01]\d|2[0-3]):[0-5]\d$/.test(text) ? text : defaultValue;
|
||||
const match = /^(\d{1,2}):([0-5]\d)$/.exec(text);
|
||||
if (!match || Number(match[1]) > maxHour) {
|
||||
return defaultValue;
|
||||
}
|
||||
return `${String(Number(match[1])).padStart(2, '0')}:${match[2]}`;
|
||||
};
|
||||
|
||||
/**
|
||||
* 将 HH:mm 文本解析为总分钟数(用于时间先后比较)。
|
||||
* 将 HH:mm 文本解析为总分钟数(支持跨天,用于时间先后比较)。
|
||||
*
|
||||
* @param {string} timeText HH:mm 文本。
|
||||
* @param {string} timeText HH:mm 文本(小时可超过 23)。
|
||||
* @return {number} 总分钟数。
|
||||
*/
|
||||
const parseHourMinuteToMinutes = timeText => {
|
||||
const match = /^(\d{2}):(\d{2})$/.exec(String(timeText || '').trim());
|
||||
const match = /^(\d{1,2}):(\d{2})$/.exec(String(timeText || '').trim());
|
||||
if (!match) return 0;
|
||||
return Number(match[1]) * 60 + Number(match[2]);
|
||||
};
|
||||
|
||||
/**
|
||||
* 规范化「允许当天出库最后时间」配置(HH:mm)。
|
||||
* 规范化「允许当天出库最后时间」配置(HH:mm,当天内 00:00~23:59)。
|
||||
* 缺省或格式非法时回退默认 06:00。
|
||||
*
|
||||
* @param {string|undefined|null} value 原始时间文本。
|
||||
* @return {string} 规范化后的 HH:mm 文本。
|
||||
*/
|
||||
const normalizeSameDayOutboundDeadlineTime = value => normalizeHourMinuteTime(value, DEFAULT_SAME_DAY_OUTBOUND_DEADLINE_TIME);
|
||||
const normalizeSameDayOutboundDeadlineTime = value => normalizeHourMinuteTime(value, DEFAULT_SAME_DAY_OUTBOUND_DEADLINE_TIME, 23);
|
||||
|
||||
/**
|
||||
* 规范化「当天放开时间」配置(HH:mm)。
|
||||
* 规范化「放行时间」配置(HH:mm,支持跨天 00:00~47:59,如 27:00 = 次日 03:00)。
|
||||
* 缺省或格式非法时回退默认 22:00。
|
||||
*
|
||||
* @param {string|undefined|null} value 原始时间文本。
|
||||
* @return {string} 规范化后的 HH:mm 文本。
|
||||
*/
|
||||
const normalizeSameDayOutboundReleaseTime = value => normalizeHourMinuteTime(value, DEFAULT_SAME_DAY_OUTBOUND_RELEASE_TIME);
|
||||
const normalizeSameDayOutboundReleaseTime = value => normalizeHourMinuteTime(value, DEFAULT_SAME_DAY_OUTBOUND_RELEASE_TIME, 47);
|
||||
|
||||
/**
|
||||
* 规范化自动化出库规则配置。
|
||||
* 确保 enabled/require_recheck/require_pack/require_weigh/require_sync/require_print/require_pick 等字段存在且类型正确。
|
||||
* 规范化单条自动出库规则。
|
||||
* 字段:require_pack(需已打包) / require_weigh(需已称重) / require_sync(需已同步)
|
||||
* / exclude_same_day_outbound(不出库当天订单) / same_day_outbound_deadline_time
|
||||
* / same_day_outbound_release_time。
|
||||
* 三个 require_* 沿用「非 false 即 true(缺省开启)」口径;非对象项、时间越界抛错。
|
||||
*
|
||||
* @param {Object|undefined|null} rawRules 原始自动化出库规则。
|
||||
* @return {Object} 规范化后的自动化出库规则对象。
|
||||
* @param {Object} rawRule 原始单条规则。
|
||||
* @param {number} index 规则下标(用于报错定位)。
|
||||
* @return {Object} 规范化后的单条规则。
|
||||
*/
|
||||
const normalizeAutoOutboundRule = (rawRule, index) => {
|
||||
const basePath = `subject_config.auto_outbound_rules[${index}]`;
|
||||
|
||||
if (!rawRule || typeof rawRule !== 'object' || Array.isArray(rawRule)) {
|
||||
throw new Error(`${basePath} 必须是对象`);
|
||||
}
|
||||
|
||||
const sameDayOutboundDeadlineTime = normalizeSameDayOutboundDeadlineTime(rawRule.same_day_outbound_deadline_time);
|
||||
const sameDayOutboundReleaseTime = normalizeSameDayOutboundReleaseTime(rawRule.same_day_outbound_release_time);
|
||||
|
||||
// 保存时校验:允许当天出库最后时间不能大于当天放开时间
|
||||
if (parseHourMinuteToMinutes(sameDayOutboundDeadlineTime) > parseHourMinuteToMinutes(sameDayOutboundReleaseTime)) {
|
||||
throw new Error(`自动出库规则第 ${index + 1} 条:允许当天出库最后时间不能大于当天放开时间`);
|
||||
}
|
||||
|
||||
return {
|
||||
require_pack: rawRule.require_pack !== false,
|
||||
require_weigh: rawRule.require_weigh !== false,
|
||||
require_sync: rawRule.require_sync !== false,
|
||||
exclude_same_day_outbound: normalizeBooleanFlag(
|
||||
rawRule.exclude_same_day_outbound,
|
||||
`${basePath}.exclude_same_day_outbound`
|
||||
) !== false,
|
||||
same_day_outbound_deadline_time: sameDayOutboundDeadlineTime,
|
||||
same_day_outbound_release_time: sameDayOutboundReleaseTime,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 规范化自动出库规则数组。
|
||||
* 旧版本的对象结构(含 enabled/require_recheck/require_print/require_pick)不兼容:
|
||||
* 一律按默认(空数组)处理,需重新配置。
|
||||
*
|
||||
* @param {Array|Object|string|undefined|null} rawRules 原始自动出库规则。
|
||||
* @return {Array<Object>} 规范化后的自动出库规则数组。
|
||||
*/
|
||||
const normalizeAutoOutboundRules = rawRules => {
|
||||
if (rawRules === undefined || rawRules === null || rawRules === '') {
|
||||
return { ...DEFAULT_AUTO_OUTBOUND_RULES };
|
||||
return [];
|
||||
}
|
||||
|
||||
let parsed = rawRules;
|
||||
@ -250,34 +300,15 @@ module.exports = app => {
|
||||
try {
|
||||
parsed = JSON.parse(parsed);
|
||||
} catch (error) {
|
||||
return { ...DEFAULT_AUTO_OUTBOUND_RULES };
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
||||
return { ...DEFAULT_AUTO_OUTBOUND_RULES };
|
||||
if (!Array.isArray(parsed)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const sameDayOutboundDeadlineTime = normalizeSameDayOutboundDeadlineTime(parsed.same_day_outbound_deadline_time);
|
||||
const sameDayOutboundReleaseTime = normalizeSameDayOutboundReleaseTime(parsed.same_day_outbound_release_time);
|
||||
|
||||
// 保存时校验:允许当天出库最后时间不能大于当天放开时间
|
||||
if (parseHourMinuteToMinutes(sameDayOutboundDeadlineTime) > parseHourMinuteToMinutes(sameDayOutboundReleaseTime)) {
|
||||
throw new Error('自动出库规则:允许当天出库最后时间不能大于当天放开时间');
|
||||
}
|
||||
|
||||
return {
|
||||
enabled: normalizeBooleanFlag(parsed.enabled, 'auto_outbound_rules.enabled') === true,
|
||||
require_recheck: parsed.require_recheck !== false,
|
||||
require_pack: parsed.require_pack !== false,
|
||||
require_weigh: parsed.require_weigh !== false,
|
||||
require_sync: parsed.require_sync !== false,
|
||||
require_print: parsed.require_print !== false,
|
||||
require_pick: parsed.require_pick !== false,
|
||||
exclude_same_day_outbound: normalizeBooleanFlag(parsed.exclude_same_day_outbound, 'auto_outbound_rules.exclude_same_day_outbound') !== false,
|
||||
same_day_outbound_deadline_time: sameDayOutboundDeadlineTime,
|
||||
same_day_outbound_release_time: sameDayOutboundReleaseTime,
|
||||
};
|
||||
return parsed.map((rule, index) => normalizeAutoOutboundRule(rule, index));
|
||||
};
|
||||
|
||||
/**
|
||||
@ -449,6 +480,7 @@ module.exports = app => {
|
||||
return {
|
||||
...DEFAULT_SUBJECT_CONFIG,
|
||||
inventory_warning_rules: getDefaultInventoryWarningRules(),
|
||||
auto_outbound_rules: getDefaultAutoOutboundRules(),
|
||||
};
|
||||
}
|
||||
|
||||
@ -645,6 +677,10 @@ module.exports = app => {
|
||||
}
|
||||
|
||||
normalized.inventory_warning_rules = normalizeInventoryWarningRules(parsed.inventory_warning_rules);
|
||||
normalized.auto_outbound_enabled = normalizeBooleanFlag(
|
||||
parsed.auto_outbound_enabled,
|
||||
'subject_config.auto_outbound_enabled'
|
||||
) === true;
|
||||
normalized.auto_outbound_rules = normalizeAutoOutboundRules(parsed.auto_outbound_rules);
|
||||
normalized.receiving_pending_inbound_notice = normalizeReceivingPendingInboundNotice(
|
||||
parsed.receiving_pending_inbound_notice
|
||||
@ -693,6 +729,21 @@ module.exports = app => {
|
||||
normalized.allocate_start_time = DEFAULT_ALLOCATE_START_TIME;
|
||||
}
|
||||
|
||||
if (Object.prototype.hasOwnProperty.call(parsed, 'day_start_time')) {
|
||||
const dayStartTime = normalizeSubjectConfigText(parsed.day_start_time, DEFAULT_DAY_START_TIME);
|
||||
if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(dayStartTime)) {
|
||||
throw new Error('subject_config.day_start_time 格式必须为 HH:mm(如 06:00)');
|
||||
}
|
||||
if (dayStartTime < DAY_START_TIME_MIN || dayStartTime > DAY_START_TIME_MAX) {
|
||||
normalized.day_start_time = DEFAULT_DAY_START_TIME;
|
||||
} else {
|
||||
normalized.day_start_time = dayStartTime;
|
||||
}
|
||||
} else {
|
||||
// 旧数据补齐默认自然日开始时间
|
||||
normalized.day_start_time = DEFAULT_DAY_START_TIME;
|
||||
}
|
||||
|
||||
// 跨字段校验:仅当显式同时提交两个时间字段且相等时拒绝(自动分配窗口为空)
|
||||
if (Object.prototype.hasOwnProperty.call(parsed, 'allocate_start_time')
|
||||
&& Object.prototype.hasOwnProperty.call(parsed, 'cutoff_order_time')
|
||||
@ -927,6 +978,7 @@ module.exports = app => {
|
||||
Store.DEFAULT_INVENTORY_WARNING_RULES = DEFAULT_INVENTORY_WARNING_RULES;
|
||||
Store.DEFAULT_SUBJECT_CONFIG = DEFAULT_SUBJECT_CONFIG;
|
||||
Store.normalizeSubjectConfig = normalizeSubjectConfig;
|
||||
Store.normalizeAutoOutboundRules = normalizeAutoOutboundRules;
|
||||
|
||||
// 实例方法:检查商家是否启用
|
||||
Store.prototype.isEnabled = function() {
|
||||
|
||||
@ -12,6 +12,10 @@ module.exports = app => {
|
||||
router.get('/Authorization', controller.wechatOpen.authorization);
|
||||
router.post('/Authorization', controller.wechatOpen.authorization);
|
||||
|
||||
// 授权方(小程序/公众号)消息与事件推送(GET=URL验证,POST=事件推送)
|
||||
router.get('/events/appid/:appid', controller.wechatOpen.events);
|
||||
router.post('/events/appid/:appid', controller.wechatOpen.events);
|
||||
|
||||
// 内部网关接口
|
||||
router.post('/internal/v1/gateway', controller.gateway.internal);
|
||||
|
||||
@ -72,6 +76,10 @@ module.exports = app => {
|
||||
|
||||
// 测试接口
|
||||
router.get('/testSendData', controller.home.testSendData);
|
||||
|
||||
// 扫描报文接收(联调入口,POST)
|
||||
router.post('/scan', controller.home.scan);
|
||||
|
||||
// IM交互入口
|
||||
router.post('/im', controller.im.index);
|
||||
};
|
||||
|
||||
@ -2,20 +2,22 @@
|
||||
|
||||
/**
|
||||
* 自动化出库定时任务。
|
||||
* 每分钟在单 worker 中扫描一次:当订单满足仓库配置的自动化出库条件时,
|
||||
* 自动标记出库并将订单状态更新为已完成。
|
||||
* 每分钟在单 worker 中扫描一次:当订单满足仓库配置的自动化出库规则时,
|
||||
* 自动标记出库并将订单状态更新为已完成,同时写入订单操作日志(ORDER_AUTO_OUTBOUND)。
|
||||
*
|
||||
* 出库条件(由仓库 subject_config.auto_outbound_rules 控制):
|
||||
* 1. 已复核:recheck_status = 'fin'
|
||||
* 2. 已打包:pack_status = 'fin'
|
||||
* 3. 已称重:wms_order_express.weighing_weight > 0
|
||||
* 4. 已同步:sync_status = 'fin'
|
||||
* 5. 已打印:print_status = 'fin'
|
||||
* 6. 已拣货:pick_status = 'fin'
|
||||
* 开关与规则(仓库 subject_config):
|
||||
* - auto_outbound_enabled:是否启用,默认 false(关闭);
|
||||
* - auto_outbound_rules:规则数组(空数组时不自动出库),每项规则独立判断,任一命中即出库。
|
||||
*
|
||||
* 各条件是否必须可由仓库配置独立控制。
|
||||
* 固定基线条件:已复核(recheck_status='fin')+ 已分配储位(storage_status='fin'),
|
||||
* 未复核订单一律不自动出库。
|
||||
*
|
||||
* 当天订单限制(exclude_same_day_outbound,默认 true):
|
||||
* 单条规则可选条件(仅校验这三项):
|
||||
* 1. 已打包:pack_status = 'fin'(require_pack)
|
||||
* 2. 已称重:wms_order_express.weighing_weight > 0(require_weigh)
|
||||
* 3. 已同步:sync_status = 'fin'(require_sync)
|
||||
*
|
||||
* 当天订单限制(exclude_same_day_outbound,默认 true,按规则独立生效):
|
||||
* 开启时,在当天放开时间(same_day_outbound_release_time,默认北京时间 22:00)前,
|
||||
* 北京时间当天「允许当天出库最后时间」(same_day_outbound_deadline_time,默认 06:00)
|
||||
* 起复核(recheck_time)的订单不自动出库;
|
||||
|
||||
@ -800,8 +800,25 @@ class InboxFunctionsService extends Service {
|
||||
} catch (_err) { /* 定位失败,降级三表遍历 */ }
|
||||
}
|
||||
|
||||
if (!found) {
|
||||
// 用运单关联的发货单号精确查找订单
|
||||
if (!found && exactOrderId > 0) {
|
||||
// 序列表未命中 → 三表按订单主键遍历(主键唯一,避免按发货单号跨货主串单)
|
||||
for (const cfg of tableConfigs) {
|
||||
const model = await cfg.getModel(factory, warehouseId);
|
||||
if (!model) continue;
|
||||
const row = await model.findOne({
|
||||
attributes,
|
||||
where: { id: exactOrderId, store_id: storeId },
|
||||
raw: true,
|
||||
});
|
||||
if (row) {
|
||||
found = { table: cfg.key, table_label: cfg.label, ...row };
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!found && exactExpress.delivery_order_code) {
|
||||
// 兼容历史运单(order_id 缺失)时按发货单号兜底;已限定 store_id,单号唯一
|
||||
found = await findInDeliveryTables({
|
||||
store_id: storeId,
|
||||
delivery_order_code: exactExpress.delivery_order_code,
|
||||
@ -827,12 +844,12 @@ class InboxFunctionsService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
// ========== 第三步:查关联运单信息 ==========
|
||||
// ========== 第三步:查关联运单信息(按订单主键,不用发货单号)==========
|
||||
const linkedExpress = await ctx.model.OrderExpress.findAll({
|
||||
attributes: [ 'waybill_code', 'logistics_name', 'weighing_weight', 'status', 'is_galaxy_receive' ],
|
||||
where: {
|
||||
delivery_order_code: found.delivery_order_code,
|
||||
store_id: storeId,
|
||||
order_id: found.id,
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
raw: true,
|
||||
});
|
||||
|
||||
@ -1794,6 +1794,9 @@ class RecheckOrderService extends OrderBaseService {
|
||||
// 若全部完成则更新波次状态为复核完成(wave_status=5),使波次从 batchList 中消失
|
||||
await this._tryCompleteWaveIfAllOrdersRechecked(orderId, order.wave_id, warehouseId, operator, now);
|
||||
|
||||
// 通知仓库面板刷新(大屏增量更新,失败不影响主流程)
|
||||
await this.service.systems.warehousePanel.touchLastChangeAt(Number(warehouseId));
|
||||
|
||||
return {
|
||||
order_id: orderId,
|
||||
waybill_no: waybillNo,
|
||||
@ -2013,6 +2016,9 @@ class RecheckOrderService extends OrderBaseService {
|
||||
now,
|
||||
});
|
||||
|
||||
// 通知仓库面板刷新(大屏增量更新,失败不影响主流程)
|
||||
await this.service.systems.warehousePanel.touchLastChangeAt(Number(warehouseId));
|
||||
|
||||
return {
|
||||
wave_id: normalizedWaveId,
|
||||
success_count: normalOrders.length,
|
||||
@ -4251,6 +4257,9 @@ class RecheckOrderService extends OrderBaseService {
|
||||
}
|
||||
}
|
||||
|
||||
// 通知仓库面板刷新(大屏增量更新,失败不影响主流程)
|
||||
await this.service.systems.warehousePanel.touchLastChangeAt(Number(warehouseId));
|
||||
|
||||
return {
|
||||
success: successOrders,
|
||||
failed: failedOrders,
|
||||
@ -4444,6 +4453,9 @@ class RecheckOrderService extends OrderBaseService {
|
||||
}
|
||||
}
|
||||
|
||||
// 通知仓库面板刷新(大屏增量更新,失败不影响主流程)
|
||||
await this.service.systems.warehousePanel.touchLastChangeAt(Number(warehouseId));
|
||||
|
||||
return {
|
||||
success: allSuccessOrders,
|
||||
failed: allFailedOrders,
|
||||
|
||||
@ -24,14 +24,13 @@ class OutboundService extends MainService {
|
||||
/**
|
||||
* 手动触发自动化出库扫描。
|
||||
*
|
||||
* 扫描当前仓库下满足自动化出库条件的订单并执行出库操作。
|
||||
* 条件由仓库 subject_config.auto_outbound_rules 控制:
|
||||
* - recheck_status = 'fin'(已复核)
|
||||
* - pack_status = 'fin'(已打包)
|
||||
* - wms_order_express.weighing_weight > 0(已称重)
|
||||
* - sync_status = 'fin'(已同步)
|
||||
* - print_status = 'fin'(已打印)
|
||||
* - pick_status = 'fin'(已拣货)
|
||||
* 扫描当前仓库下满足自动化出库规则的订单并执行出库操作(任一规则命中即出库)。
|
||||
* 开关与规则由仓库 subject_config 控制:
|
||||
* - auto_outbound_enabled:是否启用(默认关闭);
|
||||
* - auto_outbound_rules:规则数组(空数组时不执行),每项仅校验:
|
||||
* require_pack(pack_status='fin')/ require_weigh(wms_order_express.weighing_weight>0)
|
||||
* / require_sync(sync_status='fin')。
|
||||
* 固定基线条件:已复核(recheck_status='fin')+ 已分配储位(storage_status='fin')。
|
||||
*
|
||||
* @param {Object} data 请求参数。
|
||||
* @param {number} [data.warehouseId] 指定仓库ID,不传则使用当前用户上下文仓库。
|
||||
@ -71,13 +70,19 @@ class OutboundService extends MainService {
|
||||
}
|
||||
}
|
||||
|
||||
const autoOutboundRules = subjectConfig && subjectConfig.auto_outbound_rules;
|
||||
const orderAutoOutboundService = ctx.service.systems.orderAutoOutbound;
|
||||
|
||||
if (!autoOutboundRules || !autoOutboundRules.enabled) {
|
||||
if (!orderAutoOutboundService.isAutoOutboundEnabled(subjectConfig)) {
|
||||
throw new Error('当前仓库未启用自动化出库');
|
||||
}
|
||||
|
||||
const result = await ctx.service.systems.orderAutoOutbound.processWarehouseAutoOutbound(
|
||||
const autoOutboundRules = orderAutoOutboundService.resolveAutoOutboundRules(subjectConfig);
|
||||
|
||||
if (autoOutboundRules.length === 0) {
|
||||
throw new Error('当前仓库未配置自动化出库规则');
|
||||
}
|
||||
|
||||
const result = await orderAutoOutboundService.processWarehouseAutoOutbound(
|
||||
warehouseId,
|
||||
autoOutboundRules
|
||||
);
|
||||
|
||||
@ -11,7 +11,8 @@ class WechatService extends MainService {
|
||||
// getAuthUrl:需登录、免权限、不记系统日志;loginByCode/getUserAgreementText:免登录、免权限、免鉴权;
|
||||
// pushLoginCode/queryauth/wxaauth/registerMiniprogram/getTemplateList/commit/getTrialQRCode/submitAudit/userList/getUserAgreement/setUserAgreement/getAgreementVersion:需登录、免权限(PC 已登录用户操作);
|
||||
// bindUser/updateInfo/uploadHeadimg/getMyLoginCode:微信登录态中间层(_noNeedBind),未绑定真实用户也可访问
|
||||
this.systemInit('loginByCode,getUserAgreementText', 'getAuthUrl,pushLoginCode,queryauth,wxaauth,registerMiniprogram,getTemplateList,commit,getTrialQRCode,submitAudit,userList,getAuthorizerInfo,getUserAgreement,setUserAgreement,getAgreementVersion', '*', 'getAuthUrl,pushLoginCode,queryauth,wxaauth,registerMiniprogram,getTemplateList,commit,getTrialQRCode,submitAudit,userList,getAuthorizerInfo,getUserAgreement,setUserAgreement,getAgreementVersion', 'bindUser,updateInfo,uploadHeadimg,getMyLoginCode');
|
||||
// _noNeedLog:除 loginByCode 外其余方法不记系统日志(loginByCode 保留日志,便于排查登录请求的入参出参)
|
||||
this.systemInit('loginByCode,getUserAgreementText', 'getAuthUrl,pushLoginCode,queryauth,wxaauth,registerMiniprogram,getTemplateList,commit,getTrialQRCode,submitAudit,userList,getAuthorizerInfo,getUserAgreement,setUserAgreement,getAgreementVersion', 'getAuthUrl,getUserAgreementText,getMyLoginCode,bindUser,bindByEmployee,pushLoginCode,queryauth,wxaauth,registerMiniprogram,updateInfo,uploadHeadimg,getTemplateList,getAuthorizerInfo,commit,submitAudit,getTrialQRCode,userList,getUserAgreement,setUserAgreement,getAgreementVersion', 'getAuthUrl,pushLoginCode,queryauth,wxaauth,registerMiniprogram,getTemplateList,commit,getTrialQRCode,submitAudit,userList,getAuthorizerInfo,getUserAgreement,setUserAgreement,getAgreementVersion', 'bindUser,updateInfo,uploadHeadimg,getMyLoginCode');
|
||||
}
|
||||
|
||||
/**
|
||||
@ -298,7 +299,7 @@ class WechatService extends MainService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取小程序模板库列表(需登录,Redis 缓存 24h)。
|
||||
* 获取小程序模板库列表(需登录,实时拉取,不缓存)。
|
||||
*
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
|
||||
@ -8,22 +8,35 @@ const OUTBOUND_STEP = 4;
|
||||
const ORDER_STATUS_FINISHED = 'finished';
|
||||
const MAX_BATCH_SIZE = 500;
|
||||
const STORAGE_STATUS_FIN = 'fin';
|
||||
const RECHECK_STATUS_FIN = 'fin';
|
||||
const DAY_MS = 24 * 3600 * 1000;
|
||||
const BEIJING_OFFSET_MS = 8 * 3600 * 1000;
|
||||
// 出库操作日志编码(app/dict/businessDict.js OPERATION_CODE)
|
||||
const AUTO_OUTBOUND_OPERATION_CODE = 'ORDER_AUTO_OUTBOUND';
|
||||
// 定时任务无用户上下文,按系统操作人记录
|
||||
const AUTO_OUTBOUND_OPERATOR = Object.freeze({ id: null, name: '系统' });
|
||||
|
||||
/**
|
||||
* 订单自动化出库服务。
|
||||
* 当订单满足仓库配置的自动化出库规则时,自动标记出库并完成订单。
|
||||
*
|
||||
* 当仓库开启 auto_outbound_enabled 且配置了 auto_outbound_rules(数组,任一命中即出库)时,
|
||||
* 自动将满足条件的订单标记为出库并将订单状态更新为已完成。
|
||||
* 规则前置条件固定为「已复核」(recheck_status=fin)+「已分配储位」(storage_status=fin)。
|
||||
*/
|
||||
class OrderAutoOutboundService extends MainService {
|
||||
/**
|
||||
* 获取所有启用了自动化出库的仓库配置。
|
||||
* 获取所有启用了自动化出库且配置了规则的仓库。
|
||||
*
|
||||
* @return {Promise<Array<{storeId: number, warehouseId: number, rules: Object}>>} 仓库配置列表。
|
||||
* 自动出库配置以仓库为单位生效(wms_store.id 即 warehouse_id),
|
||||
* 处理范围仅限当前仓库,不再扩散到该货主签约的外部合同仓。
|
||||
*
|
||||
* @return {Promise<Array<{storeId: number, warehouseId: number, rules: Array<Object>}>>} 仓库配置列表。
|
||||
*/
|
||||
async getEnabledAutoOutboundWarehouses() {
|
||||
const { app } = this;
|
||||
const { Store, StoreWarehouse } = app.model;
|
||||
const { Store } = app.model;
|
||||
|
||||
if (!Store || !StoreWarehouse) {
|
||||
if (!Store) {
|
||||
return [];
|
||||
}
|
||||
|
||||
@ -39,48 +52,68 @@ class OrderAutoOutboundService extends MainService {
|
||||
const result = [];
|
||||
|
||||
for (const store of stores) {
|
||||
const subjectConfig = this.normalizeSubjectConfigForAutoOutbound(store.subject_config);
|
||||
const autoOutboundRules = subjectConfig && subjectConfig.auto_outbound_rules;
|
||||
|
||||
if (!autoOutboundRules || !autoOutboundRules.enabled) {
|
||||
if (!this.isAutoOutboundEnabled(store.subject_config)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const contracts = await StoreWarehouse.findAll({
|
||||
where: {
|
||||
store_id: store.id,
|
||||
auth_status: 2,
|
||||
},
|
||||
attributes: [ 'warehouse_id' ],
|
||||
raw: true,
|
||||
});
|
||||
const rules = this.resolveAutoOutboundRules(store.subject_config);
|
||||
|
||||
// 空数组表示不出库任何订单,直接跳过(无需告警)
|
||||
if (rules.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 始终将 store.id 自身的仓库加入扫描(store.id 即 warehouse_id)
|
||||
const scannedWarehouseIds = new Set();
|
||||
result.push({
|
||||
storeId: store.id,
|
||||
warehouseId: store.id,
|
||||
rules: autoOutboundRules,
|
||||
rules,
|
||||
});
|
||||
scannedWarehouseIds.add(store.id);
|
||||
|
||||
// 追加外部合同中的仓库(去重)
|
||||
for (const contract of contracts) {
|
||||
const contractWarehouseId = contract.warehouse_id;
|
||||
if (!scannedWarehouseIds.has(contractWarehouseId)) {
|
||||
result.push({
|
||||
storeId: store.id,
|
||||
warehouseId: contractWarehouseId,
|
||||
rules: autoOutboundRules,
|
||||
});
|
||||
scannedWarehouseIds.add(contractWarehouseId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断仓库是否启用自动出库(subject_config.auto_outbound_enabled)。
|
||||
*
|
||||
* @param {Object|string|null|undefined} rawConfig subject_config 原始值。
|
||||
* @return {boolean} 是否启用。
|
||||
*/
|
||||
isAutoOutboundEnabled(rawConfig) {
|
||||
const subjectConfig = this.normalizeSubjectConfigForAutoOutbound(rawConfig);
|
||||
const enabled = subjectConfig && subjectConfig.auto_outbound_enabled;
|
||||
|
||||
return enabled === true || enabled === 1 || enabled === '1' || enabled === 'true';
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析自动出库规则数组(复用 Store 模型归一化,补齐缺省字段)。
|
||||
* 旧对象结构或非法规则一律按空数组处理(空数组 = 不出库任何订单)。
|
||||
*
|
||||
* @param {Object|string|null|undefined} rawConfig subject_config 原始值。
|
||||
* @return {Array<Object>} 规则数组。
|
||||
*/
|
||||
resolveAutoOutboundRules(rawConfig) {
|
||||
const subjectConfig = this.normalizeSubjectConfigForAutoOutbound(rawConfig);
|
||||
const rules = subjectConfig && subjectConfig.auto_outbound_rules;
|
||||
const storeModel = this.app && this.app.model && this.app.model.Store;
|
||||
|
||||
if (storeModel && typeof storeModel.normalizeAutoOutboundRules === 'function') {
|
||||
try {
|
||||
return storeModel.normalizeAutoOutboundRules(rules);
|
||||
} catch (error) {
|
||||
this.ctx.logger.warn(`[auto-outbound] 自动出库规则配置非法,已按空规则处理: ${error.message}`);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
if (!Array.isArray(rules)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return rules.filter(rule => rule && typeof rule === 'object' && !Array.isArray(rule));
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化 subject_config,支持字符串 JSON 和对象两种格式。
|
||||
*
|
||||
@ -108,186 +141,262 @@ class OrderAutoOutboundService extends MainService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造自动化出库的订单查询条件。
|
||||
* 根据配置规则组合各状态字段的 WHERE 条件。
|
||||
* 构造单条自动化出库规则的订单查询条件。
|
||||
*
|
||||
* 基础条件(所有规则固定):已复核(recheck_status='fin')+ 已分配储位(storage_status='fin')
|
||||
* + 未出库(outbound_status='none')+ 状态非 cancel/error/finished。
|
||||
*
|
||||
* @param {Object} rule 自动化出库规则(单条),支持字段:
|
||||
* - {boolean} [rule.require_pack] 是否要求已打包(pack_status='fin')
|
||||
* - {boolean} [rule.require_sync] 是否要求已同步(sync_status='fin')
|
||||
* - {boolean} [rule.exclude_same_day_outbound] 是否不出库当天复核订单(默认 true);
|
||||
* 开启后按「复核时间所在北京日 D」判定:
|
||||
* recheck_time < D + deadline(默认 06:00)的订单不受影响;
|
||||
* recheck_time ≥ D + deadline 的订单在 now < D + release(默认 22:00)前不出库,到达后放行。
|
||||
* release 支持跨天(最大 47:59),如 27:00 表示次日 03:00 放行;
|
||||
* recheck_time 为 null 的订单不受限制。
|
||||
* - {string} [rule.same_day_outbound_deadline_time] 允许当天出库最后时间(HH:mm,默认 '06:00',当天内)。
|
||||
* - {string} [rule.same_day_outbound_release_time] 放行时间(HH:mm,默认 '22:00',支持 00:00~47:59)。
|
||||
* 常用组合:deadline='00:00' + release='23:59' → 当天复核的订单当天不出库,过了零点全部出库;
|
||||
* deadline='00:00' + release='27:00' → 到次日 03:00 才全部出库。
|
||||
* 注:require_weigh(已称重)涉及 wms_order_express,由调用方通过订单ID 子集约束,不在此处拼装。
|
||||
*
|
||||
* @param {Object} rules 自动化出库规则,包含以下可选字段:
|
||||
* - {boolean} [rules.require_recheck] 是否要求已复核(recheck_status='fin')
|
||||
* - {boolean} [rules.require_pack] 是否要求已打包(pack_status='fin')
|
||||
* - {boolean} [rules.require_sync] 是否要求已同步(sync_status='fin')
|
||||
* - {boolean} [rules.require_print] 是否要求已打印(print_status='fin')
|
||||
* - {boolean} [rules.require_pick] 是否要求已拣货(pick_status='fin')
|
||||
* - {boolean} [rules.exclude_same_day_outbound] 是否不出库当天复核订单(默认 true);
|
||||
* 为 true 时,在到达当天放开时间(same_day_outbound_release_time,默认北京时间 22:00)前,
|
||||
* 北京时间当天「允许当天出库最后时间」(same_day_outbound_deadline_time,默认 06:00)起复核(recheck_time)的订单当天不参与自动出库;
|
||||
* recheck_time 早于该最后时间或为 null 的订单不受影响;
|
||||
* 到达放开时间后当天复核订单恢复自动出库。
|
||||
* - {string} [rules.same_day_outbound_deadline_time] 允许当天出库最后时间(HH:mm,默认 '06:00'),
|
||||
* 复核时间早于该时间的订单不受「不出库当天订单」开启的影响。
|
||||
* - {string} [rules.same_day_outbound_release_time] 当天放开时间(HH:mm,默认 '22:00'),
|
||||
* 仅在 exclude_same_day_outbound 为 true 时生效。
|
||||
* @return {Object} Sequelize where 条件对象。
|
||||
*/
|
||||
buildAutoOutboundWhere(rules) {
|
||||
buildAutoOutboundWhere(rule) {
|
||||
const safeRule = rule && typeof rule === 'object' ? rule : {};
|
||||
const where = {
|
||||
outbound_status: 'none',
|
||||
status: {
|
||||
[Op.notIn]: [ 'cancel', 'error', 'finished' ],
|
||||
},
|
||||
storage_status: STORAGE_STATUS_FIN,
|
||||
// 未复核订单一律不自动出库(固定基线)
|
||||
recheck_status: RECHECK_STATUS_FIN,
|
||||
};
|
||||
|
||||
if (rules.require_recheck) {
|
||||
where.recheck_status = 'fin';
|
||||
}
|
||||
|
||||
// 开启「不出库当天订单」(默认开启)时:当天到达放开时间(默认北京时间 22:00)前,
|
||||
// 排除当天「允许当天出库最后时间」(默认 06:00)起复核的订单(recheck_time 为 null 不排除);
|
||||
// 到达放开时间后不再限制当天复核订单,当天即可出库。
|
||||
// 开启「不出库当天订单」(默认开启)时:按复核时间所在北京日计算未放行窗口,
|
||||
// 未放行窗口内的订单(recheck_time ∈ [D+deadline, D+24h) 且 now < D+release)不自动出库。
|
||||
// 注意:应用按 UTC 读写 DATETIME,recheck_time 存储为 UTC 时刻,边界需按北京时间(UTC+8)换算。
|
||||
if (rules.exclude_same_day_outbound !== false) {
|
||||
const now = new Date();
|
||||
const releaseUtc = this.buildSameDayReleaseUtc(now, rules.same_day_outbound_release_time);
|
||||
if (now.getTime() < releaseUtc.getTime()) {
|
||||
const sameDayCutoffUtc = this.buildSameDayOutboundCutoffUtc(now, rules.same_day_outbound_deadline_time);
|
||||
where.recheck_time = {
|
||||
[Op.or]: [
|
||||
{ [Op.lt]: sameDayCutoffUtc },
|
||||
{ [Op.is]: null },
|
||||
],
|
||||
};
|
||||
if (safeRule.exclude_same_day_outbound !== false) {
|
||||
const recheckCondition = this.buildSameDayOutboundRecheckCondition(new Date(), safeRule);
|
||||
if (recheckCondition) {
|
||||
where.recheck_time = recheckCondition;
|
||||
}
|
||||
}
|
||||
|
||||
if (rules.require_pack) {
|
||||
if (safeRule.require_pack) {
|
||||
where.pack_status = 'fin';
|
||||
}
|
||||
|
||||
if (rules.require_sync) {
|
||||
if (safeRule.require_sync) {
|
||||
where.sync_status = 'fin';
|
||||
}
|
||||
|
||||
if (rules.require_print) {
|
||||
where.print_status = 'fin';
|
||||
}
|
||||
|
||||
if (rules.require_pick) {
|
||||
where.pick_status = 'fin';
|
||||
}
|
||||
|
||||
return where;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取仓库下满足自动化出库条件的订单ID列表。
|
||||
* 扫描仓库下命中任一自动出库规则的订单ID。
|
||||
*
|
||||
* 逐条规则查询(规则内条件 AND),命中即纳入结果;订单ID 去重并保留首个命中的规则下标。
|
||||
* 需要称重的规则先取称重订单ID(同仓库只查一次,跨规则复用)。
|
||||
*
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @param {Object} rules 自动化出库规则。
|
||||
* @param {number} [limit=MAX_BATCH_SIZE] 单次扫描上限。
|
||||
* @return {Promise<Array<{id: number}>>} 订单ID列表。
|
||||
* @param {Array<Object>} rules 自动化出库规则数组。
|
||||
* @param {number} [limit=MAX_BATCH_SIZE] 单次扫描上限(按仓库汇总)。
|
||||
* @return {Promise<{orderIds: Array<number>, ruleIndexById: Map<number, number>}>} 命中订单ID与规则下标映射。
|
||||
*/
|
||||
async findAutoOutboundOrders(warehouseId, rules, limit = MAX_BATCH_SIZE) {
|
||||
async findAutoOutboundOrderIds(warehouseId, rules, limit = MAX_BATCH_SIZE) {
|
||||
const { ctx } = this;
|
||||
const factory = ctx.model && ctx.model.OrderDeliveryFactory;
|
||||
const emptyResult = { orderIds: [], ruleIndexById: new Map() };
|
||||
|
||||
if (!factory || typeof factory.getCurrentModel !== 'function') {
|
||||
return [];
|
||||
return emptyResult;
|
||||
}
|
||||
|
||||
const orderModel = await factory.getCurrentModel(warehouseId);
|
||||
if (!orderModel) {
|
||||
return [];
|
||||
return emptyResult;
|
||||
}
|
||||
|
||||
const where = this.buildAutoOutboundWhere(rules);
|
||||
const ruleList = Array.isArray(rules) ? rules : [];
|
||||
const orderIds = [];
|
||||
const ruleIndexById = new Map();
|
||||
let weighOrderIds = null;
|
||||
|
||||
if (rules.require_weigh) {
|
||||
const orderIdsWithWeigh = await this.findOrderIdsWithWeigh(warehouseId);
|
||||
if (orderIdsWithWeigh.length === 0) {
|
||||
return [];
|
||||
for (let index = 0; index < ruleList.length; index += 1) {
|
||||
const remaining = limit - orderIds.length;
|
||||
if (remaining <= 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
const rule = ruleList[index] && typeof ruleList[index] === 'object' ? ruleList[index] : {};
|
||||
const where = this.buildAutoOutboundWhere(rule);
|
||||
|
||||
if (rule.require_weigh) {
|
||||
if (weighOrderIds === null) {
|
||||
weighOrderIds = await this.findOrderIdsWithWeigh(warehouseId);
|
||||
}
|
||||
if (weighOrderIds.length === 0) {
|
||||
continue;
|
||||
}
|
||||
where.id = { [Op.in]: weighOrderIds };
|
||||
}
|
||||
|
||||
const orders = await orderModel.findAll({
|
||||
where,
|
||||
attributes: [ 'id' ],
|
||||
limit: remaining,
|
||||
raw: true,
|
||||
});
|
||||
|
||||
for (const order of orders) {
|
||||
const orderId = Number(order && order.id);
|
||||
if (!Number.isFinite(orderId) || orderId <= 0 || ruleIndexById.has(orderId)) {
|
||||
continue;
|
||||
}
|
||||
ruleIndexById.set(orderId, index);
|
||||
orderIds.push(orderId);
|
||||
}
|
||||
where.id = { [Op.in]: orderIdsWithWeigh };
|
||||
}
|
||||
|
||||
const orders = await orderModel.findAll({
|
||||
where,
|
||||
attributes: [ 'id' ],
|
||||
limit,
|
||||
raw: true,
|
||||
});
|
||||
|
||||
return orders;
|
||||
return { orderIds, ruleIndexById };
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算「允许当天出库最后时间」边界(UTC 时刻)。
|
||||
* 解析 HH:mm 时间配置为小时/分钟,支持跨天(小时可超过 23)。
|
||||
* 缺省、格式非法或超出 maxHour 时回退指定默认值。
|
||||
*
|
||||
* 边界为北京时间当天配置时刻(默认 06:00,UTC+8):
|
||||
* - recheck_time(UTC 存储)早于该边界 → 不受「不出库当天订单」开启影响,当天允许自动出库;
|
||||
* - recheck_time 晚于或等于该边界 → 在到达当天放开时间前不自动出库,
|
||||
* 到达放开时间(默认 22:00)后放开。
|
||||
*
|
||||
* 用 UTC 显式换算,不依赖 Node 进程时区(生产服务器 TZ 可能与北京时间不一致)。
|
||||
*
|
||||
* @param {Date} [now] 当前时刻(用于计算“今天”,默认 new Date())。
|
||||
* @param {string} [timeText] 允许当天出库最后时间(HH:mm,默认 '06:00')。
|
||||
* @return {Date} 北京时间当天该时刻对应的 UTC Date。
|
||||
*/
|
||||
buildSameDayOutboundCutoffUtc(now = new Date(), timeText) {
|
||||
const DAY_MS = 24 * 3600 * 1000;
|
||||
const BEIJING_OFFSET_MS = 8 * 3600 * 1000;
|
||||
const { hour, minute } = this.resolveSameDayTime(timeText, 6, 0);
|
||||
// 当前时刻换算为北京时刻后,取北京当天 0 点的毫秒基准
|
||||
const beijingNowMs = now.getTime() + BEIJING_OFFSET_MS;
|
||||
const beijingMidnightMs = Math.floor(beijingNowMs / DAY_MS) * DAY_MS;
|
||||
return new Date(beijingMidnightMs + hour * 3600 * 1000 + minute * 60 * 1000 - BEIJING_OFFSET_MS);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 HH:mm 时间配置为小时/分钟,缺省或格式非法时回退指定默认值。
|
||||
*
|
||||
* @param {string} [timeText] 时间文本,如 '22:00'。
|
||||
* @param {string} [timeText] 时间文本,如 '22:00'、'27:00'(= 次日 03:00)。
|
||||
* @param {number} defaultHour 默认小时。
|
||||
* @param {number} defaultMinute 默认分钟。
|
||||
* @param {number} [maxHour=23] 允许的最大小时(放开时间支持 47,表示可跨到次日)。
|
||||
* @return {{hour: number, minute: number}} 小时与分钟。
|
||||
*/
|
||||
resolveSameDayTime(timeText, defaultHour, defaultMinute) {
|
||||
resolveSameDayTime(timeText, defaultHour, defaultMinute, maxHour = 23) {
|
||||
const text = typeof timeText === 'string' ? timeText.trim() : '';
|
||||
const match = /^([01]\d|2[0-3]):([0-5]\d)$/.exec(text);
|
||||
const match = /^(\d{1,2}):([0-5]\d)$/.exec(text);
|
||||
if (!match) {
|
||||
return { hour: defaultHour, minute: defaultMinute };
|
||||
}
|
||||
return { hour: Number(match[1]), minute: Number(match[2]) };
|
||||
const hour = Number(match[1]);
|
||||
if (hour > maxHour) {
|
||||
return { hour: defaultHour, minute: defaultMinute };
|
||||
}
|
||||
return { hour, minute: Number(match[2]) };
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析「当天放开时间」配置为小时/分钟(HH:mm)。
|
||||
* 缺省或格式非法时回退默认 22:00。
|
||||
* 解析「允许当天出库最后时间」(当天内,最大 23:59;缺省/非法回退 06:00)。
|
||||
*
|
||||
* @param {string} [timeText] 时间文本,如 '22:00'。
|
||||
* @param {string} [timeText] 时间文本。
|
||||
* @return {{hour: number, minute: number}} 小时与分钟。
|
||||
*/
|
||||
resolveSameDayDeadlineTime(timeText) {
|
||||
return this.resolveSameDayTime(timeText, 6, 0, 23);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析「放行时间」(支持跨天,最大 47:59;27:00 = 次日 03:00;缺省/非法回退 22:00)。
|
||||
*
|
||||
* @param {string} [timeText] 时间文本。
|
||||
* @return {{hour: number, minute: number}} 小时与分钟。
|
||||
*/
|
||||
resolveSameDayReleaseTime(timeText) {
|
||||
return this.resolveSameDayTime(timeText, 22, 0);
|
||||
return this.resolveSameDayTime(timeText, 22, 0, 47);
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算北京时间当天「放开时间」对应的 UTC Date。
|
||||
* 计算北京时间「当天 00:00」对应的 UTC 时刻。
|
||||
*
|
||||
* 仅在开启「不出库当天订单」时使用:当前时刻早于该边界时,
|
||||
* 当天最后时间之后复核的订单不自动出库;晚于或等于该边界时放开。
|
||||
* 用 UTC 显式换算,不依赖 Node 进程时区(生产服务器 TZ 可能与北京时间不一致)。
|
||||
*
|
||||
* @param {Date} [now] 当前时刻(默认 new Date())。
|
||||
* @param {string} [timeText] 放开时间(HH:mm,默认 22:00)。
|
||||
* @return {Date} 北京时间当天放开时间对应的 UTC Date。
|
||||
* @return {Date} 北京时间当天 0 点对应的 UTC Date。
|
||||
*/
|
||||
buildSameDayReleaseUtc(now = new Date(), timeText) {
|
||||
const DAY_MS = 24 * 3600 * 1000;
|
||||
const BEIJING_OFFSET_MS = 8 * 3600 * 1000;
|
||||
const { hour, minute } = this.resolveSameDayReleaseTime(timeText);
|
||||
buildBeijingDayStartUtc(now = new Date()) {
|
||||
const beijingNowMs = now.getTime() + BEIJING_OFFSET_MS;
|
||||
const beijingMidnightMs = Math.floor(beijingNowMs / DAY_MS) * DAY_MS;
|
||||
return new Date(beijingMidnightMs + hour * 3600 * 1000 + minute * 60 * 1000 - BEIJING_OFFSET_MS);
|
||||
return new Date(beijingMidnightMs - BEIJING_OFFSET_MS);
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算「不出库当天订单」的未放行窗口(按**复核时间所在北京日**对齐,支持跨天)。
|
||||
*
|
||||
* 口径(第 D 天复核的订单,D 为复核时间的北京日):
|
||||
* - recheck_time < D + deadline → 不受限制(豁免,照常出库);
|
||||
* - recheck_time ≥ D + deadline 且 now < D + release → 未放行,不出库;
|
||||
* - now ≥ D + release → 放行(照常出库)。
|
||||
*
|
||||
* 由于 release 最大 47:59,复核日只可能是「今天」或「昨天」,故返回至多两个窗口。
|
||||
*
|
||||
* @param {Date} now 当前时刻。
|
||||
* @param {Object} rule 自动化出库规则(单条)。
|
||||
* @return {Array<{start: number, end: number}>} 未放行窗口(UTC 毫秒区间,已合并相邻/重叠)。
|
||||
*/
|
||||
buildSameDayOutboundHoldWindows(now, rule) {
|
||||
const safeRule = rule && typeof rule === 'object' ? rule : {};
|
||||
const release = this.resolveSameDayReleaseTime(safeRule.same_day_outbound_release_time);
|
||||
const deadline = this.resolveSameDayDeadlineTime(safeRule.same_day_outbound_deadline_time);
|
||||
const releaseMs = (release.hour * 60 + release.minute) * 60000;
|
||||
const deadlineMs = (deadline.hour * 60 + deadline.minute) * 60000;
|
||||
const todayStartMs = this.buildBeijingDayStartUtc(now).getTime();
|
||||
|
||||
const windows = [];
|
||||
for (const dayOffset of [ -1, 0 ]) {
|
||||
const dayStartMs = todayStartMs + dayOffset * DAY_MS;
|
||||
if (now.getTime() >= dayStartMs + releaseMs) {
|
||||
continue; // 该复核日的放行时刻已到
|
||||
}
|
||||
windows.push({ start: dayStartMs + deadlineMs, end: dayStartMs + DAY_MS });
|
||||
}
|
||||
|
||||
windows.sort((a, b) => a.start - b.start);
|
||||
const merged = [];
|
||||
for (const window of windows) {
|
||||
const last = merged[merged.length - 1];
|
||||
if (last && window.start <= last.end) {
|
||||
last.end = Math.max(last.end, window.end);
|
||||
} else {
|
||||
merged.push({ ...window });
|
||||
}
|
||||
}
|
||||
|
||||
return merged;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成「不出库当天订单」对 recheck_time 的查询约束(允许集 = 未放行窗口的补集 + NULL)。
|
||||
*
|
||||
* 返回 null 表示当前时刻没有任何未放行窗口(即完全不限制)。
|
||||
*
|
||||
* @param {Date} now 当前时刻。
|
||||
* @param {Object} rule 自动化出库规则(单条)。
|
||||
* @return {Object|null} Sequelize 条件对象或 null。
|
||||
*/
|
||||
buildSameDayOutboundRecheckCondition(now, rule) {
|
||||
const windows = this.buildSameDayOutboundHoldWindows(now, rule);
|
||||
if (windows.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const ranges = [];
|
||||
let cursor = null;
|
||||
for (const window of windows) {
|
||||
if (cursor === null) {
|
||||
ranges.push({ [Op.lt]: new Date(window.start) });
|
||||
} else if (window.start > cursor) {
|
||||
ranges.push({ [Op.gte]: new Date(cursor), [Op.lt]: new Date(window.start) });
|
||||
}
|
||||
cursor = cursor === null ? window.end : Math.max(cursor, window.end);
|
||||
}
|
||||
ranges.push({ [Op.gte]: new Date(cursor) });
|
||||
// recheck_time 为 null 的订单不受限制(既有口径)
|
||||
ranges.push({ [Op.is]: null });
|
||||
|
||||
return { [Op.or]: ranges };
|
||||
}
|
||||
|
||||
/**
|
||||
@ -321,8 +430,11 @@ class OrderAutoOutboundService extends MainService {
|
||||
/**
|
||||
* 对指定仓库执行单次自动化出库扫描与执行。
|
||||
*
|
||||
* 按规则逐条扫描(任一规则命中即出库),订单ID 去重后一次性更新,
|
||||
* 并对本次出库订单写入操作日志(写日志失败仅告警,不影响出库主流程)。
|
||||
*
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @param {Object} rules 自动化出库规则。
|
||||
* @param {Array<Object>} rules 自动化出库规则数组。
|
||||
* @return {Promise<{warehouseId: number, processedCount: number, errorMessage: string|null}>} 执行结果。
|
||||
*/
|
||||
async processWarehouseAutoOutbound(warehouseId, rules) {
|
||||
@ -334,13 +446,8 @@ class OrderAutoOutboundService extends MainService {
|
||||
};
|
||||
|
||||
try {
|
||||
const orders = await this.findAutoOutboundOrders(warehouseId, rules);
|
||||
const { orderIds, ruleIndexById } = await this.findAutoOutboundOrderIds(warehouseId, rules);
|
||||
|
||||
if (!orders || orders.length === 0) {
|
||||
return result;
|
||||
}
|
||||
|
||||
const orderIds = orders.map(order => Number(order.id)).filter(Boolean);
|
||||
if (orderIds.length === 0) {
|
||||
return result;
|
||||
}
|
||||
@ -371,6 +478,8 @@ class OrderAutoOutboundService extends MainService {
|
||||
ctx.logger.info(
|
||||
`[auto-outbound] 仓库 ${warehouseId} 自动化出库 ${result.processedCount} 条订单,订单ID: ${orderIds.join(',')}`
|
||||
);
|
||||
|
||||
await this.writeAutoOutboundOperationLogs(warehouseId, orderIds, rules, ruleIndexById);
|
||||
}
|
||||
} catch (error) {
|
||||
result.errorMessage = error.message;
|
||||
@ -380,6 +489,83 @@ class OrderAutoOutboundService extends MainService {
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入自动出库订单操作日志(business_type=order,operation_code=ORDER_AUTO_OUTBOUND)。
|
||||
*
|
||||
* 日志写入失败仅告警,不影响出库主流程。
|
||||
*
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @param {Array<number>} orderIds 本次出库的订单ID列表。
|
||||
* @param {Array<Object>} rules 自动化出库规则数组。
|
||||
* @param {Map<number, number>} ruleIndexById 订单ID → 命中规则下标。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async writeAutoOutboundOperationLogs(warehouseId, orderIds, rules, ruleIndexById) {
|
||||
const { ctx } = this;
|
||||
const operationLogService = ctx.service
|
||||
&& ctx.service.systems
|
||||
&& ctx.service.systems.operationLog;
|
||||
|
||||
if (!operationLogService || typeof operationLogService.createOperationLogs !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
const ruleList = Array.isArray(rules) ? rules : [];
|
||||
const payloads = orderIds.map(orderId => {
|
||||
const ruleIndex = ruleIndexById && typeof ruleIndexById.get === 'function' && ruleIndexById.has(orderId)
|
||||
? ruleIndexById.get(orderId)
|
||||
: -1;
|
||||
const rule = ruleIndex >= 0 ? ruleList[ruleIndex] : null;
|
||||
|
||||
return {
|
||||
businessType: 'order',
|
||||
businessId: orderId,
|
||||
operationCode: AUTO_OUTBOUND_OPERATION_CODE,
|
||||
operator: AUTO_OUTBOUND_OPERATOR,
|
||||
extras: {
|
||||
warehouseId,
|
||||
message: ruleIndex >= 0
|
||||
? `自动出库(命中规则${ruleIndex + 1}:${this.buildAutoOutboundRuleSummary(rule)})`
|
||||
: '自动出库',
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
try {
|
||||
await operationLogService.createOperationLogs(payloads);
|
||||
} catch (error) {
|
||||
ctx.logger.warn(
|
||||
`[auto-outbound] 仓库 ${warehouseId} 写入自动出库操作日志失败,不影响出库: ${error.message}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成规则条件摘要(用于操作日志 message)。
|
||||
*
|
||||
* @param {Object} rule 自动化出库规则。
|
||||
* @return {string} 规则摘要文本。
|
||||
*/
|
||||
buildAutoOutboundRuleSummary(rule) {
|
||||
const safeRule = rule && typeof rule === 'object' ? rule : {};
|
||||
const conditions = [];
|
||||
|
||||
if (safeRule.require_pack) {
|
||||
conditions.push('需已打包');
|
||||
}
|
||||
if (safeRule.require_weigh) {
|
||||
conditions.push('需已称重');
|
||||
}
|
||||
if (safeRule.require_sync) {
|
||||
conditions.push('需已同步');
|
||||
}
|
||||
if (safeRule.exclude_same_day_outbound !== false) {
|
||||
conditions.push('不出库当天订单');
|
||||
}
|
||||
|
||||
return conditions.length > 0 ? conditions.join('、') : '无附加条件';
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行全局自动化出库扫描。
|
||||
* 遍历所有启用了自动化出库的仓库,对每个仓库扫描并执行符合条件的订单出库。
|
||||
|
||||
@ -1953,6 +1953,7 @@ class PickSystemService extends Service {
|
||||
|
||||
// 检查目标订单是否进入拦截流程,拦截订单直接跳过:
|
||||
// 不完成拣货、不扣减库存(不取出)、不报错,其余订单照常完成
|
||||
// 同时记录打印状态:已打印面单的拦截订单保持不动,不做自动移出波次
|
||||
const skippedInterceptedOrders = [];
|
||||
if (targetOrderIds.length > 0) {
|
||||
const interceptCheckModel = await this.getOrderModel(warehouseId);
|
||||
@ -1966,7 +1967,7 @@ class PickSystemService extends Service {
|
||||
[this.app.Sequelize.Op.ne]: INTERCEPT_STATUS_NONE,
|
||||
},
|
||||
},
|
||||
attributes: [ 'id', 'intercept_status' ],
|
||||
attributes: [ 'id', 'intercept_status', 'print_status' ],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
@ -1979,19 +1980,36 @@ class PickSystemService extends Service {
|
||||
skippedInterceptedOrders.push({
|
||||
order_id: Number(orderRow && orderRow.id || 0),
|
||||
intercept_status: String(orderRow && orderRow.intercept_status || '').trim() || 'none',
|
||||
print_status: String(orderRow && orderRow.print_status || '').trim().toLowerCase() || 'none',
|
||||
});
|
||||
}
|
||||
targetOrderIds = targetOrderIds.filter(orderId => !interceptedOrderIdSet.has(orderId));
|
||||
}
|
||||
}
|
||||
|
||||
// source !== 0(PDA/后台抓取创建的任务)时,被跳过的拦截订单直接从波次中移除:
|
||||
// 订单 wave_id 清零、重建波次索引、回写波次统计,并移除任务订单关联
|
||||
// 已打印面单的拦截订单保持不动:面单实物已在波次流程中,自动移出会导致
|
||||
// 面单与波次记录分离,此类订单需人工通过 wave.batchRemoveOrders 处理
|
||||
const printedSkippedOrderIdSet = new Set(skippedInterceptedOrders
|
||||
.filter(item => {
|
||||
const printStatus = String(item && item.print_status || '').trim().toLowerCase();
|
||||
return printStatus && printStatus !== 'none';
|
||||
})
|
||||
.map(item => Number(item && item.order_id || 0)));
|
||||
const keptInterceptedOrderIds = [ ...printedSkippedOrderIdSet ];
|
||||
if (keptInterceptedOrderIds.length > 0) {
|
||||
ctx.logger.warn(`[pick.wavePickTaskComplete] 已打印拦截订单保持不动,不自动移出波次,需人工处理, taskId=${taskId}, orderIds=${keptInterceptedOrderIds.join(',')}`);
|
||||
}
|
||||
|
||||
// source !== 0(PDA/后台抓取创建的任务)时,被跳过的拦截订单中「未打印」的
|
||||
// 直接从波次中移除:订单 wave_id 清零、删除波次索引、回写波次统计,
|
||||
// 并移除任务订单关联;已打印的保持不动(见上方 keptInterceptedOrderIds)
|
||||
const removedFromWaveOrderLogItems = [];
|
||||
const removedFromWaveOrderIds = [];
|
||||
const affectedWaveIdsForUnbind = [];
|
||||
if (skippedInterceptedOrders.length > 0 && taskSource !== 0) {
|
||||
const skippedOrderIds = skippedInterceptedOrders.map(item => item.order_id);
|
||||
const skippedOrderIds = skippedInterceptedOrders
|
||||
.map(item => Number(item && item.order_id || 0))
|
||||
.filter(orderId => !printedSkippedOrderIdSet.has(orderId));
|
||||
const interceptOrderModel = await this.getOrderModel(warehouseId);
|
||||
const removableRows = await interceptOrderModel.findAll({
|
||||
attributes: [ 'id', 'wave_id', 'wave_no' ],
|
||||
@ -2249,6 +2267,7 @@ class PickSystemService extends Service {
|
||||
skipped_intercepted_order_ids: skippedInterceptedOrders.map(item => item.order_id),
|
||||
skipped_intercepted_orders: skippedInterceptedOrders,
|
||||
removed_from_wave_order_ids: removedFromWaveOrderIds,
|
||||
kept_intercepted_order_ids: keptInterceptedOrderIds,
|
||||
is_completed: skipProgress.isCompleted,
|
||||
task_completed: skipTaskCompleted,
|
||||
progress: {
|
||||
@ -2559,6 +2578,9 @@ class PickSystemService extends Service {
|
||||
});
|
||||
}
|
||||
|
||||
// 通知仓库面板刷新(大屏增量更新,失败不影响主流程)
|
||||
await this.service.systems.warehousePanel.touchLastChangeAt(Number(warehouseId));
|
||||
|
||||
return {
|
||||
task_id: taskId,
|
||||
mode,
|
||||
@ -2566,6 +2588,7 @@ class PickSystemService extends Service {
|
||||
skipped_intercepted_order_ids: skippedInterceptedOrders.map(item => item.order_id),
|
||||
skipped_intercepted_orders: skippedInterceptedOrders,
|
||||
removed_from_wave_order_ids: removedFromWaveOrderIds,
|
||||
kept_intercepted_order_ids: keptInterceptedOrderIds,
|
||||
is_completed: progress.isCompleted,
|
||||
task_completed: taskCompleted,
|
||||
progress: {
|
||||
|
||||
@ -1037,6 +1037,11 @@ class ReturnReceivedService extends Service {
|
||||
case 'notin':
|
||||
return { [Op.notIn]: Array.isArray(value) ? value : [ value ] };
|
||||
case 'like':
|
||||
if (Array.isArray(value) && value.length > 0) {
|
||||
return {
|
||||
[Op.or]: value.map(item => ({ [Op.like]: `%${item}%` })),
|
||||
};
|
||||
}
|
||||
return { [Op.like]: `%${value}%` };
|
||||
case 'gt':
|
||||
return { [Op.gt]: value };
|
||||
|
||||
@ -331,6 +331,11 @@ class ReturnWaybillService extends Service {
|
||||
case 'notin':
|
||||
return { [Op.notIn]: Array.isArray(value) ? value : [ value ] };
|
||||
case 'like':
|
||||
if (Array.isArray(value) && value.length > 0) {
|
||||
return {
|
||||
[Op.or]: value.map(item => ({ [Op.like]: `%${item}%` })),
|
||||
};
|
||||
}
|
||||
return { [Op.like]: `%${value}%` };
|
||||
case 'gt':
|
||||
return { [Op.gt]: value };
|
||||
|
||||
@ -220,24 +220,28 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([
|
||||
required: false,
|
||||
description: '可配置多个库存预警项,每项包含 name、key、expire_days、tip_text',
|
||||
}),
|
||||
Object.freeze({
|
||||
key: 'auto_outbound_enabled',
|
||||
name: '启用自动出库',
|
||||
type: 'flag',
|
||||
default: false,
|
||||
required: false,
|
||||
description: '是否启用自动出库,默认 false(关闭)。开启后按 auto_outbound_rules 中的规则扫描订单并自动标记出库',
|
||||
}),
|
||||
Object.freeze({
|
||||
key: 'auto_outbound_rules',
|
||||
name: '自动出库规则',
|
||||
type: 'object',
|
||||
default: Object.freeze({ enabled: false, require_recheck: true, require_pack: true, require_weigh: true, require_sync: true, require_print: true, require_pick: true, exclude_same_day_outbound: true, same_day_outbound_deadline_time: '06:00', same_day_outbound_release_time: '22:00' }),
|
||||
type: 'array',
|
||||
default: [],
|
||||
required: false,
|
||||
description: '满足条件自动标记出库。全部条件满足时自动标记待出库',
|
||||
description: '自动出库规则数组,每项规则独立判断,订单满足任意一条规则即自动出库;空数组时不自动出库。规则前置条件固定为「已复核」(recheck_status=fin)+「已分配储位」(storage_status=fin),未复核订单一律不自动出库',
|
||||
item_keys: Object.freeze([
|
||||
Object.freeze({ key: 'enabled', name: '启用', type: 'flag', required: true, description: '是否启用自动出库' }),
|
||||
Object.freeze({ key: 'require_recheck', name: '需已复核', type: 'flag', required: false, description: '是否要求 recheck_status=fin' }),
|
||||
Object.freeze({ key: 'require_pack', name: '需已打包', type: 'flag', required: false, description: '是否要求 pack_status=fin' }),
|
||||
Object.freeze({ key: 'require_weigh', name: '需已称重', type: 'flag', required: false, description: '是否要求 weighing_weight>0' }),
|
||||
Object.freeze({ key: 'require_sync', name: '需已同步', type: 'flag', required: false, description: '是否要求 sync_status=fin' }),
|
||||
Object.freeze({ key: 'require_print', name: '需已打印', type: 'flag', required: false, description: '是否要求 print_status=fin' }),
|
||||
Object.freeze({ key: 'require_pick', name: '需已拣货', type: 'flag', required: false, description: '是否要求 pick_status=fin' }),
|
||||
Object.freeze({ key: 'exclude_same_day_outbound', name: '不出库当天订单', type: 'flag', required: false, default: true, description: '开启后,在当天放开时间前,「允许当天出库最后时间」之后复核的订单不自动出库,到达当天放开时间后恢复' }),
|
||||
Object.freeze({ key: 'same_day_outbound_deadline_time', name: '允许当天出库最后时间', type: 'string', required: false, default: '06:00', maxLength: 5, min: '00:00', max: '23:59', description: '复核时间早于该时间的订单不受「不出库当天订单」开启的影响,格式 HH:mm,不能大于当天放开时间' }),
|
||||
Object.freeze({ key: 'same_day_outbound_release_time', name: '当天放开时间', type: 'string', required: false, default: '22:00', maxLength: 5, min: '00:00', max: '23:59', description: '开启「不出库当天订单」时,当天到达该时间后不再限制当天复核订单的自动出库,格式 HH:mm' }),
|
||||
Object.freeze({ key: 'require_pack', name: '需已打包', type: 'flag', required: false, default: true, description: '是否要求已打包(pack_status=fin),默认 true' }),
|
||||
Object.freeze({ key: 'require_weigh', name: '需已称重', type: 'flag', required: false, default: true, description: '是否要求已称重(weighing_weight>0),默认 true' }),
|
||||
Object.freeze({ key: 'require_sync', name: '需已同步', type: 'flag', required: false, default: true, description: '是否要求已同步(sync_status=fin),默认 true' }),
|
||||
Object.freeze({ key: 'exclude_same_day_outbound', name: '不出库当天订单', type: 'flag', required: false, default: true, description: '开启后,按订单复核时间所在日计算:复核时间在「允许当天出库最后时间」之后的订单,需等到该复核日的「放行时间」才自动出库;复核时间早于该最后时间、或为空的订单不受影响' }),
|
||||
Object.freeze({ key: 'same_day_outbound_deadline_time', name: '允许当天出库最后时间', type: 'string', required: false, default: '06:00', maxLength: 5, min: '00:00', max: '23:59', description: '复核时间早于该时间的订单不受「不出库当天订单」影响,格式 HH:mm(当天内 00:00~23:59),不能大于放行时间。想表达「当天复核的订单全天不出库」时设为 00:00' }),
|
||||
Object.freeze({ key: 'same_day_outbound_release_time', name: '放行时间', type: 'string', required: false, default: '22:00', maxLength: 5, min: '00:00', max: '47:59', description: '到达该时刻后,该复核日被限制的订单放行。格式 HH:mm,支持跨天 00:00~47:59(24:00 之后的数字表示次日,如 27:00 = 次日 03:00)。常用:23:59 = 当天不放、过了零点出库;27:00 = 到次日 03:00 才出库' }),
|
||||
]),
|
||||
}),
|
||||
Object.freeze({
|
||||
@ -259,6 +263,17 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([
|
||||
max: '23:59',
|
||||
description: '开始自动分配时间,格式 HH:mm,如 08:00;早于该时间的订单与超过截单时间行为一致,不自动分配快递和储位,不自动加团;晚于截单时间时截单时间视为次日',
|
||||
}),
|
||||
Object.freeze({
|
||||
key: 'day_start_time',
|
||||
name: '自然日开始时间',
|
||||
type: 'string',
|
||||
default: '06:00',
|
||||
required: false,
|
||||
maxLength: 5,
|
||||
min: '00:00',
|
||||
max: '23:59',
|
||||
description: '自然日开始时间(业务日分界点),格式 HH:mm,默认 06:00;今日统计窗口为 [该时间点, 次日该时间点),当前时间早于今日该时间点时窗口从昨日该时间点开始(昨日 06:00 后的订单视为今日)',
|
||||
}),
|
||||
Object.freeze({
|
||||
key: 'cutoff_order_time',
|
||||
name: '截单时间',
|
||||
@ -812,6 +827,27 @@ class SettingWarehouseService extends Service {
|
||||
await this.validateDefaultLocation(nextPatch.default_location_id, warehouseId);
|
||||
}
|
||||
|
||||
// 自动出库规则必须是数组(旧的对象结构已废弃):写路径显式报错,避免被静默重置为默认值
|
||||
if (Object.prototype.hasOwnProperty.call(nextPatch, 'auto_outbound_rules')) {
|
||||
const rawAutoOutboundRules = nextPatch.auto_outbound_rules;
|
||||
if (rawAutoOutboundRules !== undefined && rawAutoOutboundRules !== null && rawAutoOutboundRules !== '') {
|
||||
let parsedAutoOutboundRules = rawAutoOutboundRules;
|
||||
if (typeof parsedAutoOutboundRules === 'string') {
|
||||
try {
|
||||
parsedAutoOutboundRules = JSON.parse(parsedAutoOutboundRules);
|
||||
} catch (error) {
|
||||
parsedAutoOutboundRules = null;
|
||||
}
|
||||
}
|
||||
if (!Array.isArray(parsedAutoOutboundRules)) {
|
||||
throw this.createError(
|
||||
'subject_config.auto_outbound_rules 必须是数组(每项包含 require_pack/require_weigh/require_sync 等字段),旧对象结构已废弃,请重新配置',
|
||||
400
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const nextPatchForMerge = {
|
||||
...nextPatch,
|
||||
};
|
||||
|
||||
@ -23,6 +23,14 @@ const SUBMIT_ALLOWED_STATUSES = Object.freeze([ 'created', 'rejected' ]);
|
||||
/** 允许取消的主表状态 */
|
||||
const CANCEL_ALLOWED_STATUSES = Object.freeze([ 'created', 'submitted', 'rejected' ]);
|
||||
|
||||
/**
|
||||
* 有效库位过滤 SQL(库位未删除且所属 zone 存在且未删除)。
|
||||
* 无头库位(zone 不存在/已删除)不纳入盘点范围:明细生成、商品作业视图库位枚举均按此过滤。
|
||||
*/
|
||||
const VALID_SPACE_SQL = '(SELECT ls.id FROM wms_location_space ls '
|
||||
+ 'JOIN wms_location_zone z ON z.id = ls.zone_id AND z.deleted_at IS NULL '
|
||||
+ 'WHERE ls.deleted_at IS NULL)';
|
||||
|
||||
/** 盘点范围类型中文标签 */
|
||||
const STOCK_CHECK_TYPE_LABELS = Object.freeze({
|
||||
all: '全盘',
|
||||
@ -1135,11 +1143,17 @@ class StockCheckService extends Service {
|
||||
});
|
||||
} else {
|
||||
let codes = locationCodes;
|
||||
// 全盘:未显式传库位时自动拉取全仓库启用库位
|
||||
// 全盘:未显式传库位时自动拉取全仓库启用库位(排除无头库位:zone 必须存在且未删除)
|
||||
if (checkType === 'all' && codes.length === 0) {
|
||||
const enabledSpaces = await ctx.model.LocationSpace.findAll({
|
||||
where: { warehouse_id: Number(warehouseId), is_enabled: true },
|
||||
attributes: [ 'space_code' ],
|
||||
include: [{
|
||||
model: ctx.model.LocationZone,
|
||||
as: 'zone',
|
||||
attributes: [],
|
||||
required: true,
|
||||
}],
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
@ -1309,12 +1323,16 @@ class StockCheckService extends Service {
|
||||
const existingStockIds = new Set(existingRows.map(item => Number(item.stock_id)));
|
||||
|
||||
// 商品在本仓库的启用库存库位(按库位拆分明细行:商品任务必须按库位盘点,
|
||||
// 一个商品多个库位对应多行,各行账面 = 该库位库存 SUM(可用+锁定);无库存库位商品不可盘点)
|
||||
// 一个商品多个库位对应多行,各行账面 = 该库位库存 SUM(可用+锁定);无库存库位商品不可盘点;
|
||||
// 库位有效性:仅统计有效库位(所属 zone 存在且未删除),无头库位(zone 不存在/已删除)不纳入盘点)
|
||||
const storageRows = await ctx.model.Storage.findAll({
|
||||
where: {
|
||||
warehouse_id: Number(warehouseId),
|
||||
stock_id: { [Op.in]: numericStockIds },
|
||||
is_enabled: 1,
|
||||
space_id: {
|
||||
[Op.in]: literal(VALID_SPACE_SQL),
|
||||
},
|
||||
},
|
||||
attributes: [
|
||||
'stock_id',
|
||||
@ -1414,6 +1432,13 @@ class StockCheckService extends Service {
|
||||
space_code: { [Op.in]: codes },
|
||||
},
|
||||
attributes: [ 'id', 'space_code' ],
|
||||
// 库位有效性:zone 必须存在且未删除(无头库位记入 invalidLocations,与不存在同口径)
|
||||
include: [{
|
||||
model: ctx.model.LocationZone,
|
||||
as: 'zone',
|
||||
attributes: [],
|
||||
required: true,
|
||||
}],
|
||||
raw: true,
|
||||
});
|
||||
const spaceByCode = new Map(spaceRows.map(item => [ String(item.space_code), item ]));
|
||||
@ -1485,13 +1510,20 @@ class StockCheckService extends Service {
|
||||
const { ctx } = this;
|
||||
const { Op } = ctx.app.Sequelize;
|
||||
|
||||
// 直接按 ID 查库校验(仓库隔离),查不到的 ID 记入 invalidLocationIds(不报错)
|
||||
// 直接按 ID 查库校验(仓库隔离),查不到的 ID 记入 invalidLocationIds(不报错);
|
||||
// 库位有效性:zone 必须存在且未删除(无头库位同样记入 invalidLocationIds)
|
||||
const spaceRows = await ctx.model.LocationSpace.findAll({
|
||||
where: {
|
||||
id: { [Op.in]: numericLocationIds },
|
||||
warehouse_id: Number(warehouseId),
|
||||
},
|
||||
attributes: [ 'id', 'space_code' ],
|
||||
include: [{
|
||||
model: ctx.model.LocationZone,
|
||||
as: 'zone',
|
||||
attributes: [],
|
||||
required: true,
|
||||
}],
|
||||
raw: true,
|
||||
});
|
||||
const spaceById = new Map(spaceRows.map(item => [ Number(item.id), item ]));
|
||||
@ -3367,6 +3399,8 @@ class StockCheckService extends Service {
|
||||
warehouse_id: Number(warehouseId),
|
||||
stock_id: { [Op.in]: stockIds },
|
||||
is_enabled: 1,
|
||||
// 排除无头库位(与明细生成口径一致)
|
||||
space_id: { [Op.in]: literal(VALID_SPACE_SQL) },
|
||||
},
|
||||
attributes: [
|
||||
'stock_id',
|
||||
@ -3621,6 +3655,8 @@ class StockCheckService extends Service {
|
||||
warehouse_id: Number(warehouseId),
|
||||
stock_id: { [Op.in]: stockIds },
|
||||
is_enabled: 1,
|
||||
// 排除无头库位(与明细生成口径一致)
|
||||
space_id: { [Op.in]: literal(VALID_SPACE_SQL) },
|
||||
},
|
||||
attributes: [
|
||||
'space_id',
|
||||
|
||||
@ -231,7 +231,8 @@ class StockCheckPatternsService extends Service {
|
||||
|
||||
/**
|
||||
* 空库位定式:收集账面为空的启用库位。
|
||||
* 口径:wms_location_space(warehouse_id 匹配、is_enabled=1、未删除)在
|
||||
* 口径:wms_location_space(warehouse_id 匹配、is_enabled=1、未删除、库位有效——
|
||||
* 所属 zone 存在且未删除,排除无头库位)在
|
||||
* wms_storage 不存在任何 quantity>0 且未删除的库存记录(LEFT JOIN 判空)。
|
||||
*
|
||||
* @param {Object} context 收集上下文。
|
||||
@ -244,6 +245,9 @@ class StockCheckPatternsService extends Service {
|
||||
`
|
||||
SELECT ls.id AS location_id, ls.space_code AS location_code
|
||||
FROM wms_location_space ls
|
||||
JOIN wms_location_zone z
|
||||
ON z.id = ls.zone_id
|
||||
AND z.deleted_at IS NULL
|
||||
LEFT JOIN wms_storage st
|
||||
ON st.space_id = ls.id
|
||||
AND st.delete_at IS NULL
|
||||
|
||||
@ -17,9 +17,6 @@ const FULFILLMENT_STAGES = [
|
||||
{ key: 'ship', icon: 'ship', undone: '待出库', done: '已出库', field: 'outbound_status' },
|
||||
];
|
||||
|
||||
// 今日订单趋势固定横轴(08:00-18:00 共 11 点)
|
||||
const TREND_HOURS = [ 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 ];
|
||||
|
||||
// 拣货任务活跃状态(排除 9=已取消)
|
||||
const PICK_TASK_ACTIVE_STATUSES = [ 0, 1, 2, 3 ];
|
||||
|
||||
@ -34,6 +31,86 @@ class WarehousePanelService extends Service {
|
||||
return `${PANEL_CACHE_KEY_PREFIX}:lastChangeAt:${warehouseId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 通知面板数据已变化(公共方法):更新对应仓库的最后更新时间戳,供大屏增量轮询感知新数据。
|
||||
* 只写时间戳(整值替换,data 自然失效),面板接口下次拉取时会查库重建数据。
|
||||
* 供拣货完成/复核完成/打包完成等业务写路径调用;失败仅告警不影响主流程。
|
||||
*
|
||||
* @param {number|string} warehouseId 仓库 ID
|
||||
* @return {Promise<number>} 写入的时间戳(Unix 秒);失败返回 0
|
||||
*/
|
||||
async touchLastChangeAt(warehouseId) {
|
||||
try {
|
||||
const key = this.getPanelCacheKey(Number(warehouseId));
|
||||
const nowTs = Math.floor(Date.now() / 1000);
|
||||
await this.app.setCacheAsync(key, { last_change_at: nowTs }, PANEL_CACHE_TTL_SECONDS);
|
||||
return nowTs;
|
||||
} catch (error) {
|
||||
const logger = this.ctx.logger;
|
||||
if (logger && typeof logger.warn === 'function') {
|
||||
logger.warn(`[WarehousePanel] 更新最后更新时间失败 warehouseId=${warehouseId}: ${error && error.message}`);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取仓库自然日开始时间(wms_store.subject_config.day_start_time)。
|
||||
*
|
||||
* 配置缺失/非法/查询异常时回退默认 06:00。
|
||||
*
|
||||
* @param {number} warehouseId 仓库 ID
|
||||
* @return {Promise<string>} HH:mm 格式时间(如 06:00)
|
||||
*/
|
||||
async getWarehouseDayStartTime(warehouseId) {
|
||||
try {
|
||||
const store = await this.ctx.model.Store.findOne({
|
||||
where: { id: warehouseId, project: 'warehouse' },
|
||||
attributes: [ 'subject_config' ],
|
||||
raw: true,
|
||||
});
|
||||
let config = store && store.subject_config ? store.subject_config : {};
|
||||
if (typeof config === 'string') {
|
||||
try {
|
||||
config = JSON.parse(config);
|
||||
} catch (parseError) {
|
||||
config = {};
|
||||
}
|
||||
}
|
||||
const raw = config.day_start_time;
|
||||
if (typeof raw === 'string' && /^([01]\d|2[0-3]):[0-5]\d$/.test(raw)) {
|
||||
return raw;
|
||||
}
|
||||
return '06:00';
|
||||
} catch (error) {
|
||||
const logger = this.ctx.logger;
|
||||
if (logger && typeof logger.warn === 'function') {
|
||||
logger.warn(`[WarehousePanel] 读取自然日开始时间失败,回退 06:00: ${error.message}`);
|
||||
}
|
||||
return '06:00';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析业务日窗口 [businessStart, businessEnd)。
|
||||
*
|
||||
* 业务日从配置的 day_start_time 开始持续 24 小时;当前时间早于今日该时间点时,
|
||||
* 窗口从昨日该时间点开始(昨日该时间点后的订单视为今日)。
|
||||
*
|
||||
* @param {number} warehouseId 仓库 ID
|
||||
* @param {Date} now 当前时间
|
||||
* @return {Promise<Array<Date>>} [ 业务日开始, 业务日结束 ]
|
||||
*/
|
||||
async resolveBusinessDayRange(warehouseId, now) {
|
||||
const dayStartTime = await this.getWarehouseDayStartTime(warehouseId);
|
||||
const [ hh, mm ] = dayStartTime.split(':').map(Number);
|
||||
let businessStart = new Date(now.getFullYear(), now.getMonth(), now.getDate(), hh, mm, 0, 0);
|
||||
if (now < businessStart) {
|
||||
businessStart = new Date(businessStart.getTime() - 86400000);
|
||||
}
|
||||
return [ businessStart, new Date(businessStart.getTime() + 86400000) ];
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取面板数据。
|
||||
*
|
||||
@ -101,7 +178,8 @@ class WarehousePanelService extends Service {
|
||||
|
||||
const now = new Date();
|
||||
const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
const tomorrowStart = new Date(todayStart.getTime() + 86400000);
|
||||
// 业务日窗口(仓库配置 day_start_time,默认 06:00):昨日 06:00 后的订单视为今日
|
||||
const [ businessStart, businessEnd ] = await this.resolveBusinessDayRange(warehouseId, now);
|
||||
|
||||
const factory = model.OrderDeliveryFactory;
|
||||
const [ currentModel, dispatchModel ] = await Promise.all([
|
||||
@ -118,24 +196,33 @@ class WarehousePanelService extends Service {
|
||||
};
|
||||
|
||||
const blocks = await Promise.all([
|
||||
this.queryFulfillment(currentModel, pendingBase).catch(error => this.logBlockError('fulfillment', error)),
|
||||
this.queryStageOverview(warehouseId, currentModel, pendingBase, todayStart, tomorrowStart)
|
||||
this.queryFulfillment(currentModel, dispatchModel, pendingBase, warehouseId, businessStart, businessEnd)
|
||||
.catch(error => this.logBlockError('fulfillment', error)),
|
||||
this.queryStageOverview(warehouseId, currentModel, dispatchModel, pendingBase, businessStart, businessEnd)
|
||||
.catch(error => this.logBlockError('stageOverview', error)),
|
||||
this.queryB2b(currentModel, dispatchModel, todayStart, tomorrowStart)
|
||||
this.queryB2b(currentModel, dispatchModel, businessStart, businessEnd)
|
||||
.catch(error => this.logBlockError('b2b', error)),
|
||||
this.queryPickingBlock(warehouseId, currentTableName, dispatchTableName, [ 1, 5 ], todayStart, tomorrowStart)
|
||||
this.queryPickingBlock(warehouseId, currentTableName, dispatchTableName, true, businessStart, businessEnd)
|
||||
.catch(error => this.logBlockError('groupPicking', error)),
|
||||
this.queryPickingBlock(warehouseId, currentTableName, dispatchTableName, [ 2, 3, 4 ], todayStart, tomorrowStart)
|
||||
this.queryPickingBlock(warehouseId, currentTableName, dispatchTableName, false, businessStart, businessEnd)
|
||||
.catch(error => this.logBlockError('scatterPicking', error)),
|
||||
this.queryPackingPersonal(warehouseId, todayStart, tomorrowStart)
|
||||
.catch(error => this.logBlockError('packingRank', error)),
|
||||
this.queryTrend(currentModel, pendingBase, todayStart)
|
||||
this.queryPackingBlock(warehouseId, businessStart, businessEnd, true)
|
||||
.catch(error => this.logBlockError('groupPacking', error)),
|
||||
this.queryPackingBlock(warehouseId, businessStart, businessEnd, false)
|
||||
.catch(error => this.logBlockError('scatterPacking', error)),
|
||||
this.queryTrend(currentModel, dispatchModel, pendingBase, businessStart, businessEnd)
|
||||
.catch(error => this.logBlockError('trend', error)),
|
||||
this.queryWeeklyIntercept(currentModel, dispatchModel, todayStart)
|
||||
.catch(error => this.logBlockError('weeklyEfficiency', error)),
|
||||
]);
|
||||
|
||||
const [ fulfillment, stageOverview, b2b, groupPicking, scatterPicking, packingRank, trend, weeklyEfficiency ] = blocks;
|
||||
const [ fulfillment, stageOverview, b2b, groupPicking, scatterPicking, groupPacking, scatterPacking, trend, weeklyEfficiency ] = blocks;
|
||||
|
||||
// 趋势补充总单量字段(与 fulfillment.total 同口径:待处理订单池 + 配送表今日出库;
|
||||
// fulfillment 块失败时兜底 0)
|
||||
if (trend) {
|
||||
trend.total = fulfillment ? (fulfillment.total || 0) : 0;
|
||||
}
|
||||
|
||||
const data = {
|
||||
title: ctx.user?.store_name || '',
|
||||
@ -144,7 +231,8 @@ class WarehousePanelService extends Service {
|
||||
b2b,
|
||||
groupPicking,
|
||||
scatterPicking,
|
||||
packingRank,
|
||||
groupPacking,
|
||||
scatterPacking,
|
||||
trend,
|
||||
weeklyEfficiency,
|
||||
};
|
||||
@ -168,41 +256,139 @@ class WarehousePanelService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 订单履约链路:6 个环节 × 未/已 + 分母。
|
||||
* 订单履约链路:6 个环节 × 未/已 + 分母 + 今日退回指标。
|
||||
*
|
||||
* 配送表补数:已出库订单会从常用表迁移到配送分表(outbound_status=fin);
|
||||
* 各环节未* = 池内未完成 + 配送表今日出库未完成(真实状态);
|
||||
* 各环节已* 口径:分配/打印/拣货/打包从订单表状态获取(池内 fin + 配送表今日出库 fin,
|
||||
* 保证已分配≥已打印≥已拣货≥已复核≥已打包的流程约束),
|
||||
* 复核=今日复核时间(recheck_time)双表、出库=今日出库数。
|
||||
*
|
||||
* 今日退回收件数/今日拆包件数:按 wms_return_received / wms_return_unpack
|
||||
* 的 created_at 落在今日(含今天 00:00)且仓库匹配统计,以两项追加在
|
||||
* items 数组末尾(label/icon/value 与环节项同构)。
|
||||
*
|
||||
* @param {Object} currentModel 常用分表模型
|
||||
* @param {Object} dispatchModel 配送分表模型
|
||||
* @param {Object} pendingBase 待处理基础过滤
|
||||
* @return {Promise<Object>} { total, items }
|
||||
* @param {number} warehouseId 仓库 ID
|
||||
* @param {Date} todayStart 今日开始
|
||||
* @param {Date} tomorrowStart 明日开始
|
||||
* @return {Promise<Object>} { total, items }(items 末尾追加今日退件/今日拆包两项)
|
||||
*/
|
||||
async queryFulfillment(currentModel, pendingBase) {
|
||||
async queryFulfillment(currentModel, dispatchModel, pendingBase, warehouseId, todayStart, tomorrowStart) {
|
||||
const { model } = this.ctx;
|
||||
const { Op } = this.app.Sequelize;
|
||||
const todayRange = { [Op.gte]: todayStart, [Op.lt]: tomorrowStart };
|
||||
|
||||
// 配送表今日出库且未取消:出库环节已*(今日出库数)与总数叠加(已迁移订单)
|
||||
const dispatchTodayBase = {
|
||||
status: { [Op.ne]: 'cancel' },
|
||||
outbound_status: 'fin',
|
||||
delivery_time: todayRange,
|
||||
dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] },
|
||||
};
|
||||
|
||||
const totalCountPromise = currentModel.count({ where: pendingBase });
|
||||
const stageCounts = await Promise.all(FULFILLMENT_STAGES.map(async stage => {
|
||||
const undone = await currentModel.count({
|
||||
const dispatchTodayCountPromise = dispatchModel.count({ where: dispatchTodayBase });
|
||||
// 各环节已* 口径:分配/打印/拣货/打包均从订单表状态获取(池内 fin + 配送表今日出库 fin),
|
||||
// 保证已分配 ≥ 已打印 ≥ 已拣货 ≥ 已复核 ≥ 已打包 的流程约束;
|
||||
// 注:打包环节此前用「今日打包任务订单数」口径,会大于已复核(打包任务快照含未复核/重复计入),
|
||||
// 已改回订单状态存量口径(pack_status=fin);复核=今日复核时间、出库=今日出库数
|
||||
const todayAllocOrdersPromise = Promise.all([
|
||||
currentModel.count({ where: { ...pendingBase, post_status: 'fin' } }),
|
||||
dispatchModel.count({ where: { ...dispatchTodayBase, post_status: 'fin' } }),
|
||||
]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount);
|
||||
const todayPrintOrdersPromise = Promise.all([
|
||||
currentModel.count({ where: { ...pendingBase, print_status: 'fin' } }),
|
||||
dispatchModel.count({ where: { ...dispatchTodayBase, print_status: 'fin' } }),
|
||||
]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount);
|
||||
const todayPickOrdersPromise = Promise.all([
|
||||
currentModel.count({ where: { ...pendingBase, pick_status: 'fin' } }),
|
||||
dispatchModel.count({
|
||||
where: {
|
||||
...pendingBase,
|
||||
[Op.or]: [
|
||||
{ [stage.field]: { [Op.ne]: 'fin' } },
|
||||
{ [stage.field]: { [Op.is]: null } },
|
||||
],
|
||||
status: { [Op.ne]: 'cancel' },
|
||||
outbound_status: 'fin',
|
||||
pick_status: 'fin',
|
||||
delivery_time: todayRange,
|
||||
dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] },
|
||||
},
|
||||
});
|
||||
const done = await currentModel.count({
|
||||
where: { ...pendingBase, [stage.field]: 'fin' },
|
||||
});
|
||||
return { undone, done };
|
||||
}),
|
||||
]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount);
|
||||
const todayPackOrdersPromise = Promise.all([
|
||||
currentModel.count({ where: { ...pendingBase, pack_status: 'fin' } }),
|
||||
dispatchModel.count({ where: { ...dispatchTodayBase, pack_status: 'fin' } }),
|
||||
]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount);
|
||||
const todayRecheckOrdersPromise = Promise.all([
|
||||
currentModel.count({ where: { status: { [Op.ne]: 'cancel' }, recheck_time: todayRange } }),
|
||||
dispatchModel.count({
|
||||
where: {
|
||||
status: { [Op.ne]: 'cancel' },
|
||||
recheck_time: todayRange,
|
||||
dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] },
|
||||
},
|
||||
}),
|
||||
]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount);
|
||||
const returnReceivedTodayPromise = model.ReturnReceived.count({
|
||||
where: { warehouse_id: warehouseId, created_at: todayRange },
|
||||
});
|
||||
const returnUnpackTodayPromise = model.ReturnUnpack.count({
|
||||
where: { warehouse_id: warehouseId, created_at: todayRange },
|
||||
});
|
||||
const stageCounts = await Promise.all(FULFILLMENT_STAGES.map(async stage => {
|
||||
const [ undoneCurrent, dispatchFin, dispatchTodayOutbound, todayAlloc, todayPrint, todayPick, todayRecheck, todayPack ] = await Promise.all([
|
||||
currentModel.count({
|
||||
where: {
|
||||
...pendingBase,
|
||||
[Op.or]: [
|
||||
{ [stage.field]: { [Op.ne]: 'fin' } },
|
||||
{ [stage.field]: { [Op.is]: null } },
|
||||
],
|
||||
},
|
||||
}),
|
||||
dispatchModel.count({
|
||||
where: { ...dispatchTodayBase, [stage.field]: 'fin' },
|
||||
}),
|
||||
dispatchTodayCountPromise,
|
||||
todayAllocOrdersPromise,
|
||||
todayPrintOrdersPromise,
|
||||
todayPickOrdersPromise,
|
||||
todayRecheckOrdersPromise,
|
||||
todayPackOrdersPromise,
|
||||
]);
|
||||
// 已* 按环节取今日作业口径数据源;出库环节=今日出库数;
|
||||
// 未* = 池内未完成 + 配送表今日出库未完成(真实状态)
|
||||
const doneTodayMap = {
|
||||
post_status: todayAlloc,
|
||||
print_status: todayPrint,
|
||||
pick_status: todayPick,
|
||||
recheck_status: todayRecheck,
|
||||
pack_status: todayPack,
|
||||
outbound_status: dispatchTodayOutbound,
|
||||
};
|
||||
const doneToday = doneTodayMap[stage.field] || 0;
|
||||
return {
|
||||
undone: undoneCurrent + (dispatchTodayOutbound - dispatchFin),
|
||||
done: doneToday,
|
||||
};
|
||||
}));
|
||||
|
||||
const total = await totalCountPromise;
|
||||
const [ total, dispatchTodayOutbound, returnReceivedToday, returnUnpackToday ] = await Promise.all([
|
||||
totalCountPromise,
|
||||
dispatchTodayCountPromise,
|
||||
returnReceivedTodayPromise,
|
||||
returnUnpackTodayPromise,
|
||||
]);
|
||||
const items = [];
|
||||
FULFILLMENT_STAGES.forEach((stage, index) => {
|
||||
const counts = stageCounts[index] || { undone: 0, done: 0 };
|
||||
items.push({ label: stage.undone, icon: stage.icon, value: counts.undone || 0 });
|
||||
items.push({ label: stage.done, icon: stage.icon, value: counts.done || 0 });
|
||||
});
|
||||
items.push({ label: '今日退件', icon: 'returnReceived', value: returnReceivedToday || 0 });
|
||||
items.push({ label: '今日拆包', icon: 'returnUnpack', value: returnUnpackToday || 0 });
|
||||
|
||||
return { total: total || 0, items };
|
||||
return { total: (total || 0) + dispatchTodayOutbound, items };
|
||||
}
|
||||
|
||||
/**
|
||||
@ -226,12 +412,13 @@ class WarehousePanelService extends Service {
|
||||
*
|
||||
* @param {number} warehouseId 仓库 ID
|
||||
* @param {Object} currentModel 常用分表模型
|
||||
* @param {Object} dispatchModel 配送分表模型(已出库订单迁移目标,今日出库双表合计)
|
||||
* @param {Object} pendingBase 待处理基础过滤
|
||||
* @param {Date} todayStart 今日开始
|
||||
* @param {Date} tomorrowStart 明日开始
|
||||
* @return {Promise<Object>} { totalOrders, interceptOrders, stages }
|
||||
*/
|
||||
async queryStageOverview(warehouseId, currentModel, pendingBase, todayStart, tomorrowStart) {
|
||||
async queryStageOverview(warehouseId, currentModel, dispatchModel, pendingBase, todayStart, tomorrowStart) {
|
||||
const { model } = this.ctx;
|
||||
const { Op } = this.app.Sequelize;
|
||||
const todayRange = { [Op.gte]: todayStart, [Op.lt]: tomorrowStart };
|
||||
@ -254,9 +441,19 @@ class WarehousePanelService extends Service {
|
||||
packAbnormal,
|
||||
] = await Promise.all([
|
||||
currentModel.count({ where: pendingBase }),
|
||||
currentModel.count({
|
||||
where: { step: 4, outbound_status: 'fin', status: { [Op.ne]: 'cancel' }, delivery_time: todayRange },
|
||||
}),
|
||||
Promise.all([
|
||||
currentModel.count({
|
||||
where: { step: 4, outbound_status: 'fin', status: { [Op.ne]: 'cancel' }, delivery_time: todayRange },
|
||||
}),
|
||||
dispatchModel.count({
|
||||
where: {
|
||||
status: { [Op.ne]: 'cancel' },
|
||||
outbound_status: 'fin',
|
||||
delivery_time: todayRange,
|
||||
dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] },
|
||||
},
|
||||
}),
|
||||
]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount),
|
||||
currentModel.count({
|
||||
where: { ...pendingBase, intercept_status: { [Op.not]: null, [Op.ne]: 'none' } },
|
||||
}),
|
||||
@ -265,19 +462,53 @@ class WarehousePanelService extends Service {
|
||||
model.Receiving.count({
|
||||
where: { warehouse_id: warehouseId, storage_status: { [Op.in]: [ 'waiting', 'partial' ] } },
|
||||
}),
|
||||
this.countSql(
|
||||
`SELECT COUNT(*) AS cnt FROM wms_wave_pick_task
|
||||
WHERE warehouse_id = :warehouseId AND status IN (:statuses)
|
||||
AND finish_time >= :start AND finish_time < :end`,
|
||||
{ warehouseId, statuses: [ 2, 3 ], start: todayStart, end: tomorrowStart }
|
||||
),
|
||||
this.countSql(
|
||||
`SELECT COUNT(*) AS cnt FROM wms_wave_pick_task
|
||||
WHERE warehouse_id = :warehouseId AND status = 1`,
|
||||
{ warehouseId }
|
||||
),
|
||||
currentModel.count({ where: { ...pendingBase, pick_status: 'error' } }),
|
||||
currentModel.count({ where: { status: { [Op.ne]: 'cancel' }, recheck_time: todayRange } }),
|
||||
Promise.all([
|
||||
currentModel.count({ where: { ...pendingBase, pick_status: 'fin' } }),
|
||||
dispatchModel.count({
|
||||
where: {
|
||||
status: { [Op.ne]: 'cancel' },
|
||||
outbound_status: 'fin',
|
||||
pick_status: 'fin',
|
||||
delivery_time: todayRange,
|
||||
dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] },
|
||||
},
|
||||
}),
|
||||
]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount),
|
||||
// 拣货中订单数:订单表 pick_status='padding'(池内 + 配送表今日出库,与已拣货同源订单表口径)
|
||||
Promise.all([
|
||||
currentModel.count({ where: { ...pendingBase, pick_status: 'padding' } }),
|
||||
dispatchModel.count({
|
||||
where: {
|
||||
status: { [Op.ne]: 'cancel' },
|
||||
outbound_status: 'fin',
|
||||
pick_status: 'padding',
|
||||
delivery_time: todayRange,
|
||||
dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] },
|
||||
},
|
||||
}),
|
||||
]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount),
|
||||
Promise.all([
|
||||
currentModel.count({ where: { ...pendingBase, pick_status: 'error' } }),
|
||||
dispatchModel.count({
|
||||
where: {
|
||||
status: { [Op.ne]: 'cancel' },
|
||||
outbound_status: 'fin',
|
||||
pick_status: 'error',
|
||||
delivery_time: todayRange,
|
||||
dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] },
|
||||
},
|
||||
}),
|
||||
]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount),
|
||||
Promise.all([
|
||||
currentModel.count({ where: { status: { [Op.ne]: 'cancel' }, recheck_time: todayRange } }),
|
||||
dispatchModel.count({
|
||||
where: {
|
||||
status: { [Op.ne]: 'cancel' },
|
||||
recheck_time: todayRange,
|
||||
dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] },
|
||||
},
|
||||
}),
|
||||
]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount),
|
||||
model.WaveBatch.count({
|
||||
where: {
|
||||
warehouse_id: warehouseId,
|
||||
@ -285,10 +516,62 @@ class WarehousePanelService extends Service {
|
||||
wave_status: { [Op.in]: [ 3, 4 ] },
|
||||
},
|
||||
}),
|
||||
currentModel.count({ where: { ...pendingBase, recheck_status: 'error' } }),
|
||||
model.PackTask.count({ where: { warehouse_id: warehouseId, create_time: todayRange } }),
|
||||
model.PackTask.count({ where: { warehouse_id: warehouseId, status: 1 } }),
|
||||
model.PackTask.count({ where: { warehouse_id: warehouseId, status: 3 } }),
|
||||
Promise.all([
|
||||
currentModel.count({ where: { ...pendingBase, recheck_status: 'error' } }),
|
||||
dispatchModel.count({
|
||||
where: {
|
||||
status: { [Op.ne]: 'cancel' },
|
||||
outbound_status: 'fin',
|
||||
recheck_status: 'error',
|
||||
delivery_time: todayRange,
|
||||
dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] },
|
||||
},
|
||||
}),
|
||||
]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount),
|
||||
this.countSql(
|
||||
`SELECT
|
||||
(SELECT COUNT(*) FROM wms_pack_task
|
||||
WHERE warehouse_id = :warehouseId
|
||||
AND create_time >= :start AND create_time < :end
|
||||
AND status = 2 AND deleted_at IS NULL
|
||||
AND pack_mode != 2)
|
||||
+
|
||||
(SELECT COUNT(*) FROM wms_order_wave_index
|
||||
WHERE wave_id IN (
|
||||
SELECT DISTINCT wave_id FROM wms_pack_task
|
||||
WHERE warehouse_id = :warehouseId
|
||||
AND create_time >= :start AND create_time < :end
|
||||
AND status = 2 AND deleted_at IS NULL
|
||||
AND pack_mode = 2
|
||||
)) AS cnt`,
|
||||
{ warehouseId, start: todayStart, end: tomorrowStart }
|
||||
),
|
||||
// 打包中订单数:订单表 pack_status='padding'(池内 + 配送表今日出库,与未打包/已打包同源订单表口径)
|
||||
Promise.all([
|
||||
currentModel.count({ where: { ...pendingBase, pack_status: 'padding' } }),
|
||||
dispatchModel.count({
|
||||
where: {
|
||||
status: { [Op.ne]: 'cancel' },
|
||||
outbound_status: 'fin',
|
||||
pack_status: 'padding',
|
||||
delivery_time: todayRange,
|
||||
dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] },
|
||||
},
|
||||
}),
|
||||
]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount),
|
||||
// 打包异常订单数:订单表 pack_status='error'(池内 + 配送表今日出库,与打包中同源订单表口径)
|
||||
Promise.all([
|
||||
currentModel.count({ where: { ...pendingBase, pack_status: 'error' } }),
|
||||
dispatchModel.count({
|
||||
where: {
|
||||
status: { [Op.ne]: 'cancel' },
|
||||
outbound_status: 'fin',
|
||||
pack_status: 'error',
|
||||
delivery_time: todayRange,
|
||||
dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] },
|
||||
},
|
||||
}),
|
||||
]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount),
|
||||
]);
|
||||
|
||||
const stages = [
|
||||
@ -380,24 +663,26 @@ class WarehousePanelService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 拣货统计块(团购 pick_mode=1,5;散单 pick_mode=2,3,4)。
|
||||
* 拣货统计块(团购 wave_scope IN (1,3);散单其余)。
|
||||
*
|
||||
* 窗口:今日创建(create_time 今日)且未取消的任务;
|
||||
* orders/wave 取任务快照(order_count/wave_count);
|
||||
* goods/sku 经 wms_wave_pick_task_order 关联订单分表快照(items_total/items_count)。
|
||||
* orders/goods/sku/wave 汇总按订单表状态口径(池内 pick fin + 配送表今日出库 pick fin,
|
||||
* 与 fulfillment 已拣货一致,保证团购+散单=已拣货);
|
||||
* top 按今日创建任务(pick_mode 1,5 团购 / 2,3,4 散单)按人聚合(任务口径)。
|
||||
*
|
||||
* @param {number} warehouseId 仓库 ID
|
||||
* @param {string} currentTableName 常用分表名
|
||||
* @param {string} dispatchTableName 配送分表名
|
||||
* @param {Array<number>} pickModes 拣货模式集合
|
||||
* @param {boolean} isGroup true=团购(wave_scope 1/3);false=散单(其余)
|
||||
* @param {Date} todayStart 今日开始
|
||||
* @param {Date} tomorrowStart 明日开始
|
||||
* @return {Promise<Object>} { orders, goods, sku, wave, top }
|
||||
*/
|
||||
async queryPickingBlock(warehouseId, currentTableName, dispatchTableName, pickModes, todayStart, tomorrowStart) {
|
||||
async queryPickingBlock(warehouseId, currentTableName, dispatchTableName, isGroup, todayStart, tomorrowStart) {
|
||||
const { model } = this.ctx;
|
||||
const { QueryTypes } = model;
|
||||
|
||||
const scopeWhere = isGroup ? 'wave_scope IN (1, 3)' : 'wave_scope NOT IN (1, 3)';
|
||||
const pickModes = isGroup ? [ 1, 5 ] : [ 2, 3, 4 ];
|
||||
const replacements = {
|
||||
warehouseId,
|
||||
pickModes,
|
||||
@ -406,18 +691,33 @@ class WarehousePanelService extends Service {
|
||||
end: tomorrowStart,
|
||||
};
|
||||
|
||||
// top:今日创建任务按人聚合(任务口径)
|
||||
const taskWindowWhere = `
|
||||
t.warehouse_id = :warehouseId AND t.pick_mode IN (:pickModes)
|
||||
AND t.create_time >= :start AND t.create_time < :end
|
||||
AND t.status IN (:activeStatuses)
|
||||
`;
|
||||
|
||||
const [ summaryRows, topRows ] = await Promise.all([
|
||||
model.query(`
|
||||
SELECT COUNT(*) AS task_count, COALESCE(SUM(order_count), 0) AS orders, COALESCE(SUM(wave_count), 0) AS waves
|
||||
FROM wms_wave_pick_task t
|
||||
WHERE ${taskWindowWhere}
|
||||
`, { replacements, type: QueryTypes.SELECT }),
|
||||
// 汇总:订单表状态口径(池内 pick fin + 配送表今日出库 pick fin,与已拣货一致)
|
||||
const summarySql = (tableName, whereFragment) => `
|
||||
SELECT COUNT(*) AS orders, COALESCE(SUM(items_total), 0) AS goods,
|
||||
COALESCE(SUM(items_count), 0) AS sku,
|
||||
COUNT(DISTINCT CASE WHEN wave_id > 0 THEN wave_id END) AS wave
|
||||
FROM \`${tableName}\` WHERE ${whereFragment}
|
||||
`;
|
||||
const poolWhere = `
|
||||
step IN (1, 2, 3) AND outbound_status != 'padding' AND status != 'cancel'
|
||||
AND pick_status = 'fin' AND ${scopeWhere}
|
||||
`;
|
||||
const dispatchWhere = `
|
||||
status != 'cancel' AND outbound_status = 'fin' AND pick_status = 'fin'
|
||||
AND dispatch_lane IN ('m4', 'm5')
|
||||
AND delivery_time >= :start AND delivery_time < :end AND ${scopeWhere}
|
||||
`;
|
||||
|
||||
const [ currentRows, dispatchRows, topRows ] = await Promise.all([
|
||||
model.query(summarySql(currentTableName, poolWhere), { replacements, type: QueryTypes.SELECT }),
|
||||
model.query(summarySql(dispatchTableName, dispatchWhere), { replacements, type: QueryTypes.SELECT }),
|
||||
model.query(`
|
||||
SELECT t.pick_user_id AS user_id, t.pick_user_name AS name,
|
||||
COALESCE(SUM(t.order_count), 0) AS orders, COALESCE(SUM(t.wave_count), 0) AS waves
|
||||
@ -429,11 +729,20 @@ class WarehousePanelService extends Service {
|
||||
`, { replacements, type: QueryTypes.SELECT }),
|
||||
]);
|
||||
|
||||
const [ goodsSkuRows, topGoodsSkuRows ] = await this.queryPickingGoodsSku(
|
||||
const current = Array.isArray(currentRows) && currentRows.length > 0 ? currentRows[0] : {};
|
||||
const dispatch = Array.isArray(dispatchRows) && dispatchRows.length > 0 ? dispatchRows[0] : {};
|
||||
const summary = {
|
||||
orders: Number(current.orders || 0) + Number(dispatch.orders || 0),
|
||||
goods: Number(current.goods || 0) + Number(dispatch.goods || 0),
|
||||
sku: Number(current.sku || 0) + Number(dispatch.sku || 0),
|
||||
wave: Number(current.wave || 0) + Number(dispatch.wave || 0),
|
||||
};
|
||||
|
||||
// top 的 goods/sku 仍按任务口径(订单表无拣货人,无法按人拆分)
|
||||
const [ , topGoodsSkuRows ] = await this.queryPickingGoodsSku(
|
||||
currentTableName, dispatchTableName, taskWindowWhere, replacements
|
||||
);
|
||||
|
||||
const summary = Array.isArray(summaryRows) && summaryRows.length > 0 ? summaryRows[0] : {};
|
||||
const topGoodsSkuMap = new Map();
|
||||
(topGoodsSkuRows || []).forEach(row => {
|
||||
topGoodsSkuMap.set(String(row.user_id), { goods: Number(row.goods || 0), sku: Number(row.sku || 0) });
|
||||
@ -452,10 +761,10 @@ class WarehousePanelService extends Service {
|
||||
});
|
||||
|
||||
return {
|
||||
orders: Number(summary.orders || 0),
|
||||
goods: Number(goodsSkuRows.goods || 0),
|
||||
sku: Number(goodsSkuRows.sku || 0),
|
||||
wave: Number(summary.waves || 0),
|
||||
orders: summary.orders,
|
||||
goods: summary.goods,
|
||||
sku: summary.sku,
|
||||
wave: summary.wave,
|
||||
top,
|
||||
};
|
||||
}
|
||||
@ -473,18 +782,56 @@ class WarehousePanelService extends Service {
|
||||
const { model } = this.ctx;
|
||||
const { QueryTypes } = model;
|
||||
|
||||
const goodsSkuSelect = `
|
||||
SELECT COALESCE(SUM(od.items_total), 0) AS goods, COALESCE(SUM(od.items_count), 0) AS sku
|
||||
FROM wms_wave_pick_task t
|
||||
JOIN wms_wave_pick_task_order pto ON pto.task_id = t.id
|
||||
JOIN \`${currentTableName}\` od ON od.id = pto.order_id AND od.status != 'cancel'
|
||||
WHERE ${taskWindowWhere}
|
||||
`;
|
||||
const goodsSkuSelectDispatch = goodsSkuSelect.replace(`\`${currentTableName}\``, `\`${dispatchTableName}\``);
|
||||
// 任务订单关联表缺失的任务(如 pick_mode=1 团购任务,实测 60 个任务 3862 单无 pto 记录)
|
||||
// 按 wave_id 从订单分表统计,避免 goods/sku 漏算;有 pto 记录的仍走 pto 精确统计
|
||||
const taskWindowWhere2 = taskWindowWhere.replace(/\bt\./g, 't2.');
|
||||
|
||||
const [ currentRows, dispatchRows ] = await Promise.all([
|
||||
model.query(goodsSkuSelect, { replacements, type: QueryTypes.SELECT }),
|
||||
model.query(goodsSkuSelectDispatch, { replacements, type: QueryTypes.SELECT }),
|
||||
const goodsSkuSelect = tableName => `
|
||||
SELECT COALESCE(SUM(x.items_total), 0) AS goods, COALESCE(SUM(x.items_count), 0) AS sku
|
||||
FROM (
|
||||
SELECT od.items_total, od.items_count
|
||||
FROM wms_wave_pick_task t
|
||||
JOIN wms_wave_pick_task_order pto ON pto.task_id = t.id
|
||||
JOIN \`${tableName}\` od ON od.id = pto.order_id AND od.status != 'cancel'
|
||||
WHERE ${taskWindowWhere}
|
||||
UNION ALL
|
||||
SELECT od2.items_total, od2.items_count
|
||||
FROM wms_wave_pick_task t2
|
||||
JOIN \`${tableName}\` od2 ON od2.wave_id = t2.wave_id AND od2.status != 'cancel'
|
||||
WHERE ${taskWindowWhere2} AND t2.wave_id > 0
|
||||
AND NOT EXISTS (SELECT 1 FROM wms_wave_pick_task_order pto2 WHERE pto2.task_id = t2.id)
|
||||
) x
|
||||
`;
|
||||
|
||||
// 第一分支必须限定今日任务窗口(同 goodsSkuSelect):否则 pto 全历史关联订单分表,
|
||||
// 派生子查询 g 物化扫描百万行(生产慢日志实测 1.75M 行 / 9.4s 超时)
|
||||
const taskWindowWhereTp = taskWindowWhere.replace(/\bt\./g, 'tp.');
|
||||
|
||||
const topGoodsSkuSelect = tableName => `
|
||||
SELECT t.pick_user_id AS user_id, COALESCE(SUM(g.items_total), 0) AS goods, COALESCE(SUM(g.items_count), 0) AS sku
|
||||
FROM wms_wave_pick_task t
|
||||
JOIN (
|
||||
SELECT tp.id AS task_id, od.items_total, od.items_count
|
||||
FROM wms_wave_pick_task tp
|
||||
JOIN wms_wave_pick_task_order pto ON pto.task_id = tp.id
|
||||
JOIN \`${tableName}\` od ON od.id = pto.order_id AND od.status != 'cancel'
|
||||
WHERE ${taskWindowWhereTp}
|
||||
UNION ALL
|
||||
SELECT t2.id AS task_id, od2.items_total, od2.items_count
|
||||
FROM wms_wave_pick_task t2
|
||||
JOIN \`${tableName}\` od2 ON od2.wave_id = t2.wave_id AND od2.status != 'cancel'
|
||||
WHERE ${taskWindowWhere2} AND t2.wave_id > 0
|
||||
AND NOT EXISTS (SELECT 1 FROM wms_wave_pick_task_order pto2 WHERE pto2.task_id = t2.id)
|
||||
) g ON g.task_id = t.id
|
||||
WHERE ${taskWindowWhere}
|
||||
GROUP BY t.pick_user_id
|
||||
`;
|
||||
|
||||
const [ currentRows, dispatchRows, topCurrentRows, topDispatchRows ] = await Promise.all([
|
||||
model.query(goodsSkuSelect(currentTableName), { replacements, type: QueryTypes.SELECT }),
|
||||
model.query(goodsSkuSelect(dispatchTableName), { replacements, type: QueryTypes.SELECT }),
|
||||
model.query(topGoodsSkuSelect(currentTableName), { replacements, type: QueryTypes.SELECT }),
|
||||
model.query(topGoodsSkuSelect(dispatchTableName), { replacements, type: QueryTypes.SELECT }),
|
||||
]);
|
||||
|
||||
const current = Array.isArray(currentRows) && currentRows.length > 0 ? currentRows[0] : {};
|
||||
@ -494,21 +841,6 @@ class WarehousePanelService extends Service {
|
||||
sku: Number(current.sku || 0) + Number(dispatch.sku || 0),
|
||||
};
|
||||
|
||||
const topGoodsSkuSelect = `
|
||||
SELECT t.pick_user_id AS user_id, COALESCE(SUM(od.items_total), 0) AS goods, COALESCE(SUM(od.items_count), 0) AS sku
|
||||
FROM wms_wave_pick_task t
|
||||
JOIN wms_wave_pick_task_order pto ON pto.task_id = t.id
|
||||
JOIN \`${currentTableName}\` od ON od.id = pto.order_id AND od.status != 'cancel'
|
||||
WHERE ${taskWindowWhere}
|
||||
GROUP BY t.pick_user_id
|
||||
`;
|
||||
const topGoodsSkuSelectDispatch = topGoodsSkuSelect.replace(`\`${currentTableName}\``, `\`${dispatchTableName}\``);
|
||||
|
||||
const [ topCurrentRows, topDispatchRows ] = await Promise.all([
|
||||
model.query(topGoodsSkuSelect, { replacements, type: QueryTypes.SELECT }),
|
||||
model.query(topGoodsSkuSelectDispatch, { replacements, type: QueryTypes.SELECT }),
|
||||
]);
|
||||
|
||||
const topGoodsSkuMap = new Map();
|
||||
[ ...(topCurrentRows || []), ...(topDispatchRows || []) ].forEach(row => {
|
||||
const key = String(row.user_id);
|
||||
@ -523,36 +855,52 @@ class WarehousePanelService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 打包个人排名(散单+团购任务合并,按打包员姓名聚合)。
|
||||
* 打包统计块(按波次范围区分:wave_scope 1 大团购/3 小团购为团购块,其余为散单块)。
|
||||
*
|
||||
* 口径:今日创建(create_time 今日)且非异常(status != 3)的任务;
|
||||
* 团购任务多人打包时同一任务计入多人(不折算)。
|
||||
* 口径:今日创建(create_time 今日)且已完成(status = 2)且未删除的任务
|
||||
* (打包中 status=1 不计入,见 stageOverview doing 打包中任务数);
|
||||
* orders 按打包模式统计——pack_mode=2(团购模式)按 pack_quantity(波次订单数快照)
|
||||
* 求和,pack_mode=1 散单每任务 1 单;
|
||||
* 团购块 top 按打包台(wms_workbench.name)聚合;散单块 top 按打包员
|
||||
* (pack_task_packer.account_name)聚合。
|
||||
*
|
||||
* @param {number} warehouseId 仓库 ID
|
||||
* @param {Date} todayStart 今日开始
|
||||
* @param {Date} tomorrowStart 明日开始
|
||||
* @return {Promise<Object>} { orders, goods, sku, wave, top }
|
||||
* @param {boolean} isGroup true=团购(wave_scope 1/3,top 按打包台);false=散单(wave_scope 非 1/3,top 按打包员)
|
||||
* @return {Promise<Object>} 团购 { orders, goods, sku, wave, top };散单 { orders, goods, sku, top }(无 wave)
|
||||
*/
|
||||
async queryPackingPersonal(warehouseId, todayStart, tomorrowStart) {
|
||||
async queryPackingBlock(warehouseId, todayStart, tomorrowStart, isGroup) {
|
||||
const { model } = this.ctx;
|
||||
const { QueryTypes } = model;
|
||||
|
||||
const scopeWhere = isGroup ? 'pt.wave_scope IN (1, 3)' : 'pt.wave_scope NOT IN (1, 3)';
|
||||
// 订单数口径:pack_mode=2(团购模式,含 wave_scope=3 小团购)按 pack_quantity 求和;散单每任务 1 单
|
||||
const ordersExpr = 'SUM(CASE WHEN pt.pack_mode = 2 THEN pt.pack_quantity ELSE 1 END) AS orders';
|
||||
const replacements = { warehouseId, start: todayStart, end: tomorrowStart };
|
||||
const taskWindowWhere = `
|
||||
pt.warehouse_id = :warehouseId AND pt.create_time >= :start AND pt.create_time < :end
|
||||
AND pt.status != 3 AND pt.deleted_at IS NULL
|
||||
pt.warehouse_id = :warehouseId AND ${scopeWhere}
|
||||
AND pt.create_time >= :start AND pt.create_time < :end
|
||||
AND pt.status = 2 AND pt.deleted_at IS NULL
|
||||
`;
|
||||
|
||||
const [ summaryRows, topRows ] = await Promise.all([
|
||||
model.query(`
|
||||
SELECT COUNT(*) AS orders, COALESCE(SUM(pt.item_quantity), 0) AS goods,
|
||||
// 团购块按打包台聚合;散单块按打包员聚合
|
||||
const topSql = isGroup
|
||||
? `
|
||||
SELECT COALESCE(w.name, '未指定打包台') AS name, ${ordersExpr},
|
||||
COALESCE(SUM(pt.item_quantity), 0) AS goods,
|
||||
COALESCE(SUM(pt.sku_count), 0) AS sku,
|
||||
COUNT(DISTINCT CASE WHEN pt.wave_id > 0 THEN pt.wave_id END) AS wave
|
||||
FROM wms_pack_task pt
|
||||
LEFT JOIN wms_workbench w ON w.id = pt.workbench_id AND w.deleted_at IS NULL
|
||||
WHERE ${taskWindowWhere}
|
||||
`, { replacements, type: QueryTypes.SELECT }),
|
||||
model.query(`
|
||||
SELECT pp.account_name AS name, COUNT(*) AS orders, COALESCE(SUM(pt.item_quantity), 0) AS goods,
|
||||
GROUP BY pt.workbench_id, w.name
|
||||
ORDER BY orders DESC
|
||||
LIMIT 5
|
||||
`
|
||||
: `
|
||||
SELECT pp.account_name AS name, ${ordersExpr},
|
||||
COALESCE(SUM(pt.item_quantity), 0) AS goods,
|
||||
COALESCE(SUM(pt.sku_count), 0) AS sku,
|
||||
COUNT(DISTINCT CASE WHEN pt.wave_id > 0 THEN pt.wave_id END) AS wave
|
||||
FROM wms_pack_task pt
|
||||
@ -561,60 +909,123 @@ class WarehousePanelService extends Service {
|
||||
GROUP BY pp.account_name
|
||||
ORDER BY orders DESC
|
||||
LIMIT 5
|
||||
`;
|
||||
|
||||
const [ summaryRows, topRows ] = await Promise.all([
|
||||
model.query(`
|
||||
SELECT ${ordersExpr}, COALESCE(SUM(pt.item_quantity), 0) AS goods,
|
||||
COALESCE(SUM(pt.sku_count), 0) AS sku,
|
||||
COUNT(DISTINCT CASE WHEN pt.wave_id > 0 THEN pt.wave_id END) AS wave
|
||||
FROM wms_pack_task pt
|
||||
WHERE ${taskWindowWhere}
|
||||
`, { replacements, type: QueryTypes.SELECT }),
|
||||
model.query(topSql, { replacements, type: QueryTypes.SELECT }),
|
||||
]);
|
||||
|
||||
const summary = Array.isArray(summaryRows) && summaryRows.length > 0 ? summaryRows[0] : {};
|
||||
const top = (topRows || []).map((row, index) => ({
|
||||
rank: index + 1,
|
||||
name: row.name || '',
|
||||
orders: Number(row.orders || 0),
|
||||
goods: Number(row.goods || 0),
|
||||
sku: Number(row.sku || 0),
|
||||
wave: Number(row.wave || 0),
|
||||
}));
|
||||
const top = (topRows || []).map((row, index) => {
|
||||
const item = {
|
||||
rank: index + 1,
|
||||
name: row.name || '',
|
||||
orders: Number(row.orders || 0),
|
||||
goods: Number(row.goods || 0),
|
||||
sku: Number(row.sku || 0),
|
||||
};
|
||||
// 仅团购块输出波次数(散单块无波次语义)
|
||||
if (isGroup) {
|
||||
item.wave = Number(row.wave || 0);
|
||||
}
|
||||
return item;
|
||||
});
|
||||
|
||||
return {
|
||||
const result = {
|
||||
orders: Number(summary.orders || 0),
|
||||
goods: Number(summary.goods || 0),
|
||||
sku: Number(summary.sku || 0),
|
||||
wave: Number(summary.wave || 0),
|
||||
top,
|
||||
};
|
||||
if (isGroup) {
|
||||
result.wave = Number(summary.wave || 0);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 今日订单实时趋势(固定 08:00-18:00 共 11 点,按小时补零)。
|
||||
* 今日订单实时趋势(业务日窗口 24 点,label 从仓库自然日开始时间起每小时一点,到次日自然日开始时间)。
|
||||
* created_count:业务日窗口内下单量(池内待处理 + 配送表今日出库订单,按订单创建时间落桶)
|
||||
* 按小时累计(最后一点=业务日内下单总量);窗口即业务日:未到次日自然日开始时间时
|
||||
* 为 [今日自然日开始时间, 次日自然日开始时间),凌晨(已过零点)时为 [昨日自然日开始时间, 今日自然日开始时间)。
|
||||
*
|
||||
* @param {Object} currentModel 常用分表模型
|
||||
* @param {Object} dispatchModel 配送分表模型
|
||||
* @param {Object} pendingBase 待处理基础过滤
|
||||
* @param {Date} todayStart 今日开始
|
||||
* @return {Promise<Object>} { max, points }
|
||||
* @param {Date} todayStart 业务日开始时间(仓库自然日 day_start_time)
|
||||
* @param {Date} tomorrowStart 业务日结束时间(次日自然日开始时间)
|
||||
* @return {Promise<Object>} { max, points },points 每项 { label, created_count }
|
||||
*/
|
||||
async queryTrend(currentModel, pendingBase, todayStart) {
|
||||
async queryTrend(currentModel, dispatchModel, pendingBase, todayStart, tomorrowStart) {
|
||||
const { Op, fn, col, literal } = this.app.Sequelize;
|
||||
const now = new Date();
|
||||
|
||||
const rows = await currentModel.findAll({
|
||||
attributes: [
|
||||
[ fn('HOUR', col('create_at')), 'hour' ],
|
||||
[ fn('COUNT', literal('*')), 'count' ],
|
||||
],
|
||||
where: { ...pendingBase, create_at: { [Op.gte]: todayStart, [Op.lt]: now } },
|
||||
group: [ 'hour' ],
|
||||
raw: true,
|
||||
// 横轴 24 点:从自然日开始时间起每小时一点(跨天,label=桶起点 HH:00)
|
||||
const points = [];
|
||||
const bucketByHour = new Map();
|
||||
for (let index = 0; index < 24; index++) {
|
||||
const bucketStart = new Date(todayStart.getTime() + index * 3600000);
|
||||
bucketByHour.set(bucketStart.getHours(), index);
|
||||
points.push({
|
||||
label: `${String(bucketStart.getHours()).padStart(2, '0')}:00`,
|
||||
created_count: 0,
|
||||
});
|
||||
}
|
||||
const bucketIndexOf = hour => {
|
||||
const bucket = bucketByHour.get(Number(hour));
|
||||
return bucket === undefined ? 0 : bucket;
|
||||
};
|
||||
|
||||
// 下单量按创建时间落桶(池内待处理 + 配送表今日出库,窗口=业务日 [todayStart, tomorrowStart))
|
||||
const dispatchTodayBase = {
|
||||
status: { [Op.ne]: 'cancel' },
|
||||
outbound_status: 'fin',
|
||||
delivery_time: { [Op.gte]: todayStart, [Op.lt]: tomorrowStart },
|
||||
dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] },
|
||||
};
|
||||
const [
|
||||
createdRows,
|
||||
dispatchCreatedRows,
|
||||
] = await Promise.all([
|
||||
currentModel.findAll({
|
||||
attributes: [
|
||||
[ fn('HOUR', col('create_at')), 'hour' ],
|
||||
[ fn('COUNT', literal('*')), 'count' ],
|
||||
],
|
||||
where: { ...pendingBase, create_at: { [Op.gte]: todayStart, [Op.lt]: tomorrowStart } },
|
||||
group: [ 'hour' ],
|
||||
raw: true,
|
||||
}),
|
||||
dispatchModel.findAll({
|
||||
attributes: [
|
||||
[ fn('HOUR', col('create_at')), 'hour' ],
|
||||
[ fn('COUNT', literal('*')), 'count' ],
|
||||
],
|
||||
where: { ...dispatchTodayBase, create_at: { [Op.gte]: todayStart, [Op.lt]: tomorrowStart } },
|
||||
group: [ 'hour' ],
|
||||
raw: true,
|
||||
}),
|
||||
]);
|
||||
|
||||
[ ...(createdRows || []), ...(dispatchCreatedRows || []) ].forEach(row => {
|
||||
points[bucketIndexOf(row.hour)].created_count += Number(row.count || 0);
|
||||
});
|
||||
|
||||
const hourMap = new Map();
|
||||
(rows || []).forEach(row => {
|
||||
hourMap.set(Number(row.hour), Number(row.count || 0));
|
||||
});
|
||||
// 累计口径:每点为截至该小时结束的累计总数(最后一点=业务日内下单总量)
|
||||
for (let index = 1; index < points.length; index++) {
|
||||
points[index].created_count += points[index - 1].created_count;
|
||||
}
|
||||
|
||||
const points = TREND_HOURS.map(hour => ({
|
||||
label: `${String(hour).padStart(2, '0')}:00`,
|
||||
value: hourMap.get(hour) || 0,
|
||||
}));
|
||||
const peak = points.reduce((maxValue, point) => Math.max(maxValue, point.value), 0);
|
||||
const peak = points.reduce(
|
||||
(maxValue, point) => Math.max(maxValue, point.created_count),
|
||||
0
|
||||
);
|
||||
const max = Math.max(Math.ceil(peak / 10) * 10, 10);
|
||||
|
||||
return { max, points };
|
||||
|
||||
@ -6,6 +6,9 @@ const WechatOpenClient = require('../../lib/wechat_open_client');
|
||||
|
||||
const STATE_TTL_SECONDS = 600;
|
||||
|
||||
// 系统默认用户须知的保留 appid(种子行,不面向真实小程序),供首次授权时作为第一版复制
|
||||
const SYSTEM_AGREEMENT_APPID = 'system';
|
||||
|
||||
/**
|
||||
* 生成登录码:{uuid, form} JSON 的 base64 字符串。
|
||||
* uuid 格式为 `{id}_{6位随机数}`(id 为 wms_user_oauth.id),form 固定 wechat;
|
||||
@ -625,6 +628,40 @@ class WechatSystemsService extends Service {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 首次授权的小程序自动写入系统默认用户须知作为第一版(幂等:已有任意版本则跳过)。
|
||||
*
|
||||
* 系统默认内容来自 wms_wechat_agreement_version 中 appid='system' 的最新一条记录;
|
||||
* 后续 PC 端 setUserAgreement 可继续追加新版本。
|
||||
*
|
||||
* @param {string} appid 小程序 AppID。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async ensureDefaultAgreementVersion(appid) {
|
||||
const { ctx } = this;
|
||||
if (!appid) return;
|
||||
|
||||
const existing = await ctx.model.WechatAgreementVersion.findOne({
|
||||
where: { appid },
|
||||
attributes: [ 'id' ],
|
||||
raw: true,
|
||||
});
|
||||
if (existing) return;
|
||||
|
||||
const systemDefault = await ctx.model.WechatAgreementVersion.findOne({
|
||||
where: { appid: SYSTEM_AGREEMENT_APPID },
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
attributes: [ 'content' ],
|
||||
raw: true,
|
||||
});
|
||||
if (!systemDefault || !systemDefault.content) {
|
||||
ctx.logger.warn(`[wechat] 缺少系统默认用户须知(appid=${SYSTEM_AGREEMENT_APPID}),跳过写入 appid=${appid}`);
|
||||
return;
|
||||
}
|
||||
|
||||
await ctx.model.WechatAgreementVersion.create({ appid, content: systemDefault.content });
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定协议版本内容(需登录免权限):传入版本记录 id(wms_wechat_agreement_version.id,
|
||||
* 可在 wechat.userList 的 agreement_version_id 获取),校验该版本对应 appid 属于当前仓库的
|
||||
@ -1349,9 +1386,7 @@ class WechatSystemsService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取小程序模板库列表(需登录),只拉取普通模板(template_type=0),Redis 缓存 24h。
|
||||
*
|
||||
* 有缓存直接返回缓存列表;无缓存时调微信 gettemplatelist 拉取并写入缓存。
|
||||
* 获取小程序模板库列表(需登录),只拉取普通模板(template_type=0),不缓存(每次实时拉取)。
|
||||
*
|
||||
* @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。
|
||||
*/
|
||||
@ -1359,20 +1394,6 @@ class WechatSystemsService extends Service {
|
||||
const { ctx } = this;
|
||||
|
||||
const client = new WechatOpenClient(ctx);
|
||||
const CACHE_KEY = 'wechat:template:list:normal';
|
||||
const CACHE_TTL_SECONDS = 24 * 3600;
|
||||
|
||||
const cached = await client.cacheGet(CACHE_KEY);
|
||||
if (cached) {
|
||||
try {
|
||||
const list = JSON.parse(cached);
|
||||
if (Array.isArray(list)) {
|
||||
return { success: true, data: { list, from_cache: true }, code: 200, message: '获取成功' };
|
||||
}
|
||||
} catch (e) {
|
||||
// 缓存损坏,忽略并重新拉取
|
||||
}
|
||||
}
|
||||
|
||||
const result = await client.getTemplateList(0);
|
||||
if (!result || Number(result.errcode) !== 0) {
|
||||
@ -1381,9 +1402,8 @@ class WechatSystemsService extends Service {
|
||||
}
|
||||
|
||||
const list = Array.isArray(result.template_list) ? result.template_list : [];
|
||||
await client.cacheSet(CACHE_KEY, JSON.stringify(list), CACHE_TTL_SECONDS);
|
||||
|
||||
return { success: true, data: { list, from_cache: false }, code: 200, message: '获取成功' };
|
||||
return { success: true, data: { list }, code: 200, message: '获取成功' };
|
||||
}
|
||||
|
||||
/**
|
||||
@ -1490,7 +1510,7 @@ class WechatSystemsService extends Service {
|
||||
* → 调微信 commit → 成功后回写 wms_wechat_app.template_id/user_version。
|
||||
*
|
||||
* @param {object} data 入参。
|
||||
* @param {number|string} data.template_id 代码模板 ID(getTemplateList 获取)。
|
||||
* @param {number|string} data.template_id 代码模板 ID(getTemplateList 获取,允许 0:普通模板库模板 ID 从 0 开始)。
|
||||
* @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。
|
||||
*/
|
||||
async commit(data = {}) {
|
||||
@ -1509,9 +1529,10 @@ class WechatSystemsService extends Service {
|
||||
return { success: false, data: null, code: 0, message: '当前仓库未授权小程序' };
|
||||
}
|
||||
|
||||
// template_id 允许 0:普通模板库的模板 ID 从 0 开始,0 表示第一个模板(微信官方 wxa/commit 示例即 "0")
|
||||
const templateId = Number(data.template_id);
|
||||
if (!Number.isInteger(templateId) || templateId <= 0) {
|
||||
return { success: false, data: null, code: 0, message: 'template_id 必须为正整数' };
|
||||
if (!Number.isInteger(templateId) || templateId < 0) {
|
||||
return { success: false, data: null, code: 0, message: 'template_id 必须为非负整数' };
|
||||
}
|
||||
|
||||
// 判断授权权限:需包含代码管理权限集 18
|
||||
|
||||
@ -53,6 +53,8 @@ const OSD_CACHE_KEY_PREFIX = 'osd_';
|
||||
const OSD_CACHE_TTL_SECONDS = 3600;
|
||||
/** @type {string} 打包任务结束(空闲态)时的摄像头 OSD 叠加文字 */
|
||||
const OSD_IDLE_TEXT = '无任务';
|
||||
/** @type {number} 打包开始(下发 OSD)时工作台摄像头跳转的预置点编号 */
|
||||
const PACK_PRESET_GOTO_ID = 1;
|
||||
|
||||
class WorkbenchService extends Service {
|
||||
/**
|
||||
@ -257,6 +259,7 @@ class WorkbenchService extends Service {
|
||||
const cachedCtx = await this._loadPackCtx(bizData);
|
||||
return await this._packOrder({
|
||||
delivery_order_code: cachedCtx.delivery_order_code,
|
||||
order_id: cachedCtx.order_id,
|
||||
wave_no: cachedCtx.wave_no,
|
||||
wave_scope: cachedCtx.wave_scope,
|
||||
waybill_code: cachedCtx.waybill_code,
|
||||
@ -264,7 +267,10 @@ class WorkbenchService extends Service {
|
||||
workbench_id: cachedCtx.workbench_id != null ? Number(cachedCtx.workbench_id) : null,
|
||||
});
|
||||
}
|
||||
return await this._packOrder(bizData);
|
||||
// 旧参数模式:order_id 不接受设备上报(仅 key 模式由后端缓存注入,防篡改),
|
||||
// 避免设备用外部键/主键交叉传参造成查单口径漂移
|
||||
const { order_id: _ignoredOrderId, ...legacyPackParams } = bizData;
|
||||
return await this._packOrder(legacyPackParams);
|
||||
}
|
||||
case 'finishPack':
|
||||
return await this._finishPack(data || {});
|
||||
@ -772,6 +778,9 @@ class WorkbenchService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
// 通知仓库面板刷新(大屏增量更新,失败不影响主流程)
|
||||
await this.service.systems.warehousePanel.touchLastChangeAt(Number(warehouseId));
|
||||
|
||||
return orderPackStatus;
|
||||
}
|
||||
|
||||
@ -784,14 +793,16 @@ class WorkbenchService extends Service {
|
||||
* 服务端复查落库,防止前端失真;写入 wms_pack_task.wave_scope。
|
||||
* 响应附大团购倒计时字段:wave_scope=1 时下发 pack_wait_seconds(大团购打包系数 × 当前波次打包数 ÷ 当前工作台打包人数,秒)
|
||||
* 与 pack_start_time(开始打包时间,毫秒时间戳)供前端倒计时;其他波次两字段均为 0。
|
||||
* @param {Object} params - { delivery_order_code, wave_no, wave_scope, warehouse_id, workbench_id, status, pack_time, waybill_code, users }
|
||||
* @param {Object} params - { delivery_order_code, order_id, wave_no, wave_scope, warehouse_id, workbench_id, status, pack_time, waybill_code, users }
|
||||
* @param {number} [params.order_id] 订单主键(key 模式由扫码上下文注入,优先用它定位订单;
|
||||
* 发货单号唯一性仅为「单号+货主+仓库」,跨货主可重复,不作为首选查单键)
|
||||
* @param {string} [params.waybill_code] 扫描打包的运单号(可选,用于运单维度记录流水)
|
||||
* @param {number} [params.wave_scope] 波次范围(0未分配 1大团购 2散单 3小团购 4单品单件,可选)
|
||||
* @returns {Promise<Object>} 打包结果 { task_id, order_id, delivery_order_code, wave_no, isSandan, pack_mode, status, pack_wait_seconds, pack_start_time, batch? }
|
||||
*/
|
||||
async _packOrder(params) {
|
||||
const { ctx } = this;
|
||||
const { delivery_order_code: deliveryOrderCode, wave_no: waveNo,
|
||||
const { delivery_order_code: deliveryOrderCode, order_id: orderIdParam, wave_no: waveNo,
|
||||
wave_scope: waveScopeParam,
|
||||
warehouse_id: inputWarehouseId, workbench_id: workbenchIdRaw,
|
||||
status: packStatus, pack_time: packTime,
|
||||
@ -801,7 +812,9 @@ class WorkbenchService extends Service {
|
||||
waybill_code: waybillCodeParam,
|
||||
users: usersParam } = params;
|
||||
|
||||
if (!deliveryOrderCode) throw new Error('发货单号不能为空');
|
||||
if (!deliveryOrderCode && !(Number.isInteger(Number(orderIdParam)) && Number(orderIdParam) > 0)) {
|
||||
throw new Error('发货单号不能为空');
|
||||
}
|
||||
if (!inputWarehouseId) throw new Error('仓库ID不能为空');
|
||||
|
||||
const warehouseId = parseInt(inputWarehouseId);
|
||||
@ -814,28 +827,49 @@ class WorkbenchService extends Service {
|
||||
: null;
|
||||
const packTimeMs = packTime ? Number(packTime) * 1000 : Date.now();
|
||||
|
||||
// 步骤1:查找订单
|
||||
// 步骤1:查找订单(current → dispatch 分表遍历)
|
||||
// 优先按订单主键定位:发货单号唯一索引为 (delivery_order_code, store_id, warehouse_id),
|
||||
// 跨货主可重复,按「发货单号 + 仓库」反查在撞号时会串到别的货主的订单(历史缺陷);
|
||||
// 仅在无 order_id(旧参数模式)或主键未命中时,才按发货单号兜底。
|
||||
const orderDeliveryFactory = ctx.model.OrderDeliveryFactory;
|
||||
const tableOrders = [
|
||||
{ label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) },
|
||||
{ label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) },
|
||||
];
|
||||
const normalizedOrderIdParam = Number(orderIdParam);
|
||||
const hasOrderIdParam = Number.isInteger(normalizedOrderIdParam) && normalizedOrderIdParam > 0;
|
||||
|
||||
let orderRow = null;
|
||||
for (const entry of tableOrders) {
|
||||
try {
|
||||
const model = await entry.getModel();
|
||||
if (!model) continue;
|
||||
const row = await model.findOne({
|
||||
where: { delivery_order_code: deliveryOrderCode, warehouse_id: warehouseId },
|
||||
raw: true,
|
||||
});
|
||||
if (row) { orderRow = row; break; }
|
||||
} catch (_err) { continue; }
|
||||
}
|
||||
const findOneInTables = async where => {
|
||||
for (const entry of tableOrders) {
|
||||
try {
|
||||
const model = await entry.getModel();
|
||||
if (!model) continue;
|
||||
const row = await model.findOne({ where, raw: true });
|
||||
if (row) return row;
|
||||
} catch (_err) { continue; }
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const orderByPrimaryKey = hasOrderIdParam
|
||||
? await findOneInTables({ id: normalizedOrderIdParam, warehouse_id: warehouseId })
|
||||
: null;
|
||||
const orderRow = orderByPrimaryKey
|
||||
|| await findOneInTables({ delivery_order_code: deliveryOrderCode, warehouse_id: warehouseId });
|
||||
|
||||
if (!orderRow) throw new Error(`未找到发货单 [${deliveryOrderCode}]`);
|
||||
|
||||
// 主键与发货单号反查结果不一致时留痕(主键优先,防止串单)
|
||||
if (hasOrderIdParam && Number(orderRow.id) !== normalizedOrderIdParam) {
|
||||
ctx.logger.warn('[Workbench._packOrder] order_id 未命中、改按发货单号兜底命中 orderIdParam=%d hitOrderId=%d deliveryOrderCode=%s',
|
||||
normalizedOrderIdParam, Number(orderRow.id), deliveryOrderCode);
|
||||
}
|
||||
if (deliveryOrderCode && orderRow.delivery_order_code
|
||||
&& String(orderRow.delivery_order_code) !== String(deliveryOrderCode)) {
|
||||
ctx.logger.warn('[Workbench._packOrder] 发货单号与命中订单不一致,以订单主键为准 orderId=%d passed=%s hit=%s',
|
||||
Number(orderRow.id), deliveryOrderCode, orderRow.delivery_order_code);
|
||||
}
|
||||
|
||||
const orderId = orderRow.id;
|
||||
const waveId = orderRow.wave_id || 0;
|
||||
const actualWaveNo = waveNo || orderRow.wave_no || '';
|
||||
@ -1207,6 +1241,8 @@ class WorkbenchService extends Service {
|
||||
|
||||
const OsdClient = require('../../lib/osd_client');
|
||||
const osdClient = new OsdClient(ctx);
|
||||
const PtzClient = require('../../lib/ptz_client');
|
||||
const ptzClient = new PtzClient(ctx);
|
||||
|
||||
try {
|
||||
await Promise.all(cameraIds.map(async cameraId => {
|
||||
@ -1217,6 +1253,21 @@ class WorkbenchService extends Service {
|
||||
});
|
||||
if (!camera || !camera.ip) return;
|
||||
|
||||
// 打包开始:先跳转预设点1(机位复位),失败仅告警,不影响 OSD 下发
|
||||
try {
|
||||
const presetResult = await ptzClient.presetGoto({
|
||||
camera,
|
||||
warehouseId,
|
||||
presetId: PACK_PRESET_GOTO_ID,
|
||||
});
|
||||
if (!presetResult.success) {
|
||||
ctx.logger.warn('[Workbench._packOrder] 预设点跳转失败 cameraId=%d presetId=%d error=%s',
|
||||
cameraId, PACK_PRESET_GOTO_ID, presetResult.error || '打印服务返回异常');
|
||||
}
|
||||
} catch (presetErr) {
|
||||
ctx.logger.warn('[Workbench._packOrder] 预设点跳转异常 cameraId=%d err=%s', cameraId, presetErr.message);
|
||||
}
|
||||
|
||||
const result = await osdClient.setOsd({
|
||||
camera,
|
||||
warehouseId,
|
||||
@ -3925,11 +3976,16 @@ class WorkbenchService extends Service {
|
||||
}
|
||||
packParams = {
|
||||
delivery_order_code: cachedCtx.delivery_order_code,
|
||||
// 订单主键由后端扫码上下文注入:发货单号唯一性仅为 (单号, 货主, 仓库),
|
||||
// 跨货主可重复,按单号+仓库反查会串单,故打包以主键为准
|
||||
order_id: cachedCtx.order_id,
|
||||
wave_no: cachedCtx.wave_no,
|
||||
waybill_code: cachedCtx.waybill_code,
|
||||
};
|
||||
} else {
|
||||
packParams = legacyParams || {};
|
||||
// 旧参数模式:order_id 不接受设备上报(仅 key 模式由后端缓存注入,防篡改)
|
||||
const { order_id: _ignoredOrderId, ...restLegacyParams } = legacyParams || {};
|
||||
packParams = restLegacyParams;
|
||||
}
|
||||
|
||||
const result = await this._packOrder({
|
||||
|
||||
@ -0,0 +1,20 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* wms_return_unpack 补充登记时间索引。
|
||||
* 看板 fulfillment 今日拆包件数按 warehouse_id + created_at 今日范围计数,
|
||||
* 原表仅有 (warehouse_id, unpack_date) 等索引,按登记时间过滤会退化为
|
||||
* 全表扫描,新增 (warehouse_id, created_at) 复合索引使范围过滤走索引
|
||||
* (对齐 wms_return_received 的 idx_warehouse_created_at)。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
await queryInterface.addIndex('wms_return_unpack', [ 'warehouse_id', 'created_at' ], {
|
||||
name: 'idx_warehouse_created_at',
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.removeIndex('wms_return_unpack', 'idx_warehouse_created_at');
|
||||
},
|
||||
};
|
||||
98
database/migrations/20261013100000-create-wms-container.js
Normal file
98
database/migrations/20261013100000-create-wms-container.js
Normal file
@ -0,0 +1,98 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 创建容器(篮筐)资产登记表 wms_container。
|
||||
*
|
||||
* 用于登记仓库的物理容器(篮筐)资产:容器编号、使用状态、是否损坏、损坏说明、备注等。
|
||||
* 同一仓库内容器编号唯一(uk_warehouse_container_no),通过 warehouse_id 做数据隔离。
|
||||
*
|
||||
* 后续用途:散单拣货把购物车商品临时转移到容器时,通过 status 标记容器占用/空闲。
|
||||
*
|
||||
* 字段:
|
||||
* warehouse_id 仓库ID(数据隔离维度)
|
||||
* container_no 容器编号(篮筐编号)
|
||||
* status 使用状态(idle=空闲 in_use=占用)
|
||||
* is_damaged 是否损坏(Y=损坏 N=正常)
|
||||
* damage_remark 损坏说明
|
||||
* remark 备注
|
||||
* creator_id / creator_name 登记人
|
||||
* created_at / updated_at 审计时间
|
||||
*
|
||||
* 索引:
|
||||
* uk_warehouse_container_no(warehouse_id + container_no 唯一)
|
||||
* idx_warehouse_id
|
||||
* idx_status
|
||||
* idx_is_damaged
|
||||
*/
|
||||
|
||||
const TABLE_NAME = 'wms_container';
|
||||
|
||||
module.exports = {
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
async up(queryInterface, Sequelize) {
|
||||
const { BIGINT, STRING, ENUM, DATE } = Sequelize;
|
||||
await queryInterface.createTable(TABLE_NAME, {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '仓库ID(数据隔离维度)',
|
||||
},
|
||||
container_no: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '容器编号(篮筐编号)',
|
||||
},
|
||||
status: {
|
||||
type: ENUM('idle', 'in_use'),
|
||||
allowNull: false,
|
||||
defaultValue: 'idle',
|
||||
comment: '使用状态:idle=空闲 in_use=占用(散单商品临时转移)',
|
||||
},
|
||||
is_damaged: {
|
||||
type: ENUM('Y', 'N'),
|
||||
allowNull: false,
|
||||
defaultValue: 'N',
|
||||
comment: '是否损坏:Y=损坏 N=正常',
|
||||
},
|
||||
damage_remark: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '损坏说明',
|
||||
},
|
||||
remark: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '备注',
|
||||
},
|
||||
creator_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '登记人账户ID',
|
||||
},
|
||||
creator_name: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '登记人名称快照',
|
||||
},
|
||||
created_at: { type: DATE, allowNull: false, comment: '创建时间' },
|
||||
updated_at: { type: DATE, allowNull: false, comment: '更新时间' },
|
||||
});
|
||||
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'container_no' ], { unique: true, name: 'uk_warehouse_container_no' });
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id' ], { name: 'idx_warehouse_id' });
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'status' ], { name: 'idx_status' });
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'is_damaged' ], { name: 'idx_is_damaged' });
|
||||
},
|
||||
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.dropTable(TABLE_NAME);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,44 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 用户须知系统默认版本种子(2026-10-14):
|
||||
* - appid='system' 作为系统级默认须知模板(保留行,不面向真实小程序);
|
||||
* - 新授权的小程序(首次授权)自动复制该内容作为第一版
|
||||
* (见 app/service/systems/wechat.js#ensureDefaultAgreementVersion);
|
||||
* - 幂等:已存在 appid='system' 记录则跳过。
|
||||
*/
|
||||
|
||||
const TABLE_NAME = 'wms_wechat_agreement_version';
|
||||
const SYSTEM_APPID = 'system';
|
||||
|
||||
const DEFAULT_CONTENT = [
|
||||
'<h3>小程序用户须知</h3>',
|
||||
'<p>欢迎使用本小程序。在使用本小程序及相关服务前,请仔细阅读并理解本须知。</p>',
|
||||
'<p>1. 账号与绑定:登录后可通过「绑定账号」功能关联您的仓库系统账号;绑定信息仅用于身份识别与业务操作,请妥善保管账号密码。</p>',
|
||||
'<p>2. 数据与隐私:小程序仅收集提供仓储、物流等服务所必需的信息(如登录凭证、订单与库存数据),不会向无关第三方泄露。</p>',
|
||||
'<p>3. 使用规范:请勿利用本小程序从事违反法律法规或侵害他人权益的行为;如发现异常,请及时联系本小程序运营方。</p>',
|
||||
'<p>4. 条款更新:本须知可能适时更新,更新后的内容自发布时生效。</p>',
|
||||
].join('');
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
const rows = await queryInterface.sequelize.query(
|
||||
`SELECT id FROM ${TABLE_NAME} WHERE appid = ? LIMIT 1`,
|
||||
{ replacements: [ SYSTEM_APPID ], type: queryInterface.sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
if (rows && rows.length > 0) {
|
||||
return;
|
||||
}
|
||||
await queryInterface.sequelize.query(
|
||||
`INSERT INTO ${TABLE_NAME} (appid, content, created_at, updated_at) VALUES (?, ?, NOW(), NOW())`,
|
||||
{ replacements: [ SYSTEM_APPID, DEFAULT_CONTENT ] }
|
||||
);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.sequelize.query(
|
||||
`DELETE FROM ${TABLE_NAME} WHERE appid = ?`,
|
||||
{ replacements: [ SYSTEM_APPID ] }
|
||||
);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,49 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 回填系统默认用户须知(2026-10-14):
|
||||
* - 对 wms_wechat_app 中尚不存在任何用户须知版本的小程序,复制系统默认须知
|
||||
* (wms_wechat_agreement_version 中 appid='system' 最新一条)作为第一版;
|
||||
* - 幂等:已有任意版本的小程序跳过;无系统默认行则跳过(依赖种子迁移 20261014100000)。
|
||||
*/
|
||||
|
||||
const TABLE_NAME = 'wms_wechat_agreement_version';
|
||||
const SYSTEM_APPID = 'system';
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
const { QueryTypes } = queryInterface.sequelize;
|
||||
|
||||
const systemRows = await queryInterface.sequelize.query(
|
||||
`SELECT content FROM ${TABLE_NAME} WHERE appid = ? ORDER BY id DESC LIMIT 1`,
|
||||
{ replacements: [ SYSTEM_APPID ], type: QueryTypes.SELECT }
|
||||
);
|
||||
const systemContent = systemRows && systemRows.length > 0 ? systemRows[0].content : null;
|
||||
if (!systemContent) {
|
||||
console.log('[backfill] 缺少系统默认须知(appid=system),跳过回填');
|
||||
return;
|
||||
}
|
||||
|
||||
const appids = await queryInterface.sequelize.query(
|
||||
`SELECT a.appid FROM wms_wechat_app a
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM ${TABLE_NAME} v WHERE v.appid = a.appid
|
||||
)
|
||||
ORDER BY a.id ASC`,
|
||||
{ type: QueryTypes.SELECT }
|
||||
);
|
||||
|
||||
for (const row of appids) {
|
||||
await queryInterface.sequelize.query(
|
||||
`INSERT INTO ${TABLE_NAME} (appid, content, created_at, updated_at) VALUES (?, ?, NOW(), NOW())`,
|
||||
{ replacements: [ row.appid, systemContent ] }
|
||||
);
|
||||
}
|
||||
|
||||
console.log(`[backfill] 回填系统默认须知 appid 数量: ${appids.length}`);
|
||||
},
|
||||
|
||||
async down() {
|
||||
// 回填行与人工版本无法可靠区分,不做逆向删除
|
||||
},
|
||||
};
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,8 +1,8 @@
|
||||
{
|
||||
"module": "system",
|
||||
"description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内",
|
||||
"version": "0.3.262",
|
||||
"updatedAt": "2026-10-10",
|
||||
"version": "0.3.301",
|
||||
"updatedAt": "2026-10-16",
|
||||
"headers": [
|
||||
{
|
||||
"name": "platform",
|
||||
@ -2621,15 +2621,18 @@
|
||||
"name": "data",
|
||||
"type": "object",
|
||||
"required": true,
|
||||
"description": "面板数据对象;is_change=false 时为空对象(节约流量),is_change=true 时输出。已输出字段:title(仓库名)、fulfillment(订单履约链路 6 环节未/已 + total)、stageOverview(totalOrders/interceptOrders/stages 5 卡:receiving/shelf/pick/recheck/pack)、b2b(orders/goods/sku)、groupPicking、scatterPicking(orders/goods/sku/wave/top5)、packingRank(personal:orders/goods/sku/wave/top5)、trend(max/points 08:00-18:00 共 11 点)、weeklyEfficiency(days 7 天 intercept)"
|
||||
"description": "面板数据对象;is_change=false 时为空对象(节约流量),is_change=true 时输出。已输出字段:title(仓库名)、fulfillment(订单履约链路 6 环节未/已 + total + items 末尾两项今日退件/今日拆包;各环节未/已均含配送表今日出库按环节状态拆分补数,打包环节已* 用订单状态存量口径(池内 pack_status=fin + 配送表今日出库 pack_status=fin,保证已复核≥已打包))、stageOverview(totalOrders/interceptOrders/stages 5 卡:receiving/shelf/pick/recheck/pack,pack 卡 today=今日已完成打包的真实订单数(status=2,不含打包中):散单任务数 + 团购波次 wms_order_wave_index 真实订单数(替代 pack_quantity 快照),doing=打包中订单数(订单表 pack_status=padding 池内+配送今日出库双表)、abnormal=异常订单数(订单表对应状态 error 池内+配送今日出库双表;拣货 doing 同样为订单表 pick_status=padding 双表))、b2b(orders/goods/sku)、groupPicking、scatterPicking(orders/goods/sku/wave/top5)、groupPacking、scatterPacking(各含 orders/goods/sku/wave/top5,按波次范围 wave_scope 区分:团购块 top 按打包台、散单块 top 按打包员)、trend(max/total/points 业务日 24 点:label 从仓库自然日开始时间(day_start_time)起到次日自然日开始时间,每点 { label, created_count }——created_count=业务日窗口内下单量(池内待处理 + 配送表今日出库订单按订单创建时间落桶,窗口即业务日 [自然日开始时间, 次日自然日开始时间):未到次日自然日开始时间时=今日自然日开始时间起,凌晨(已过零点)时=昨日自然日开始时间起)并按小时累计(最后一点=业务日内下单总量);total=今日总单量(与 fulfillment.total 同口径:待处理订单池 + 配送表今日出库))、weeklyEfficiency(days 7 天 intercept)"
|
||||
}
|
||||
],
|
||||
"errors": [],
|
||||
"notes": [
|
||||
"外部驱动公共方法(本次新增):app/service/systems/warehouse_panel.js#touchLastChangeAt(warehouseId)——业务数据变化时调用一行即可更新该仓库面板最后更新时间戳(只写时间戳整值替换、TTL 300 秒,失败仅告警不影响主流程);已接入拣货完成(systems/pick.js#wavePickTaskComplete)、复核完成(systemMethods/order/recheckOrder.js#confirmRecheck/confirmRecheckByWaveId/batchQuickRecheck/batchQuickRecheckByWave)、打包完成(systems/workbench.js#_updateOrderPackStatus,覆盖工作台手动结束/新任务关闭旧任务/超时自动结束等全部打包结束路径)。",
|
||||
"缓存键 index:warehousePanel:lastChangeAt:{warehouseId},值为 { last_change_at, data },TTL 300 秒。拉取逻辑:缓存有最后更新时间且传入时间戳未过期 → is_change=false + 空 data 不查库;时间戳过期且缓存有数据 → 直接输出缓存数据;时间戳过期但缓存无数据(外部只驱动了时间戳)→ 查库拉数据补入缓存并保留外部时间戳;缓存无最后更新时间(未命中/过期)→ 查库拉数据并设置最后更新时间",
|
||||
"最后更新时间一般由外部驱动:业务数据变化时由外部写入缓存键的 last_change_at(只写时间戳即可,数据由本接口下次拉取时补入)",
|
||||
"未输出字段(数据源或口径未定):履约链路第 7 环节退件签收、stageOverview 质检卡、收货/上架卡的 today/abnormal、weeklyEfficiency 的 throughput/max、packingRank 的 group(组别口径未定)",
|
||||
"口径:fulfillment 各环节按订单分表状态字段(post_status/print_status/pick_status/recheck_status/pack_status/outbound_status)未/已;groupPicking=wave_pick_task pick_mode 1,5,scatterPicking=2,3,4(今日创建任务,orders/wave 取任务快照,goods/sku 经任务订单关联表 join 订单分表 items_total/items_count);packingRank.personal 按 pack_task_packer.account_name 聚合(今日创建且非异常任务);trend 固定 08:00-18:00 按小时补零;weeklyEfficiency.days 时间锚点=COALESCE(intercept_time, create_at)"
|
||||
"未输出字段(数据源或口径未定):履约链路第 7 环节退件签收、stageOverview 质检卡、收货/上架卡的 today/abnormal、weeklyEfficiency 的 throughput/max",
|
||||
"口径:fulfillment 各环节未* = 常用表池内未完成 + 配送分表今日出库未完成(真实状态);已* 口径:分配/打印/拣货均从订单表状态获取(池内 fin + 配送表今日出库 fin,保证已分配≥已打印≥已拣货的流程约束),复核=今日复核时间(recheck_time 双表)、打包=订单状态存量口径(池内 pack_status=fin + 配送表今日出库 pack_status=fin,保证已复核≥已打包;此前「今日打包任务订单数」口径会大于已复核(打包任务快照含未复核订单),已改回)、出库=今日出库数;出库环节未+已=total,其余环节已* 为状态/今日作业口径、未* 为真实状态口径;面板全部今日统计窗口按仓库配置自然日开始时间 day_start_time(默认 06:00)划分:今日=[当日06:00, 次日06:00),当前时间早于当日 06:00 时窗口为 [昨日06:00, 当日06:00)(昨日 06:00 后的订单视为今日);trend 按业务日窗口双值:横轴 24 点从自然日开始时间起到次日自然日开始时间,created_count(业务日窗口内下单量:池内待处理 + 配送表今日出库订单按订单创建时间落桶,窗口即业务日 [自然日开始时间, 次日自然日开始时间),凌晨(已过零点)时为 [昨日自然日开始时间, 今日自然日开始时间))按小时累计(最后一点=业务日内下单总量);trend 另含 total(今日总单量,与 fulfillment.total 同口径);weeklyEfficiency(7 日)仍按自然日;fulfillment 的 items 末尾两项(今日退件/今日拆包)按 wms_return_received/wms_return_unpack 的 warehouse_id 隔离 + created_at 今日 [00:00, 次日 00:00) 计数;",
|
||||
"groupPicking/scatterPicking 汇总(orders/goods/sku/wave)按订单表状态口径:池内 pick fin + 配送表今日出库 pick fin,团购=wave_scope IN (1,3)、散单=NOT IN (1,3),团购+散单=已拣货;top 仍按今日创建任务(pick_mode 1,5 团购 / 2,3,4 散单)按人聚合(任务口径,订单表无拣货人);",
|
||||
"stageOverview 的 pack 卡 today=今日已完成打包的真实订单数(status=2 排除打包中;散单任务数 + 团购任务 wave_id 关联 wms_order_wave_index 的真实订单数去重,替代 pack_quantity 快照避免虚高),窗口内已完成未删除;doing/abnormal 为任务数(打包中/异常任务);"
|
||||
]
|
||||
}
|
||||
]
|
||||
@ -15323,7 +15326,7 @@
|
||||
"list": [
|
||||
{
|
||||
"method": "setting.warehouse.getSettings",
|
||||
"description": "获取当前登录仓库的 subject_config;subject_config 新增大团购打包系数 big_group_pack_coefficient(数字,默认 3,单位秒/单,必须大于 0,用于 workbench 大团购波次打包时长闸门与倒计时);新增散单称重是否需要打包 single_weigh_require_pack(flag 布尔,默认 false 关闭;开启后散单称重(订单波次范围 wave_scope 非 1 大团购/3 小团购)前必须已打包完成 pack_status=fin,未打包时拒绝称重并返回错误)",
|
||||
"description": "获取当前登录仓库的 subject_config;subject_config 新增大团购打包系数 big_group_pack_coefficient(数字,默认 3,单位秒/单,必须大于 0,用于 workbench 大团购波次打包时长闸门与倒计时);新增散单称重是否需要打包 single_weigh_require_pack(flag 布尔,默认 false 关闭;开启后散单称重(订单波次范围 wave_scope 非 1 大团购/3 小团购)前必须已打包完成 pack_status=fin,未打包时拒绝称重并返回错误);本次调整自动出库配置:新增 subject_config.auto_outbound_enabled(flag,默认 false 关闭);subject_config.auto_outbound_rules 由对象改为数组(每项仅校验 require_pack/require_weigh/require_sync,任一规则命中即出库;固定前置条件为已复核 recheck_status=fin 与已分配储位 storage_status=fin),移除 rules.enabled 与 require_recheck/require_print/require_pick 字段;本次文档补充「不出库当天订单」的时间口径:时间字段范围 00:00~23:59(不支持 24:00),常用组合为 允许当天出库最后时间=00:00 + 当天放开时间=23:59 表示「当天复核的订单全天不出库、过了零点后全部出库」;本次补充「不出库当天订单」的跨天口径:按订单复核时间所在日计算,放行时间支持 00:00~47:59(27:00 = 次日 03:00 放行)",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
@ -15354,23 +15357,17 @@
|
||||
"required": true,
|
||||
"description": "是否启用外部快递编码;默认 false(关闭)。开启后允许按外部系统传入的快递编码进行处理(如无匹配仍以业务校验为准)"
|
||||
},
|
||||
{
|
||||
"name": "subject_config.auto_outbound_enabled",
|
||||
"type": "boolean",
|
||||
"required": true,
|
||||
"description": "是否启用自动出库(flag),默认 false(关闭);开启后按 auto_outbound_rules 中的规则扫描订单并自动标记出库"
|
||||
},
|
||||
{
|
||||
"name": "subject_config.auto_outbound_rules",
|
||||
"type": "object",
|
||||
"type": "array",
|
||||
"required": true,
|
||||
"description": "自动出库规则配置。全部条件满足时自动标记待出库"
|
||||
},
|
||||
{
|
||||
"name": "subject_config.auto_outbound_rules.enabled",
|
||||
"type": "boolean",
|
||||
"required": true,
|
||||
"description": "是否启用自动出库,默认 false"
|
||||
},
|
||||
{
|
||||
"name": "subject_config.auto_outbound_rules.require_recheck",
|
||||
"type": "boolean",
|
||||
"required": true,
|
||||
"description": "是否要求已复核(recheck_status=fin),默认 true"
|
||||
"description": "自动出库规则数组,每项规则独立判断,订单满足任意一条规则即自动出库;空数组时不自动出库。所有规则的固定前置条件为「已复核」(recheck_status=fin)与「已分配储位」(storage_status=fin),未复核订单一律不自动出库。旧版本的对象结构(含 enabled/require_recheck/require_print/require_pick)已废弃不再兼容,保存为非数组时返回 400"
|
||||
},
|
||||
{
|
||||
"name": "subject_config.auto_outbound_rules.require_pack",
|
||||
@ -15382,7 +15379,7 @@
|
||||
"name": "subject_config.auto_outbound_rules.require_weigh",
|
||||
"type": "boolean",
|
||||
"required": true,
|
||||
"description": "是否要求已称重(weighing_weight>0),默认 true"
|
||||
"description": "是否要求已称重(wms_order_express.weighing_weight>0),默认 true"
|
||||
},
|
||||
{
|
||||
"name": "subject_config.auto_outbound_rules.require_sync",
|
||||
@ -15391,16 +15388,22 @@
|
||||
"description": "是否要求已同步(sync_status=fin),默认 true"
|
||||
},
|
||||
{
|
||||
"name": "subject_config.auto_outbound_rules.require_print",
|
||||
"name": "subject_config.auto_outbound_rules.exclude_same_day_outbound",
|
||||
"type": "boolean",
|
||||
"required": true,
|
||||
"description": "是否要求已打印(print_status=fin),默认 true"
|
||||
"description": "是否不出库当天复核订单(flag),默认 true;开启后按订单复核时间所在日计算:复核时间在「允许当天出库最后时间」之后的订单,需等到该复核日的「放行时间」才自动出库;复核时间早于该最后时间、或为空的订单不受影响"
|
||||
},
|
||||
{
|
||||
"name": "subject_config.auto_outbound_rules.require_pick",
|
||||
"type": "boolean",
|
||||
"name": "subject_config.auto_outbound_rules.same_day_outbound_deadline_time",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "是否要求已拣货(pick_status=fin),默认 true"
|
||||
"description": "允许当天出库最后时间(HH:mm,默认 06:00,当天内 00:00~23:59);复核时间早于该时间的订单不受「不出库当天订单」影响,不能大于放行时间。想表达「当天复核的订单全天不出库」时设为 00:00"
|
||||
},
|
||||
{
|
||||
"name": "subject_config.auto_outbound_rules.same_day_outbound_release_time",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "放行时间(HH:mm,默认 22:00,支持跨天 00:00~47:59:24:00 之后的数字表示次日,如 27:00 = 次日 03:00);到达该时刻后,该复核日被限制的订单放行。常用:23:59 = 当天不放、过了零点出库;27:00 = 到次日 03:00 才出库"
|
||||
},
|
||||
{
|
||||
"name": "subject_config.sender_name",
|
||||
@ -15504,6 +15507,12 @@
|
||||
"required": false,
|
||||
"description": "截单时间,格式 HH:mm,默认 18:00,范围 00:00-23:59;作为最后允许自动分配的时间,开始时间晚于截单时间时截单时间视为次日(跨天窗口)"
|
||||
},
|
||||
{
|
||||
"name": "subject_config.day_start_time",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"description": "自然日开始时间(业务日分界点),格式 HH:mm,默认 06:00,范围 00:00-23:59;今日统计窗口为 [该时间点, 次日该时间点),当前时间早于今日该时间点时窗口从昨日该时间点开始(昨日 06:00 后的订单视为今日)"
|
||||
},
|
||||
{
|
||||
"name": "subject_config.receiving_pending_inbound_notice",
|
||||
"type": "object",
|
||||
@ -15582,7 +15591,7 @@
|
||||
},
|
||||
{
|
||||
"method": "setting.warehouse.getFieldMeta",
|
||||
"description": "获取仓库设置字段元信息;本次 list 新增「大团购打包系数」(key=big_group_pack_coefficient,type=number,default=3,min=0.1,单位秒/单,用于大团购波次打包时长闸门与倒计时);本次新增「散单称重是否需要打包」(key=single_weigh_require_pack,type=flag,default=false,required=false,开启后散单称重(wave_scope 非 1 大团购/3 小团购)前必须已打包完成 pack_status=fin)",
|
||||
"description": "获取仓库设置字段元信息;本次 list 新增「大团购打包系数」(key=big_group_pack_coefficient,type=number,default=3,min=0.1,单位秒/单,用于大团购波次打包时长闸门与倒计时);本次新增「散单称重是否需要打包」(key=single_weigh_require_pack,type=flag,default=false,required=false,开启后散单称重(wave_scope 非 1 大团购/3 小团购)前必须已打包完成 pack_status=fin);本次新增「启用自动出库」(key=auto_outbound_enabled,type=flag,default=false,required=false);「自动出库规则」(key=auto_outbound_rules)由 object 调整为 array(default=[],item_keys 仅含 require_pack/require_weigh/require_sync/exclude_same_day_outbound/same_day_outbound_deadline_time/same_day_outbound_release_time)",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
@ -15667,7 +15676,7 @@
|
||||
},
|
||||
{
|
||||
"method": "setting.warehouse.saveSettings",
|
||||
"description": "修改仓库设置并清理指定仓库缓存(subject_config 支持部分字段更新,本次新增 subject_config.single_weigh_require_pack);本次文档补漏 subject_config.big_group_pack_coefficient 入参说明(对齐 getSettings/getFieldMeta 与代码实现)",
|
||||
"description": "修改仓库设置并清理指定仓库缓存(subject_config 支持部分字段更新,本次新增 subject_config.single_weigh_require_pack);本次文档补漏 subject_config.big_group_pack_coefficient 入参说明(对齐 getSettings/getFieldMeta 与代码实现);本次调整自动出库配置:新增 subject_config.auto_outbound_enabled(flag,默认 false);subject_config.auto_outbound_rules 改为数组(每项仅校验 require_pack/require_weigh/require_sync,任一命中即出库;固定前置条件为已复核 + 已分配储位),非数组(旧对象结构)保存时返回 400;本次文档补充 same_day_outbound_deadline_time / same_day_outbound_release_time 的范围(00:00~23:59,不支持 24:00)与常用组合(00:00 + 23:59 = 当天不放、过零点全部出库);本次补充 same_day_outbound_release_time 支持跨天(00:00~47:59,27:00 = 次日 03:00)与 same_day_outbound_deadline_time 仍限当天内(00:00~23:59)",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
@ -15708,25 +15717,18 @@
|
||||
"description": "是否启用外部快递编码;默认 false(关闭)。开启后允许按外部系统传入的快递编码进行处理(如无匹配仍以业务校验为准)"
|
||||
},
|
||||
{
|
||||
"name": "subject_config.auto_outbound_rules",
|
||||
"type": "object",
|
||||
"name": "subject_config.auto_outbound_enabled",
|
||||
"type": "boolean",
|
||||
"required": false,
|
||||
"source": "body.subject_config",
|
||||
"description": "自动出库规则配置。全部条件满足时自动标记待出库"
|
||||
"description": "是否启用自动出库(flag),默认 false(关闭);开启后按 auto_outbound_rules 中的规则扫描订单并自动标记出库"
|
||||
},
|
||||
{
|
||||
"name": "subject_config.auto_outbound_rules.enabled",
|
||||
"type": "boolean",
|
||||
"name": "subject_config.auto_outbound_rules",
|
||||
"type": "array",
|
||||
"required": false,
|
||||
"source": "body.subject_config.auto_outbound_rules",
|
||||
"description": "是否启用自动出库,默认 false"
|
||||
},
|
||||
{
|
||||
"name": "subject_config.auto_outbound_rules.require_recheck",
|
||||
"type": "boolean",
|
||||
"required": false,
|
||||
"source": "body.subject_config.auto_outbound_rules",
|
||||
"description": "是否要求已复核(recheck_status=fin),默认 true"
|
||||
"source": "body.subject_config",
|
||||
"description": "自动出库规则数组,每项规则独立判断,订单满足任意一条规则即自动出库;空数组时不自动出库。所有规则的固定前置条件为「已复核」(recheck_status=fin)与「已分配储位」(storage_status=fin),未复核订单一律不自动出库。旧版本的对象结构(含 enabled/require_recheck/require_print/require_pick)已废弃不再兼容,保存为非数组时返回 400"
|
||||
},
|
||||
{
|
||||
"name": "subject_config.auto_outbound_rules.require_pack",
|
||||
@ -15740,7 +15742,7 @@
|
||||
"type": "boolean",
|
||||
"required": false,
|
||||
"source": "body.subject_config.auto_outbound_rules",
|
||||
"description": "是否要求已称重(weighing_weight>0),默认 true"
|
||||
"description": "是否要求已称重(wms_order_express.weighing_weight>0),默认 true"
|
||||
},
|
||||
{
|
||||
"name": "subject_config.auto_outbound_rules.require_sync",
|
||||
@ -15750,18 +15752,25 @@
|
||||
"description": "是否要求已同步(sync_status=fin),默认 true"
|
||||
},
|
||||
{
|
||||
"name": "subject_config.auto_outbound_rules.require_print",
|
||||
"name": "subject_config.auto_outbound_rules.exclude_same_day_outbound",
|
||||
"type": "boolean",
|
||||
"required": false,
|
||||
"source": "body.subject_config.auto_outbound_rules",
|
||||
"description": "是否要求已打印(print_status=fin),默认 true"
|
||||
"description": "是否不出库当天复核订单(flag),默认 true;开启后按订单复核时间所在日计算:复核时间在「允许当天出库最后时间」之后的订单,需等到该复核日的「放行时间」才自动出库;复核时间早于该最后时间、或为空的订单不受影响"
|
||||
},
|
||||
{
|
||||
"name": "subject_config.auto_outbound_rules.require_pick",
|
||||
"type": "boolean",
|
||||
"name": "subject_config.auto_outbound_rules.same_day_outbound_deadline_time",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body.subject_config.auto_outbound_rules",
|
||||
"description": "是否要求已拣货(pick_status=fin),默认 true"
|
||||
"description": "允许当天出库最后时间(HH:mm,默认 06:00,当天内 00:00~23:59);复核时间早于该时间的订单不受「不出库当天订单」影响,不能大于放行时间。想表达「当天复核的订单全天不出库」时设为 00:00"
|
||||
},
|
||||
{
|
||||
"name": "subject_config.auto_outbound_rules.same_day_outbound_release_time",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body.subject_config.auto_outbound_rules",
|
||||
"description": "放行时间(HH:mm,默认 22:00,支持跨天 00:00~47:59:24:00 之后的数字表示次日,如 27:00 = 次日 03:00);到达该时刻后,该复核日被限制的订单放行。常用:23:59 = 当天不放、过了零点出库;27:00 = 到次日 03:00 才出库"
|
||||
},
|
||||
{
|
||||
"name": "subject_config.sender_name",
|
||||
@ -21697,7 +21706,7 @@
|
||||
},
|
||||
{
|
||||
"method": "pick.wavePickTaskComplete",
|
||||
"description": "完全提交拣货任务。支持 mode=1 全部确认,mode=2 部分确认(需传 order_ids)。提交后根据是否全部完成自动推进任务状态。后台抓取创建的任务(source=2)必须先绑定拣货车才能提交,否则返回 400。",
|
||||
"description": "完全提交拣货任务。支持 mode=1 全部确认,mode=2 部分确认(需传 order_ids)。提交后根据是否全部完成自动推进任务状态。后台抓取创建的任务(source=2)必须先绑定拣货车才能提交,否则返回 400。目标订单中已进入拦截流程的订单直接跳过(不完成拣货、不扣减库存、不报错);其中未打印面单(print_status=none/空)的拦截订单自动移出波次(wave_id 清零、删波次索引、回写波次统计、移除任务订单关联与篮子明细,并写 ORDER_WAVE_REMOVE 日志、触发策略快扫),已打印面单(print_status!=none)的拦截订单保持不动(保留波次/任务关联,需人工 wave.batchRemoveOrders 处理),返回 kept_intercepted_order_ids。",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"isNeedRight": false,
|
||||
@ -21751,6 +21760,30 @@
|
||||
"required": true,
|
||||
"description": "本次成功确认的订单ID列表"
|
||||
},
|
||||
{
|
||||
"name": "skipped_intercepted_order_ids",
|
||||
"type": "array",
|
||||
"required": true,
|
||||
"description": "被跳过(已进入拦截流程)的订单ID列表"
|
||||
},
|
||||
{
|
||||
"name": "skipped_intercepted_orders",
|
||||
"type": "array",
|
||||
"required": true,
|
||||
"description": "被跳过的拦截订单明细,每项含 order_id、intercept_status、print_status"
|
||||
},
|
||||
{
|
||||
"name": "removed_from_wave_order_ids",
|
||||
"type": "array",
|
||||
"required": true,
|
||||
"description": "被自动移出波次的未打印拦截订单ID列表"
|
||||
},
|
||||
{
|
||||
"name": "kept_intercepted_order_ids",
|
||||
"type": "array",
|
||||
"required": true,
|
||||
"description": "已打印面单保持不动的拦截订单ID列表(不自动移出波次,需人工 wave.batchRemoveOrders 处理)"
|
||||
},
|
||||
{
|
||||
"name": "is_completed",
|
||||
"type": "boolean",
|
||||
@ -29694,6 +29727,12 @@
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"description": "截单时间字段元信息:key=cutoff_order_time,type=string,default=18:00,min=00:00(下限已从 12:00 放开,支持凌晨截单/跨天窗口),max=23:59,maxLength=5"
|
||||
},
|
||||
{
|
||||
"name": "data[].day_start_time",
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"description": "自然日开始时间字段元信息:key=day_start_time,type=string,default=06:00,min=00:00,max=23:59,maxLength=5;今日统计窗口为 [该时间点, 次日该时间点),当前时间早于今日该时间点时窗口从昨日该时间点开始"
|
||||
}
|
||||
],
|
||||
"errors": []
|
||||
@ -38215,7 +38254,7 @@
|
||||
},
|
||||
{
|
||||
"method": "stock.check.addDetail",
|
||||
"description": "添加盘点明细(商品或库位,按任务盘点类型决定):type=store/goods 按 stock_ids 添加商品行(scope_type=goods,商品任务必须按库位盘点:按商品在仓库的启用库存库位(wms_storage is_enabled=1,按 space_id 分组 SUM)拆行——每个「商品+库位」生成一条明细行,location_id/location_code 快照绑定库存库位、system_quantity=该库位库存 SUM,一个商品多个库位对应多行;无启用库存库位的商品计入 invalid_stock_ids 不入明细),商品必须属于本仓库,且任务 store_id 非空时商品货主必须与任务货主一致(不一致的商品记入 invalid_stock_ids);type=all/location 按 locations(库位编码)或 location_ids(库位ID)添加库位行(scope_type=location),location_ids 优先(两者都传时 locations 忽略)——库位ID路径直接按 wms_location_space.id+warehouse_id 查库校验(不再按编码二次解析),查不到的 ID 记入 invalid_location_ids,编码路径按 warehouse_id+space_code 匹配 wms_location_space,不存在的编码记入 invalid_locations;type=all 未传库位且未传库位ID时自动拉取全仓库启用库位生成盘点范围;兼容历史任务:type=all 且已存在商品明细行(scope_type=goods,改造前创建)时继续按商品模式接受 stock_ids,避免旧调用报 400;stock_ids 与 locations/location_ids 按任务类型二选一(传错维度报 400:按库位盘点传 stock_ids 报『当前盘点类型按库位盘点,请传 locations 或 location_ids(如需按商品盘点请创建 type=goods 任务)』,按商品盘点传 locations 报『当前盘点类型按商品盘点,请传 stock_ids』、传 location_ids 报『当前盘点类型按商品盘点,不能添加库位明细』),locations 兼容 location_codes 写法(locations 优先)、location_ids 兼容 locationIds 驼峰写法(location_ids 优先);仅 created/rejected 状态允许;已存在同盘点项(商品行 stock_id / 库位行 location_code)自动跳过(幂等);完成后重算主表 total_items。",
|
||||
"description": "添加盘点明细(商品或库位,按任务盘点类型决定):type=store/goods 按 stock_ids 添加商品行(scope_type=goods,商品任务必须按库位盘点:按商品在仓库的启用库存库位(wms_storage is_enabled=1 且库位有效——库位未删除且所属 zone 存在未删除,排除无头库位,按 space_id 分组 SUM)拆行——每个「商品+库位」生成一条明细行,location_id/location_code 快照绑定库存库位、system_quantity=该库位库存 SUM,一个商品多个库位对应多行;无启用库存库位的商品计入 invalid_stock_ids 不入明细),商品必须属于本仓库,且任务 store_id 非空时商品货主必须与任务货主一致(不一致的商品记入 invalid_stock_ids);type=all/location 按 locations(库位编码)或 location_ids(库位ID)添加库位行(scope_type=location),location_ids 优先(两者都传时 locations 忽略)——库位ID路径直接按 wms_location_space.id+warehouse_id 查库校验(不再按编码二次解析),查不到的 ID 记入 invalid_location_ids,编码路径按 warehouse_id+space_code 匹配 wms_location_space,不存在的编码记入 invalid_locations;库位必须有效(未删除且所属 zone 存在未删除):无头库位(zone 不存在/已删除)分别记入 invalid_location_ids / invalid_locations;type=all 未传库位且未传库位ID时自动拉取全仓库启用且有效库位(排除无头库位)生成盘点范围;兼容历史任务:type=all 且已存在商品明细行(scope_type=goods,改造前创建)时继续按商品模式接受 stock_ids,避免旧调用报 400;stock_ids 与 locations/location_ids 按任务类型二选一(传错维度报 400:按库位盘点传 stock_ids 报『当前盘点类型按库位盘点,请传 locations 或 location_ids(如需按商品盘点请创建 type=goods 任务)』,按商品盘点传 locations 报『当前盘点类型按商品盘点,请传 stock_ids』、传 location_ids 报『当前盘点类型按商品盘点,不能添加库位明细』),locations 兼容 location_codes 写法(locations 优先)、location_ids 兼容 locationIds 驼峰写法(location_ids 优先);仅 created/rejected 状态允许;已存在同盘点项(商品行 stock_id / 库位行 location_code)自动跳过(幂等);完成后重算主表 total_items。",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
@ -38304,13 +38343,13 @@
|
||||
"name": "invalid_stock_ids",
|
||||
"type": "array",
|
||||
"required": true,
|
||||
"description": "无效商品库存ID列表(不存在、不属于当前仓库、商品货主与任务货主不一致或在仓库无启用库存库位)"
|
||||
"description": "无效商品库存ID列表(不存在、不属于当前仓库、商品货主与任务货主不一致、在仓库无启用库存库位或启用库存全部在无头库位)"
|
||||
},
|
||||
{
|
||||
"name": "invalid_locations",
|
||||
"type": "array",
|
||||
"required": true,
|
||||
"description": "无效库位编码列表(当前仓库不存在对应库位编码)"
|
||||
"description": "无效库位编码列表(当前仓库不存在对应库位编码或无头库位(所属 zone 不存在/已删除))"
|
||||
},
|
||||
{
|
||||
"name": "invalid_location_ids",
|
||||
@ -38344,13 +38383,14 @@
|
||||
}
|
||||
],
|
||||
"notes": [
|
||||
"无头库位排除(本次变更):库位所属 zone 不存在或已删除即视为无头库位,一律不纳入盘点——商品路径仅按有效库位拆行(启用库存全部在无头库位的商品计入 invalid_stock_ids)、库位编码/ID 路径计入 invalid_locations/invalid_location_ids(不报错)、全盘自动范围直接排除;workData goods/space 视图库位枚举与明细生成同口径过滤。代码依据:app/service/systems/stock_check.js#VALID_SPACE_SQL(模块常量:wms_location_space JOIN wms_location_zone deleted_at IS NULL)。",
|
||||
"按类型二选一:type=store/goods 传 stock_ids(传 locations 报『当前盘点类型按商品盘点,请传 stock_ids』、传 location_ids 报『当前盘点类型按商品盘点,不能添加库位明细』);type=all/location 传 locations 或 location_ids(传 stock_ids 报『当前盘点类型按库位盘点,请传 locations 或 location_ids(如需按商品盘点请创建 type=goods 任务)』)。",
|
||||
"location_ids 优先:两者都传时忽略 locations,直接按 wms_location_space.id+warehouse_id 查库校验(不再按 space_code 二次解析),查不到的 ID 记入 invalid_location_ids(不报错)。",
|
||||
"历史任务兼容:改造前创建的 type=all 任务按商品添加明细(明细行 scope_type='goods');判定口径为该任务在 wms_stock_check_detail 中 scope_type='goods' 行存在(count>0)即继续按商品模式接受 stock_ids(此时传 locations/location_ids 分别报『当前盘点类型按商品盘点,请传 stock_ids』/『当前盘点类型按商品盘点,不能添加库位明细』);全新 type=all 任务(无任何商品明细行)维持按库位语义,只能传 locations/location_ids。仅 type=all 走兼容判定,store/goods/location 类型判定不变。",
|
||||
"商品货主限制:任务 store_id 非空时商品 store_id 必须与之一致,不一致计入 invalid_stock_ids(限制非本货主商品加入盘点)。",
|
||||
"全盘自动范围:type=all 且未传库位且未传 location_ids 时,自动拉取当前仓库全部启用库位(is_enabled=true)的 space_code 生成库位行;无启用库位时报 400。",
|
||||
"全盘自动范围:type=all 且未传库位且未传 location_ids 时,自动拉取当前仓库全部启用且有效库位(is_enabled=true 且所属 zone 存在未删除,排除无头库位)的 space_code 生成库位行;无启用库位时报 400。",
|
||||
"幂等:商品行按 check_id+stock_id 整体跳过(同商品重复添加整体跳过,不重复拆行)、库位行按 check_id+location_code 跳过(商品行唯一索引 uk_check_stock_location(check_id, stock_id, location_id),库位行原唯一约束 uk_check_location 已放宽为普通索引 idx_check_location、幂等由应用层查重保证);location_ids 路径跳过项按库位ID记入 skipped。",
|
||||
"商品拆行口径(本次改造,商品任务必须按库位盘点):type=store/goods 传 stock_ids 后按商品在仓库的启用库存库位(wms_storage is_enabled=1,按 space_id 分组 SUM(available_quantity+locked_quantity)(=可用+锁定))拆行——每个「商品+库位」生成一条 scope_type=goods 明细行(location_id/location_code 快照绑定库存库位、system_quantity=该库位库存 SUM(可用+锁定));一个商品多个库位对应多行;无启用库存库位的商品计入 invalid_stock_ids 不入明细;added/total_items 均为拆分明细行数。代码依据:app/service/systems/stock_check.js#_addGoodsDetailRows(Storage.findAll warehouse_id+stock_id in+is_enabled=1、attributes SUM(quantity)、group=[stock_id, space_id];LocationSpace 按 id 取 space_code 快照)。",
|
||||
"商品拆行口径(本次改造,商品任务必须按库位盘点):type=store/goods 传 stock_ids 后按商品在仓库的启用库存库位(wms_storage is_enabled=1 且库位有效(未删除且所属 zone 存在未删除,排除无头库位),按 space_id 分组 SUM(available_quantity+locked_quantity)(=可用+锁定))拆行——每个「商品+库位」生成一条 scope_type=goods 明细行(location_id/location_code 快照绑定库存库位、system_quantity=该库位库存 SUM(可用+锁定));一个商品多个库位对应多行;无启用库存库位的商品计入 invalid_stock_ids 不入明细;added/total_items 均为拆分明细行数。代码依据:app/service/systems/stock_check.js#_addGoodsDetailRows(Storage.findAll warehouse_id+stock_id in+is_enabled=1、attributes SUM(quantity)、group=[stock_id, space_id];LocationSpace 按 id 取 space_code 快照)。",
|
||||
"响应统一 data 层封装(2026-10-02 起):成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp }。本方法业务数据整体位于 data 内,data 内字段口径与改造前一致(原顶层业务字段全部移入 data.children)。代码依据:app/service/systemMethods/stock/check.js#_call(22 个方法共用统一包装)+ app/lib/api_response.js#toSuccess(识别标准载荷后顶层补充 timestamp)。"
|
||||
]
|
||||
},
|
||||
@ -38784,7 +38824,7 @@
|
||||
],
|
||||
"notes": [
|
||||
"代码依据:app/service/systemMethods/stock/check.js#workData(warehouse_id 由服务端从 ctx.user.store_id 自动注入,前端无需传递;const { id, is_goods: isGoodsSnake, isGoods: isGoodsCamel, pagination } = data || {},isGoods=is_goods 未定义时回退 isGoods(兼容 isGoods 驼峰写法);不再读取、不再校验 view,透传 { warehouseId, id, isGoods, pagination })+ app/service/systems/stock_check.js#workData(id 非正整数抛 400『盘点任务ID不能为空』;任务不存在(按 id+warehouse_id 查 wms_stock_check)抛 400『盘点任务不存在』;状态守卫:任务状态非 REPORT_ALLOWED_STATUSES(approved/checking)时抛 400『当前状态(xx)不允许拉取盘点作业数据,仅审核完成(approved)或盘点作业中(checking)的任务可拉取』;视图解析:normalizedType=String(check.type||'').trim(),type=location/all 一律 location 视图(无视 view/is_goods),否则 goodsViewRequested=isGoods===true||'true'||1 时 goods 视图、其余默认 space 视图;按解析视图分派 _buildLocationWorkRows/_buildGoodsWorkRows/_buildSpaceWorkRows,统一返回 { check: _formatCheckRow 口径, rows, total: rows.length, page, pageSize })。本次代码已改(view 入参废弃、is_goods 驱动视图)并测试通过 197/197、ESLint 0 错误。",
|
||||
"三视图口径(由任务范围 + is_goods 解析后分派):location=库位结构(库位范围任务一律该视图),以任务库位范围行(scope_type=location)为列表(按明细 id 升序),行内挂该库位盘点作业记录 goods 子列表(已知商品与未知商品记录均入内:已知商品 stock_id 有值,商品信息批量取自 stockWarehouse.getStockDetails 带缓存、货主名 _resolveStoreNameMap 解析;未知商品 stock_id=null,item_code 用条码兜底、item_name 用名称快照兜底条码、store_id/store_name 为 null;已知/未知商品的 images 均为作业记录照片(经 _attachRecordImages 挂载 FileReference business_type=stock_check_record,已知商品不再输出商品主图 image_url)),has_unknown 标记该库位是否含未知商品记录;goods=商品结构(商品范围任务且 is_goods=true 时该视图),以任务商品范围行(scope_type=goods)为列表(按明细 id 升序),行内 locations 为商品所在全部库位列表(商品库存库位取自 wms_storage 启用未删除存储 DISTINCT space_id 按拣货路径排序,无库存但已有作业记录的库位按首条记录 id 升序追加在末尾,空库位归 location_code=null 组排在最后;明盘每库位含 system_quantity 该库位账面数量与 quantity 该库位盘点数量(未盘库位 0),盲盘仅 location_code/checked_at/checker_name/record_ids/images);space=聚合库位列表(商品范围任务默认该视图),库位集合=当前库存库位 ∪ 作业记录库位——当前库存库位:wms_storage(warehouse_id + stock_id 在集合 + is_enabled=1 未删除)DISTINCT space_id;作业记录库位:wms_stock_check_record 的 location_id 已回填直接用、未回填的按 location_code 匹配 wms_location_space.space_code 补查,与库存库位去重后并集;行内 goods 为该库位下的任务商品;盘点前库存已出空但已有盘点作业记录的库位也能展示(该库位商品行账面 system_quantity 按 0、checked_quantity 按该库位实盘合计)。",
|
||||
"三视图口径(由任务范围 + is_goods 解析后分派):location=库位结构(库位范围任务一律该视图),以任务库位范围行(scope_type=location)为列表(按明细 id 升序),行内挂该库位盘点作业记录 goods 子列表(已知商品与未知商品记录均入内:已知商品 stock_id 有值,商品信息批量取自 stockWarehouse.getStockDetails 带缓存、货主名 _resolveStoreNameMap 解析;未知商品 stock_id=null,item_code 用条码兜底、item_name 用名称快照兜底条码、store_id/store_name 为 null;已知/未知商品的 images 均为作业记录照片(经 _attachRecordImages 挂载 FileReference business_type=stock_check_record,已知商品不再输出商品主图 image_url)),has_unknown 标记该库位是否含未知商品记录;goods=商品结构(商品范围任务且 is_goods=true 时该视图),以任务商品范围行(scope_type=goods)为列表(按明细 id 升序),行内 locations 为商品所在全部库位列表(商品库存库位取自 wms_storage 启用未删除存储且库位有效(未删除且所属 zone 存在未删除,排除无头库位)DISTINCT space_id 按拣货路径排序,无库存但已有作业记录的库位按首条记录 id 升序追加在末尾,空库位归 location_code=null 组排在最后;明盘每库位含 system_quantity 该库位账面数量与 quantity 该库位盘点数量(未盘库位 0),盲盘仅 location_code/checked_at/checker_name/record_ids/images);space=聚合库位列表(商品范围任务默认该视图),库位集合=当前库存库位 ∪ 作业记录库位——当前库存库位:wms_storage(warehouse_id + stock_id 在集合 + is_enabled=1 未删除且库位有效(排除无头库位))DISTINCT space_id;作业记录库位:wms_stock_check_record 的 location_id 已回填直接用、未回填的按 location_code 匹配 wms_location_space.space_code 补查,与库存库位去重后并集;行内 goods 为该库位下的任务商品;盘点前库存已出空但已有盘点作业记录的库位也能展示(该库位商品行账面 system_quantity 按 0、checked_quantity 按该库位实盘合计)。",
|
||||
"明盘/盲盘数量控制:明盘(mode=open)goods 视图行返回 system_quantity(明细账面快照)/checked_quantity(已盘合计=locations.quantity 合计)/diff_quantity(已盘-账面,仅存在作业记录的行计算)/is_diff(差异非 0 为 1),locations 各项含 system_quantity(该库位账面数量=可用+锁定,wms_storage 该库位 SUM(available_quantity+locked_quantity),无库存记录库位为 0)、locked_quantity(该库位锁定数量,wms_storage 该库位 SUM(locked_quantity))与 quantity(该库位盘点数量=实盘合计,未盘库位为 0);space 视图 goods 各项含 system_quantity(wms_storage space+stock SUM(available_quantity+locked_quantity) 账面,该库位无库存记录时按 0)/locked_quantity(wms_storage space+stock SUM(locked_quantity))/checked_quantity(该商品在该库位的实盘合计);盲盘(mode=blind)不返回任何数量字段(goods 视图 locations 仅 location_code/checked_at/checker_name/record_ids/images,space 视图 goods 仅商品信息+images/record_ids/status);goods 视图 locations 为商品所在全部库位列表(含未盘库位,无作业记录时各项为空信息),无作业记录的行明盘已盘合计恒 0、差异/is_diff 恒 0(避免未盘行误显盘亏差异)。",
|
||||
"排序口径:space 视图库位仅按库位拣货顺序排序——pick_sequence 升序(pick_priority 与库位 id 均不参与,同值保持库位查询顺序);space 行内 goods 按 stock_id 升序;location/goods 视图行按明细 id 升序;goods 视图 locations 按首条记录 id 升序。",
|
||||
"权限口径:随 ALL_METHOD_NAMES(22 个:create/list/addDetail/addLocationDetail/detailDelete/detail/result/workData/report/markEmpty/recordList/recordDelete/recheckClearLocation/finish/submit/cancel/audit/batchDelete/export/exportTaskProgress/patternList/patternCreate)免 API 权限(isNeedAuth=false)、免仓库有效期鉴权(_noNeedAuth)、必须登录(isNeedLogin=true,免登录清单为空);为查询类方法,加入免日志清单 _noNeedLog(list/detail/result/workData/recordList/export/exportTaskProgress/patternList),不记录操作日志。",
|
||||
@ -40928,13 +40968,13 @@
|
||||
"static 定式静态记录表口径:收集阶段排除 wms_stock_static_check_task 已有记录(未删除)的 stock_id(已进入静态已盘点商品);任务创建成功后把本次命中的 stock_id 批量写入该表(task_time=创建时间),写入失败仅记告警日志、不影响主流程。",
|
||||
"权限口径:免 API 权限(isNeedAuth=false)、免仓库有效期鉴权、必须登录(isNeedLogin=true);patternCreate 为写操作,不在免日志清单(_noNeedLog)中,记录操作日志(patternList 为查询类,免日志)。",
|
||||
"单号生成:check_no=PD+YYYYMMDD+6 位序号(全局递增不按仓库隔离),并发下撞 uk_check_no 唯一键自动重取重试(最多 5 次)。",
|
||||
"goods 定式拆行口径(本次改造):商品类定式(mis_shipment/expiring/static/warning,type=goods)收集到 stock_ids 后走 _addGoodsDetailRows 同款逻辑——按商品在仓库的启用库存库位(wms_storage is_enabled=1,按 space_id 分组 SUM)拆行,每个「商品+库位」一条 scope_type=goods 明细行(location_id/location_code 绑定库存库位、system_quantity=该库位库存 SUM);无启用库存库位的商品不产生明细行,total_items 按拆分行重算。代码依据:app/service/systems/stock_check.js#patternCreate(pattern.type==='goods' 调 _addGoodsDetailRows)。",
|
||||
"goods 定式拆行口径(本次改造):商品类定式(mis_shipment/expiring/static/warning,type=goods)收集到 stock_ids 后走 _addGoodsDetailRows 同款逻辑——按商品在仓库的启用库存库位(wms_storage is_enabled=1 且库位有效(未删除且所属 zone 存在未删除,排除无头库位),按 space_id 分组 SUM)拆行,每个「商品+库位」一条 scope_type=goods 明细行(location_id/location_code 绑定库存库位、system_quantity=该库位库存 SUM);无启用库存库位的商品不产生明细行,total_items 按拆分行重算。代码依据:app/service/systems/stock_check.js#patternCreate(pattern.type==='goods' 调 _addGoodsDetailRows)。",
|
||||
"响应统一 data 层封装(2026-10-02 起):成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp }。本方法业务数据整体位于 data 内,data 内字段口径与改造前一致(原顶层业务字段全部移入 data.children)。代码依据:app/service/systemMethods/stock/check.js#_call(22 个方法共用统一包装)+ app/lib/api_response.js#toSuccess(识别标准载荷后顶层补充 timestamp)。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"method": "stock.check.addLocationDetail",
|
||||
"description": "批量添加库位明细(兼容入口,薄封装转调 addDetail 的库位ID直查路径):入参 id(盘点任务ID)+ location_ids(库位ID列表,兼容 locationIds 驼峰写法);服务端直接按 wms_location_space.id+warehouse_id 查库校验,不经过 space_code 二次解析;转发前保留旧口径参数校验(任务ID不能为空、库位ID不能为空、单次上限 200),任务存在性/状态/类型分派校验统一由 addDetail 处理;幂等添加 scope_type=location 明细行,已存在的同库位明细自动跳过;返回结构从 addDetail 映射为 { added, skipped, invalid_location_ids, total_items }(过滤 invalid_locations/invalid_stock_ids),保持原返回口径不变。",
|
||||
"description": "批量添加库位明细(兼容入口,薄封装转调 addDetail 的库位ID直查路径):入参 id(盘点任务ID)+ location_ids(库位ID列表,兼容 locationIds 驼峰写法);服务端直接按 wms_location_space.id+warehouse_id 查库校验(库位必须有效:未删除且所属 zone 存在未删除,无头库位记入 invalid_location_ids),不经过 space_code 二次解析;转发前保留旧口径参数校验(任务ID不能为空、库位ID不能为空、单次上限 200),任务存在性/状态/类型分派校验统一由 addDetail 处理;幂等添加 scope_type=location 明细行,已存在的同库位明细自动跳过;返回结构从 addDetail 映射为 { added, skipped, invalid_location_ids, total_items }(过滤 invalid_locations/invalid_stock_ids),保持原返回口径不变。",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
@ -47570,7 +47610,7 @@
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body.where",
|
||||
"description": "退回收件运单号(模糊搜索,传 {operator:'like',value} 或直接值)"
|
||||
"description": "退回收件运单号(模糊搜索,传 {operator:'like',value} 或直接值;value 为数组时多值 OR 包含匹配)"
|
||||
},
|
||||
{
|
||||
"name": "where.scan_date",
|
||||
@ -47776,7 +47816,7 @@
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "查询条件,语义与 returnReceived.list 的 where 一致(支持 {operator,value} 标准结构或直接值;字段含 waybill_code 模糊、scan_date/created_at/updated_at 范围、scanner_id/scanner_name/store_id/order_express_id/order_id/return_received_task_id 等值、is_original_return 是否原单退回);禁止传入 warehouse_id/warehouseId(服务端注入)"
|
||||
"description": "查询条件,语义与 returnReceived.list 的 where 一致(支持 {operator,value} 标准结构或直接值;字段含 waybill_code 模糊(like 支持数组多值 OR 包含)、scan_date/created_at/updated_at 范围、scanner_id/scanner_name/store_id/order_express_id/order_id/return_received_task_id 等值、is_original_return 是否原单退回);禁止传入 warehouse_id/warehouseId(服务端注入)"
|
||||
},
|
||||
{
|
||||
"name": "sort",
|
||||
@ -49708,7 +49748,7 @@
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body.where",
|
||||
"description": "运单号(模糊搜索,传 {operator:'like',value} 或直接值)"
|
||||
"description": "运单号(模糊搜索,传 {operator:'like',value} 或直接值;value 为数组时多值 OR 包含匹配)"
|
||||
},
|
||||
{
|
||||
"name": "where.store_id",
|
||||
@ -52774,7 +52814,7 @@
|
||||
},
|
||||
{
|
||||
"method": "wechat.getUserAgreementText",
|
||||
"description": "获取小程序用户须知富文本(免登录):传入 appId(小程序 AppID),从副表 wms_wechat_agreement_version 拉取最新版本(id 自增即最新);Redis 缓存 24 小时(key wechat:userAgreement:{appid}),有缓存直接使用缓存;无版本返回错误",
|
||||
"description": "获取小程序用户须知富文本(免登录):传入 appId(小程序 AppID),从副表 wms_wechat_agreement_version 拉取最新版本(id 自增即最新);Redis 缓存 24 小时(key wechat:userAgreement:{appid}),有缓存直接使用缓存;无版本返回错误(新授权小程序会自动写入系统默认须知作为第一版)",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": false,
|
||||
"headers": [],
|
||||
@ -53260,7 +53300,7 @@
|
||||
},
|
||||
{
|
||||
"method": "wechat.getTemplateList",
|
||||
"description": "获取小程序模板库列表(需登录):只拉取普通模板(template_type=0,GET wxa/gettemplatelist + component_access_token),Redis 缓存 24h(key wechat:template:list:normal);有缓存直接返回(from_cache=true),无缓存拉取后写入缓存",
|
||||
"description": "获取小程序模板库列表(需登录):只拉取普通模板(template_type=0,GET wxa/gettemplatelist + component_access_token),每次实时拉取不缓存",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
@ -53278,12 +53318,6 @@
|
||||
"type": "array",
|
||||
"required": true,
|
||||
"description": "模板信息列表(create_time/user_version/user_desc/template_id/draft_id/source_miniprogram_appid/source_miniprogram/template_type 等)"
|
||||
},
|
||||
{
|
||||
"name": "from_cache",
|
||||
"type": "boolean",
|
||||
"required": true,
|
||||
"description": "是否来自缓存"
|
||||
}
|
||||
],
|
||||
"errors": [
|
||||
@ -53312,7 +53346,7 @@
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"source": "body",
|
||||
"description": "代码库中的代码模板 ID(getTemplateList 获取)"
|
||||
"description": "代码库中的代码模板 ID(getTemplateList 获取,允许 0:普通模板库模板 ID 从 0 开始,0 表示第一个模板)"
|
||||
}
|
||||
],
|
||||
"response": [
|
||||
@ -53350,7 +53384,7 @@
|
||||
"errors": [
|
||||
{
|
||||
"code": "400",
|
||||
"message": "未识别仓库/未授权小程序/未授权权限集 18/模板不存在或缺少版本号/代码描述/上传失败(微信 errcode 透传:85014 模板不存在、9402202 并发限制等)"
|
||||
"message": "template_id 必须为非负整数/未识别仓库/未授权小程序/未授权权限集 18/模板不存在或缺少版本号/代码描述/上传失败(微信 errcode 透传:85014 模板不存在、9402202 并发限制等)"
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
@ -69,7 +69,7 @@
|
||||
"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",
|
||||
"depeeloy": "npm run deploy:prod",
|
||||
"deploy:prod": "node ./script/deploy-remote.cjs production",
|
||||
"rollback": "npm run rollback:prod",
|
||||
"rollback:prod": "node ./script/rollback-remote.cjs production",
|
||||
|
||||
@ -186,6 +186,7 @@ describe('test/app/model/order_delivery_dispatch_factory.test.js dispatch 模式
|
||||
...baseIndexes.slice(3).filter(line => !/_list_updated_at|_list_delivery_time/.test(line)),
|
||||
'KEY `idx_dispatch_100000_list_updated_at` (`warehouse_id`,`dispatch_lane`,`updated_at`,`id`)',
|
||||
'KEY `idx_dispatch_100000_list_delivery_time` (`warehouse_id`,`dispatch_lane`,`delivery_time`,`id`)',
|
||||
'KEY `idx_dispatch_100000_panel_fulfillment` (`delivery_time`,`outbound_status`)',
|
||||
];
|
||||
const expectedDispatchIndexOptions = [
|
||||
baseIndexOptions[0],
|
||||
@ -204,6 +205,10 @@ describe('test/app/model/order_delivery_dispatch_factory.test.js dispatch 模式
|
||||
name: 'idx_dispatch_100000_list_delivery_time',
|
||||
fields: [ 'warehouse_id', 'dispatch_lane', 'delivery_time', 'id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_dispatch_100000_panel_fulfillment',
|
||||
fields: [ 'delivery_time', 'outbound_status' ],
|
||||
},
|
||||
];
|
||||
|
||||
assert.equal(baseColumns.length, Object.keys(orderDeliveryModel.rawAttributes).length);
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user