Co-authored-by: Copilot <copilot@github.com>
This commit is contained in:
liufumingren 2026-04-29 17:43:54 +08:00
parent ea8c6ebe82
commit b7f980188f
61 changed files with 2857 additions and 867 deletions

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

@ -118,7 +118,7 @@ module.exports = app => {
allowNull: true,
comment: '平台店铺',
},
address:{
address: {
type: STRING(255),
allowNull: true,
comment: '地址',

View File

@ -6,26 +6,26 @@ module.exports = app => {
// 状态机枚举定义
const StatusEnum = {
STATUS: ['pedding', 'created', 'cancel', 'error'],
SYNC_STATUS: ['padding', 'fin', 'error'],
POST_STATUS: ['padding', 'fin', 'timeout', 'error', 'none'],
STORAGE_STATUS: ['padding', 'fin', 'error', 'none'],
PICK_STATUS: ['padding', 'fin', 'error', 'none'],
PACK_STATUS: ['none', 'padding', 'fin', 'error'],
SENDED_STATUS: ['none', 'padding', 'fin', 'error'],
INSPECTION_STATUS: ['none', 'padding', 'running', 'fin', 'error'],
PRINT_STATUS: ['none', 'padding', 'fin', 'error'],
CLAIM_STATUS: ['none', 'padding', 'fin', 'error'],
OUTBOUND_STATUS: ['none', 'padding', 'fin', 'timeout', 'error'],
LOCK_STATUS: ['none', 'warehouse', 'store'],
STATUS: [ 'pedding', 'created', 'cancel', 'error' ],
SYNC_STATUS: [ 'padding', 'fin', 'error' ],
POST_STATUS: [ 'padding', 'fin', 'timeout', 'error', 'none' ],
STORAGE_STATUS: [ 'padding', 'fin', 'error', 'none' ],
PICK_STATUS: [ 'padding', 'fin', 'error', 'none' ],
PACK_STATUS: [ 'none', 'padding', 'fin', 'error' ],
SENDED_STATUS: [ 'none', 'padding', 'fin', 'error' ],
INSPECTION_STATUS: [ 'none', 'padding', 'running', 'fin', 'error' ],
PRINT_STATUS: [ 'none', 'padding', 'fin', 'error' ],
CLAIM_STATUS: [ 'none', 'padding', 'fin', 'error' ],
OUTBOUND_STATUS: [ 'none', 'padding', 'fin', 'timeout', 'error' ],
LOCK_STATUS: [ 'none', 'warehouse', 'store' ],
INTERCEPT_STATUS: [
'none', 'requesting', 'requested', 'intercepting',
'intercepted_in_transit', 'intercepted_at_warehouse',
'returning', 'returned', 'delivered_by_mistake',
'timeout', 'cancelled', 'failed', 'exception',
],
URGENCY: ['Y', 'N'],
INVOICE: ['Y', 'N'],
URGENCY: [ 'Y', 'N' ],
INVOICE: [ 'Y', 'N' ],
};
// 基础模型定义
@ -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,
@ -470,16 +476,16 @@ module.exports = app => {
indexes: [
{
name: 'idx_current_store_id',
fields: ['store_id'],
fields: [ 'store_id' ],
},
{
name: 'idx_current_warehouse_id',
fields: ['warehouse_id'],
fields: [ 'warehouse_id' ],
},
{
name: 'idx_current_delivery_code',
unique: true,
fields: ['delivery_order_code', 'store_id', 'warehouse_id'],
fields: [ 'delivery_order_code', 'store_id', 'warehouse_id' ],
},
{
name: 'idx_items',
@ -487,15 +493,15 @@ module.exports = app => {
},
{
name: 'idx_items_hash',
fields: ['items_hash'],
fields: [ 'items_hash' ],
},
{
name: 'idx_hash_crc',
fields: ['items_hash', 'items_crc', 'warehouse_id'],
fields: [ 'items_hash', 'items_crc', 'warehouse_id' ],
},
{
name: 'wave_id',
fields: ['status', 'wave_id'],
fields: [ 'status', 'wave_id' ],
},
// 状态机索引
{

View File

@ -102,16 +102,16 @@ module.exports = app => {
allowNull: true,
comment: '加密打印信息',
},
encryptedtoken:{
encryptedtoken: {
type: TEXT,
allowNull: true,
comment: '加密令牌',
},
warehouse_id:{
warehouse_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '仓库ID',
}
},
}, {
tableName: 'wms_order_express',
freezeTableName: true,

View File

@ -55,11 +55,11 @@ module.exports = app => {
allowNull: true,
comment: '店铺类型',
},
ordersource:{
ordersource: {
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。';
@ -21,7 +21,7 @@ const BADGE_COUNT_OVER_LIMIT_VALUE = '99+';
const ORDER_LIST_BASE_ATTRIBUTES = Object.freeze([
'id', 'delivery_order_code', 'pre_delivery_order_code', 'pre_delivery_order_id',
'order_type', 'order_flag','source_order_codes',
'order_type', 'order_flag', 'source_order_codes',
'sys_platform_code', 'sys_platform_name',
'create_at',
'place_order_time', 'pay_time', 'pay_no', 'service_code',
@ -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 {
@ -102,7 +102,7 @@ class ExpressService extends Service {
normalizeWaybillBusinessKeys(businessKey = null) {
const rawBusinessKeys = Array.isArray(businessKey)
? businessKey.flat(Infinity)
: [businessKey];
: [ businessKey ];
const normalizedBusinessKeys = [];
const seenBusinessKeys = new Set();
@ -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) {
@ -509,7 +509,7 @@ class ExpressService extends Service {
return;
}
for (const [exceptionText, orderIds] of failedOrdersByReason.entries()) {
for (const [ exceptionText, orderIds ] of failedOrdersByReason.entries()) {
await this.markWaybillOrdersAsException(orderDeliveryModel, orderIds, exceptionText, transaction);
}
}
@ -624,11 +624,11 @@ class ExpressService extends Service {
}
const rows = await expressSettingModel.findAll({
attributes: ['id', 'code', 'name', 'express_code'],
attributes: [ 'id', 'code', 'name', 'express_code' ],
where: {
warehouse_id: normalizedWarehouseId,
},
order: [['code', 'ASC']],
order: [[ 'code', 'ASC' ]],
raw: true,
});
@ -784,7 +784,7 @@ class ExpressService extends Service {
async loadExpressListFromDatabase() {
const rows = await this.ctx.model.Express.findAll({
order: [['code', 'ASC']],
order: [[ 'code', 'ASC' ]],
raw: true,
});
@ -815,8 +815,8 @@ class ExpressService extends Service {
async loadExpressProductTypeListFromDatabase(expressCode = '') {
const normalizedExpressCode = String(expressCode || '').trim();
const query = {
attributes: ['code', 'name', 'express_code'],
order: [['express_code', 'ASC'], ['code', 'ASC']],
attributes: [ 'code', 'name', 'express_code' ],
order: [[ 'express_code', 'ASC' ], [ 'code', 'ASC' ]],
raw: true,
};
@ -862,7 +862,7 @@ class ExpressService extends Service {
return expressList;
}
const [expressList, expressSettingList] = await Promise.all([
const [ expressList, expressSettingList ] = await Promise.all([
this.loadExpressListFromDatabase(),
this.loadExpressSettingListFromDatabase(warehouseId),
]);
@ -1336,9 +1336,9 @@ class ExpressService extends Service {
if (typeof dispatchMethod !== 'function') {
throw new Error(normalizedPlatformCode + '接口未实现');
}
//console.log("业务数据骨架", JSON.stringify(bizcontent));
// console.log("业务数据骨架", JSON.stringify(bizcontent));
const dispatchResult = await dispatchMethod.call(expressPlatformService, bizcontent);
//console.log("平台接口返回结果", JSON.stringify(dispatchResult));
// console.log("平台接口返回结果", JSON.stringify(dispatchResult));
if (dispatchResult && typeof dispatchResult === 'object' && dispatchResult.flag === 'failure') {
throw new Error(dispatchResult.message || normalizedPlatformCode + '接口调用失败');
}
@ -1477,10 +1477,10 @@ class ExpressService extends Service {
id: orderList.map(order => Number(order && order.order_id)).filter(orderId => Number.isFinite(orderId) && orderId > 0),
warehouse_id: warehouseId,
step: {
[Op.in]: [1, 2, 3],
[Op.in]: [ 1, 2, 3 ],
},
},
attributes: ['id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name','store_id'],
attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id' ],
raw: true,
});
console.log('createWaybillCodePipeline 查询订单主表结果', orders_arr);
@ -1504,13 +1504,13 @@ class ExpressService extends Service {
const batches = this.splitWaybillOrdersIntoBatches(groupedOrder.orders);
const listByWarehousePlatformCode = await this.service.systems.setting.expressInterface.listByWarehousePlatformCode({ warehouseId, platform_code: groupedOrder.options.sys_platform_code });
console.log('createWaybillCodePipeline 按批次切分结果', batches, 'expressInterfaceList', listByWarehousePlatformCode, 'matchedPlatform', matchedPlatform);
//先获取货主配置货主是否配置了发件人,如果没有再使用快递接口的发件人信息。发件人信息在 listByWarehousePlatformCode.data[0] 中。
// 先获取货主配置货主是否配置了发件人,如果没有再使用快递接口的发件人信息。发件人信息在 listByWarehousePlatformCode.data[0] 中。
const storeInfo = await this.service.systems.storeWarehouse.getContractConfig(warehouseId, groupedOrder.options.store_id);
const expressInterface= listByWarehousePlatformCode.data[0];
const expressInterface = listByWarehousePlatformCode.data[0];
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);
@ -1548,7 +1548,7 @@ class ExpressService extends Service {
if (!listByWarehousePlatformCode) {
throw new Error(`当前订单平台【${options.sys_platform_name}】,快递【${options.logistics_name}】,未配置有效的快递接口`);
}
if(!matchedPlatform){
if (!matchedPlatform) {
throw new Error(`未找到订单平台【${options.sys_platform_name}】的有效平台配置`);
}
await this.createWaybillCode(batch, matchedPlatform, listByWarehousePlatformCode);
@ -1655,7 +1655,7 @@ class ExpressService extends Service {
orderDeliveryInclude.push({
model: orderItemsModel,
as: 'orderItems',
attributes: ['id', 'order_id', 'item_code', 'item_name', 'plan_qty','source_order_code'],
attributes: [ 'id', 'order_id', 'item_code', 'item_name', 'plan_qty', 'source_order_code' ],
required: false,
});
}
@ -1682,7 +1682,7 @@ class ExpressService extends Service {
business_key: order.business_key,
})),
},
attributes: ['order_id', 'business_key', 'status'],
attributes: [ 'order_id', 'business_key', 'status' ],
raw: true,
transaction,
});
@ -1718,7 +1718,7 @@ class ExpressService extends Service {
const relationRows = relationWhereList.length > 0
? await storeWarehouseModel.findAll({
attributes: ['id', 'store_id', 'warehouse_id', 'print_quantity', 'print_quantity_locked', 'policy_config'],
attributes: [ 'id', 'store_id', 'warehouse_id', 'print_quantity', 'print_quantity_locked', 'policy_config' ],
where: {
[Op.or]: relationWhereList,
},
@ -1763,7 +1763,7 @@ class ExpressService extends Service {
warehouse_id: currentWarehouseId,
})),
},
attributes: ['id', 'order_id', 'business_key', 'status', 'retry_count','warehouse_id'],
attributes: [ 'id', 'order_id', 'business_key', 'status', 'retry_count', 'warehouse_id' ],
raw: true,
transaction,
lock: transaction.LOCK.UPDATE,
@ -1938,7 +1938,7 @@ class ExpressService extends Service {
if (restoreRelationMap.size > 0) {
const restoreRelationList = Array.from(restoreRelationMap.values());
const restoreRows = await storeWarehouseModel.findAll({
attributes: ['id', 'store_id', 'warehouse_id', 'print_quantity_locked'],
attributes: [ 'id', 'store_id', 'warehouse_id', 'print_quantity_locked' ],
where: {
[Op.or]: restoreRelationList.map(item => ({
store_id: item.store_id,

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') {
@ -184,13 +184,13 @@ class ExpressPlatformService extends MainService {
if (orderIdList.length > 0) {
const allocatedWaybillRows = await orderExpressModel.findAll({
attributes: ['order_id', 'business_key', 'waybill_code'],
attributes: [ 'order_id', 'business_key', 'waybill_code' ],
where: {
order_id: {
[Op.in]: orderIdList,
},
},
order: [['id', 'ASC']],
order: [[ 'id', 'ASC' ]],
raw: true,
});
@ -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') {
@ -302,7 +302,7 @@ class ExpressPlatformService extends MainService {
switch (listByWarehousePlatformCode.platform_code) {
case 'KS':
successUpdates = (result.results || []).map(item => {
const [warehouse_id, order_id, business_key] = String(item.orderno || '').split('_');
const [ warehouse_id, order_id, business_key ] = String(item.orderno || '').split('_');
const waybillCode = resolveWaybillCode(item);
return {
warehouse_id,
@ -332,7 +332,7 @@ class ExpressPlatformService extends MainService {
break;
case 'DYXD':
successUpdates = (result.results || []).map(item => {
const [warehouse_id, order_id, business_key] = String(item.orderno || '').split('_');
const [ warehouse_id, order_id, business_key ] = String(item.orderno || '').split('_');
const waybillCode = resolveWaybillCode(item);
return {
warehouse_id,
@ -449,7 +449,7 @@ class ExpressPlatformService extends MainService {
const { Op } = this.app.Sequelize;
const relationList = Array.from(settlementRelationMap.values());
const relationRows = await storeWarehouseModel.findAll({
attributes: ['id', 'store_id', 'warehouse_id', 'print_quantity', 'print_quantity_locked'],
attributes: [ 'id', 'store_id', 'warehouse_id', 'print_quantity', 'print_quantity_locked' ],
where: {
[Op.or]: relationList.map(item => ({
store_id: item.store_id,
@ -537,7 +537,7 @@ class ExpressPlatformService extends MainService {
extras: {
message: `订单${orderId}获取快递单成功,单号:${item.waybill_code}`,
warehouseId,
}
},
});
}
}
@ -548,7 +548,7 @@ class ExpressPlatformService extends MainService {
message: '菠萝派平台数据处理成功',
data: result,
};
//throw new Error('菠萝派平台接口未实现');
// throw new Error('菠萝派平台接口未实现');
}
/**

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

@ -695,7 +695,7 @@ async function finalizeLocalChannelOrdersInternal(service, createChannel, groupe
const orderModel = await service.ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
const orderItemsModel = await service.ctx.model.OrderItemsFactory.getCurrentModel(warehouseId);
const { Op } = service.app.Sequelize;
const [orderRows, orderItemRows] = await Promise.all([
const [ orderRows, orderItemRows ] = await Promise.all([
orderModel.findAll({
where: {
id: {

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

@ -34,22 +34,22 @@ class PoloApiService extends Service {
},
});
}
async request(method,bizcontent = {},config = {},token) {
async request(method, bizcontent = {}, config = {}, token) {
console.log('查询菠萝派平台数据,入参bizcontent:', JSON.stringify(bizcontent));
return this.client.request({
method,
bizcontent: bizcontent,
bizcontent,
config,
token
token,
});
}
async get(method,bizcontent = {},config = {},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

@ -3,9 +3,9 @@
const Service = require('egg').Service;
const result = {
platform:null,
count:0,
datas:[],
platform: null,
count: 0,
datas: [],
};
class PrintDataService extends Service {

View File

@ -69,7 +69,7 @@ class ReceivingService extends Service {
},
order: [],
attributes: {
exclude: ['deleted_at'],
exclude: [ 'deleted_at' ],
},
};
@ -115,7 +115,7 @@ class ReceivingService extends Service {
parsedResult = parsed.result;
}
const dynamicConditions = [...(parsedResult.dynamicConditions || [])];
const dynamicConditions = [ ...(parsedResult.dynamicConditions || []) ];
const quickWhereRaw = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere)
|| normalizedWhere.quickWhere;
@ -153,14 +153,14 @@ class ReceivingService extends Service {
];
const actualSortField = validSortFields.includes(sortField) ? sortField : 'create_at';
const actualSortOrder = sortOrder.toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
queryOptions.order.push([actualSortField, actualSortOrder]);
queryOptions.order.push([ actualSortField, actualSortOrder ]);
const offset = (page - 1) * pageSize;
const include = [
{
model: ctx.model.StoreWarehouse,
as: 'store',
attributes: ['store_remask'],
attributes: [ 'store_remask' ],
where: {
use_status: 1,
warehouse_id: ctx.user.store_id,
@ -170,12 +170,12 @@ class ReceivingService extends Service {
{
model: ctx.model.AccountStoreEmployee,
as: 'creator',
attributes: ['real_name'],
attributes: [ 'real_name' ],
required: true,
},
];
const [total, data] = await Promise.all([
const [ total, data ] = await Promise.all([
ctx.model.Receiving.count({
where: queryOptions.where,
include,
@ -209,7 +209,7 @@ class ReceivingService extends Service {
{
model: ctx.model.File,
as: 'file',
attributes: ['file_url'],
attributes: [ 'file_url' ],
required: true,
},
],
@ -341,7 +341,7 @@ class ReceivingService extends Service {
include: [{
model: ctx.model.File,
as: 'file',
attributes: ['file_url'],
attributes: [ 'file_url' ],
required: true,
}],
});
@ -372,7 +372,7 @@ class ReceivingService extends Service {
include: [{
model: ctx.model.File,
as: 'file',
attributes: ['file_url'],
attributes: [ 'file_url' ],
required: true,
}],
});
@ -671,7 +671,7 @@ class ReceivingService extends Service {
case 'daterange':
// 处理日期范围:数组的第一个元素是开始时间,第二个元素是结束时间
if (Array.isArray(value) && value.length === 2) {
const [startDate, endDate] = value;
const [ startDate, endDate ] = value;
return [
startDate ? service.main.normalizeDate(startDate, false) : null, // 开始时间设为00:00:00
endDate ? service.main.normalizeDate(endDate, true) : null, // 结束时间设为23:59:59
@ -705,15 +705,15 @@ class ReceivingService extends Service {
const suffixStartIndex = prefix.length + 1;
const maxReceiving = await app.model.Receiving.findOne({
attributes: ['receiving_number'],
attributes: [ 'receiving_number' ],
where: {
receiving_number: {
[app.Sequelize.Op.like]: `${prefix}%`,
},
},
order: [
[app.Sequelize.literal(`CAST(SUBSTRING(receiving_number, ${suffixStartIndex}) AS UNSIGNED)`), 'DESC'],
['receiving_number', 'DESC'],
[ app.Sequelize.literal(`CAST(SUBSTRING(receiving_number, ${suffixStartIndex}) AS UNSIGNED)`), 'DESC' ],
[ 'receiving_number', 'DESC' ],
],
});
@ -943,7 +943,7 @@ class ReceivingService extends Service {
};
}
if (['receiving', 'completed'].includes(receiving.status) && Number(receiving.store_id || 0) > 0) {
if ([ 'receiving', 'completed' ].includes(receiving.status) && Number(receiving.store_id || 0) > 0) {
await transaction.rollback();
return {
code: 400,
@ -957,7 +957,7 @@ class ReceivingService extends Service {
store_id: storeId,
use_status: 1,
},
attributes: ['store_id', 'store_remask'],
attributes: [ 'store_id', 'store_remask' ],
transaction,
});
@ -1053,7 +1053,7 @@ class ReceivingService extends Service {
include: [{
model: ctx.model.StoreWarehouse,
as: 'store',
attributes: ['store_remask'],
attributes: [ 'store_remask' ],
where: {
use_status: 1,
warehouse_id: warehouseId,
@ -1062,7 +1062,7 @@ class ReceivingService extends Service {
}, {
model: ctx.model.AccountStoreEmployee,
as: 'creator',
attributes: ['real_name'],
attributes: [ 'real_name' ],
required: false,
}],
// 不需要order,因为根据id查询已经是唯一的
@ -1080,10 +1080,10 @@ class ReceivingService extends Service {
{
model: ctx.model.LocationSpace,
as: 'receiving_space',
attributes: ['space_code', 'custom_barcode', 'custom_name'],
attributes: [ 'space_code', 'custom_barcode', 'custom_name' ],
},
],
order: [['id', 'DESC']], // 保持倒序,最新在前
order: [[ 'id', 'DESC' ]], // 保持倒序,最新在前
});
// 3. 获取明细ID数组
@ -1102,7 +1102,7 @@ class ReceivingService extends Service {
include: [{
model: ctx.model.File,
as: 'file',
attributes: ['file_url'],
attributes: [ 'file_url' ],
required: true,
}],
});
@ -1136,7 +1136,7 @@ class ReceivingService extends Service {
include: [{
model: ctx.model.File,
as: 'file',
attributes: ['file_url'],
attributes: [ 'file_url' ],
required: true,
}],
});
@ -1216,7 +1216,7 @@ class ReceivingService extends Service {
// 获取更新后的明细列表
const allDetails = await ctx.model.ReceivingDetail.findAll({
where: { receiving_id },
order: [['id', 'DESC']],
order: [[ 'id', 'DESC' ]],
});
// 格式化返回数据
@ -1322,7 +1322,7 @@ class ReceivingService extends Service {
{
model: app.model.Receiving,
as: 'receiving',
attributes: ['id', 'warehouse_id', 'store_id', 'store_name', 'status'],
attributes: [ 'id', 'warehouse_id', 'store_id', 'store_name', 'status' ],
where: {
warehouse_id: warehouseId,
},
@ -1347,12 +1347,12 @@ class ReceivingService extends Service {
app.model.StoreWarehouse.buildStoreStockInclude({
warehouseId,
required: false,
attributes: ['store_id', 'store_remask'],
attributes: [ 'store_id', 'store_remask' ],
}),
{
model: app.model.StockBarcode,
as: 'barcodes',
attributes: ['barcode'],
attributes: [ 'barcode' ],
required: false,
},
],
@ -1511,7 +1511,7 @@ class ReceivingService extends Service {
{
model: ctx.model.Receiving,
as: 'receiving',
attributes: ['id', 'status'],
attributes: [ 'id', 'status' ],
},
],
});
@ -1604,7 +1604,7 @@ class ReceivingService extends Service {
}
// 更新明细
const [affectedRows] = await ctx.model.ReceivingDetail.update(updateData, {
const [ affectedRows ] = await ctx.model.ReceivingDetail.update(updateData, {
where: { id },
});
@ -1627,7 +1627,7 @@ class ReceivingService extends Service {
{
model: ctx.model.StockWarehouse,
as: 'system_product',
attributes: ['id', 'name', 'barcode', 'spec', 'unit', 'images'],
attributes: [ 'id', 'name', 'barcode', 'spec', 'unit', 'images' ],
},
],
});
@ -1676,7 +1676,7 @@ class ReceivingService extends Service {
ctx.model.StoreWarehouse.buildStoreStockInclude({
warehouseId: ctx.user.store_id,
required: false,
attributes: ['store_id', 'store_remask'],
attributes: [ 'store_id', 'store_remask' ],
}),
],
});
@ -1759,8 +1759,8 @@ class ReceivingService extends Service {
const stats = await ctx.model.ReceivingDetail.findAll({
where: { receiving_id: receivingId },
attributes: [
[ctx.model.fn('COUNT', ctx.model.col('id')), 'total_items'],
[ctx.model.fn('SUM', ctx.model.col('actual_quantity')), 'total_quantity'],
[ ctx.model.fn('COUNT', ctx.model.col('id')), 'total_items' ],
[ ctx.model.fn('SUM', ctx.model.col('actual_quantity')), 'total_quantity' ],
],
raw: true,
transaction,
@ -1843,7 +1843,7 @@ class ReceivingService extends Service {
{
model: ctx.model.Receiving,
as: 'receiving',
attributes: ['id', 'status'],
attributes: [ 'id', 'status' ],
where: {
warehouse_id,
},
@ -1894,7 +1894,7 @@ class ReceivingService extends Service {
// 获取删除后的所有明细
const remainingDetails = await ctx.model.ReceivingDetail.findAll({
where: { receiving_id },
order: [['id', 'DESC']],
order: [[ 'id', 'DESC' ]],
});
// 格式化返回数据
@ -2013,7 +2013,7 @@ class ReceivingService extends Service {
{
model: app.model.Receiving,
as: 'receiving',
attributes: ['id', 'warehouse_id', 'store_id', 'store_name'],
attributes: [ 'id', 'warehouse_id', 'store_id', 'store_name' ],
where: {
warehouse_id: warehouseId,
id: receiving_id,
@ -2090,12 +2090,12 @@ class ReceivingService extends Service {
app.model.StoreWarehouse.buildStoreStockInclude({
warehouseId,
required: false,
attributes: ['store_id', 'store_remask'],
attributes: [ 'store_id', 'store_remask' ],
}),
{
model: app.model.StockBarcode,
as: 'barcodes',
attributes: ['barcode'],
attributes: [ 'barcode' ],
required: false,
},
],
@ -2390,11 +2390,11 @@ class ReceivingService extends Service {
const deliveryMethod = String((receiving && receiving.delivery_method) || '').trim();
if (deliveryMethod === 'truck') {
return [['车牌号', receiving && receiving.license_plate]];
return [[ '车牌号', receiving && receiving.license_plate ]];
}
if (deliveryMethod === 'express') {
return [['物流单号', receiving && receiving.tracking_number]];
return [[ '物流单号', receiving && receiving.tracking_number ]];
}
return [];
@ -2448,7 +2448,7 @@ class ReceivingService extends Service {
);
const buildLinkCell = urls => {
const normalizedUrls = (Array.isArray(urls) ? urls : [urls])
const normalizedUrls = (Array.isArray(urls) ? urls : [ urls ])
.map(item => String(item || '').trim())
.filter(Boolean);
@ -2484,22 +2484,22 @@ class ReceivingService extends Service {
pushReportRow([]);
[
['收货单ID', receiving && receiving.id],
['收货单号', receiving && receiving.receiving_number],
['货主', receiving && receiving.store_name],
['来货方式', this.formatDeliveryMethod(receiving && receiving.delivery_method)],
[ '收货单ID', receiving && receiving.id ],
[ '收货单号', receiving && receiving.receiving_number ],
[ '货主', receiving && receiving.store_name ],
[ '来货方式', this.formatDeliveryMethod(receiving && receiving.delivery_method) ],
...this.getCompletionContactFields(receiving),
['总明细数', stats.total_details || details.length],
['已匹配明细数', stats.matched_details || 0],
['未匹配明细数', stats.unmatched_details || 0],
['总数量', stats.total_quantity || 0],
['总箱数', receiving && receiving.total_boxes],
['总托盘数', receiving && receiving.total_pallets],
['完成人', operator.employees_name || operator.real_name || operator.name || ''],
['完成时间', this.formatReportDate(receiving && receiving.receiving_end_time)],
['备注', receiving && receiving.remark],
].forEach(([field, value]) => {
pushReportRow([field, value], {
[ '总明细数', stats.total_details || details.length ],
[ '已匹配明细数', stats.matched_details || 0 ],
[ '未匹配明细数', stats.unmatched_details || 0 ],
[ '总数量', stats.total_quantity || 0 ],
[ '总箱数', receiving && receiving.total_boxes ],
[ '总托盘数', receiving && receiving.total_pallets ],
[ '完成人', operator.employees_name || operator.real_name || operator.name || '' ],
[ '完成时间', this.formatReportDate(receiving && receiving.receiving_end_time) ],
[ '备注', receiving && receiving.remark ],
].forEach(([ field, value ]) => {
pushReportRow([ field, value ], {
toCol: 2,
style: {
alignment: { vertical: 'top', wrapText: true },
@ -2508,7 +2508,7 @@ class ReceivingService extends Service {
});
if (mainImageUrls.length === 0) {
pushReportRow(['收货图片', '无'], {
pushReportRow([ '收货图片', '无' ], {
toCol: 2,
style: {
alignment: { vertical: 'top', wrapText: true },
@ -2517,7 +2517,7 @@ class ReceivingService extends Service {
} else {
const summaryLinkCell = buildLinkCell(mainImageUrls);
const imagePlaceholders = Array(Math.max(mainImageUrls.length, 1)).fill('');
const firstImageRowIndex = pushReportRow(['收货图片', summaryLinkCell, ...imagePlaceholders], {
const firstImageRowIndex = pushReportRow([ '收货图片', summaryLinkCell, ...imagePlaceholders ], {
toCol: 2 + imagePlaceholders.length,
height: 88,
style: {
@ -2554,7 +2554,7 @@ class ReceivingService extends Service {
});
if (details.length === 0) {
pushReportRow(['', '', '无明细'], {
pushReportRow([ '', '', '无明细' ], {
toCol: detailColumns.length,
style: {
alignment: { vertical: 'top', wrapText: true },
@ -2703,7 +2703,7 @@ class ReceivingService extends Service {
(completionReport && (completionReport.filename || completionReport.fileKey || completionReport.key)) || `收货完成_${receivingNumber}.xlsx`
).trim();
const title = `收货单${receivingNumber}已完成`;
const contactLines = this.getCompletionContactFields(receiving).map(([field, value]) => `${field}:${value || '无'}`);
const contactLines = this.getCompletionContactFields(receiving).map(([ field, value ]) => `${field}:${value || '无'}`);
const content = [
`收货单号:${receivingNumber} 已完成`,
`货主:${receiving.store_name || '未知'}`,
@ -2957,7 +2957,7 @@ class ReceivingService extends Service {
include: [{
model: ctx.model.File,
as: 'file',
attributes: ['file_url'],
attributes: [ 'file_url' ],
required: false,
}],
transaction,
@ -2985,7 +2985,7 @@ class ReceivingService extends Service {
include: [{
model: ctx.model.File,
as: 'file',
attributes: ['file_url'],
attributes: [ 'file_url' ],
required: false,
}],
transaction,
@ -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;
// 只处理已绑定系统商品的明细
@ -3229,7 +3229,7 @@ class ReceivingService extends Service {
warehouse_id: warehouseId,
deleted_at: null,
},
attributes: ['id', 'is_images', 'gross_weight'],
attributes: [ 'id', 'is_images', 'gross_weight' ],
raw: true,
});
@ -3242,7 +3242,7 @@ class ReceivingService extends Service {
business_id: String(detail.id),
warehouse_id: warehouseId,
},
attributes: ['file_id'],
attributes: [ 'file_id' ],
raw: true,
});
@ -3254,7 +3254,7 @@ class ReceivingService extends Service {
business_id: String(systemProductId),
warehouse_id: warehouseId,
},
attributes: ['file_id'],
attributes: [ 'file_id' ],
raw: true,
}).then(rows => rows.map(r => r.file_id));

View File

@ -2286,7 +2286,7 @@ class SettingStoreWarehouseService extends Service {
warehouse_id: normalizedWarehouseId,
store_id: normalizedStoreId,
},
attributes: ['id', 'store_id', 'warehouse_id', 'auth_status', 'policy_config'],
attributes: [ 'id', 'store_id', 'warehouse_id', 'auth_status', 'policy_config' ],
raw: true,
});

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);
});
});