Compare commits

..

No commits in common. "98bc0889292dff0b7e775f6836644461d8653056" and "75a248fdf6d6048c189607298f290a508d98817b" have entirely different histories.

13 changed files with 19 additions and 1890 deletions

View File

@ -100,16 +100,6 @@ module.exports = app => {
allowNull: true, allowNull: true,
comment: '货主ID,原单退回/识别到系统商品时回填', comment: '货主ID,原单退回/识别到系统商品时回填',
}, },
source_order_codes: {
type: STRING(500),
allowNull: true,
comment: '平台交易单号快照(原单退回时回填)',
},
shop_name: {
type: STRING(50),
allowNull: true,
comment: '店铺名称快照(货主自定义店铺名称 store_remask)',
},
camera_ids: { camera_ids: {
type: JSON_TYPE, type: JSON_TYPE,
allowNull: true, allowNull: true,

View File

@ -56,7 +56,6 @@ module.exports = app => {
district_name: '', district_name: '',
town_name: '', town_name: '',
address: '', address: '',
receiver_address: '',
group_wave_prefix: 'B', group_wave_prefix: 'B',
delete_order_wave_prefix: 'A', delete_order_wave_prefix: 'A',
inventory_warning_rules: DEFAULT_INVENTORY_WARNING_RULES, inventory_warning_rules: DEFAULT_INVENTORY_WARNING_RULES,

View File

@ -44,17 +44,6 @@ class InboxAIService extends Service {
} }
let content = result.data.choices?.[0]?.message?.content || ''; let content = result.data.choices?.[0]?.message?.content || '';
const reasoning = result.data.choices?.[0]?.message?.reasoning_content || '';
const finishReason = result.data.choices?.[0]?.finish_reason || '';
// 推理模型会把 max_tokens 消耗在 reasoning 上,导致 content 为空(finish_reason=length)
if (!content.trim() && finishReason === 'length') {
ctx.logger.warn(
`[inbox ai] DeepSeek 输出被截断: reasoning=${reasoning.length} 字符, content 为空, finish_reason=length`
);
throw new Error('DeepSeek 输出被截断(max_tokens 被推理过程占满),请提高 max_tokens');
}
// 清理 markdown 代码块 // 清理 markdown 代码块
content = content.replace(/^```json\s*/i, '').replace(/\s*```$/i, ''); content = content.replace(/^```json\s*/i, '').replace(/\s*```$/i, '');
content = content.replace(/^```\s*/i, '').replace(/\s*```$/i, ''); content = content.replace(/^```\s*/i, '').replace(/\s*```$/i, '');
@ -196,7 +185,6 @@ class InboxAIService extends Service {
let finalReply = null; let finalReply = null;
let lastFunctionName = null; let lastFunctionName = null;
let lastFunctionResult = null; let lastFunctionResult = null;
let jsonRetryNote = '';
const systemPrompt = `你是一个 WMS 仓库管理系统的智能助手,支持多步推理。 const systemPrompt = `你是一个 WMS 仓库管理系统的智能助手,支持多步推理。
已注册函数:\n${functionListText}\n 已注册函数:\n${functionListText}\n
@ -253,17 +241,7 @@ ${historyContext}
- 用户说"第1个""第2个"时,按 searchStock 返回的顺序对应选择 - 用户说"第1个""第2个"时,按 searchStock 返回的顺序对应选择
- 需要上下文但记忆不足时,主动调用 recallHistory 回顾对话历史 - 需要上下文但记忆不足时,主动调用 recallHistory 回顾对话历史
- 【防误判规则 - interceptWaybill】讨论已有售后工单(AS开头编号)、询问物流进度、问"快递到哪了"、转发售后截图等均不是拦截请求,严禁调用 interceptWaybill。只有用户明确说"拦截/退回/召回/追回/取消"运单时才可调用 - 【防误判规则 - interceptWaybill】讨论已有售后工单(AS开头编号)、询问物流进度、问"快递到哪了"、转发售后截图等均不是拦截请求,严禁调用 interceptWaybill。只有用户明确说"拦截/退回/召回/追回/取消"运单时才可调用
- 【措辞规则 - interceptWaybill】拦截结果回复严禁使用"已拦截""拦截成功"等确定口吻,必须使用"拦截信息已登记""已提交拦截申请"等措辞。因为快递拦截可能失败,实际结果以快递公司反馈为准。回复时需列出工单号供用户跟进 - 【措辞规则 - interceptWaybill】拦截结果回复严禁使用"已拦截""拦截成功"等确定口吻,必须使用"拦截信息已登记""已提交拦截申请"等措辞。因为快递拦截可能失败,实际结果以快递公司反馈为准。回复时需列出工单号供用户跟进`;
- 【规则 - handleStoreFeedback】货主售后群中客户反馈"错发/发错""破损/坏了""多发/发多""少发/漏发"且提供了运单号时,调用 handleStoreFeedback 创建售后工单(初始状态未开始处理,不通知快递群);若消息中无运单号,先向客户确认运单号再调用
- 【规则 - changeAddr】货主售后群中客户消息含"改地址/改电话/改联系人/改收件人/地址更改/改手机/催退回/尽快安排派送/催促退回"等诉求且提供了运单号时,调用 changeAddr(issue_type:addr=改地址类诉求,return=催退回类诉求);函数会创建售后工单并把客户原文转发到对应快递群,返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用
- 【规则 - weishoudao】货主售后群中客户消息含"核实签收/未收到/是否发出/是否已经发货/核实/没有找到快递"等诉求且提供了运单号时,调用 weishoudao 创建核实签收售后工单,并把"运单号+核实签收"转发到对应快递群;返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用
- 【规则 - changeExpress】货主售后群中客户要求"改快递/换快递/改圆通/改中通/改顺丰"等且提供了订单号时,调用 changeExpress(keyword=订单号,express=目标快递名称或编码);仅待处理表中未分配快递的订单可以修改,已分配快递或不在待处理表的订单不能修改;返回的 data.message 是模板消息必须原样回复;若消息中缺订单号或目标快递,先向客户确认再调用
- 【模板消息 - queryReturn】queryReturn 返回的 data.message 是已排版好的模板消息,必须原样作为最终回复输出,禁止改写、删减、增补内容,禁止添加 Markdown 或额外说明
- 【规则 - queryWarehouseAddress】用户询问"仓库地址/收货地址/退货地址/退件地址/寄回地址"时,调用 queryWarehouseAddress 查询仓库配置中的 receiver_address;返回的 data.message 是模板消息必须原样回复
- 【模板消息 - handleStoreFeedback】handleStoreFeedback 返回的 data.message 是已排版好的模板消息(运单号+问题类型+工单号+"稍后客服将人工核实跟进"),必须原样作为最终回复输出,禁止改写、删减或增补内容
- 用户发送"查退回+运单号"时,调用 queryReturn 查询退回明细,不要误调 queryOrder 或 interceptWaybill
- 【查询类请求强制调函数】查订单/查退回/查库存等查询类请求必须实际调用对应函数获取结果后再回复,严禁仅凭历史对话或猜测臆测"服务不可用/无法处理"而跳过函数调用
- 【历史失败回复免疫】群历史中 AI 的历史回复(尤其含"失败""异常""无法处理"等字样的兜底回复)只是历史记录,不代表当前功能不可用;严禁模仿、引用这类历史回复,也严禁据此判断函数不可用而拒绝调用;登记/操作/查询类请求必须实际调用对应函数获取最新结果`;
// 多轮推理循环 // 多轮推理循环
for (let round = 1; round <= MAX_ROUNDS; round++) { for (let round = 1; round <= MAX_ROUNDS; round++) {
@ -283,7 +261,7 @@ ${historyContext}
...(contextLines.length > 0 ? [{ role: 'system', content: contextLines.join('\n') }] : []), ...(contextLines.length > 0 ? [{ role: 'system', content: contextLines.join('\n') }] : []),
{ role: 'user', content: round === 1 { role: 'user', content: round === 1
? content ? content
: (jsonRetryNote ? `${jsonRetryNote}\n` : '') + (executedFunctions.length > 0 : (executedFunctions.length > 0
? `已获取到函数执行结果,请根据结果 reply 告知用户(禁止 silent)。第 ${round}/${MAX_ROUNDS} 轮` ? `已获取到函数执行结果,请根据结果 reply 告知用户(禁止 silent)。第 ${round}/${MAX_ROUNDS} 轮`
: `请根据已获取的信息,决定下一步:继续调用函数还是给出最终回复。第 ${round}/${MAX_ROUNDS} 轮`), : `请根据已获取的信息,决定下一步:继续调用函数还是给出最终回复。第 ${round}/${MAX_ROUNDS} 轮`),
}, },
@ -291,8 +269,7 @@ ${historyContext}
let raw = ''; let raw = '';
try { try {
// 推理模型(deepseek-v4-pro)需要充足 max_tokens:推理过程会先占用配额,过小会导致 content 被截断为空 raw = await this.callDeepSeek(messages, { maxTokens: 600 });
raw = await this.callDeepSeek(messages, { maxTokens: 4000 });
ctx.logger.info(`[inbox ai] 第 ${round}/${MAX_ROUNDS} 轮: ${raw}`); ctx.logger.info(`[inbox ai] 第 ${round}/${MAX_ROUNDS} 轮: ${raw}`);
const result = JSON.parse(raw); const result = JSON.parse(raw);
@ -341,19 +318,6 @@ ${historyContext}
if (lastThought) lastThought.functionResult = lastFunctionResult; if (lastThought) lastThought.functionResult = lastFunctionResult;
ctx.logger.info(`[inbox ai] 执行 ${fnName}: ${JSON.stringify(lastFunctionResult)}`); ctx.logger.info(`[inbox ai] 执行 ${fnName}: ${JSON.stringify(lastFunctionResult)}`);
// 函数携带模板消息(direct_reply=true)→ 直接作为最终回复,不再交由 AI 改写
const directReply = lastFunctionResult
&& lastFunctionResult.data
&& lastFunctionResult.data.direct_reply === true
&& lastFunctionResult.data.message
? String(lastFunctionResult.data.message)
: '';
if (directReply) {
ctx.logger.info(`[inbox ai] 函数 ${fnName} 返回模板消息,直接回复 (length=${directReply.length})`);
finalReply = directReply;
break;
}
// 最后一轮强制输出 // 最后一轮强制输出
if (round === MAX_ROUNDS) { if (round === MAX_ROUNDS) {
finalReply = lastFunctionResult?.data?.message finalReply = lastFunctionResult?.data?.message
@ -369,15 +333,9 @@ ${historyContext}
} catch (error) { } catch (error) {
ctx.logger.warn(`[inbox ai] 第 ${round} 轮异常: ${error.message}, raw: ${raw}`); ctx.logger.warn(`[inbox ai] 第 ${round} 轮异常: ${error.message}, raw: ${raw}`);
// 模型输出疑似被截断的 JSON → 提醒后重试,避免把原始 JSON 当作回复发给用户
if (error instanceof SyntaxError && raw) {
const trimmedRaw = String(raw).trim();
if (trimmedRaw.startsWith('{') || trimmedRaw.startsWith('[')) {
jsonRetryNote = '上一轮模型输出不是合法 JSON(疑似截断),请重新输出完整合法的纯 JSON,不要包含任何额外文字';
continue;
}
// 不是 JSON → 当作文本回复 // 不是 JSON → 当作文本回复
finalReply = trimmedRaw; if (error instanceof SyntaxError && raw) {
finalReply = raw;
break; break;
} }

File diff suppressed because it is too large Load Diff

View File

@ -26,7 +26,7 @@ const GROUP_TYPES = [
type: 'warehouse', type: 'warehouse',
label: '仓库群', label: '仓库群',
mainGroup: 'bound:warehouse', mainGroup: 'bound:warehouse',
wildcardGroup: 'bound:warehouse:*', wildcardGroup: null,
subTypes: [ subTypes: [
{ key: 'receiving', label: '收货' }, { key: 'receiving', label: '收货' },
{ key: 'production', label: '生产' }, { key: 'production', label: '生产' },

View File

@ -66,16 +66,15 @@ class ReturnUnpackMethodService extends MainService {
* @param {Object} data 请求体。 * @param {Object} data 请求体。
* @param {number} data.id 拆包单ID。 * @param {number} data.id 拆包单ID。
* @param {number} [data.stock_id] 系统商品ID(wms_stock_warehouse.id)。 * @param {number} [data.stock_id] 系统商品ID(wms_stock_warehouse.id)。
* @param {string} [data.barcode] 扫描条码(stock_id 为空时按条码反查商品)。
* @param {number} [data.quantity] 数量。 * @param {number} [data.quantity] 数量。
* @param {string} [data.product_status] 产品状态 normal/damaged。 * @param {string} [data.product_status] 产品状态 normal/damaged。
* @param {string} [data.remark] 备注。 * @param {string} [data.remark] 备注。
* @return {Promise<Object>} 统一 success 包装。 * @return {Promise<Object>} 统一 success 包装。
*/ */
async addDetail(data = {}) { async addDetail(data = {}) {
const { id, stock_id, barcode, quantity, product_status, remark } = data; const { id, stock_id, quantity, product_status, remark } = data;
return this._call( return this._call(
() => this.service.systems.returnUnpack.addDetail({ id, stock_id, barcode, quantity, product_status, remark }), () => this.service.systems.returnUnpack.addDetail({ id, stock_id, quantity, product_status, remark }),
'录明细失败' '录明细失败'
); );
} }

View File

@ -68,18 +68,16 @@ class ReturnUnpackService extends Service {
let orderExpressId = null; let orderExpressId = null;
let orderId = null; let orderId = null;
let storeId = null; let storeId = null;
let sourceOrderCodes = null;
try { try {
const orderExpress = await ctx.model.OrderExpress.findOne({ const orderExpress = await ctx.model.OrderExpress.findOne({
where: { waybill_code: waybillCode }, where: { waybill_code: waybillCode },
attributes: [ 'id', 'order_id', 'store_id', 'source_order_codes' ], attributes: [ 'id', 'order_id', 'store_id' ],
raw: true, raw: true,
}); });
if (orderExpress) { if (orderExpress) {
orderExpressId = orderExpress.id; orderExpressId = orderExpress.id;
orderId = orderExpress.order_id; orderId = orderExpress.order_id;
storeId = orderExpress.store_id; storeId = orderExpress.store_id;
sourceOrderCodes = orderExpress.source_order_codes || null;
} }
} catch (err) { } catch (err) {
ctx.logger.warn(`[returnUnpack.create] 反查原运单失败: ${err.message}`); ctx.logger.warn(`[returnUnpack.create] 反查原运单失败: ${err.message}`);
@ -134,8 +132,6 @@ class ReturnUnpackService extends Service {
order_express_id: orderExpressId, order_express_id: orderExpressId,
order_id: orderId, order_id: orderId,
store_id: storeId, store_id: storeId,
source_order_codes: sourceOrderCodes,
shop_name: storeRemark || null,
camera_ids: normalizedCameraIds, camera_ids: normalizedCameraIds,
remark: remark ? String(remark).slice(0, 500) : null, remark: remark ? String(remark).slice(0, 500) : null,
}; };
@ -188,26 +184,22 @@ class ReturnUnpackService extends Service {
/** /**
* 录明细:以拆包单ID为依据录入一条明细(识别到系统商品时回填快照)。 * 录明细:以拆包单ID为依据录入一条明细(识别到系统商品时回填快照)。
* 仅以 stock_id 识别商品;不指定 stock_id 时一律标注未知商品,
* 不做条码自动匹配(同一商品可能存在多条条码记录/多个 stock_id,自动匹配易误配)。
* *
* @param {Object} params 明细参数。 * @param {Object} params 明细参数。
* @param {number} params.id 拆包单ID。 * @param {number} params.id 拆包单ID。
* @param {number} [params.stock_id] 系统商品ID(wms_stock_warehouse.id),为空即无关联货物(商品名称标注未知商品)。 * @param {number} [params.stock_id] 系统商品ID(wms_stock_warehouse.id),为空即无关联货物。
* @param {string} [params.barcode] 扫描条码(仅作记录,不参与商品匹配)。
* @param {number} [params.quantity] 数量,默认 1。 * @param {number} [params.quantity] 数量,默认 1。
* @param {string} [params.product_status] 产品状态 normal/damaged,默认 normal。 * @param {string} [params.product_status] 产品状态 normal/damaged,默认 normal。
* @param {string} [params.remark] 备注。 * @param {string} [params.remark] 备注。
* @return {Promise<Object>} 明细ID + 明细行 + 主表最新汇总。 * @return {Promise<Object>} 明细ID + 明细行 + 主表最新汇总。
*/ */
async addDetail({ id, stock_id, barcode, quantity, product_status, remark }) { async addDetail({ id, stock_id, quantity, product_status, remark }) {
const { ctx } = this; const { ctx } = this;
const unpack = await this._findByIdChecked(id); const unpack = await this._findByIdChecked(id);
this._assertUnpacking(unpack); this._assertUnpacking(unpack);
const normalizedStockId = stock_id ? Number(stock_id) : null; const normalizedStockId = stock_id ? Number(stock_id) : null;
const normalizedBarcode = barcode ? String(barcode).trim().slice(0, 100) : null;
const normalizedQuantity = Math.max(1, parseInt(quantity) || 1); const normalizedQuantity = Math.max(1, parseInt(quantity) || 1);
const normalizedStatus = product_status === 'damaged' ? 'damaged' : 'normal'; const normalizedStatus = product_status === 'damaged' ? 'damaged' : 'normal';
@ -247,25 +239,19 @@ class ReturnUnpackService extends Service {
item_type: stock.item_type || '', item_type: stock.item_type || '',
}); });
// 主表货主为空时回填(首个识别商品确定货主),并同步回填自定义店铺名称快照 // 主表货主为空时回填(首个识别商品确定货主)
if (currentStoreId === 0 && stockStoreId > 0) { if (currentStoreId === 0 && stockStoreId > 0) {
const backfillFields = { store_id: stockStoreId };
const shopName = await this._resolveStoreRemark(stockStoreId, unpack.warehouse_id);
if (shopName) backfillFields.shop_name = shopName;
await ctx.model.ReturnUnpack.update( await ctx.model.ReturnUnpack.update(
backfillFields, { store_id: stockStoreId },
{ where: { id: unpack.id } } { where: { id: unpack.id } }
); );
} }
} else {
// 未指定系统商品:一律标注未知商品,不做条码自动匹配(同条码可能对应多个 stock_id,易误配)
itemName = '未知商品';
} }
const created = await ctx.model.ReturnUnpackDetail.create({ const created = await ctx.model.ReturnUnpackDetail.create({
unpack_id: unpack.id, unpack_id: unpack.id,
warehouse_id: unpack.warehouse_id, warehouse_id: unpack.warehouse_id,
barcode: normalizedBarcode, barcode: null,
stock_id: normalizedStockId, stock_id: normalizedStockId,
is_recognized: isRecognized, is_recognized: isRecognized,
item_code: itemCode, item_code: itemCode,
@ -613,344 +599,6 @@ class ReturnUnpackService extends Service {
}; };
} }
/**
* 查询退回明细(按运单号,跨退回相关表汇总)。
* 依次查询:拆包主表+明细+视频(已拆包)→ 退回收到表(已收到未拆包)→ 退回查询登记表(未退回)。
* 未退回且无登记记录时自动登记到 wms_return_query_log,等待拆包后处理。
*
* @param {Object} params 查询参数。
* @param {string} params.waybill_code 退回包裹运单号(必填)。
* @param {number} params.warehouse_id 仓库ID(必填)。
* @param {number} [params.store_id] 货主ID(可选,用于货主隔离与未退回登记)。
* @return {Promise<Object>} { status, waybill_code, warehouse_name, ... }。
* status:unpacked(已拆包)/ received(已收到未拆包)/ not_returned(未退回)/ hidden(跨货主不可见)。
*/
async queryByWaybill({ waybill_code, warehouse_id, store_id } = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const waybillCode = String(waybill_code || '').trim();
if (!waybillCode) {
throw this.createBusinessError('waybill_code 不能为空', 400);
}
const warehouseId = Number(warehouse_id || 0);
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
throw this.createBusinessError('缺少仓库上下文', 400);
}
const storeId = Number(store_id || 0);
const warehouseName = await this._resolveWarehouseName(warehouseId);
// 1. 已拆包:同一运单号取最新一条有效拆包单(跳过已作废)
const unpack = await ctx.model.ReturnUnpack.findOne({
where: {
warehouse_id: warehouseId,
waybill_code: waybillCode,
status: { [Op.ne]: 'cancelled' },
},
order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]],
raw: true,
});
if (unpack) {
// 货主隔离:限定货主查询且拆包单已归属其他货主 → 不暴露数据
if (storeId > 0 && Number(unpack.store_id || 0) > 0 && Number(unpack.store_id) !== storeId) {
return { status: 'hidden', waybill_code: waybillCode, warehouse_name: warehouseName };
}
const details = await ctx.model.ReturnUnpackDetail.findAll({
where: { unpack_id: unpack.id },
order: [[ 'id', 'ASC' ]],
raw: true,
});
const videos = await ctx.model.ReturnUnpackVideo.findAll({
where: { unpack_id: unpack.id, deleted_at: null },
order: [[ 'id', 'ASC' ]],
raw: true,
});
let received = null;
if (unpack.return_received_id) {
received = await ctx.model.ReturnReceived.findOne({
where: { id: unpack.return_received_id },
raw: true,
});
}
const orderInfo = await this._resolveReturnOrderInfo({
order_express_id: unpack.order_express_id,
order_id: unpack.order_id,
warehouse_id: warehouseId,
store_id: unpack.store_id,
source_order_codes: unpack.source_order_codes,
shop_name: unpack.shop_name,
});
return {
status: 'unpacked',
waybill_code: waybillCode,
warehouse_name: warehouseName,
unpack,
details,
videos,
received,
order_info: orderInfo,
};
}
// 2. 已收到未拆包:退回收到表登记过
const received = await ctx.model.ReturnReceived.findOne({
where: { warehouse_id: warehouseId, waybill_code: waybillCode },
order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]],
raw: true,
});
if (received) {
if (storeId > 0 && Number(received.store_id || 0) > 0 && Number(received.store_id) !== storeId) {
return { status: 'hidden', waybill_code: waybillCode, warehouse_name: warehouseName };
}
// 货主确定优先级:入参 store_id > 退回登记表 store_id > 原运单反查 store_id > 0(未知)
let resolvedStoreId = storeId || Number(received.store_id || 0);
if (!resolvedStoreId) {
resolvedStoreId = await this._resolveStoreIdByWaybill(waybillCode, warehouseId);
}
// 退回登记表货主为空 → 回填变更(后续拆包/通知依赖货主)
if (Number(received.store_id || 0) <= 0 && resolvedStoreId > 0) {
try {
await ctx.model.ReturnReceived.update(
{ store_id: resolvedStoreId },
{ where: { id: received.id } }
);
received.store_id = resolvedStoreId;
ctx.logger.info(
`[returnUnpack.queryByWaybill] 退回登记表回填货主: id=${received.id} store_id=${resolvedStoreId}`
);
} catch (err) {
ctx.logger.warn(`[returnUnpack.queryByWaybill] 回填退回登记表货主失败: ${err.message}`);
}
}
// 照常登记退回查询记录(幂等:已存在则不重复创建)
let queryLog = await ctx.model.ReturnQueryLog.findOne({
where: { warehouse_id: warehouseId, waybill_code: waybillCode },
order: [[ 'id', 'DESC' ]],
raw: true,
});
if (!queryLog) {
try {
const created = await ctx.model.ReturnQueryLog.create({
warehouse_id: warehouseId,
store_id: resolvedStoreId || 0,
waybill_code: waybillCode,
remark: '站内信查询退回自动登记(已收到未拆包)',
is_notified: 0,
is_back: 0,
});
queryLog = created && typeof created.toJSON === 'function' ? created.toJSON() : created;
} catch (err) {
ctx.logger.warn(`[returnUnpack.queryByWaybill] 已收到未拆包登记退回查询记录失败: ${err.message}`);
}
}
const orderInfo = await this._resolveReturnOrderInfo({
order_express_id: received.order_express_id,
order_id: received.order_id,
warehouse_id: warehouseId,
store_id: resolvedStoreId || Number(received.store_id || 0),
});
return {
status: 'received',
waybill_code: waybillCode,
warehouse_name: warehouseName,
received,
query_log: queryLog,
order_info: orderInfo,
};
}
// 3. 未退回:查询退回查询登记表,无登记则自动登记(等待拆包后处理)
const queryLog = await ctx.model.ReturnQueryLog.findOne({
where: { warehouse_id: warehouseId, waybill_code: waybillCode },
order: [[ 'id', 'DESC' ]],
raw: true,
});
if (queryLog) {
return {
status: 'not_returned',
waybill_code: waybillCode,
warehouse_name: warehouseName,
query_log: queryLog,
registered_now: false,
};
}
// 货主确定优先级:入参 store_id > 原运单反查 store_id > 0(未知货主)
let regStoreId = storeId;
if (!regStoreId) {
regStoreId = await this._resolveStoreIdByWaybill(waybillCode, warehouseId);
}
let createdRow = null;
try {
const created = await ctx.model.ReturnQueryLog.create({
warehouse_id: warehouseId,
store_id: regStoreId || 0,
waybill_code: waybillCode,
remark: '站内信查询退回自动登记',
is_notified: 0,
is_back: 0,
});
createdRow = created && typeof created.toJSON === 'function' ? created.toJSON() : created;
} catch (err) {
// 并发/异常兜底:登记失败不影响查询结论,回查已有登记
ctx.logger.warn(`[returnUnpack.queryByWaybill] 自动登记退回查询记录失败: ${err.message}`);
try {
createdRow = await ctx.model.ReturnQueryLog.findOne({
where: { warehouse_id: warehouseId, waybill_code: waybillCode },
order: [[ 'id', 'DESC' ]],
raw: true,
});
} catch (e) {
ctx.logger.warn(`[returnUnpack.queryByWaybill] 回查退回查询记录失败: ${e.message}`);
}
}
return {
status: 'not_returned',
waybill_code: waybillCode,
warehouse_name: warehouseName,
query_log: createdRow,
registered_now: Boolean(createdRow),
};
}
/**
* 解析仓库名称(wms_store.company_name)。
*
* @param {number} warehouseId 仓库ID。
* @return {Promise<string>} 仓库名称,查询失败返回空字符串。
*/
async _resolveWarehouseName(warehouseId) {
const { ctx } = this;
try {
const store = await ctx.model.Store.findOne({
where: { id: warehouseId },
attributes: [ 'company_name' ],
raw: true,
});
return store && store.company_name ? String(store.company_name) : '';
} catch (err) {
ctx.logger.warn(`[returnUnpack._resolveWarehouseName] 查询仓库名称失败: ${err.message}`);
return '';
}
}
/**
* 按运单号反查货主(wms_order_express)。
*
* @param {string} waybillCode 运单号。
* @param {number} warehouseId 仓库ID。
* @return {Promise<number>} 货主ID,未命中返回 0。
*/
async _resolveStoreIdByWaybill(waybillCode, warehouseId) {
const { ctx } = this;
try {
const express = await ctx.model.OrderExpress.findOne({
where: { waybill_code: waybillCode, warehouse_id: warehouseId },
attributes: [ 'store_id' ],
raw: true,
});
return express && Number(express.store_id) > 0 ? Number(express.store_id) : 0;
} catch (err) {
ctx.logger.warn(`[returnUnpack._resolveStoreIdByWaybill] 反查货主失败: ${err.message}`);
return 0;
}
}
/**
* 解析退回包裹关联的原单信息:平台交易单号 / 快递 / 自定义店铺名称。
* 优先取主表快照(source_order_codes / shop_name),为空时实时兜底:
* 交易单号取原运单/原订单的 source_order_codes,店铺名称取货主合约 store_remask。
*
* @param {Object} params 关联参数。
* @param {number} [params.order_express_id] 原运单ID。
* @param {number} [params.order_id] 原订单ID。
* @param {number} [params.warehouse_id] 仓库ID(分表查询/合约查询用)。
* @param {number} [params.store_id] 货主ID(自定义店铺名称查询用)。
* @param {string} [params.source_order_codes] 平台交易单号快照。
* @param {string} [params.shop_name] 店铺名称快照。
* @return {Promise<{trade_no: string, express: string, shop_name: string}>} 原单信息。
*/
async _resolveReturnOrderInfo({ order_express_id, order_id, warehouse_id, store_id, source_order_codes, shop_name } = {}) {
const { ctx } = this;
const info = {
trade_no: String(source_order_codes || '').trim(),
express: '',
shop_name: String(shop_name || '').trim(),
};
if (order_express_id) {
try {
const express = await ctx.model.OrderExpress.findOne({
where: { id: order_express_id },
attributes: [ 'logistics_name', 'source_order_codes' ],
raw: true,
});
if (express) {
if (express.logistics_name) info.express = String(express.logistics_name);
if (!info.trade_no && express.source_order_codes) {
info.trade_no = String(express.source_order_codes);
}
}
} catch (err) {
ctx.logger.warn(`[returnUnpack._resolveReturnOrderInfo] 查询原运单失败: ${err.message}`);
}
}
if (order_id && !info.trade_no) {
try {
let order = null;
try {
order = await ctx.model.OrderDelivery.findOne({
where: { id: order_id },
raw: true,
});
} catch (err) {
// 主表查询失败,继续走工厂分表兜底
}
if (!order && ctx.model.OrderDeliveryFactory) {
try {
const factoryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouse_id);
if (factoryModel) {
order = await factoryModel.findOne({ where: { id: order_id }, raw: true });
}
} catch (err) {
// 分表查询失败忽略
}
}
if (order) {
info.trade_no = String(order.source_order_codes || order.source_platform_code || '');
if (!info.express && order.logistics_name) info.express = String(order.logistics_name);
}
} catch (err) {
ctx.logger.warn(`[returnUnpack._resolveReturnOrderInfo] 查询原订单失败: ${err.message}`);
}
}
// 自定义店铺名称兜底:货主合约 store_remask
if (!info.shop_name && store_id) {
info.shop_name = await this._resolveStoreRemark(store_id, warehouse_id);
}
return info;
}
/** /**
* 删除拆包单(后台管理,不限制状态):事务内物理删除主表 + 明细,同步软删视频。 * 删除拆包单(后台管理,不限制状态):事务内物理删除主表 + 明细,同步软删视频。
* *

View File

@ -148,15 +148,6 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([
description: '仓库默认发件详细地址', description: '仓库默认发件详细地址',
maxLength: 200, maxLength: 200,
}), }),
Object.freeze({
key: 'receiver_address',
name: '仓库收货地址',
type: 'string',
default: '',
required: false,
description: '仓库收货地址(退货/退件收件地址),一行文本',
maxLength: 500,
}),
Object.freeze({ Object.freeze({
key: 'group_wave_prefix', key: 'group_wave_prefix',
name: '团购波次前缀', name: '团购波次前缀',

View File

@ -1,36 +0,0 @@
'use strict';
/**
* wms_return_unpack 主表补充订单信息快照字段:
* - source_order_codes:平台交易单号(原单退回时回填,来源 wms_order_express.source_order_codes)
* - shop_name:店铺名称(货主自定义店铺名称快照,来源 wms_store_warehouse.store_remask)
*
* 用途:退回查询(查退回模板消息)直接取主表快照,避免依赖原运单/订单表实时关联。
*/
const TABLE_NAME = 'wms_return_unpack';
module.exports = {
// eslint-disable-next-line no-unused-vars
async up(queryInterface, Sequelize) {
const { STRING } = Sequelize;
await queryInterface.addColumn(TABLE_NAME, 'source_order_codes', {
type: STRING(500),
allowNull: true,
comment: '平台交易单号快照(原单退回时回填)',
after: 'store_id',
});
await queryInterface.addColumn(TABLE_NAME, 'shop_name', {
type: STRING(50),
allowNull: true,
comment: '店铺名称快照(货主自定义店铺名称 store_remask)',
after: 'source_order_codes',
});
},
// eslint-disable-next-line no-unused-vars
async down(queryInterface, Sequelize) {
await queryInterface.removeColumn(TABLE_NAME, 'shop_name');
await queryInterface.removeColumn(TABLE_NAME, 'source_order_codes');
},
};

View File

@ -1,22 +1,4 @@
[ [
{
"version": "2026.08.14-warehouse-receive-address",
"date": "2026-08-14",
"type": "added",
"summary": "仓库设置 setting.warehouse 新增仓库收货地址配置字段 receiver_address(一行文本,退货/退件收件地址)",
"methods": [
"setting.warehouse.getSettings",
"setting.warehouse.getFieldMeta",
"setting.warehouse.saveSettings"
],
"notes": [
"在 WAREHOUSE_SETTING_FIELDS 中新增 receiver_address(string,非必填,默认空字符串,最大长度 500)",
"wms_store.subject_config 默认值同步补齐(app/model/store.js DEFAULT_SUBJECT_CONFIG)",
"methods/system.json 中 getSettings 响应与 saveSettings 入参补充对应字段文档",
"向后兼容:新增字段为可选,不影响既有仓库设置读写"
],
"module": "setting.warehouse"
},
{ {
"version": "2026.08.13-stockQueryWhere", "version": "2026.08.13-stockQueryWhere",
"date": "2026-08-13", "date": "2026-08-13",
@ -5934,53 +5916,5 @@
"仅文档同步,其余接口与模块不动" "仅文档同步,其余接口与模块不动"
], ],
"module": "returnUnpack" "module": "returnUnpack"
},
{
"version": "2026.08.13-returnUnpack.addDetailBarcode",
"date": "2026-08-13",
"type": "updated",
"summary": "returnUnpack.addDetail 新增 barcode 入参(可选):stock_id 为空时按条码反查本仓库商品(wms_stock_barcodes)再走识别流程,反查不到按无关联货物处理;条码同步写入明细作记录(此前固定写 null)。复用基础模块条码索引,支持 PDA 扫描条码录明细。",
"methods": [
"returnUnpack.addDetail"
],
"notes": [
"params 新增 barcode(string,可选,最长100,body)",
"识别优先级:stock_id > barcode 反查 > 无关联货物",
"明细 barcode 字段由固定 null 改为记录扫描条码",
"business 层按 warehouse_id+barcode 匹配 wms_stock_barcodes(uk_barcode 全局唯一,加仓库过滤防跨仓串货)"
],
"module": "returnUnpack"
},
{
"version": "2026.08.13-returnUnpack.addDetailBarcodeV2",
"date": "2026-08-13",
"type": "updated",
"summary": "returnUnpack.addDetail 识别策略调整:未指定 stock_id 时一律标注未知商品(item_name=未知商品),移除按条码自动反查 stock_id 的逻辑(同一条码可能对应多个 stock_id,自动匹配易误配);barcode 仍写入明细作记录。",
"methods": [
"returnUnpack.addDetail"
],
"notes": [
"移除 barcode 反查 wms_stock_barcodes 自动识别逻辑(v1 新增,本次回退)",
"未指定 stock_id:is_recognized=0,item_name=未知商品(此前为 null)",
"barcode 参数保留:仅作记录写入明细,不参与商品匹配",
"docs 同步:addDetail description / stock_id / barcode 参数说明更新"
],
"module": "returnUnpack"
},
{
"version": "2026.08.13-returnUnpack.orderInfoSnapshot",
"date": "2026-08-13",
"type": "updated",
"summary": "wms_return_unpack 主表新增订单信息快照字段 source_order_codes(平台交易单号)/ shop_name(店铺名称=货主自定义店铺名称 store_remask),returnUnpack.create 原单退回时回填;退回查询(查退回)优先取主表快照返回交易单号与自定义店铺。",
"methods": [
"returnUnpack.create"
],
"notes": [
"迁移 20260813170000-add-return-unpack-order-info.js:addColumn source_order_codes VARCHAR(500) + shop_name VARCHAR(50)",
"create 原单退回:source_order_codes 取 wms_order_express.source_order_codes,shop_name 取 store_remask",
"addDetail 首个识别商品回填主表 store_id 时同步回填 shop_name",
"退回查询 _resolveReturnOrderInfo 优先主表快照,空时实时兜底(交易单号→原运单/原订单,店铺→store_remask)"
],
"module": "returnUnpack"
} }
] ]

View File

@ -13663,12 +13663,6 @@
"type": "string", "type": "string",
"required": false, "required": false,
"description": "仓库默认发件详细地址,默认空字符串" "description": "仓库默认发件详细地址,默认空字符串"
},
{
"name": "subject_config.receiver_address",
"type": "string",
"required": false,
"description": "仓库收货地址(退货/退件收件地址),一行文本,默认空字符串"
} }
], ],
"errors": [ "errors": [
@ -13912,13 +13906,6 @@
"required": false, "required": false,
"source": "body.subject_config", "source": "body.subject_config",
"description": "仓库默认发件详细地址,默认空字符串,最大长度 200" "description": "仓库默认发件详细地址,默认空字符串,最大长度 200"
},
{
"name": "subject_config.receiver_address",
"type": "string",
"required": false,
"source": "body.subject_config",
"description": "仓库收货地址(退货/退件收件地址),一行文本,默认空字符串,最大长度 500"
} }
], ],
"response": [ "response": [
@ -35044,7 +35031,7 @@
"list": [ "list": [
{ {
"method": "returnUnpack.create", "method": "returnUnpack.create",
"description": "开拆包单(明细不在此提交,由 returnUnpack.addDetail 逐件录入)。用 waybill_code 反查 wms_order_express 判定是否原单退回,命中则回填 order_express_id/order_id/store_id 及订单信息快照(source_order_codes 平台交易单号 / shop_name 店铺名称=货主自定义店铺名称 store_remask)并返回原订单详情;未命中原单时按 warehouse_id+waybill_code 从 wms_return_query_log 反查货主(限最近 3 个月内登记)。拆包单号规则 RP+YYYYMMDD+6位序号。仓库隔离:warehouse_id 由服务端注入 ctx.user.store_id,禁止前端传入。", "description": "开拆包单(明细不在此提交,由 returnUnpack.addDetail 逐件录入)。用 waybill_code 反查 wms_order_express 判定是否原单退回,命中则回填 order_express_id/order_id/store_id 并返回原订单详情;未命中原单时按 warehouse_id+waybill_code 从 wms_return_query_log 反查货主(限最近 3 个月内登记)。拆包单号规则 RP+YYYYMMDD+6位序号。仓库隔离:warehouse_id 由服务端注入 ctx.user.store_id,禁止前端传入。",
"isNeedAuth": true, "isNeedAuth": true,
"isNeedLogin": true, "isNeedLogin": true,
"headers": [], "headers": [],
@ -35089,7 +35076,7 @@
"name": "record", "name": "record",
"type": "object", "type": "object",
"required": true, "required": true,
"description": "拆包单主表记录(含 unpack_no、waybill_code、unpack_date、start_time、unpacker_id/unpacker_name、status、detail_status、camera_ids 数组、回填的 order_express_id/order_id/store_id/source_order_codes/shop_name 快照及 is_original_return 派生字段)" "description": "拆包单主表记录(含 unpack_no、waybill_code、unpack_date、start_time、unpacker_id/unpacker_name、status、detail_status、camera_ids 数组、回填的 order_express_id/order_id/store_id 及 is_original_return 派生字段)"
}, },
{ {
"name": "is_original_return", "name": "is_original_return",
@ -35139,7 +35126,7 @@
}, },
{ {
"method": "returnUnpack.addDetail", "method": "returnUnpack.addDetail",
"description": "录明细:以拆包单ID为依据录入一条明细。主单非终态(unpacking)校验;stock_id 有值时校验货主归属并回填识别快照(is_recognized=1 + item_code/item_name/spec/product_snapshot),未指定 stock_id 时一律标注未知商品(is_recognized=0,item_name=未知商品),不做条码自动匹配(同一条码可能对应多个 stock_id,自动匹配易误配),barcode 仅作记录;主表 store_id 为空时以首个识别商品回填主表货主。写明细后重算主表 total_items/total_quantity/detail_status。仓库隔离校验(仅本仓库拆包单)。", "description": "录明细:以拆包单ID为依据录入一条明细。主单非终态(unpacking)校验;stock_id 有值时校验货主归属并回填识别快照(is_recognized=1 + item_code/item_name/spec/product_snapshot),为空即无关联货物(is_recognized=0);主表 store_id 为空时以首个识别商品回填主表货主。写明细后重算主表 total_items/total_quantity/detail_status。仓库隔离校验(仅本仓库拆包单)。",
"isNeedAuth": true, "isNeedAuth": true,
"isNeedLogin": true, "isNeedLogin": true,
"headers": [], "headers": [],
@ -35156,14 +35143,7 @@
"type": "integer", "type": "integer",
"required": false, "required": false,
"source": "body", "source": "body",
"description": "系统商品ID(wms_stock_warehouse.id),为空即无关联货物(商品名称标注未知商品)" "description": "系统商品ID(wms_stock_warehouse.id),为空即无关联货物"
},
{
"name": "barcode",
"type": "string",
"required": false,
"source": "body",
"description": "扫描条码(最长100字符,仅作记录,不参与商品匹配)"
}, },
{ {
"name": "quantity", "name": "quantity",
@ -35198,7 +35178,7 @@
"name": "detail", "name": "detail",
"type": "object", "type": "object",
"required": true, "required": true,
"description": "新增的明细行(含 barcode/is_recognized/item_code/item_name(未知商品)/spec/product_snapshot 等)" "description": "新增的明细行(含 is_recognized/item_code/item_name/spec/product_snapshot 等识别结果快照)"
}, },
{ {
"name": "total_items", "name": "total_items",

View File

@ -1,243 +0,0 @@
'use strict';
/**
* 站内信消息推送调试脚本(模拟 IM 桥向仓库推送入站消息,走真实验签链路)。
*
* 用法:
* node script/debug-inbox-push.cjs
* 默认: 向 test-stock-group 推送「查退回 <随机不存在运单号>」
* node script/debug-inbox-push.cjs --content "查退回 888888888888888"
* node script/debug-inbox-push.cjs --waybill 888888888888888 --groupId test-stock-group --userName 测试用户
*
* 行为:
* 1. 按 app/lib/api_sign.js 规则签名,POST /warehouse?method=inbox.push
* 2. 等待 AI 异步处理(默认 15s)
* 3. 回查本地库: 入站消息 / AI 思考过程 / 回信内容 / wms_return_query_log 登记
*/
const crypto = require('crypto');
const http = require('http');
const mysql = require('mysql2/promise');
// ========================== 稳定序列化(与 app/lib/api_sign.js 一致) ==========================
function isPlainObject(value) {
return Object.prototype.toString.call(value) === '[object Object]';
}
function stableStringify(value) {
if (value === undefined) return '';
if (value === null || typeof value !== 'object') return JSON.stringify(value);
if (Array.isArray(value)) {
return `[${value.map(item => stableStringify(item)).join(',')}]`;
}
if (!isPlainObject(value)) return JSON.stringify(value);
const keys = Object.keys(value).sort();
return `{${keys.map(key => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(',')}}`;
}
function md5(str) {
return crypto.createHash('md5').update(str, 'utf8').digest('hex').toLowerCase();
}
function buildSign(query, body, secret) {
const ignoreSet = new Set([ 'sign', 'signature' ]);
const keys = Object.keys(query)
.filter(key => !ignoreSet.has(String(key).toLowerCase()))
.filter(key => query[key] !== undefined)
.sort();
const canonicalQuery = keys.map(key => {
const v = query[key];
if (v === undefined || v === null) return `${key}=`;
if (typeof v === 'object') return `${key}=${stableStringify(v)}`;
return `${key}=${String(v)}`;
}).join('&');
const bodySign = md5(stableStringify(body));
const signText = `${canonicalQuery}${secret}${bodySign}`;
return { canonicalQuery, bodySign, sign: md5(signText) };
}
// ========================== 参数解析 ==========================
const ARGS = {};
for (let i = 2; i < process.argv.length; i++) {
const arg = process.argv[i];
const match = arg.match(/^--([^=]+)=(.*)$/);
if (match) {
ARGS[match[1]] = match[2];
} else if (arg.startsWith('--')) {
ARGS[arg.slice(2)] = process.argv[i + 1];
i++;
}
}
const CONFIG = {
baseUrl: ARGS.baseUrl || 'http://127.0.0.1:6060',
appKey: ARGS.appKey || 'APP2025011514315678',
appSecret: ARGS.appSecret || 'sec_xyz789uvw012abc345def678ghi901jkl234mno567pqr890',
groupId: ARGS.groupId || 'test-stock-group',
groupName: ARGS.groupName || '库存查询测试群',
userName: ARGS.userName || '测试用户',
waitMs: Number(ARGS.waitMs || 15000),
waybill: ARGS.waybill || `${Date.now()}99`,
};
if (ARGS.content) {
CONFIG.content = ARGS.content;
} else {
CONFIG.content = `查退回 ${CONFIG.waybill}`;
}
// ========================== HTTP 推送 ==========================
function postWarehouse(method, body) {
const query = {
method,
v: '1.0',
timestamp: Math.floor(Date.now() / 1000),
app_key: CONFIG.appKey,
};
const { sign } = buildSign(query, body, CONFIG.appSecret);
query.sign = sign;
const qs = Object.entries(query)
.map(([ k, v ]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
.join('&');
const bodyStr = JSON.stringify(body);
const url = `${CONFIG.baseUrl}/warehouse?${qs}`;
return new Promise((resolve, reject) => {
const req = http.request(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(bodyStr),
},
timeout: 20000,
}, res => {
let data = '';
res.on('data', chunk => (data += chunk));
res.on('end', () => {
try { resolve({ status: res.statusCode, body: JSON.parse(data) }); } catch (e) { resolve({ status: res.statusCode, body: data }); }
});
});
req.on('error', reject);
req.on('timeout', () => { req.destroy(); reject(new Error('Request timeout')); });
req.write(bodyStr);
req.end();
});
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// ========================== 本地库回查 ==========================
async function queryDb(sql) {
const conn = await mysql.createConnection({
host: '127.0.0.1',
port: 3307,
user: 'wms',
password: 'dspxmRwRdRbWtbm7',
database: 'wms',
});
try {
const [ rows ] = await conn.query(sql);
return rows;
} finally {
await conn.end();
}
}
// ========================== 主流程 ==========================
(async () => {
const requestId = `debug-return-${Date.now()}`;
console.log('========== 站内信模拟推送 ==========');
console.log(` 群: ${CONFIG.groupId} (${CONFIG.groupName})`);
console.log(` 用户: ${CONFIG.userName}`);
console.log(` 内容: ${CONFIG.content}`);
console.log(` requestId: ${requestId}`);
const r = await postWarehouse('inbox.push', {
requestId,
content: CONFIG.content,
groupId: CONFIG.groupId,
groupName: CONFIG.groupName,
userId: 'debug_user',
userName: CONFIG.userName,
targetType: 'im',
});
console.log(` HTTP ${r.status}: ${JSON.stringify(r.body).slice(0, 300)}`);
if (r.status !== 200 || (r.body && r.body.ok === false)) {
console.error('推送失败,请检查签名与仓库应用配置');
process.exit(1);
}
console.log(`\n等待 AI 异步处理 ${CONFIG.waitMs / 1000}s ...`);
await sleep(CONFIG.waitMs);
const extId = `api:${CONFIG.appKey}:${requestId}`;
// 1. 入站消息 + AI 思考
const inbound = await queryDb(
`SELECT id, direction, content, ai_thoughts, push_status, created_at
FROM wms_inbox_message WHERE ext_id='${extId}' ORDER BY id DESC LIMIT 1`
);
console.log('\n[入站消息]');
if (inbound.length === 0) {
console.log(' 未找到(消息可能尚未入库)');
} else {
console.log(` id=${inbound[0].id} push_status=${inbound[0].push_status}`);
console.log(` content: ${inbound[0].content}`);
const thoughts = inbound[0].ai_thoughts;
if (thoughts && typeof thoughts === 'string') {
try {
const parsed = JSON.parse(thoughts);
console.log(` ai_thoughts: ${JSON.stringify(parsed).slice(0, 400)}`);
} catch (e) {
console.log(` ai_thoughts(raw): ${String(thoughts).slice(0, 400)}`);
}
} else {
console.log(' ai_thoughts: 无');
}
}
// 2. 回信内容
const outbound = await queryDb(
`SELECT id, direction, content, created_at
FROM wms_inbox_message
WHERE direction='outbound' AND group_id='${CONFIG.groupId}'
ORDER BY id DESC LIMIT 1`
);
console.log('\n[最新回信]');
if (outbound.length === 0) {
console.log(' 无回信');
} else {
console.log(` id=${outbound[0].id} created_at=${outbound[0].created_at}`);
console.log(` content:\n${outbound[0].content}`);
}
// 3. 退回查询登记
const waybill = CONFIG.waybill;
const queryLog = await queryDb(
`SELECT id, warehouse_id, store_id, waybill_code, remark, is_notified, is_back, created_at
FROM wms_return_query_log WHERE waybill_code='${waybill}' ORDER BY id DESC LIMIT 3`
);
console.log('\n[wms_return_query_log 登记]');
if (queryLog.length === 0) {
console.log(' 无登记');
} else {
queryLog.forEach(row => {
console.log(` id=${row.id} store_id=${row.store_id} is_back=${row.is_back} is_notified=${row.is_notified} remark=${row.remark} ${row.created_at}`);
});
}
console.log('\n完成。测试记录按需保留,无需删除。');
process.exit(0);
})().catch(e => {
console.error('异常:', e.message);
process.exit(1);
});

View File

@ -252,32 +252,4 @@ describe('test/app/service/systems/setting/warehouse.test.js', () => {
); );
assert.equal(inventoryWarningRulesField.required, false); assert.equal(inventoryWarningRulesField.required, false);
}); });
it('getFieldMeta should include warehouse receive address field', async () => {
const { ctx } = createHarness();
const service = new SettingWarehouseService(ctx);
const list = await service.getFieldMeta();
const field = list.find(item => item.key === 'receiver_address');
assert.ok(field, '字段信息应包含 receiver_address');
assert.equal(field.name, '仓库收货地址');
assert.equal(field.type, 'string');
assert.equal(field.required, false);
assert.equal(field.default, '');
assert.equal(field.maxLength, 500);
});
it('saveSettings should persist warehouse receive address field', async () => {
const { ctx, calls } = createHarness();
const service = new SettingWarehouseService(ctx);
await service.saveSettings({
subject_config: {
receiver_address: '浙江省杭州市余杭区文一西路 1000 号',
},
});
assert.equal(calls.updatePayload.subject_config.receiver_address, '浙江省杭州市余杭区文一西路 1000 号');
});
}); });