ming #1

Merged
liufumingren merged 558 commits from ming into main 2026-11-18 16:13:25 +08:00
61 changed files with 2857 additions and 867 deletions
Showing only changes of commit b7f980188f - Show all commits

View File

@ -1356,6 +1356,23 @@ function renderHtmlPage({
}).join('&');
}
/**
* 归一化 query 参数值,规则与后端签名保持一致。
* @param {*} value 参数值。
* @return {string} 可用于签名拼接的字符串。
*/
function normalizeParamValue(value) {
if (value === undefined || value === null) {
return '';
}
if (typeof value === 'object') {
return stableStringify(value);
}
return String(value);
}
/**
* 构建参与签名的 canonical query。
* @param {Object} queryParams query 对象。
@ -1370,7 +1387,7 @@ function renderHtmlPage({
return Object.keys(queryParams || {}).filter(function(key) {
return !ignoredSet[String(key).toLowerCase()] && queryParams[key] !== undefined;
}).sort().map(function(key) {
return key + '=' + String(queryParams[key] == null ? '' : queryParams[key]);
return key + '=' + normalizeParamValue(queryParams[key]);
}).join('&');
}

View File

@ -204,12 +204,11 @@ class HomeController extends Controller {
if (logData.result && logData.result.length > 65535) {
logData.result = logData.result.substring(0, 65535);
}
try {
await this.app.fileWriter.writeRecord('qimen-logs', logData);
} catch (writeErr) {
// 日志落盘改为异步投递,避免阻塞主请求响应。
Promise.resolve(this.app.fileWriter.writeRecord('qimen-logs', logData)).catch(writeErr => {
ctx.logger.error('[qimen-log-sink] 写入文件失败: ' + writeErr.message);
ctx.logger.info('[qimen-log-sink] 日志数据: ', JSON.stringify(logData));
}
});
}
}

View File

@ -101,7 +101,8 @@ function buildBodySign(body) {
? body
: stableStringify(body);
return crypto.createHash('md5').update(serializedBody, 'utf8').digest('hex').toLowerCase();
return crypto.createHash('md5').update(serializedBody, 'utf8').digest('hex')
.toLowerCase();
}
/**
@ -125,7 +126,8 @@ function signRequest({ query = {}, body, selfAppSecret, ignoreKeys } = {}) {
const canonicalQuery = buildCanonicalQuery(query, mergedIgnoreKeys);
const bodySign = buildBodySign(body);
const signText = `${canonicalQuery}${normalizedSecret}${bodySign}`;
const sign = crypto.createHash('md5').update(signText, 'utf8').digest('hex').toLowerCase();
const sign = crypto.createHash('md5').update(signText, 'utf8').digest('hex')
.toLowerCase();
return {
canonicalQuery,

View File

@ -207,7 +207,7 @@ class PoloApiClient {
if (Buffer.isBuffer(response.data)) {
// 如果是 Buffer,转字符串再解析
const str = response.data.toString('utf8');
console.log("菠萝派平台接口响应原始数据",str)
console.log('菠萝派平台接口响应原始数据', str);
result = JSON.parse(str);
} else if (typeof response.data === 'string') {
result = JSON.parse(response.data);

View File

@ -47,9 +47,9 @@ class QimenClient {
}
replaceXmlTagsWithString(xmlString, oldTag, newTag) {
const startTagRegex = new RegExp(`<\s*${oldTag}(\s+[^>]*)?>`, 'gi');
const endTagRegex = new RegExp(`<\s*/\s*${oldTag}\s*>`, 'gi');
const selfClosingRegex = new RegExp(`<\s*${oldTag}(\s+[^>]*)?\s*/>`, 'gi');
const startTagRegex = new RegExp(`<\\s*${oldTag}(\\s+[^>]*)?>`, 'gi');
const endTagRegex = new RegExp(`<\\s*/\\s*${oldTag}\\s*>`, 'gi');
const selfClosingRegex = new RegExp(`<\\s*${oldTag}(\\s+[^>]*)?\\s*/>`, 'gi');
return xmlString
.replace(startTagRegex, (match, attributes = '') => `<${newTag}${attributes}>`)
@ -57,6 +57,30 @@ class QimenClient {
.replace(selfClosingRegex, (match, attributes = '') => `<${newTag}${attributes}/>`);
}
replaceDeliveryConfirmOrderLineTags(xmlString) {
const orderLinesBlockRegex = /<\s*orderLines(\s+[^>]*)?>[\s\S]*?<\s*\/\s*orderLines\s*>/gi;
return String(xmlString || '').replace(orderLinesBlockRegex, block => {
return this.replaceXmlTagsWithString(block, 'item', 'orderLine');
});
}
replaceDeliveryConfirmPackageTags(xmlString) {
const packagesBlockRegex = /<\s*packages(\s+[^>]*)?>[\s\S]*?<\s*\/\s*packages\s*>/gi;
return String(xmlString || '').replace(packagesBlockRegex, block => {
return block
.replace(/<\s*package\s*>\s*<\s*item\s*>/gi, '<package>')
.replace(/<\s*\/\s*item\s*>\s*<\s*item\s*>/gi, '</package><package>')
.replace(/<\s*\/\s*item\s*>\s*<\s*\/\s*package\s*>/gi, '</package>');
});
}
replaceDeliveryConfirmPayloadTags(xmlString) {
const withPackages = this.replaceDeliveryConfirmPackageTags(xmlString);
return this.replaceDeliveryConfirmOrderLineTags(withPackages);
}
addSign(baseQueryParams, sign) {
return Object.assign({}, baseQueryParams, { sign });
}
@ -106,7 +130,9 @@ class QimenClient {
const baseUrl = 'http://qimen.api.taobao.com/router/qimen/service';
const requestPayload = this.normalizeRequestPayload(data);
const xmlData = await helpers.toXml(requestPayload);
const queryData = this.replaceXmlTagsWithString(xmlData, 'item', 'orderLine');
const queryData = method === 'taobao.qimen.deliveryorder.confirm'
? this.replaceDeliveryConfirmPayloadTags(xmlData)
: this.replaceXmlTagsWithString(xmlData, 'item', 'orderLine');
const sign = await helpers.signTopRequest(baseQueryParams, queryData, this.app.config.qimen.security, 'md5');
const queryParams = this.addSign(baseQueryParams, sign);
const url = this.generateUrlWithParams(baseUrl, queryParams);

View File

@ -216,6 +216,12 @@ module.exports = app => {
allowNull: true,
comment: '系统物流公司名称',
},
basket_number:{
type: STRING(50),
allowNull: true,
comment: '筐号',
},
express_code: {
type: STRING(50),
allowNull: true,

View File

@ -111,7 +111,7 @@ module.exports = app => {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '仓库ID',
}
},
}, {
tableName: 'wms_order_express',
freezeTableName: true,

View File

@ -59,7 +59,7 @@ module.exports = app => {
type: STRING(50),
allowNull: true,
comment: '订单来源',
}
},
}, {
tableName: 'wms_platform',
freezeTableName: true,

View File

@ -11,9 +11,9 @@ class indexService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = 'getI18nMessage,putI18nCollect';
const _noNeedRight = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,getExpressList,getExpressProductTypeList,getPlatformList,recognizeLicensePlate';
const _noNeedRight = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getExpressList,getExpressProductTypeList,getPlatformList,recognizeLicensePlate';
const _noNeedLog = '*';
const _noNeedAuth = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace,listInterfaceTypes,getExpressList,getExpressProductTypeList,getPlatformList,recognizeLicensePlate';
const _noNeedAuth = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getExpressList,getExpressProductTypeList,getPlatformList,recognizeLicensePlate';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
async fastWhereTree(data) {
@ -417,6 +417,61 @@ class indexService extends MainService {
});
return this.success('ok', { list, total: list.length, code: 200 });
}
async getLocationTypeList() {
const { ctx } = this;
const { Op } = this.app.Sequelize;
const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : null;
const cacheKey = `index:locationTypeList:${warehouseId || 'global'}`;
const cached = await this.app.getCacheAsync(cacheKey);
if (Array.isArray(cached)) {
return this.success('ok', { list: cached, total: cached.length, code: 200 });
}
const where = {
is_active: true,
};
if (warehouseId) {
where[Op.or] = [
{ warehouse_id: warehouseId },
{ warehouse_id: null },
];
} else {
where.warehouse_id = null;
}
const rows = await ctx.model.LocationType.findAll({
where,
attributes: [
'id',
'type_code',
'type_name',
'temperature_zone',
'allow_allocation',
'allow_transfer_out',
'description',
'warehouse_id',
],
order: [[ 'warehouse_id', 'ASC' ], [ 'id', 'ASC' ]],
raw: true,
});
const list = rows.map(item => ({
id: Number(item.id || 0),
type_code: item.type_code || '',
type_name: item.type_name || '',
temperature_zone: item.temperature_zone || '',
allow_allocation: Boolean(item.allow_allocation),
allow_transfer_out: Boolean(item.allow_transfer_out),
description: item.description || '',
warehouse_id: item.warehouse_id === null || item.warehouse_id === undefined ? null : Number(item.warehouse_id),
}));
await this.app.setCacheAsync(cacheKey, list, 300);
return this.success('ok', { list, total: list.length, code: 200 });
}
/**
* 获取快递列表。
*

View File

@ -4,7 +4,7 @@ const MainService = require('../../main');
const { parseWhereConditions } = require('../../../lib/query_condition_parser');
const DEFAULT_PAGE_SIZE = 20;
const MAX_PAGE_SIZE = 200;
const MAX_PAGE_SIZE = 500;
const FORBIDDEN_WAREHOUSE_FIELDS = new Set([ 'warehouse_id', 'warehouseId' ]);
const WAREHOUSE_FIELD_ERROR_MESSAGE = '订单工作台查询条件禁止传入 warehouse_id / warehouseId,请使用当前用户上下文的 store_id。';
@ -40,7 +40,7 @@ const ORDER_LIST_BASE_ATTRIBUTES = Object.freeze([
'wave_id',
'post_status', 'storage_status', 'pick_status', 'pack_status',
'inspection_status', 'print_status', 'claim_status',
'outbound_status', 'lock_status', 'intercept_status',
'outbound_status', 'lock_status', 'intercept_status','basket_number'
]);
const ORDER_WEIGHT_TYPE_LABELS = Object.freeze({
@ -147,6 +147,29 @@ const MODULE_CONFIGS = Object.freeze({
* 负责仓库上下文、分页规范、where 解析、模型选择与审核状态更新。
*/
class OrderBaseService extends MainService {
/**
* 脱敏展示值:保留首尾字符,中间统一替换为 ***。
* @param {string|number|null|undefined} value 原始值。
* @return {string|null} 脱敏后的值。
*/
maskListSensitiveValue(value) {
if (value === null || value === undefined) {
return value;
}
const normalizedValue = String(value);
if (!normalizedValue) {
return normalizedValue;
}
const chars = Array.from(normalizedValue);
if (chars.length <= 1) {
return normalizedValue;
}
return `${chars[0]}***${chars[chars.length - 1]}`;
}
/**
* 获取当前请求对应的仓库ID。
* @return {number|string|null} 仓库ID。
@ -393,6 +416,8 @@ class OrderBaseService extends MainService {
return {
...order,
name: this.maskListSensitiveValue(order.name),
tel: this.maskListSensitiveValue(order.tel),
weight_type: this.formatWeightTypeLabel(order.weight_type),
};
}
@ -598,6 +623,9 @@ class OrderBaseService extends MainService {
return {
...orderRow,
name: this.maskListSensitiveValue(orderRow.name),
tel: this.maskListSensitiveValue(orderRow.tel),
mobile: this.maskListSensitiveValue(orderRow.mobile),
sys_platform_name: Object.prototype.hasOwnProperty.call(orderRow, 'sys_platform_name')
? (orderRow.sys_platform_name ?? null)
: null,
@ -670,6 +698,140 @@ class OrderBaseService extends MainService {
});
}
/**
* 提取订单列表中的运单号虚拟筛选条件。
* @param {Object} whereInput 标准化后的 where 条件。
* @return {{ where: Object, expressNumbers: string[] }} 清洗后的 where 与运单号集合。
*/
extractOrderListExpressVirtualFilter(whereInput = {}) {
const normalizedWhere = this.isPlainObject(whereInput)
? { ...whereInput }
: {};
const waybillCondition = normalizedWhere.waybill_codes;
const expressCondition = normalizedWhere.express_numbers;
delete normalizedWhere.waybill_codes;
delete normalizedWhere.express_numbers;
const expressNumbers = Array.from(new Set([
...this.normalizeExpressFilterValues(waybillCondition),
...this.normalizeExpressFilterValues(expressCondition),
]));
return {
where: normalizedWhere,
expressNumbers,
};
}
/**
* 规范化运单号筛选输入,兼容字符串、数组与 { value } 结构。
* @param {*} condition 运单号筛选条件。
* @return {string[]} 规范化后的运单号列表。
*/
normalizeExpressFilterValues(condition) {
const sourceValue = this.isPlainObject(condition) && Object.prototype.hasOwnProperty.call(condition, 'value')
? condition.value
: condition;
const sourceItems = [];
if (Array.isArray(sourceValue)) {
sourceItems.push(...sourceValue);
} else if (typeof sourceValue === 'string') {
sourceItems.push(...sourceValue.split(','));
} else if (sourceValue !== undefined && sourceValue !== null && sourceValue !== '') {
sourceItems.push(sourceValue);
}
return sourceItems
.map(item => String(item || '').trim())
.filter(Boolean);
}
/**
* 根据运单号筛选条件查询命中的订单ID。
* @param {string[]} expressNumbers 运单号列表。
* @param {number|string} warehouseId 仓库ID。
* @return {Promise<number[]>} 命中的订单ID列表。
*/
async findOrderIdsByExpressNumbers(expressNumbers = [], warehouseId = this.getWarehouseId()) {
const contextWarehouseId = this.getWarehouseId();
if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') {
throw new Error('缺少当前用户仓库上下文 store_id');
}
if (warehouseId !== null && warehouseId !== undefined && warehouseId !== ''
&& String(warehouseId) !== String(contextWarehouseId)) {
throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。');
}
const normalizedExpressNumbers = Array.from(new Set(
(Array.isArray(expressNumbers) ? expressNumbers : [])
.map(item => String(item || '').trim())
.filter(Boolean)
));
if (normalizedExpressNumbers.length === 0) {
return [];
}
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function') {
return [];
}
const { Op } = this.app.Sequelize;
const rows = await orderExpressModel.findAll({
where: {
warehouse_id: contextWarehouseId,
waybill_code: {
[Op.in]: normalizedExpressNumbers,
},
},
attributes: [ 'order_id' ],
raw: true,
});
return Array.from(new Set((Array.isArray(rows) ? rows : [])
.map(row => Number(row && row.order_id))
.filter(orderId => Number.isFinite(orderId) && orderId > 0)));
}
/**
* 将命中的订单ID并入 Sequelize where 条件。
* @param {Object} queryWhere 原始 where 条件。
* @param {number[]} orderIds 命中的订单ID。
* @return {Object} 合并后的 where 条件。
*/
appendOrderIdsFilterToWhere(queryWhere = {}, orderIds = []) {
const { Op } = this.app.Sequelize;
const normalizedOrderIds = Array.from(new Set((Array.isArray(orderIds) ? orderIds : [])
.map(item => Number(item))
.filter(orderId => Number.isFinite(orderId) && orderId > 0)));
const orderIdCondition = {
id: {
[Op.in]: normalizedOrderIds,
},
};
if (!this.isPlainObject(queryWhere)
|| (Object.keys(queryWhere).length === 0 && Object.getOwnPropertySymbols(queryWhere).length === 0)) {
return orderIdCondition;
}
if (Array.isArray(queryWhere[Op.and])) {
return {
...queryWhere,
[Op.and]: [ ...queryWhere[Op.and], orderIdCondition ],
};
}
return {
[Op.and]: [ queryWhere, orderIdCondition ],
};
}
/**
* 构造列表排序参数。
* @param {Object} sort 排序参数。
@ -801,14 +963,21 @@ class OrderBaseService extends MainService {
},
},
});
const mergedWhere = this.mergeWhereObjects(this.getDefaultWhere(moduleName), where);
const queryWhere = this.buildWhere(mergedWhere, contextWarehouseId, {
const { where: sanitizedWhere, expressNumbers } = this.extractOrderListExpressVirtualFilter(where);
const mergedWhere = this.mergeWhereObjects(this.getDefaultWhere(moduleName), sanitizedWhere);
let queryWhere = this.buildWhere(mergedWhere, contextWarehouseId, {
specialFieldMap: {
quickWhere: {
bucket: 'quick',
},
},
});
if (expressNumbers.length > 0) {
const orderIds = await this.findOrderIdsByExpressNumbers(expressNumbers, contextWarehouseId);
queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, orderIds);
}
const model = await this.getOrderModel(moduleName, contextWarehouseId);
const order = this.buildListOrder(requestData.sort, moduleName);
const offset = (page - 1) * pageSize;
@ -887,19 +1056,135 @@ class OrderBaseService extends MainService {
order: [[ 'id', 'ASC' ]],
raw: true,
});
const orderItemImagesByStockId = await this.getOrderItemImagesByStockIds(orderItems);
const orderItemsWithImages = this.attachImagesToOrderItems(orderItems, orderItemImagesByStockId);
const expresses = await this.getOrderExpressesByOrderId(orderId);
const waybillCodes = Array.from(new Set(expresses
.map(item => String(item && item.waybill_code || '').trim())
.filter(Boolean)));
const logs = await this.getOrderOperationLogs(orderId);
return {
detail: order,
items: orderItemsWithImages,
expresses,
logs,
};
}
/**
* 按订单商品批量查询图片并按 stock_id 建立映射。
* @param {Object[]} orderItems 订单商品列表。
* @return {Promise<Map<number, string[]>>} stock_id 对应的图片 URL 列表。
*/
async getOrderItemImagesByStockIds(orderItems = []) {
if (!Array.isArray(orderItems) || orderItems.length === 0) {
return new Map();
}
const stockIds = [ ...new Set(
orderItems
.map(item => Number(item && item.stock_id))
.filter(Boolean)
) ];
if (stockIds.length === 0) {
return new Map();
}
const fileReferenceModel = this.ctx.model && this.ctx.model.FileReference;
const fileModel = this.ctx.model && this.ctx.model.File;
if (!fileReferenceModel || typeof fileReferenceModel.findAll !== 'function' || !fileModel) {
return new Map();
}
try {
const fileReferences = await fileReferenceModel.findAll({
where: {
business_type: 'stock',
business_id: {
[this.app.Sequelize.Op.in]: stockIds,
},
},
include: [{
model: fileModel,
as: 'file',
attributes: [ 'file_url' ],
required: false,
}],
});
const imagesByStockId = new Map();
for (const reference of fileReferences || []) {
const row = reference && typeof reference.get === 'function'
? reference.get({ plain: true })
: reference;
const stockId = Number(row && row.business_id);
const imageUrl = (row && row.file && row.file.file_url) || row?.file_url || row?.url || row?.file_path || '';
if (!stockId || !imageUrl) {
continue;
}
if (!imagesByStockId.has(stockId)) {
imagesByStockId.set(stockId, []);
}
imagesByStockId.get(stockId).push(String(imageUrl));
}
return imagesByStockId;
} catch (error) {
this.ctx.logger?.warn?.('[order.base.detail] 查询订单商品图片失败,已降级为空图片数组', {
error: error.message,
});
return new Map();
}
}
/**
* 将图片映射合并到订单商品列表中。
* @param {Object[]} orderItems 订单商品列表。
* @param {Map<number, string[]>} imagesByStockId 图片映射。
* @return {Object[]} 合并后的订单商品列表。
*/
attachImagesToOrderItems(orderItems = [], imagesByStockId = new Map()) {
if (!Array.isArray(orderItems)) {
return [];
}
return orderItems.map(item => {
const stockId = Number(item && item.stock_id);
const images = stockId ? (imagesByStockId.get(stockId) || []) : [];
return {
order,
detail: order,
orderItems: Array.isArray(orderItems) ? orderItems : [],
items: Array.isArray(orderItems) ? orderItems : [],
expresses,
waybill_codes: waybillCodes,
...item,
images: [ ...images ],
};
});
}
/**
* 获取订单操作日志列表。
* @param {number} orderId 订单ID。
* @return {Promise<Object[]>} 订单日志数组。
*/
async getOrderOperationLogs(orderId) {
const warehouseId = this.getWarehouseId();
const operationLogService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.operationLog;
if (!operationLogService || typeof operationLogService.queryOrderLogs !== 'function') {
return [];
}
if (warehouseId === null || warehouseId === undefined || warehouseId === '') {
throw new Error('缺少当前用户仓库上下文 store_id');
}
const queryResult = await operationLogService.queryOrderLogs({
id: orderId,
warehouseId,
page: 1,
pageSize: 200,
});
return Array.isArray(queryResult && queryResult.list) ? queryResult.list : [];
}
/**

View File

@ -434,6 +434,7 @@ class DeliveryOrderService extends Service {
*
* @param {Object} data 奇门/系统订单入参。
* @param {Object} info 当前仓库与货主上下文。
* @param createChannel
* @return {Promise<Object>} 创建结果。
*/
async addOrder(data, info, createChannel = '') {
@ -703,6 +704,7 @@ class DeliveryOrderService extends Service {
*
* @param {Object} deliveryOrder 订单主信息。
* @param {Object} info 当前仓库与货主上下文。
* @param createChannel
* @param {number} step 订单步骤。
* @param {Array<Object>} [operationLogs=[]] 待写入的操作日志数组。
* @return {Promise<Object>} 可入库的订单数据。
@ -891,16 +893,8 @@ class DeliveryOrderService extends Service {
}
const itemId = parseInt(wms_stock.id);
const stockId = Number(wms_stock.stock_id) || 0;
// ========== 核心库存检查逻辑 ==========
const stockResult = await ctx.service.systems.stockStore.getItemStorages(wms_stock.id, transaction);
if (!stockResult.success) {
errors.push(`SKU${wms_stock.id}商品《${wms_stock.item_name}》编码《${wms_stock.item_code}》\n${stockResult.error}`);
continue;
}
const { storage } = stockResult.data;
const stockId = storage.id;
if (!stockId) {
errors.push(`第${i + 1}行: 商品《${wms_stock.item_name}》库存记录不存在`);
continue;
@ -912,42 +906,24 @@ class DeliveryOrderService extends Service {
}
processedItemIds.add(itemId);
const totalQtyForStock = (stockQuantityMap.get(stockId) || 0) + planQty;
stockQuantityMap.set(stockId, totalQtyForStock);
// 记录商品重量(如果storage中有grossWeight)
if (storage.grossWeight !== undefined && storage.grossWeight !== null) {
const weight = parseFloat(storage.grossWeight) || 0;
stockWeightMap.set(stockId, weight);
} else {
// 如果库存中没有重量信息,记录0
stockWeightMap.set(stockId, 0);
}
if (storage.canUse < totalQtyForStock) {
const allowOversell = stockResult.data && stockResult.data.allow_oversell === true
? true
: (await ctx.service.systems.stockStore.getStoreWarehousePolicyConfigByStockId(stockId, transaction)).allowOversell;
if (!allowOversell) {
errors.push(`第${i + 1}行: 商品《${wms_stock.item_name}》库存不足,可用 ${storage.canUse},需求 ${totalQtyForStock}`);
stockQuantityMap.set(stockId, totalQtyForStock - planQty);
continue;
}
}
// 锁定库存
const lockResult = await ctx.service.systems.stockStore.lockItemStorages(
storage.id,
stockId,
planQty,
transaction
);
if (!lockResult.success) {
errors.push(`SKU${wms_stock.id}商品《${wms_stock.item_name}》编码《${wms_stock.item_code}》\n锁定失败: ${lockResult.error}`);
stockQuantityMap.set(stockId, totalQtyForStock - planQty);
continue;
}
const totalQtyForStock = (stockQuantityMap.get(stockId) || 0) + planQty;
stockQuantityMap.set(stockId, totalQtyForStock);
// 优先使用商品主数据重量,缺失时降级为0。
const weight = parseFloat(wms_stock.gross_weight) || 0;
stockWeightMap.set(stockId, weight);
// ========== 库存检查逻辑结束 ==========
// 所有检查通过,准备订单行数据

View File

@ -54,7 +54,7 @@ const WAYBILL_ORDER_DELIVERY_MIN_ATTRIBUTES = Object.freeze([
'logistics_area_code',
'oaid',
'source_order_codes',
'logistics_code'
'logistics_code',
]);
class ExpressService extends Service {
@ -242,7 +242,7 @@ class ExpressService extends Service {
const sysPlatformCode = String(order.sys_platform_code || order.sysPlatformCode || '').trim();
const logisticsCode = String(order.logistics_code || order.logisticsCode || '').trim();
const syslogisticsCode = String(order.sys_logistics_code || order.sysLogisticsCode || '').trim();
console.log("syslogisticsCode", syslogisticsCode);
console.log('syslogisticsCode', syslogisticsCode);
const platformCode = this.normalizeWaybillCreatePlatformCode(order);
for (const businessKey of businessKeys) {
@ -1510,7 +1510,7 @@ class ExpressService extends Service {
const storeConfig = storeInfo ? storeInfo.policy_config : null;
const useStoreSenderInfoValue = storeConfig ? storeConfig.use_store_sender_info : 1;
const shouldUseStoreSenderInfo = Number(useStoreSenderInfoValue === undefined || useStoreSenderInfoValue === null || useStoreSenderInfoValue === '' ? 1 : useStoreSenderInfoValue) === 1;
console.log("storeInfo",storeInfo,expressInterface);
console.log('storeInfo', storeInfo, expressInterface);
const expressInterfaceConfig = expressInterface ? {
...expressInterface,
...(shouldUseStoreSenderInfo ? {
@ -1524,7 +1524,7 @@ class ExpressService extends Service {
address: (storeConfig && storeConfig.address) || expressInterface.address || '',
} : {}),
} : null;
console.log("expressInterfaceConfig",expressInterfaceConfig);
console.log('expressInterfaceConfig', expressInterfaceConfig);
for (const batch of batches) {
// 异步不阻塞调用 createWaybillCode,快速返回结果给前端,后续的订单处理和异常回写都在 createWaybillCode 内部完成。
this.asyncTask(batch, groupedOrder.options, matchedPlatform, expressInterfaceConfig);

View File

@ -168,12 +168,12 @@ class ExpressPlatformService extends MainService {
async polyapi(data = {}) {
const { matchedPlatform, listByWarehousePlatformCode, orders } = data;
const ExpressList = await this.service.systems.express.loadExpressList();
console.log("matchedPlatform", JSON.stringify(matchedPlatform));
console.log('matchedPlatform', JSON.stringify(matchedPlatform));
console.log('接收到菠萝派快递接口入参:', JSON.stringify(listByWarehousePlatformCode));
console.log('接收到菠萝派平台数据处理请求,入参:', JSON.stringify(orders));
console.log("ExpressList", JSON.stringify(ExpressList));
console.log('ExpressList', JSON.stringify(ExpressList));
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
const allocatedWaybillMap = new Map();
if (orderExpressModel && typeof orderExpressModel.findAll === 'function') {
@ -224,9 +224,9 @@ class ExpressPlatformService extends MainService {
logisticno: allocatedWaybillMap.get(`${Number(order.id) || 0}:${Number(order_tmp.business_key) || 0}`) || '',
logistictype: order.logistics_code || '',
numpackage: order.package_count || 1,
businesstype: "JH_Normal",
businesstype: 'JH_Normal',
businessplat: order.sys_platform_code == "KS" ? order.sys_platform_code : "OTHERS",
businessplat: order.sys_platform_code == 'KS' ? order.sys_platform_code : 'OTHERS',
paymode: listByWarehousePlatformCode.paymode ?? 1,
ordertype: listByWarehousePlatformCode.ordertype ?? 'JH_Normal',
codpaymoney: order.ar_amount ?? null,
@ -243,7 +243,7 @@ class ExpressPlatformService extends MainService {
sys_express_code: listByWarehousePlatformCode.sys_express_code || '',
platform_code: listByWarehousePlatformCode.platform_code || '',
cpcode: ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code)[listByWarehousePlatformCode.platform_code] || '',
logisticsproductname: "JH_02",
logisticsproductname: 'JH_02',
dmssorting: 0,
needencrypt: 1,
ordersource: matchedPlatform.ordersource || '',
@ -255,7 +255,7 @@ class ExpressPlatformService extends MainService {
name: listByWarehousePlatformCode.sender_name || '',
phone: listByWarehousePlatformCode.sender_tel || '',
mobile: listByWarehousePlatformCode.sender_tel || '',
country: "CN",
country: 'CN',
city: listByWarehousePlatformCode.city_name || '',
province: listByWarehousePlatformCode.province_name || '',
area: listByWarehousePlatformCode.district_name || '',
@ -279,19 +279,19 @@ class ExpressPlatformService extends MainService {
},
goods: (order.orderItems && order.orderItems.map(item => ({
productid: item.item_code,
cnname: item.item_name || "商品",
cnname: item.item_name || '商品',
count: item.plan_qty || 0,
}))) || [],
Mallmaskid: '',
template_url: matchedPlatform.template_url || '',
labelformat: listByWarehousePlatformCode.labelformat || '',
extraInfo: ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code)?.polyapi_extra_info || '',
}
};
}),
shoptype: matchedPlatform.shoptype,
};
// 调用菠萝派平台接口进行数据处理
console.log('==================\n业务数据', JSON.stringify(order_bizcontent), "\n=========================\n");
console.log('==================\n业务数据', JSON.stringify(order_bizcontent), '\n=========================\n');
const result = await this.service.systems.poloApi.request('Differ.JH.Logistics.PostOrder', order_bizcontent, matchedPlatform, listByWarehousePlatformCode.token);
console.log('==================\n菠萝派平台接口返回结果', JSON.stringify(result));
if (result && result.code !== '10000') {
@ -537,7 +537,7 @@ class ExpressPlatformService extends MainService {
extras: {
message: `订单${orderId}获取快递单成功,单号:${item.waybill_code}`,
warehouseId,
}
},
});
}
}

View File

@ -56,7 +56,7 @@ class LocationService extends Service {
for (let row = 1; row <= rack_rows; row++) {
for (let column = 1; column <= rack_columns; column++) {
for (let level = 1; level <= rack_levels; level++) {
const spaceCode = `${rack.zone_code}-${row.toString().padStart(2, '0')}-${column.toString().padStart(2, '0')}-${level.toString().padStart(2, '0')}`;
const spaceCode = `${rack.zone_code}-${column.toString().padStart(2, '0')}-${row.toString().padStart(2, '0')}-${level.toString().padStart(2, '0')}`;
// 计算相对坐标
const relativeX = (column - 1) * cellLength;
@ -71,7 +71,7 @@ class LocationService extends Service {
row_no: row.toString(),
column_no: column.toString(),
level_no: level.toString(),
cell_no: `${row}-${column}-${level}`,
cell_no: `${column}-${row}-${level}`,
length: cellLength,
width: cellWidth,
height: cellHeight,

View File

@ -767,8 +767,39 @@ class LocationZoneService extends Service {
},
});
if (zone.zone_type === 'rack') {
// 货架执行删除需要检测库位是否还有库存
throw new Error('货架XX库位有库存,禁止删除,请先移库');
// 货架执行删除前,按真实库存判断是否可删。
const { Op } = ctx.app.Sequelize;
const spaces = await ctx.model.LocationSpace.findAll({
where: {
zone_id: id,
deleted_at: null,
},
attributes: [ 'id' ],
raw: true,
});
const spaceIds = (Array.isArray(spaces) ? spaces : [])
.map(space => Number(space && space.id))
.filter(spaceId => Number.isFinite(spaceId) && spaceId > 0);
if (spaceIds.length > 0) {
const stockCount = await ctx.model.Storage.count({
where: {
space_id: {
[Op.in]: spaceIds,
},
delete_at: null,
is_enabled: 1,
quantity: {
[Op.gt]: 0,
},
},
});
if (stockCount > 0) {
throw new Error('货架库位有库存,禁止删除,请先移库');
}
}
}
if (childrenCount > 0) {
throw new Error('请先删除或转移所有子分区');
@ -953,35 +984,42 @@ class LocationZoneService extends Service {
}
async generateSpacesForRack(rackId, rack, transaction = null) {
const { app } = this;
const { app, ctx } = this;
const { Op } = app.Sequelize;
const { rack_columns, rack_rows, rack_levels, direction, x, y, z } = rack;
const expectedSpaceCount = Number(rack_columns || 0) * Number(rack_rows || 0) * Number(rack_levels || 0);
// 读取已有仓位编码,用于差量补齐。
const existingSpaces = await ctx.model.LocationSpace.findAll({
where: {
zone_id: rackId,
deleted_at: null,
},
attributes: [ 'id', 'space_code' ],
raw: true,
transaction,
});
const existingSpaceCodeSet = new Set(
(Array.isArray(existingSpaces) ? existingSpaces : [])
.map(item => String(item && item.space_code || '').trim())
.filter(Boolean)
);
const rackWidth = rack.width;
const rackLength = rack.length;
const prelativeX = x;
const prelativeY = y;
const prelativeZ = z;
const cellLength = rackLength / rack_columns / rack_levels;
const cellWidth = rackWidth;
const cellHeight = rack.height / rack_rows;
const spaces = [];
let rackWidth = 0;
let rackLength = 0;
let cellLength = 0;
let cellWidth = 0;
let cellHeight = 0;
let prelativeX = 0;
let prelativeY = 0;
let prelativeZ = 0;
rackWidth = rack.width;
rackLength = rack.length;
prelativeX = x;
prelativeY = y;
prelativeZ = z;
// 计算每个仓位的尺寸
cellLength = rackLength / rack_columns / rack_levels;
cellWidth = rackWidth;
cellHeight = rack.height / rack_rows;
// 生成所有仓位
for (let column = 1; column <= rack_columns; column++) {
for (let row = 1; row <= rack_rows; row++) {
for (let column = 1; column <= rack_columns; column++) {
for (let level = 1; level <= rack_levels; level++) {
const spaceCode = `${rack.zone_code}-${column.toString().padStart(2, '0')}-${row.toString().padStart(2, '0')}-${level.toString().padStart(2, '0')}`;
// 计算相对坐标
let relativeX = 0;
let relativeY = 0;
let relativeZ = (level - 1) * cellWidth + prelativeZ;
@ -999,7 +1037,7 @@ class LocationZoneService extends Service {
spaces.push({
warehouse_id: rack.warehouse_id,
zone_id: rackId,
location_type_id: row === 1 ? 1 : 2, // 默认第一层为分拣,其他层为存储
location_type_id: row === 1 ? 1 : 2,
space_code: spaceCode,
row_no: row.toString(),
column_no: column.toString(),
@ -1008,8 +1046,8 @@ class LocationZoneService extends Service {
length: cellLength,
width: cellWidth,
height: cellHeight,
volume: cellLength * cellWidth * cellHeight / 1000000, // cm³转m³
max_weight: 100, // 默认100kg
volume: cellLength * cellWidth * cellHeight / 1000000,
max_weight: 100,
space_status: 'AVAILABLE',
is_enabled: true,
relative_x: relativeX,
@ -1021,11 +1059,104 @@ class LocationZoneService extends Service {
}
}
// 批量插入仓位
if (spaces.length > 0) {
await app.model.LocationSpace.bulkCreate(spaces, { transaction });
const expectedSpaceCodeSet = new Set(spaces.map(space => String(space.space_code || '').trim()).filter(Boolean));
const spacesNeedDelete = (Array.isArray(existingSpaces) ? existingSpaces : []).filter(space => {
const spaceCode = String(space && space.space_code || '').trim();
return spaceCode && !expectedSpaceCodeSet.has(spaceCode);
});
if (spacesNeedDelete.length > 0) {
const extraSpaceIds = spacesNeedDelete
.map(space => Number(space && space.id))
.filter(spaceId => Number.isFinite(spaceId) && spaceId > 0);
if (extraSpaceIds.length > 0) {
const storages = await ctx.model.Storage.findAll({
where: {
space_id: {
[Op.in]: extraSpaceIds,
},
delete_at: null,
is_enabled: 1,
[Op.or]: [
{ quantity: { [Op.gt]: 0 } },
{ locked_quantity: { [Op.gt]: 0 } },
{ available_quantity: { [Op.gt]: 0 } },
],
},
attributes: [ 'space_id', 'quantity', 'locked_quantity', 'available_quantity' ],
raw: true,
transaction,
});
if (Array.isArray(storages) && storages.length > 0) {
const occupiedSpaceIdSet = new Set(storages.map(item => Number(item && item.space_id)).filter(Boolean));
const occupiedSpaceCodes = spacesNeedDelete
.filter(space => occupiedSpaceIdSet.has(Number(space && space.id)))
.map(space => String(space && space.space_code || '').trim())
.filter(Boolean);
throw new Error(`发现 ${spacesNeedDelete.length} 个多余库位,其中 ${occupiedSpaceCodes.length} 个存在库存,禁止自动删除:${occupiedSpaceCodes.slice(0, 10).join(',')}`);
}
await ctx.model.LocationSpace.destroy({
where: {
id: {
[Op.in]: extraSpaceIds,
},
},
transaction,
});
}
}
const missingSpaces = spaces.filter(space => !existingSpaceCodeSet.has(String(space.space_code || '').trim()));
const existingSpaceCount = existingSpaceCodeSet.size;
if (missingSpaces.length === 0 && spacesNeedDelete.length === 0) {
return `货架 ${rack.zone_code} 已完整存在 ${existingSpaceCount} 个仓位,无需补齐`;
}
if (missingSpaces.length === 0) {
return `货架 ${rack.zone_code} 已删除 ${spacesNeedDelete.length} 个多余库位,当前总数 ${expectedSpaceCount}/${expectedSpaceCount}`;
}
try {
await app.model.LocationSpace.bulkCreate(missingSpaces, { transaction });
const finalSpaceCount = existingSpaceCount - spacesNeedDelete.length + missingSpaces.length;
if (spacesNeedDelete.length > 0) {
return `为货架 ${rack.zone_code} 删除 ${spacesNeedDelete.length} 个多余库位并补齐 ${missingSpaces.length} 个仓位(总数 ${finalSpaceCount}/${expectedSpaceCount})`;
}
return `为货架 ${rack.zone_code} 补齐 ${missingSpaces.length} 个仓位(总数 ${finalSpaceCount}/${expectedSpaceCount})`;
} catch (error) {
// 并发场景:再次按编码回查后补齐剩余缺口。
const latestSpaces = await ctx.model.LocationSpace.findAll({
where: {
zone_id: rackId,
deleted_at: null,
},
attributes: [ 'space_code' ],
raw: true,
transaction,
});
const latestSpaceCodeSet = new Set(
(Array.isArray(latestSpaces) ? latestSpaces : [])
.map(item => String(item && item.space_code || '').trim())
.filter(Boolean)
);
const retryMissingSpaces = spaces.filter(space => !latestSpaceCodeSet.has(String(space.space_code || '').trim()));
if (retryMissingSpaces.length === 0) {
return `货架 ${rack.zone_code} 已完整存在 ${latestSpaceCodeSet.size} 个仓位,无需补齐`;
}
await app.model.LocationSpace.bulkCreate(retryMissingSpaces, { transaction });
const finalSpaceCount = latestSpaceCodeSet.size + retryMissingSpaces.length;
if (spacesNeedDelete.length > 0) {
return `为货架 ${rack.zone_code} 删除 ${spacesNeedDelete.length} 个多余库位并补齐 ${retryMissingSpaces.length} 个仓位(总数 ${finalSpaceCount}/${expectedSpaceCount})`;
}
return `为货架 ${rack.zone_code} 补齐 ${retryMissingSpaces.length} 个仓位(总数 ${finalSpaceCount}/${expectedSpaceCount})`;
}
return `为货架 ${rack.zone_code} 生成了 ${spaces.length} 个仓位`;
}
async getSpaceInfo(id) {
const { ctx } = this;

View File

@ -1443,7 +1443,7 @@ class OrderStorageAllocationService extends MainService {
});
const orderMap = new Map();
console.log("orderRows", JSON.stringify(orderRows));
console.log('orderRows', JSON.stringify(orderRows));
for (const orderRow of Array.isArray(orderRows) ? orderRows : []) {
const plainOrder = toPlainRecord(orderRow);
if (!plainOrder || !Number(plainOrder.id)) {

View File

@ -38,18 +38,18 @@ class PoloApiService extends Service {
console.log('查询菠萝派平台数据,入参bizcontent:', JSON.stringify(bizcontent));
return this.client.request({
method,
bizcontent: bizcontent,
bizcontent,
config,
token
token,
});
}
async get(method, bizcontent = {}, config = {}, token) {
console.log('查询菠萝派平台数据,入参bizcontent:', JSON.stringify(bizcontent));
return this.client.get({
method,
bizcontent: bizcontent,
bizcontent,
config,
token
token,
});
}
/**

View File

@ -3209,7 +3209,7 @@ class ReceivingService extends Service {
* @return {Promise<void>}
*/
async _syncProductDataFromReceiving({ receivingId, warehouseId, details }) {
console.log("_syncProductDataFromReceiving异步执行中..."); // 调试日志
console.log('_syncProductDataFromReceiving异步执行中...'); // 调试日志
const { ctx, app } = this;
// 只处理已绑定系统商品的明细

View File

@ -167,7 +167,7 @@ module.exports = appInfo => {
deletedAt: 'deleted_at', // 软删除字段名
},
pool: {
max: 5,
max: 20,
min: 1,
idle: 10000,
acquire: 30000,

View File

@ -1 +1 @@
{"startedAt":1777218488523,"recordCount":1}
{"startedAt":1777304067412,"recordCount":8}

View File

@ -0,0 +1 @@
{"startedAt":1777304050565,"recordCount":67}

View File

@ -1,7 +1,7 @@
{
"filePath": "D:\\wms\\runtime\\file-writer\\qimen-logs\\2026\\04\\12\\qimen-logs-MINGREN-worker-p38224-0001.log",
"offset": 1713,
"processedCount": 1,
"completedAt": "2026-04-12T14:54:22.636Z",
"updatedAt": "2026-04-17T12:02:32.964Z"
"filePath": "D:\\wms\\runtime\\file-writer\\qimen-logs\\2026\\04\\27\\qimen-logs-MINGREN-worker-p17872-0001.log",
"offset": 18973,
"processedCount": 7,
"completedAt": "2026-04-27T13:30:41.800Z",
"updatedAt": "2026-04-29T09:42:51.811Z"
}

View File

@ -1 +0,0 @@
{"log_id":"QL-1777218488522-0792d4","from_key":"","to_key":23535631,"method":"deliveryorder.batchcreate","sign":"","costomer_id":"","v":"2.0","url":"http://127.0.0.1:6060/qimen?app_key=&method=deliveryorder.batchcreate&v=2.0&format=json&sign_method=md5&sign=&timestamp=1777218485","created_at":"2026-04-26T15:48:08.522Z","body":"","result":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<response>\n <flag>failure</flag>\n <code>0</code>\n <message>参数缺失或错误</message>\n</response>","use_time":0}

View File

@ -0,0 +1,7 @@
{
"filePath": "D:\\wms\\runtime\\file-writer\\qimen-logs\\2026\\04\\26\\qimen-logs-MINGREN-worker-p35616-0001.log",
"offset": 0,
"processedCount": 0,
"completedAt": "2026-04-27T13:30:41.522Z",
"updatedAt": "2026-04-27T13:30:41.522Z"
}

View File

@ -0,0 +1,7 @@
{
"filePath": "D:\\wms\\runtime\\file-writer\\qimen-logs\\2026\\04\\27\\qimen-logs-MINGREN-worker-p17872-0001.log",
"offset": 18973,
"processedCount": 7,
"completedAt": "2026-04-27T13:30:41.800Z",
"updatedAt": "2026-04-27T13:30:41.800Z"
}

View File

@ -6,7 +6,7 @@ const query = {
method: 'openapi.index',
sign: '806b7294f2545bf20eb1fdf244e7ff28',
timestamp: 1777222912,
v: '1.0'
v: '1.0',
};
const body = {};

View File

@ -69,6 +69,11 @@ describe('test/app/controller/docs.test.js', () => {
assert.match(html, /buildOpenapiQuery/);
assert.match(html, /refreshOpenapiQueryDisplays/);
assert.match(html, /applyOpenapiSign/);
assert.match(html, /function\s+normalizeParamValue\s*\(/);
assert.match(html, /return\s+key\s*\+\s*['"]=['"]\s*\+\s*normalizeParamValue\(queryParams\[key\]\)/);
assert.match(html, /var\s+ignoredSet\s*=\s*\{[\s\S]*sign\s*:\s*true,[\s\S]*signature\s*:\s*true,[\s\S]*\}/);
assert.match(html, /!ignoredSet\[String\(key\)\.toLowerCase\(\)\]/);
assert.match(html, /var\s+sign\s*=\s*md5\(canonicalQuery\s*\+\s*normalizedSecret\s*\+\s*bodySign\)/);
assert.match(html, /raw\.startsWith\(['"]\?['"]\)/);
assert.match(html, /raw\s*=\s*raw\.slice\(1\)/);
assert.doesNotMatch(html, /replace\(\/\^\?\//);

View File

@ -6,12 +6,17 @@ const QimenClient = require('../../../app/lib/qimen_client');
function buildRequestXml(payload = {}) {
const request = payload.request || {};
const orderLines = Array.isArray(request.orderLines) ? request.orderLines : [];
const packages = Array.isArray(request.packages?.package) ? request.packages.package : [];
const serializedLines = orderLines
.map(line => ` <item><orderLineNo>${line.orderLineNo || ''}</orderLineNo><itemCode>${line.itemCode || ''}</itemCode></item>`)
.join('\n');
return `<?xml version="1.0" encoding="UTF-8"?>\n<request>\n <deliveryOrder>\n <deliveryOrderCode>${request.deliveryOrder?.deliveryOrderCode || ''}</deliveryOrderCode>\n </deliveryOrder>\n <orderLines>\n${serializedLines}\n </orderLines>\n</request>`;
const serializedPackages = packages
.map(pkg => ` <item><logisticsCode>${pkg.logisticsCode || ''}</logisticsCode><logisticsName>${pkg.logisticsName || ''}</logisticsName><expressCode>${pkg.expressCode || ''}</expressCode><packageCode>${pkg.packageCode || ''}</packageCode><invoiceNo>${pkg.invoiceNo || ''}</invoiceNo></item>`)
.join('\n');
return `<?xml version="1.0" encoding="UTF-8"?>\n<request>\n <deliveryOrder>\n <deliveryOrderCode>${request.deliveryOrder?.deliveryOrderCode || ''}</deliveryOrderCode>\n </deliveryOrder>\n <packages>\n <package>\n${serializedPackages}\n </package>\n </packages>\n <orderLines>\n${serializedLines}\n </orderLines>\n</request>`;
}
describe('test/app/lib/qimen_client.test.js', () => {
@ -76,6 +81,24 @@ describe('test/app/lib/qimen_client.test.js', () => {
deliveryOrder: {
deliveryOrderCode: 'DO-1001',
},
packages: {
package: [
{
logisticsCode: 'STO',
logisticsName: '申通快递',
expressCode: '776442271858573',
packageCode: 'JY2026042225858',
invoiceNo: '',
},
{
logisticsCode: 'STO',
logisticsName: '申通快递',
expressCode: '776442271858572',
packageCode: 'JY2026042225858',
invoiceNo: '',
},
],
},
orderLines: [
{
orderLineNo: '1',
@ -86,6 +109,9 @@ describe('test/app/lib/qimen_client.test.js', () => {
assert.equal(sendResult.queryId, 'Q-TEST-1');
assert.match(sentXml, /<request>/);
assert.match(sentXml, /<packages>\s*<package>\s*<logisticsCode>STO<\/logisticsCode>/);
assert.match(sentXml, /<\/package>\s*<package>\s*<logisticsCode>STO<\/logisticsCode>/);
assert.doesNotMatch(sentXml, /<package>\s*<item>/);
assert.match(sentXml, /<orderLines>\s*<orderLine>/);
assert.doesNotMatch(sentXml, /<orderLine>\s*<orderLine>/);
});

View File

@ -453,6 +453,74 @@ describe('test/app/service/systemMethods/order.base.step.test.js', () => {
assert.equal(result.list[1].sys_logistics_name, null);
});
it('should treat waybill_codes as virtual filter and only append matched order ids to order where', async () => {
const rows = buildRows(3, index => ({
id: index + 1,
warehouse_id: 100000,
step: 1,
}));
const { service, captures } = createOrderHarness(OrderBaseService, {
rowsByModule: {
order: rows,
},
});
const expressQueries = [];
service.ctx.model = {
OrderExpress: {
async findAll(options = {}) {
expressQueries.push(options);
const where = options.where || {};
const waybillFilter = where.waybill_code && where.waybill_code[Sequelize.Op.in];
const orderIdFilter = where.order_id && where.order_id[Sequelize.Op.in];
if (Array.isArray(waybillFilter)) {
return [
{ order_id: 2 },
{ order_id: 3 },
];
}
if (Array.isArray(orderIdFilter)) {
return orderIdFilter
.filter(orderId => Number(orderId) === 2 || Number(orderId) === 3)
.map(orderId => ({
id: Number(orderId) + 100,
order_id: Number(orderId),
waybill_code: Number(orderId) === 2 ? 'WB-001' : 'WB-002',
}));
}
return [];
},
},
};
const result = await service.listByModule('order', {
pagination: {
page: 1,
pageSize: 10,
},
where: {
waybill_codes: 'WB-001',
express_numbers: [ 'WB-002' ],
},
});
assert.equal(result.pagination.total, 2);
assert.deepEqual(result.list.map(item => item.id), [ 2, 3 ]);
assert.deepEqual(result.list[0].waybill_codes, [ 'WB-001' ]);
assert.deepEqual(result.list[1].waybill_codes, [ 'WB-002' ]);
assert.deepEqual(captures[0].countWhere, captures[0].findOptions.where);
assert.equal(JSON.stringify(captures[0].countWhere).includes('waybill_codes'), false);
assert.equal(JSON.stringify(captures[0].countWhere).includes('express_numbers'), false);
assert.equal(expressQueries.length >= 1, true);
assert.deepEqual(expressQueries[0].where.waybill_code[Sequelize.Op.in], [ 'WB-001', 'WB-002' ]);
assert.equal(expressQueries[0].where.warehouse_id, 100000);
});
it('should query detail by tableType and return orderItems, items, expresses and waybill_codes', async () => {
const { service, captures } = createDetailHarness({
storeId: 100001,

View File

@ -0,0 +1,146 @@
'use strict';
const assert = require('node:assert/strict');
const OrderIndexService = require('../../../../../app/service/systemMethods/order/index');
function createHarness(storeId = 100321) {
const calls = {};
const opIn = Symbol.for('op.in');
const ctx = {
app: {
config: {},
Sequelize: {
Op: {
in: opIn,
},
},
},
logger: {
warn() {},
},
user: {
store_id: storeId,
},
model: {
File: {},
FileReference: {
async findAll(args) {
calls.findImagesArgs = args;
return [
{
business_id: '9101',
file: {
file_url: 'https://img.example.com/sku-9101-a.jpg',
},
},
{
business_id: '9101',
file: {
file_url: 'https://img.example.com/sku-9101-b.jpg',
},
},
{
business_id: '9102',
file: {
file_url: 'https://img.example.com/sku-9102-a.jpg',
},
},
];
},
},
},
service: {
systems: {
operationLog: {
async queryOrderLogs() {
return {
list: [],
pagination: {
page: 1,
pageSize: 200,
total: 0,
totalPages: 0,
},
};
},
},
},
},
};
const service = new OrderIndexService(ctx);
service.getOrderModelByTableType = async () => ({
async findOne() {
return {
id: 99,
warehouse_id: storeId,
};
},
});
service.getOrderItemsModelByTableType = async () => ({
async findAll(args) {
calls.findOrderItemsArgs = args;
return [
{ id: 1, order_id: 99, stock_id: 9101, item_code: 'SKU-9101' },
{ id: 2, order_id: 99, stock_id: 9102, item_code: 'SKU-9102' },
{ id: 3, order_id: 99, stock_id: null, item_code: 'SKU-NONE' },
];
},
});
service.getOrderExpressesByOrderId = async () => [];
return {
service,
calls,
opIn,
};
}
describe('test/app/service/systemMethods/order/detail.images.test.js', () => {
it('should load order item images by stock_id and merge into items', async () => {
const { service, calls, opIn } = createHarness(100321);
const result = await service.detail({
id: 99,
});
assert.equal(calls.findOrderItemsArgs.where.order_id, 99);
assert.equal(Array.isArray(calls.findOrderItemsArgs.order), true);
assert.equal(calls.findOrderItemsArgs.raw, true);
assert.equal(calls.findImagesArgs.where.business_type, 'stock');
assert.deepEqual(calls.findImagesArgs.where.business_id[opIn], [ 9101, 9102 ]);
assert.equal(calls.findImagesArgs.include[0].as, 'file');
assert.deepEqual(result.items, [
{
id: 1,
order_id: 99,
stock_id: 9101,
item_code: 'SKU-9101',
images: [
'https://img.example.com/sku-9101-a.jpg',
'https://img.example.com/sku-9101-b.jpg',
],
},
{
id: 2,
order_id: 99,
stock_id: 9102,
item_code: 'SKU-9102',
images: [ 'https://img.example.com/sku-9102-a.jpg' ],
},
{
id: 3,
order_id: 99,
stock_id: null,
item_code: 'SKU-NONE',
images: [],
},
]);
});
});

View File

@ -0,0 +1,99 @@
'use strict';
const assert = require('node:assert/strict');
const OrderIndexService = require('../../../../../app/service/systemMethods/order/index');
function createHarness(storeId = 100321) {
const calls = {};
const ctx = {
app: {
config: {},
Sequelize: {
Op: {
in: Symbol.for('op.in'),
},
},
},
user: {
store_id: storeId,
},
service: {
systems: {
operationLog: {
async queryOrderLogs(query) {
calls.queryOrderLogs = query;
return {
list: [{ id: 9001, operation_code: 'ORDER_CREATE' }],
pagination: {
page: 1,
pageSize: 200,
total: 1,
totalPages: 1,
},
};
},
},
},
},
};
const service = new OrderIndexService(ctx);
service.getOrderModelByTableType = async () => ({
async findOne(args) {
calls.findOrderArgs = args;
return {
id: 99,
warehouse_id: storeId,
};
},
});
service.getOrderItemsModelByTableType = async () => ({
async findAll(args) {
calls.findOrderItemsArgs = args;
return [{ id: 1, order_id: 99 }];
},
});
service.getOrderExpressesByOrderId = async orderId => {
calls.expressOrderId = orderId;
return [{ id: 11, order_id: 99, waybill_code: 'WB-001' }];
};
return {
service,
calls,
};
}
describe('test/app/service/systemMethods/order/detail.logs.test.js', () => {
it('should query and return order logs in detail response', async () => {
const { service, calls } = createHarness(100321);
const result = await service.detail({
id: 99,
});
assert.equal(calls.findOrderArgs.where.id, 99);
assert.equal(calls.findOrderArgs.where.warehouse_id, 100321);
assert.equal(calls.findOrderItemsArgs.where.order_id, 99);
assert.equal(calls.expressOrderId, 99);
assert.deepEqual(calls.queryOrderLogs, {
id: 99,
warehouseId: 100321,
page: 1,
pageSize: 200,
});
assert.ok(Array.isArray(result.log));
assert.ok(Array.isArray(result.logs));
assert.strictEqual(result.log, result.logs);
assert.deepEqual(result.log, [{ id: 9001, operation_code: 'ORDER_CREATE' }]);
assert.deepEqual(result.logs, [{ id: 9001, operation_code: 'ORDER_CREATE' }]);
assert.equal(result.detail.id, 99);
assert.equal(result.items.length, 1);
assert.equal(result.expresses.length, 1);
});
});