出站回调:
- 新增 warehouse_notify.json 文档(notify.ping/notify.reply),与 warehouse.json 互跳
- 回调体统一 { method, code, data },method 放 query,body 为业务数据
- MD5 签名: sign=MD5(appSecret+timestamp+bodyJson)
- 回调响应: {code:200} 成功,非200/非code:200 视为失败
- docs 页面支持模拟推送调试
搜索增强(searchStock/searchWarehouseStock):
- 直接查 stock_warehouse,不再依赖 stock_store
- 新增字段: gross_weight/box_spec/packing_requirements/prohibited_type
- 管理标识: is_sn_mgmt/is_shelf_life_mgmt/is_batch_mgmt
- 条码关联: wms_stock_barcodes
- 图片: wms_file_reference(business_type=stock)+wms_file,返回数组
- id 修正为 stock_warehouse.id
推送状态完善:
- handleApiMessage 增加 push_status 更新(2成功/3失败)
- 未配回调地址 → push_status=3 + error 原因
- 回调异常 catch 也更新 push_status=3 + 写日志
- 出站日志写入 wms_warehouse_log 表(WN-前缀)
消息列表:
- keyword 兼容 content/keyword,支持数组
- keyword 搜索 content/group_name/user_name 三列
- 支持 where+operator 结构化查询(parseWhereConditions)
- storeId=-1 查询无货主消息; storeId=0→IS NULL
- 日期范围: startDate/endDate
其他:
- silent 动作: AI 识别无需回复时跳过回执
- ai_enabled 灰度开关(群级)
- bindCode 文档修正
- store_name 改用 StoreWarehouse.store_remask
398 lines
13 KiB
JavaScript
398 lines
13 KiB
JavaScript
'use strict';
|
||
|
||
const MainService = require('../../main');
|
||
|
||
/**
|
||
* 系统方法层:storage.stockout(非订单出库单)。
|
||
* 说明:直接读写 wms_order_stockout + wms_order_stockout_items 表。
|
||
*/
|
||
class StorageStockoutService extends MainService {
|
||
constructor(ctx) {
|
||
super(ctx);
|
||
const _noNeedLogin = '';
|
||
const _noNeedRight = 'list,toOrder,listItems';
|
||
const _noNeedLog = 'list,toOrder,listItems';
|
||
const _noNeedAuth = 'list,toOrder,listItems';
|
||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||
}
|
||
|
||
/**
|
||
* 出库单列表查询。
|
||
* @param {Object} data 请求体
|
||
* @param {Object} [data.where] 查询条件
|
||
* @param {Object} [data.pagination] 分页参数
|
||
* @param {Object} [data.sort] 排序参数
|
||
* @return {Promise<Object>} 统一成功包装响应
|
||
*/
|
||
async list(data = {}) {
|
||
const { ctx } = this;
|
||
const { Op } = this.app.Sequelize;
|
||
const { pagination = {}, sort = {} } = data;
|
||
|
||
const { parsed } = this.prepareWhereContext(data, {
|
||
specialFieldMap: {
|
||
quickWhere: {
|
||
bucket: 'quick',
|
||
},
|
||
},
|
||
});
|
||
|
||
const page = Math.max(Number(pagination.page) || 1, 1);
|
||
const pageSize = Math.max(Number(pagination.pageSize) || 20, 1);
|
||
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
|
||
const OrderStockoutModel = ctx.model.OrderStockout;
|
||
|
||
const andConditions = [
|
||
{ warehouse_id: warehouseId },
|
||
{ deleted_at: null },
|
||
];
|
||
|
||
const dynamicConditions = Array.isArray(parsed && parsed.dynamicConditions) ? parsed.dynamicConditions : [];
|
||
if (dynamicConditions.length > 0) {
|
||
andConditions.push({ [Op.and]: dynamicConditions });
|
||
}
|
||
|
||
const quickWhereCondition = parsed && parsed.rawConditionsByField && parsed.rawConditionsByField.quickWhere;
|
||
const quickValue = quickWhereCondition && Object.prototype.hasOwnProperty.call(quickWhereCondition, 'value')
|
||
? quickWhereCondition.value
|
||
: null;
|
||
if (quickValue !== null && quickValue !== undefined && String(quickValue).trim() !== '') {
|
||
const keyword = String(quickValue).trim();
|
||
andConditions.push({
|
||
[Op.or]: [
|
||
{ stockout_order_code: { [Op.like]: `%${keyword}%` } },
|
||
{ remark: { [Op.like]: `%${keyword}%` } },
|
||
],
|
||
});
|
||
}
|
||
|
||
const validSortFields = [
|
||
'id',
|
||
'stockout_order_code',
|
||
'order_status',
|
||
'order_type',
|
||
'updated_at',
|
||
'created_at',
|
||
'order_create_time',
|
||
];
|
||
const sortField = validSortFields.includes(String(sort.sortField || '').trim())
|
||
? String(sort.sortField).trim()
|
||
: 'updated_at';
|
||
const sortOrder = String(sort.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
|
||
|
||
const finalWhere = { [Op.and]: andConditions };
|
||
const { count, rows } = await OrderStockoutModel.findAndCountAll({
|
||
where: finalWhere,
|
||
order: [[ sortField, sortOrder ], [ 'id', 'DESC' ]],
|
||
limit: pageSize,
|
||
offset: (page - 1) * pageSize,
|
||
raw: true,
|
||
});
|
||
|
||
return this.success('ok', {
|
||
list: rows,
|
||
pagination: {
|
||
page,
|
||
pageSize,
|
||
total: count,
|
||
totalPages: Math.ceil(count / pageSize),
|
||
hasPrevious: page > 1,
|
||
hasNext: page < Math.ceil(count / pageSize),
|
||
},
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 出库单转订单占位接口。
|
||
* @return {Promise<Object>} 统一失败包装响应
|
||
*/
|
||
async toOrder() {
|
||
return this.fail('接口暂未开放');
|
||
}
|
||
|
||
/**
|
||
* 出库单明细查询。
|
||
* @param {Object} data 请求体
|
||
* @param {number} [data.id] 出库单ID
|
||
* @param {string} [data.stockout_order_code] 出库单号
|
||
* @return {Promise<Object>} 统一成功包装响应
|
||
*/
|
||
async listItems(data = {}) {
|
||
const { ctx } = this;
|
||
const warehouseId = Number(ctx.user && ctx.user.store_id) || 0;
|
||
const id = Number(data.id || 0);
|
||
// 兼容 delivery_order_code 旧参数名
|
||
const stockoutOrderCode = String(data.stockout_order_code || data.delivery_order_code || '').trim();
|
||
|
||
if (!id && !stockoutOrderCode) {
|
||
return this.fail('id 或 stockout_order_code 至少传一个');
|
||
}
|
||
|
||
const OrderStockoutModel = ctx.model.OrderStockout;
|
||
const OrderStockoutItemsModel = ctx.model.OrderStockoutItems;
|
||
|
||
const where = {
|
||
warehouse_id: warehouseId,
|
||
deleted_at: null,
|
||
};
|
||
if (id > 0) {
|
||
where.id = id;
|
||
} else {
|
||
where.stockout_order_code = stockoutOrderCode;
|
||
}
|
||
|
||
const order = await OrderStockoutModel.findOne({
|
||
where,
|
||
raw: true,
|
||
});
|
||
|
||
if (!order || !order.id) {
|
||
return this.success('ok', {
|
||
order: null,
|
||
list: [],
|
||
});
|
||
}
|
||
|
||
const list = await OrderStockoutItemsModel.findAll({
|
||
where: {
|
||
order_id: order.id,
|
||
},
|
||
order: [[ 'id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
|
||
return this.success('ok', {
|
||
order,
|
||
list,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 出库单确认(直出)。
|
||
* 不改变内部库存,直接按出库单明细的计划数量确认。
|
||
* 出站同步 taobao.qimen.stockout.confirm 成功后,状态才推进到 COMPLETED。
|
||
* 要求 express_code 已填写,否则拒绝确认。
|
||
* @param {Object} data 请求体
|
||
* @param {number} data.id 出库单ID(必填)
|
||
* @return {Promise<Object>} 统一成功/失败包装响应
|
||
*/
|
||
async confirm(data = {}) {
|
||
const { ctx } = this;
|
||
const id = Number(data.id || 0);
|
||
|
||
if (!id) {
|
||
return this.fail('缺少出库单ID');
|
||
}
|
||
|
||
const order = await ctx.model.OrderStockout.findByPk(id);
|
||
if (!order) {
|
||
return this.fail('出库单不存在');
|
||
}
|
||
|
||
if (!order.canConfirm || !order.canConfirm()) {
|
||
return this.fail(`出库单当前状态(${order.order_status})不允许确认`);
|
||
}
|
||
|
||
// 校验运单号是否已填写
|
||
if (!order.waybill_code) {
|
||
return this.fail('出库单未填写运单号(waybill_code),请先更新运单号后再确认');
|
||
}
|
||
|
||
// 第一步:事务内写入明细 actual_qty(暂不改变 order_status)
|
||
const transaction = await ctx.model.transaction();
|
||
let items;
|
||
try {
|
||
items = await ctx.model.OrderStockoutItems.findAll({
|
||
where: { order_id: id },
|
||
transaction,
|
||
});
|
||
|
||
for (const item of items) {
|
||
await item.update({
|
||
actual_qty: item.plan_qty,
|
||
updated_at: new Date(),
|
||
}, { transaction });
|
||
}
|
||
|
||
await transaction.commit();
|
||
} catch (err) {
|
||
await transaction.rollback();
|
||
ctx.logger.error('[stockout.confirm] 明细更新失败:', err);
|
||
return this.fail(`确认失败:${err.message}`);
|
||
}
|
||
|
||
// 第二步:出站通知 ERP(taobao.qimen.stockout.confirm)
|
||
const { app } = this;
|
||
let qimenSuccess = false;
|
||
let qimenMessage = '';
|
||
|
||
if (app.qimenClient && order.qimen_owner_code && order.qimen_warehouse_code) {
|
||
try {
|
||
const now = app.formatDate(new Date());
|
||
const waybillCodes = Array.isArray(order.waybill_codes) && order.waybill_codes.length > 0
|
||
? order.waybill_codes
|
||
: [ order.waybill_code ].filter(Boolean);
|
||
|
||
const outboundData = {
|
||
deliveryOrder: {
|
||
totalOrderLines: order.total_order_lines,
|
||
deliveryOrderCode: order.stockout_order_code,
|
||
deliveryOrderId: order.id,
|
||
warehouseCode: order.qimen_warehouse_code,
|
||
orderType: order.order_type,
|
||
status: 'DELIVERED',
|
||
outBizCode: order.stockout_order_code,
|
||
confirmType: 0,
|
||
orderConfirmTime: now,
|
||
operatorCode: '',
|
||
operatorName: '',
|
||
},
|
||
packages: {
|
||
package: waybillCodes.map(code => ({
|
||
logisticsCode: order.express_code || 'OTHER',
|
||
logisticsName: order.express_name || 'OTHER',
|
||
expressCode: code,
|
||
packageCode: order.stockout_order_code,
|
||
items: items.map(item => ({
|
||
itemCode: item.item_code || '',
|
||
itemId: item.item_id || '',
|
||
quantity: item.plan_qty || 0,
|
||
})),
|
||
})),
|
||
},
|
||
orderLines: items.map(item => ({
|
||
orderLineNo: item.order_line_no || '',
|
||
ownerCode: item.owner_code || order.qimen_owner_code,
|
||
itemCode: item.item_code || '',
|
||
itemId: item.item_id || '',
|
||
itemName: item.item_name || '',
|
||
planQty: item.plan_qty || 0,
|
||
actualQty: item.plan_qty || 0,
|
||
inventoryType: item.inventory_type || 'ZP',
|
||
})),
|
||
};
|
||
|
||
const sendResult = await app.qimenClient.send(
|
||
'taobao.qimen.stockout.confirm',
|
||
order.qimen_owner_code,
|
||
outboundData,
|
||
{ ctx }
|
||
);
|
||
|
||
// 解析奇门响应
|
||
const response = (sendResult && sendResult.xmlArray && sendResult.xmlArray.response)
|
||
? (Array.isArray(sendResult.xmlArray.response) ? sendResult.xmlArray.response[0] : sendResult.xmlArray.response)
|
||
: {};
|
||
qimenSuccess = String(response.flag || '').trim() === 'success';
|
||
qimenMessage = qimenSuccess ? '' : `${response.code || ''} ${response.message || '未知错误'}`.trim();
|
||
} catch (outboundErr) {
|
||
qimenMessage = outboundErr.message || '出站通知异常';
|
||
ctx.logger.error(`[stockout.confirm] 出站通知异常: ${qimenMessage}`);
|
||
}
|
||
} else {
|
||
ctx.logger.warn(`[stockout.confirm] 跳过出站通知: qimenClient=${!!app.qimenClient}, ownerCode=${order.qimen_owner_code}, warehouseCode=${order.qimen_warehouse_code}`);
|
||
}
|
||
|
||
// 第三步:根据出站结果更新状态
|
||
if (qimenSuccess) {
|
||
await ctx.model.OrderStockout.update(
|
||
{ order_status: 'COMPLETED', sync_status: 'SUCCESS', sync_message: '', updated_at: new Date() },
|
||
{ where: { id: order.id } }
|
||
);
|
||
ctx.logger.info(`[stockout.confirm] 确认完成: ${order.stockout_order_code}`);
|
||
|
||
return this.success('确认成功', {
|
||
id: order.id,
|
||
stockout_order_code: order.stockout_order_code,
|
||
order_status: 'COMPLETED',
|
||
logisticsName: 'OTHER',
|
||
expressCode: order.express_code,
|
||
expressCodes: order.express_codes,
|
||
qimenSync: 'success',
|
||
});
|
||
}
|
||
|
||
// 出站失败:更新 sync_status,order_status 不变
|
||
await ctx.model.OrderStockout.update(
|
||
{ sync_status: 'FAILED', sync_message: qimenMessage, updated_at: new Date() },
|
||
{ where: { id: order.id } }
|
||
);
|
||
ctx.logger.error(`[stockout.confirm] 出站同步失败: ${order.stockout_order_code} - ${qimenMessage}`);
|
||
|
||
return this.fail(`出站同步失败: ${qimenMessage || '未发起出站通知'}`);
|
||
}
|
||
|
||
/**
|
||
* 更新出库单快递和运单号。
|
||
* 用于在确认前填写 express_code / waybill_code / waybill_codes。
|
||
* express_code 传入后自动从系统快递表解析 express_name。
|
||
* @param {Object} data 请求体
|
||
* @param {number} data.id 出库单ID(必填)
|
||
* @param {string} [data.express_code] 快递公司编码(如 SF、STO),传入后自动解析 express_name
|
||
* @param {string} [data.waybill_code] 运单号
|
||
* @param {string[]} [data.waybill_codes] 运单号列表
|
||
* @return {Promise<Object>} 统一成功/失败包装响应
|
||
*/
|
||
async updateExpress(data = {}) {
|
||
const { ctx } = this;
|
||
const id = Number(data.id || 0);
|
||
|
||
if (!id) {
|
||
return this.fail('缺少出库单ID');
|
||
}
|
||
|
||
const order = await ctx.model.OrderStockout.findByPk(id);
|
||
if (!order) {
|
||
return this.fail('出库单不存在');
|
||
}
|
||
|
||
const updateData = { updated_at: new Date() };
|
||
|
||
// express_code:自动解析 express_name
|
||
if (data.express_code !== undefined) {
|
||
updateData.express_code = data.express_code || null;
|
||
if (data.express_code) {
|
||
try {
|
||
const expressMap = await ctx.service.systems.setting.express.getSystemExpressMap();
|
||
const info = expressMap.get(String(data.express_code).trim().toUpperCase());
|
||
updateData.express_name = info ? info.name : '';
|
||
} catch (e) {
|
||
ctx.logger.warn('[updateExpress] 解析快递名称失败: ' + e.message);
|
||
updateData.express_name = '';
|
||
}
|
||
} else {
|
||
updateData.express_name = null;
|
||
}
|
||
}
|
||
|
||
if (data.waybill_code !== undefined) {
|
||
updateData.waybill_code = data.waybill_code || null;
|
||
}
|
||
if (data.waybill_codes !== undefined) {
|
||
const codes = data.waybill_codes;
|
||
if (codes !== null && !Array.isArray(codes)) {
|
||
return this.fail('waybill_codes 必须是数组或 null');
|
||
}
|
||
updateData.waybill_codes = codes;
|
||
}
|
||
|
||
if (Object.keys(updateData).length <= 1) {
|
||
return this.fail('没有需要更新的字段');
|
||
}
|
||
|
||
await order.update(updateData);
|
||
await order.reload();
|
||
|
||
return this.success('更新成功', {
|
||
id: order.id,
|
||
stockout_order_code: order.stockout_order_code,
|
||
express_code: order.express_code,
|
||
express_name: order.express_name,
|
||
waybill_code: order.waybill_code,
|
||
waybill_codes: order.waybill_codes,
|
||
});
|
||
}
|
||
}
|
||
|
||
module.exports = StorageStockoutService;
|