Co-authored-by: Copilot <copilot@github.com>
This commit is contained in:
liufumingren 2026-04-29 17:43:54 +08:00
parent ea8c6ebe82
commit 5ce689d771
80 changed files with 5372 additions and 1132 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

@ -20,7 +20,7 @@ class QimenClient {
? signService.toXml.bind(signService)
: qimenService && typeof qimenService.formatResponse === 'function'
? qimenService.formatResponse.bind(qimenService)
: null),
: null),
parseXmlToArray: runtime.parseXmlToArray || (qimenService && typeof qimenService.parseXmlToArray === 'function'
? qimenService.parseXmlToArray.bind(qimenService)
: null),
@ -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);
@ -213,4 +239,4 @@ class QimenClient {
}
}
module.exports = QimenClient;
module.exports = QimenClient;

View File

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

View File

@ -39,6 +39,8 @@ module.exports = app => {
Object.freeze({ code: 'all', name: '全部事件', business: 'all', description: '订阅后接收所有通知事件' }),
Object.freeze({ code: '*', name: '全部事件(兼容别名)', business: 'all', description: '兼容旧配置,等价于 all' }),
Object.freeze({ code: 'receiving_completed', name: '收货完成', business: 'receiving', description: '收货单完成后的通知' }),
Object.freeze({ code: 'receiving_rejected', name: '收货驳回', business: 'receiving', description: '收货单被驳回并恢复为收货中后的通知' }),
Object.freeze({ code: 'receiving_reviewed', name: '收货审核完成', business: 'receiving', description: '收货单批量审核通过后的通知' }),
Object.freeze({ code: 'order_sync_completed', name: '订单同步完成', business: 'order', description: '本地创建入口同步完成后的通知' }),
Object.freeze({ code: 'order_cancel_intercepted', name: '订单取消拦截', business: 'order', description: '订单取消失败并触发拦截执行后的通知' }),
Object.freeze({

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

@ -615,7 +615,7 @@ module.exports = app => {
* @param {Object} [DynamicModel] 已构建的动态模型。
* @return {Promise<boolean>} 是否执行了同步。
*/
async ensureManagedTableSchema(tableName, type, warehouseId, DynamicModel = null) {
const modelType = this.resolveModelType(type);
const dynamicModel = DynamicModel || this.buildManagedModel(warehouseId, modelType, tableName);

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

@ -1,6 +1,6 @@
// app/model/receiving.js
module.exports = app => {
const { STRING, INTEGER, DATE, TEXT, BOOLEAN, ENUM } = app.Sequelize;
const { STRING, INTEGER, BIGINT, DATE, TEXT, BOOLEAN, ENUM, TINYINT } = app.Sequelize;
const Receiving = app.model.define('wms_receiving', {
id: {
@ -108,6 +108,22 @@ module.exports = app => {
type: DATE,
comment: '收货结束时间',
},
is_review: {
type: TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '是否已审核:0-未审核,1-已审核',
},
reviewer_name: {
type: STRING(50),
allowNull: true,
comment: '审核人姓名',
},
reviewer_employee_id: {
type: BIGINT.UNSIGNED,
allowNull: true,
comment: '审核人员工ID,关联 wms_account_store_employee.id',
},
is_deleted: {
type: BOOLEAN,
defaultValue: false,

View File

@ -25,6 +25,14 @@ module.exports = app => {
required: false,
description: '收货上架时是否自动推荐库位',
}),
Object.freeze({
key: 'allow_receiving_quick_putaway',
name: '收货单快捷入库',
type: 'flag',
default: 0,
required: false,
description: '控制该货主在当前仓库下是否允许使用收货单快捷入库',
}),
Object.freeze({
key: 'allow_mix_batch',
name: '允许混批',

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',
@ -29,7 +29,7 @@ const ORDER_LIST_BASE_ATTRIBUTES = Object.freeze([
'shop_nick', 'seller_nick', 'buyer_nick',
'total_amount', 'item_amount', 'discount_amount', 'freight',
'ar_amount', 'got_amount', 'service_fee',
'logistics_name',
'logistics_name',
'delivery_type', 'weight_type',
'is_urgency', 'invoice_flag', 'status',
'name', 'zip_code', 'tel', 'mobile', 'email',
@ -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,21 +1056,137 @@ 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 {
order,
detail: order,
orderItems: Array.isArray(orderItems) ? orderItems : [],
items: Array.isArray(orderItems) ? orderItems : [],
items: orderItemsWithImages,
expresses,
waybill_codes: waybillCodes,
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 {
...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 : [];
}
/**
* 将审核状态映射为 step。
* @param {string} reviewStatus 审核状态。

View File

@ -10,9 +10,9 @@ class configService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct';
const _noNeedLog = 'getReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct';
const _noNeedAuth = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct';
const _noNeedRight = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs';
const _noNeedLog = 'getReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct,queryReceivingLogs';
const _noNeedAuth = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -128,13 +128,13 @@ class configService extends MainService {
}
/**
* 保存收货单(兼容接口)。
* 保存收货单。
* @param {Object} data 请求体
* @return {Promise<Object>} 统一成功包装响应
*/
async saveReceiving(data) {
async save(data) {
const { service } = this;
const result = await service.systems.storage.receiving.saveReceiving(data);
const result = await service.systems.storage.receiving.save(data);
return this.success('ok', result);
}
@ -206,5 +206,61 @@ class configService extends MainService {
const result = await service.systems.storage.receiving.completeReceiving(data);
return this.success('ok', result);
}
/**
* 驳回收货单:将已完成收货单恢复为收货中,记录审核人信息与驳回理由。
* @param {Object} data 请求体
* @param {number[]} data.ids 收货单ID数组
* @param {string} [data.remark] 驳回理由(覆盖原备注)
* @return {Promise<Object>} 统一成功包装响应
*/
async rejectReceiving(data) {
const { service } = this;
const result = await service.systems.storage.receiving.rejectReceiving(data);
return this.success('ok', result);
}
/**
* 批量审核收货单。
* @param {Object} data 请求体
* @param {number[]} data.ids 收货单ID数组
* @return {Promise<Object>} 统一成功包装响应
*/
async reviewReceiving(data) {
const { service } = this;
const { ids } = data || {};
const result = await service.systems.storage.receiving.reviewReceiving({ ids });
return this.success('ok', result);
}
/**
* 查询收货单操作日志(分页)。
* @param {Object} data 请求体
* @param {number|string} [data.id] 收货单ID
* @param {number|string} [data.receiving_id] 收货单ID(兼容字段)
* @param {number} [data.page] 页码
* @param {number} [data.pageSize] 每页数量
* @param {Object} [data.pagination] 分页对象,支持 page/pageSize
* @return {Promise<Object>} 统一成功包装响应
*/
async queryReceivingLogs(data = {}) {
const { ctx, service } = this;
const requestData = data && typeof data === 'object' ? data : {};
const pagination = requestData.pagination && typeof requestData.pagination === 'object'
? requestData.pagination
: {};
const result = await service.systems.operationLog.queryReceivingLogs({
id: requestData.id || requestData.receiving_id,
page: requestData.page || pagination.page,
pageSize: requestData.pageSize || pagination.pageSize || pagination.page_size,
warehouseId: ctx.user.store_id,
});
return this.success('ok', {
data: result,
code: 200,
});
}
}
module.exports = configService;

View File

@ -193,36 +193,6 @@ class warehouseService extends MainService {
this.fail(error.message);
}
}
async createRack() {
const { ctx } = this;
const params = ctx.request.body;
// 验证参数
ctx.validate({
warehouse_id: { type: 'int', required: true },
zone_code: { type: 'string', required: true },
zone_name: { type: 'string', required: true },
parent_id: { type: 'int', required: false },
x: { type: 'int', required: true },
y: { type: 'int', required: true },
z: { type: 'int', required: false, default: 0 },
length: { type: 'int', required: true },
width: { type: 'int', required: true },
height: { type: 'int', required: true },
rack_columns: { type: 'int', required: true },
rack_rows: { type: 'int', required: true },
rack_levels: { type: 'int', required: true },
direction: { type: 'enum', values: [ 'north', 'south', 'east', 'west' ], required: false },
color: { type: 'string', required: false },
});
try {
const rack = await ctx.service.location.createRackWithSpaces(params);
ctx.success(rack, '货架创建成功');
} catch (error) {
this.fail(error.message, 400);
}
}
/**
* 获取拣货路径

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();
@ -225,13 +225,13 @@ class ExpressService extends Service {
const normalizedOrders = Array.isArray(orders) ? orders : [];
console.log('normalizeWaybillCreateOrders 原始订单列表', normalizedOrders);
const normalizedOrderMap = new Map();
const ExpressList = await this.loadExpressList();
for (const order of normalizedOrders) {
if (!order || typeof order !== 'object') {
continue;
}
const orderId = Number(order.id || order.order_id);
const businessKeys = this.normalizeWaybillBusinessKeys(order.business_key);
console.log('businessKeys', businessKeys);
@ -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),
]);
@ -918,7 +918,7 @@ class ExpressService extends Service {
*/
groupWaybillOrdersByPlatformAndLogistics(orders = []) {
// 【step2】按平台 + 快递编码+货主id分组,后续按组串行处理。
const groupedOrders = [];
const groupedOrderMap = new Map();
@ -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);
@ -1638,246 +1638,246 @@ class ExpressService extends Service {
try {
// 【step6】开启事务,确保余额锁定、异常回写和快递记录写入保持原子性。
return await app.model.transaction(async transaction => {
// 【step6】事务内先加载订单主表快照,后续所有判断都基于同一批视图。
const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(currentWarehouseId);
const orderItemsFactory = ctx.model && ctx.model.OrderItemsFactory;
const orderItemsModel = orderItemsFactory && typeof orderItemsFactory.getCurrentModel === 'function'
? await orderItemsFactory.getCurrentModel(currentWarehouseId)
: null;
if (!orderDeliveryModel
// 【step6】事务内先加载订单主表快照,后续所有判断都基于同一批视图。
const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(currentWarehouseId);
const orderItemsFactory = ctx.model && ctx.model.OrderItemsFactory;
const orderItemsModel = orderItemsFactory && typeof orderItemsFactory.getCurrentModel === 'function'
? await orderItemsFactory.getCurrentModel(currentWarehouseId)
: null;
if (!orderDeliveryModel
|| typeof orderDeliveryModel.findAll !== 'function'
|| typeof orderDeliveryModel.update !== 'function') {
throw new Error('订单主表模型未初始化');
}
const orderDeliveryInclude = [];
if (orderItemsModel) {
orderDeliveryInclude.push({
model: orderItemsModel,
as: 'orderItems',
attributes: ['id', 'order_id', 'item_code', 'item_name', 'plan_qty','source_order_code'],
required: false,
});
}
const orderDeliveryRows = await orderDeliveryModel.findAll({
// 保留后处理 order_list 需要的最小字段集,同时控制在 15 个字段以内。
// warehouse_id 由当前仓库 ID 兜底,因此不额外查询。
attributes: WAYBILL_ORDER_DELIVERY_MIN_ATTRIBUTES,
where: {
id: {
[Op.in]: normalizedOrders.map(order => order.order_id),
},
},
include: orderDeliveryInclude,
transaction,
});
const orderDeliveryMap = this.buildWaybillOrderDeliveryMap(orderDeliveryRows);
const existingCompletedRows = await orderExpressModel.findAll({
where: {
warehouse_id: currentWarehouseId,
[Op.or]: normalizedOrders.map(order => ({
order_id: order.order_id,
business_key: order.business_key,
})),
},
attributes: ['order_id', 'business_key', 'status'],
raw: true,
transaction,
});
const completedOrderKeySet = new Set();
for (const row of Array.isArray(existingCompletedRows) ? existingCompletedRows : []) {
const orderId = Number(row && row.order_id);
const businessKey = Number(row && row.business_key);
const status = Number(row && row.status);
if (Number.isFinite(orderId) && orderId > 0 && Number.isInteger(businessKey) && status === 1) {
completedOrderKeySet.add(`${orderId}:${businessKey}`);
}
}
const pendingOrders = normalizedOrders.filter(order => !completedOrderKeySet.has(`${order.order_id}:${order.business_key}`));
if (pendingOrders.length === 0) {
return {
orders: [],
waybill_codes: [],
};
}
const {
relationGroupMap,
missingOrderIds,
} = this.buildWaybillCreateRelationGroups(pendingOrders, orderDeliveryRows, currentWarehouseId);
const relationWhereList = Array.from(relationGroupMap.values()).map(group => ({
store_id: group.store_id,
warehouse_id: group.warehouse_id,
}));
const relationRows = relationWhereList.length > 0
? await storeWarehouseModel.findAll({
attributes: ['id', 'store_id', 'warehouse_id', 'print_quantity', 'print_quantity_locked', 'policy_config'],
where: {
[Op.or]: relationWhereList,
},
raw: true,
transaction,
lock: transaction.LOCK.UPDATE,
})
: [];
const relationMap = new Map();
for (const relation of Array.isArray(relationRows) ? relationRows : []) {
const relationKey = `${Number(relation.store_id || 0)}:${Number(relation.warehouse_id || 0)}`;
if (relationKey !== '0:0') {
relationMap.set(relationKey, relation);
}
}
const {
successOrderKeySet,
failedOrdersByReason,
balanceWarnings,
} = await this.collectWaybillRelationProcessingState(relationGroupMap, relationMap);
if (missingOrderIds.length > 0) {
const exceptionText = '订单不存在或不属于当前仓库';
failedOrdersByReason.set(exceptionText, (failedOrdersByReason.get(exceptionText) || []).concat(missingOrderIds));
}
// 【step5】事务内统一回写失败订单异常,避免成功与失败状态分离。
await this.writeWaybillOrderExceptions(orderDeliveryModel, failedOrdersByReason, transaction);
if (balanceWarnings.length > 0) {
ctx.logger.warn('[ExpressService.createWaybillCode] 余额不足但允许超额分配: %s', balanceWarnings.join(';'));
}
const successOrders = pendingOrders.filter(order => successOrderKeySet.has(`${order.order_id}:${order.business_key}`));
const existingRows = await orderExpressModel.findAll({
where: {
[Op.or]: successOrders.map(order => ({
order_id: order.order_id,
business_key: order.business_key,
warehouse_id: currentWarehouseId,
})),
},
attributes: ['id', 'order_id', 'business_key', 'status', 'retry_count','warehouse_id'],
raw: true,
transaction,
lock: transaction.LOCK.UPDATE,
});
const existingMap = new Map();
const retryIds = [];
for (const row of Array.isArray(existingRows) ? existingRows : []) {
const orderId = Number(row && row.order_id);
const businessKey = Number(row && row.business_key);
if (!Number.isFinite(orderId) || orderId <= 0 || !Number.isInteger(businessKey)) {
continue;
}
const orderKey = `${orderId}:${businessKey}`;
existingMap.set(orderKey, row);
// 过滤 status != 0 的已存在记录。
if (Number(row && row.status) === 0) {
retryIds.push(row.id);
}
}
// 【step6】先重置可重试记录,再补插缺失记录。
const retryableIds = Array.from(new Set(retryIds.filter(id => Number.isFinite(Number(id)) && Number(id) > 0)));
if (retryableIds.length > 0) {
await orderExpressModel.update({
retry_count: 0,
}, {
where: {
id: {
[Op.in]: retryableIds,
},
},
transaction,
});
}
const successOrdersWithDelivery = successOrders
.filter(order => {
const existingRow = existingMap.get(`${order.order_id}:${order.business_key}`);
return !existingRow || Number(existingRow.status) === 0;
})
.map(order => ({
...order,
order_delivery: orderDeliveryMap.get(order.order_id) || null,
}));
if (successOrdersWithDelivery.length > 0) {
const successOrderIds = Array.from(new Set(successOrdersWithDelivery
.map(order => Number(order.order_id))
.filter(orderId => Number.isFinite(orderId) && orderId > 0)));
if (successOrderIds.length > 0) {
await orderDeliveryModel.update({
step: 2,
updated_at: new Date(),
}, {
where: {
id: {
[Op.in]: successOrderIds,
},
},
transaction,
});
}
}
if (successOrdersWithDelivery.length === 0) {
return {
orders: [],
waybill_codes: [],
};
}
// 【step6】组装待插入记录,保持已存在且非 0 状态的记录不被覆盖。
const rowsToCreate = [];
for (const order of successOrders) {
const orderKey = `${order.order_id}:${order.business_key}`;
const existingRow = existingMap.get(orderKey);
if (existingRow) {
const status = Number(existingRow.status);
if (status !== 0) {
continue;
throw new Error('订单主表模型未初始化');
}
continue;
}
const orderDeliveryInclude = [];
if (orderItemsModel) {
orderDeliveryInclude.push({
model: orderItemsModel,
as: 'orderItems',
attributes: [ 'id', 'order_id', 'item_code', 'item_name', 'plan_qty', 'source_order_code' ],
required: false,
});
}
rowsToCreate.push({
order_id: order.order_id,
business_key: order.business_key,
status: 0,
retry_count: 0,
warehouse_id: this.getCurrentWarehouseId(),
});
}
const orderDeliveryRows = await orderDeliveryModel.findAll({
// 保留后处理 order_list 需要的最小字段集,同时控制在 15 个字段以内。
// warehouse_id 由当前仓库 ID 兜底,因此不额外查询。
attributes: WAYBILL_ORDER_DELIVERY_MIN_ATTRIBUTES,
where: {
id: {
[Op.in]: normalizedOrders.map(order => order.order_id),
},
},
include: orderDeliveryInclude,
transaction,
});
const orderDeliveryMap = this.buildWaybillOrderDeliveryMap(orderDeliveryRows);
const relationLockMap = this.buildWaybillRelationLockMap(successOrders, orderDeliveryMap, existingMap);
if (relationLockMap.size > 0) {
await this.lockWaybillRelationBalance(relationLockMap, relationMap, storeWarehouseModel, transaction);
}
const existingCompletedRows = await orderExpressModel.findAll({
where: {
warehouse_id: currentWarehouseId,
[Op.or]: normalizedOrders.map(order => ({
order_id: order.order_id,
business_key: order.business_key,
})),
},
attributes: [ 'order_id', 'business_key', 'status' ],
raw: true,
transaction,
});
// 【step6】批量插入新快递记录后,事务提交。
if (rowsToCreate.length > 0) {
await orderExpressModel.bulkCreate(rowsToCreate, {
transaction,
});
}
const completedOrderKeySet = new Set();
for (const row of Array.isArray(existingCompletedRows) ? existingCompletedRows : []) {
const orderId = Number(row && row.order_id);
const businessKey = Number(row && row.business_key);
const status = Number(row && row.status);
if (Number.isFinite(orderId) && orderId > 0 && Number.isInteger(businessKey) && status === 1) {
completedOrderKeySet.add(`${orderId}:${businessKey}`);
}
}
return {
orders: successOrdersWithDelivery,
waybill_codes: [],
};
const pendingOrders = normalizedOrders.filter(order => !completedOrderKeySet.has(`${order.order_id}:${order.business_key}`));
if (pendingOrders.length === 0) {
return {
orders: [],
waybill_codes: [],
};
}
const {
relationGroupMap,
missingOrderIds,
} = this.buildWaybillCreateRelationGroups(pendingOrders, orderDeliveryRows, currentWarehouseId);
const relationWhereList = Array.from(relationGroupMap.values()).map(group => ({
store_id: group.store_id,
warehouse_id: group.warehouse_id,
}));
const relationRows = relationWhereList.length > 0
? await storeWarehouseModel.findAll({
attributes: [ 'id', 'store_id', 'warehouse_id', 'print_quantity', 'print_quantity_locked', 'policy_config' ],
where: {
[Op.or]: relationWhereList,
},
raw: true,
transaction,
lock: transaction.LOCK.UPDATE,
})
: [];
const relationMap = new Map();
for (const relation of Array.isArray(relationRows) ? relationRows : []) {
const relationKey = `${Number(relation.store_id || 0)}:${Number(relation.warehouse_id || 0)}`;
if (relationKey !== '0:0') {
relationMap.set(relationKey, relation);
}
}
const {
successOrderKeySet,
failedOrdersByReason,
balanceWarnings,
} = await this.collectWaybillRelationProcessingState(relationGroupMap, relationMap);
if (missingOrderIds.length > 0) {
const exceptionText = '订单不存在或不属于当前仓库';
failedOrdersByReason.set(exceptionText, (failedOrdersByReason.get(exceptionText) || []).concat(missingOrderIds));
}
// 【step5】事务内统一回写失败订单异常,避免成功与失败状态分离。
await this.writeWaybillOrderExceptions(orderDeliveryModel, failedOrdersByReason, transaction);
if (balanceWarnings.length > 0) {
ctx.logger.warn('[ExpressService.createWaybillCode] 余额不足但允许超额分配: %s', balanceWarnings.join(';'));
}
const successOrders = pendingOrders.filter(order => successOrderKeySet.has(`${order.order_id}:${order.business_key}`));
const existingRows = await orderExpressModel.findAll({
where: {
[Op.or]: successOrders.map(order => ({
order_id: order.order_id,
business_key: order.business_key,
warehouse_id: currentWarehouseId,
})),
},
attributes: [ 'id', 'order_id', 'business_key', 'status', 'retry_count', 'warehouse_id' ],
raw: true,
transaction,
lock: transaction.LOCK.UPDATE,
});
const existingMap = new Map();
const retryIds = [];
for (const row of Array.isArray(existingRows) ? existingRows : []) {
const orderId = Number(row && row.order_id);
const businessKey = Number(row && row.business_key);
if (!Number.isFinite(orderId) || orderId <= 0 || !Number.isInteger(businessKey)) {
continue;
}
const orderKey = `${orderId}:${businessKey}`;
existingMap.set(orderKey, row);
// 过滤 status != 0 的已存在记录。
if (Number(row && row.status) === 0) {
retryIds.push(row.id);
}
}
// 【step6】先重置可重试记录,再补插缺失记录。
const retryableIds = Array.from(new Set(retryIds.filter(id => Number.isFinite(Number(id)) && Number(id) > 0)));
if (retryableIds.length > 0) {
await orderExpressModel.update({
retry_count: 0,
}, {
where: {
id: {
[Op.in]: retryableIds,
},
},
transaction,
});
}
const successOrdersWithDelivery = successOrders
.filter(order => {
const existingRow = existingMap.get(`${order.order_id}:${order.business_key}`);
return !existingRow || Number(existingRow.status) === 0;
})
.map(order => ({
...order,
order_delivery: orderDeliveryMap.get(order.order_id) || null,
}));
if (successOrdersWithDelivery.length > 0) {
const successOrderIds = Array.from(new Set(successOrdersWithDelivery
.map(order => Number(order.order_id))
.filter(orderId => Number.isFinite(orderId) && orderId > 0)));
if (successOrderIds.length > 0) {
await orderDeliveryModel.update({
step: 2,
updated_at: new Date(),
}, {
where: {
id: {
[Op.in]: successOrderIds,
},
},
transaction,
});
}
}
if (successOrdersWithDelivery.length === 0) {
return {
orders: [],
waybill_codes: [],
};
}
// 【step6】组装待插入记录,保持已存在且非 0 状态的记录不被覆盖。
const rowsToCreate = [];
for (const order of successOrders) {
const orderKey = `${order.order_id}:${order.business_key}`;
const existingRow = existingMap.get(orderKey);
if (existingRow) {
const status = Number(existingRow.status);
if (status !== 0) {
continue;
}
continue;
}
rowsToCreate.push({
order_id: order.order_id,
business_key: order.business_key,
status: 0,
retry_count: 0,
warehouse_id: this.getCurrentWarehouseId(),
});
}
const relationLockMap = this.buildWaybillRelationLockMap(successOrders, orderDeliveryMap, existingMap);
if (relationLockMap.size > 0) {
await this.lockWaybillRelationBalance(relationLockMap, relationMap, storeWarehouseModel, transaction);
}
// 【step6】批量插入新快递记录后,事务提交。
if (rowsToCreate.length > 0) {
await orderExpressModel.bulkCreate(rowsToCreate, {
transaction,
});
}
return {
orders: successOrdersWithDelivery,
waybill_codes: [],
};
});
} catch (err) {
const errorCode = err && err.parent && err.parent.code;
@ -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

@ -159,422 +159,422 @@ const MainService = require('../main');
* @property {number} items_weight 商品总重量。
*/
class ExpressPlatformService extends MainService {
/**
/**
* 菠萝派数据处理接口。
*
* @param {Object} [data={}] 平台业务入参。
* @return {Promise<never>} 当前暂未实现,直接抛出异常。
*/
async polyapi(data = {}) {
const { matchedPlatform, listByWarehousePlatformCode, orders } = data;
const ExpressList = await this.service.systems.express.loadExpressList();
console.log("matchedPlatform", JSON.stringify(matchedPlatform));
async polyapi(data = {}) {
const { matchedPlatform, listByWarehousePlatformCode, orders } = data;
const ExpressList = await this.service.systems.express.loadExpressList();
console.log('matchedPlatform', JSON.stringify(matchedPlatform));
console.log('接收到菠萝派快递接口入参:', JSON.stringify(listByWarehousePlatformCode));
console.log('接收到菠萝派快递接口入参:', JSON.stringify(listByWarehousePlatformCode));
console.log('接收到菠萝派平台数据处理请求,入参:', JSON.stringify(orders));
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') {
const { Op } = this.app.Sequelize;
const orderIdList = Array.from(new Set((Array.isArray(orders) ? orders : [])
.map(order => Number(order && order.order_id))
.filter(orderId => Number.isFinite(orderId) && orderId > 0)));
console.log('接收到菠萝派平台数据处理请求,入参:', JSON.stringify(orders));
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') {
const { Op } = this.app.Sequelize;
const orderIdList = Array.from(new Set((Array.isArray(orders) ? orders : [])
.map(order => Number(order && order.order_id))
.filter(orderId => Number.isFinite(orderId) && orderId > 0)));
if (orderIdList.length > 0) {
const allocatedWaybillRows = await orderExpressModel.findAll({
attributes: ['order_id', 'business_key', 'waybill_code'],
where: {
order_id: {
[Op.in]: orderIdList,
},
},
order: [['id', 'ASC']],
raw: true,
});
if (orderIdList.length > 0) {
const allocatedWaybillRows = await orderExpressModel.findAll({
attributes: [ 'order_id', 'business_key', 'waybill_code' ],
where: {
order_id: {
[Op.in]: orderIdList,
},
},
order: [[ 'id', 'ASC' ]],
raw: true,
});
for (const row of Array.isArray(allocatedWaybillRows) ? allocatedWaybillRows : []) {
const orderId = Number(row && row.order_id);
const businessKey = Number(row && row.business_key);
const waybillCode = String(row && row.waybill_code || '').trim();
if (!Number.isFinite(orderId) || orderId <= 0 || !Number.isFinite(businessKey) || businessKey <= 0 || !waybillCode) {
continue;
}
for (const row of Array.isArray(allocatedWaybillRows) ? allocatedWaybillRows : []) {
const orderId = Number(row && row.order_id);
const businessKey = Number(row && row.business_key);
const waybillCode = String(row && row.waybill_code || '').trim();
if (!Number.isFinite(orderId) || orderId <= 0 || !Number.isFinite(businessKey) || businessKey <= 0 || !waybillCode) {
continue;
}
const waybillKey = `${orderId}:${businessKey}`;
if (!allocatedWaybillMap.has(waybillKey)) {
allocatedWaybillMap.set(waybillKey, waybillCode);
}
}
}
const waybillKey = `${orderId}:${businessKey}`;
if (!allocatedWaybillMap.has(waybillKey)) {
allocatedWaybillMap.set(waybillKey, waybillCode);
}
}
const Dictionary_bizcontent = {
}
}
const Dictionary_bizcontent = {
};
const Dictionary_result = await this.service.systems.poloApi.request('Differ.JH.LogisticsPlatFeatures', Dictionary_bizcontent, matchedPlatform, listByWarehousePlatformCode.token);
console.log('==================\n菠萝派平台字典接口返回结果', JSON.stringify(Dictionary_result));
const order_bizcontent = {
orders: orders.map(order_tmp => {
const order = order_tmp.order_delivery;
return {
orderno: `${order.warehouse_id}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单号必须为字符串
plattradeno: order.source_order_codes || order.delivery_order_code || '',
ismultiplepieces: order.package_count > 1 ? 1 : 0,
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',
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,
packagemoney: order.item_amount ?? null,
weight: Number(order.items_weight) || 0,
supporpaymoney: order.total_amount ?? null,
length: Number(order.length) || 0,
width: Number(order.width) || 0,
height: Number(order.height) || 0,
volume: Number(order.volume) || 0,
ispickup: listByWarehousePlatformCode.ispickup ?? 0,
producttype: listByWarehousePlatformCode.product_type || '',
Sipshopid: listByWarehousePlatformCode.shop_id || '',
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',
dmssorting: 0,
needencrypt: 1,
ordersource: matchedPlatform.ordersource || '',
inputsite: listByWarehousePlatformCode.site_code || '',
sitecode: listByWarehousePlatformCode.site_code || '',
shipperno: listByWarehousePlatformCode.client_id || '',
sender: {
company: listByWarehousePlatformCode.shop_name || '',
name: listByWarehousePlatformCode.sender_name || '',
phone: listByWarehousePlatformCode.sender_tel || '',
mobile: listByWarehousePlatformCode.sender_tel || '',
country: 'CN',
city: listByWarehousePlatformCode.city_name || '',
province: listByWarehousePlatformCode.province_name || '',
area: listByWarehousePlatformCode.district_name || '',
town: listByWarehousePlatformCode.town_name || '',
address: listByWarehousePlatformCode.address || '',
}, // 需要实现
receiver: {
name: order.name || '',
company: order.company || '',
phone: order.mobile || order.tel || '',
mobile: order.mobile || order.tel || '',
country: order.country_code || 'CN',
province: order.province || '',
city: order.city || '',
area: order.area || '',
town: order.town || '',
address: order.detail_address || '',
zip: order.zip_code || '',
email: order.email || '',
},
goods: (order.orderItems && order.orderItems.map(item => ({
productid: item.item_code,
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 || '',
};
const Dictionary_result = await this.service.systems.poloApi.request('Differ.JH.LogisticsPlatFeatures', Dictionary_bizcontent, matchedPlatform, listByWarehousePlatformCode.token);
console.log('==================\n菠萝派平台字典接口返回结果', JSON.stringify(Dictionary_result));
}),
shoptype: matchedPlatform.shoptype,
};
// 调用菠萝派平台接口进行数据处理
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') {
throw new Error(`菠萝派平台接口返回错误信息:${result.submessage},原始错误信息: \`\`\`${JSON.stringify(result)}\`\`\`` || '菠萝派平台接口调用失败');
} else if (result && result.code === '10000') {
const resolveWaybillCode = item => String(item && (item.waybill_code || item.logisticno) || '').trim();
let successUpdates = [];
switch (listByWarehousePlatformCode.platform_code) {
case 'KS':
successUpdates = (result.results || []).map(item => {
const [ warehouse_id, order_id, business_key ] = String(item.orderno || '').split('_');
const waybillCode = resolveWaybillCode(item);
return {
warehouse_id,
order_id,
business_key,
waybill_code: waybillCode,
orderExpressValues: {
waybill_code: waybillCode,
printinfo: item.printinfo,
signature: item.signature,
encryptprintinfo: item.encryptprintinfo,
create_at: new Date(),
logistics_code: listByWarehousePlatformCode.logistics_code || '',
logistics_interface_id: listByWarehousePlatformCode.id || null,
logistics_name: listByWarehousePlatformCode.logistics_name || '',
logistics_interface_name: listByWarehousePlatformCode.name || '',
platform_code: listByWarehousePlatformCode.platform_code || '',
status: 1,
retry_count: 0,
},
orderDeliveryValues: {
post_status: 'fin',
order_flag: '',
},
};
});
break;
case 'DYXD':
successUpdates = (result.results || []).map(item => {
const [ warehouse_id, order_id, business_key ] = String(item.orderno || '').split('_');
const waybillCode = resolveWaybillCode(item);
return {
warehouse_id,
order_id,
business_key,
waybill_code: waybillCode,
orderExpressValues: {
waybill_code: waybillCode,
signature: item.signature,
encryptedtoken: item.encryptedtoken,
encryptprintinfo: item.encryptprintinfo,
create_at: new Date(),
logistics_code: listByWarehousePlatformCode.logistics_code || '',
logistics_interface_id: listByWarehousePlatformCode.id || null,
logistics_name: listByWarehousePlatformCode.logistics_name || '',
logistics_interface_name: listByWarehousePlatformCode.name || '',
platform_code: listByWarehousePlatformCode.platform_code || '',
status: 1,
retry_count: 0,
},
orderDeliveryValues: {
post_status: 'fin',
order_flag: '',
},
};
});
break;
case 'JD':
case 'XHS':
case 'SPH':
default:
break;
}
const order_bizcontent = {
orders: orders.map(order_tmp => {
const order = order_tmp.order_delivery;
return {
orderno: `${order.warehouse_id}_${order.id}_${order_tmp.business_key}`, // 菠萝派平台要求订单号必须为字符串
plattradeno: order.source_order_codes || order.delivery_order_code || '',
ismultiplepieces: order.package_count > 1 ? 1 : 0,
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",
const orderMetaMap = new Map();
for (const order of Array.isArray(orders) ? orders : []) {
const orderDelivery = order && order.order_delivery;
const warehouseId = Number(orderDelivery && orderDelivery.warehouse_id) || 0;
const orderId = Number(orderDelivery && orderDelivery.id) || 0;
const businessKey = Number(order && order.business_key) || 0;
if (!warehouseId || !orderId || !businessKey) {
continue;
}
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,
packagemoney: order.item_amount ?? null,
weight: Number(order.items_weight) || 0,
supporpaymoney: order.total_amount ?? null,
length: Number(order.length) || 0,
width: Number(order.width) || 0,
height: Number(order.height) || 0,
volume: Number(order.volume) || 0,
ispickup: listByWarehousePlatformCode.ispickup ?? 0,
producttype: listByWarehousePlatformCode.product_type || '',
Sipshopid: listByWarehousePlatformCode.shop_id || '',
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",
dmssorting: 0,
needencrypt: 1,
ordersource: matchedPlatform.ordersource || '',
inputsite: listByWarehousePlatformCode.site_code || '',
sitecode: listByWarehousePlatformCode.site_code || '',
shipperno: listByWarehousePlatformCode.client_id || '',
sender: {
company: listByWarehousePlatformCode.shop_name || '',
name: listByWarehousePlatformCode.sender_name || '',
phone: listByWarehousePlatformCode.sender_tel || '',
mobile: listByWarehousePlatformCode.sender_tel || '',
country: "CN",
city: listByWarehousePlatformCode.city_name || '',
province: listByWarehousePlatformCode.province_name || '',
area: listByWarehousePlatformCode.district_name || '',
town: listByWarehousePlatformCode.town_name || '',
address: listByWarehousePlatformCode.address || '',
}, // 需要实现
receiver: {
name: order.name || '',
company: order.company || '',
phone: order.mobile || order.tel || '',
mobile: order.mobile || order.tel || '',
country: order.country_code || 'CN',
province: order.province || '',
city: order.city || '',
area: order.area || '',
town: order.town || '',
address: order.detail_address || '',
zip: order.zip_code || '',
email: order.email || '',
orderMetaMap.set(`${warehouseId}_${orderId}_${businessKey}`, {
store_id: Number(orderDelivery && orderDelivery.store_id) || 0,
warehouse_id: warehouseId,
});
}
},
goods: (order.orderItems && order.orderItems.map(item => ({
productid: item.item_code,
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,
const settlementRelationMap = new Map();
for (const item of successUpdates) {
const warehouseId = Number(item.warehouse_id) || 0;
const orderId = Number(item.order_id) || 0;
const businessKey = Number(item.business_key) || 0;
if (!warehouseId || !orderId || !businessKey) {
continue;
}
const orderMeta = orderMetaMap.get(`${warehouseId}_${orderId}_${businessKey}`);
if (!orderMeta) {
continue;
}
const storeId = Number(orderMeta.store_id) || 0;
if (!storeId) {
continue;
}
const relationKey = `${storeId}:${warehouseId}`;
const currentRelation = settlementRelationMap.get(relationKey) || {
store_id: storeId,
warehouse_id: warehouseId,
success_count: 0,
};
//调用菠萝派平台接口进行数据处理
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') {
throw new Error(`菠萝派平台接口返回错误信息:${result.submessage},原始错误信息: \`\`\`${JSON.stringify(result)}\`\`\`` || '菠萝派平台接口调用失败');
} else if (result && result.code === '10000') {
const resolveWaybillCode = item => String(item && (item.waybill_code || item.logisticno) || '').trim();
let successUpdates = [];
switch (listByWarehousePlatformCode.platform_code) {
case 'KS':
successUpdates = (result.results || []).map(item => {
const [warehouse_id, order_id, business_key] = String(item.orderno || '').split('_');
const waybillCode = resolveWaybillCode(item);
return {
warehouse_id,
order_id,
business_key,
waybill_code: waybillCode,
orderExpressValues: {
waybill_code: waybillCode,
printinfo: item.printinfo,
signature: item.signature,
encryptprintinfo: item.encryptprintinfo,
create_at: new Date(),
logistics_code: listByWarehousePlatformCode.logistics_code || '',
logistics_interface_id: listByWarehousePlatformCode.id || null,
logistics_name: listByWarehousePlatformCode.logistics_name || '',
logistics_interface_name: listByWarehousePlatformCode.name || '',
platform_code: listByWarehousePlatformCode.platform_code || '',
status: 1,
retry_count: 0,
},
orderDeliveryValues: {
post_status: 'fin',
order_flag: '',
},
};
});
break;
case 'DYXD':
successUpdates = (result.results || []).map(item => {
const [warehouse_id, order_id, business_key] = String(item.orderno || '').split('_');
const waybillCode = resolveWaybillCode(item);
return {
warehouse_id,
order_id,
business_key,
waybill_code: waybillCode,
orderExpressValues: {
waybill_code: waybillCode,
signature: item.signature,
encryptedtoken: item.encryptedtoken,
encryptprintinfo: item.encryptprintinfo,
create_at: new Date(),
logistics_code: listByWarehousePlatformCode.logistics_code || '',
logistics_interface_id: listByWarehousePlatformCode.id || null,
logistics_name: listByWarehousePlatformCode.logistics_name || '',
logistics_interface_name: listByWarehousePlatformCode.name || '',
platform_code: listByWarehousePlatformCode.platform_code || '',
status: 1,
retry_count: 0,
},
orderDeliveryValues: {
post_status: 'fin',
order_flag: '',
},
};
});
break;
case 'JD':
case 'XHS':
case 'SPH':
default:
break;
currentRelation.success_count += 1;
settlementRelationMap.set(relationKey, currentRelation);
}
const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse;
if (typeof this.ctx.model.transaction === 'function' && successUpdates.length > 0) {
await this.ctx.model.transaction(async transaction => {
for (const item of successUpdates) {
const warehouseId = Number(item.warehouse_id) || 0;
const orderId = Number(item.order_id) || 0;
const businessKey = Number(item.business_key) || 0;
if (!warehouseId || !orderId || !businessKey) {
continue;
}
const orderMetaMap = new Map();
for (const order of Array.isArray(orders) ? orders : []) {
const orderDelivery = order && order.order_delivery;
const warehouseId = Number(orderDelivery && orderDelivery.warehouse_id) || 0;
const orderId = Number(orderDelivery && orderDelivery.id) || 0;
const businessKey = Number(order && order.business_key) || 0;
if (!warehouseId || !orderId || !businessKey) {
continue;
}
await this.ctx.model.OrderExpress.update(item.orderExpressValues, {
where: {
order_id: orderId,
business_key: businessKey,
warehouse_id: warehouseId,
},
transaction,
});
orderMetaMap.set(`${warehouseId}_${orderId}_${businessKey}`, {
store_id: Number(orderDelivery && orderDelivery.store_id) || 0,
warehouse_id: warehouseId,
});
if (item.orderDeliveryValues) {
const orderModel = await this.service.systems.express.getWaybillAsyncOrderDeliveryModel(item.warehouse_id);
await orderModel.update(item.orderDeliveryValues, {
where: {
id: orderId,
},
transaction,
});
}
}
const settlementRelationMap = new Map();
for (const item of successUpdates) {
const warehouseId = Number(item.warehouse_id) || 0;
const orderId = Number(item.order_id) || 0;
const businessKey = Number(item.business_key) || 0;
if (!warehouseId || !orderId || !businessKey) {
continue;
}
const orderMeta = orderMetaMap.get(`${warehouseId}_${orderId}_${businessKey}`);
if (!orderMeta) {
continue;
}
const storeId = Number(orderMeta.store_id) || 0;
if (!storeId) {
continue;
}
const relationKey = `${storeId}:${warehouseId}`;
const currentRelation = settlementRelationMap.get(relationKey) || {
store_id: storeId,
warehouse_id: warehouseId,
success_count: 0,
};
currentRelation.success_count += 1;
settlementRelationMap.set(relationKey, currentRelation);
}
const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse;
if (typeof this.ctx.model.transaction === 'function' && successUpdates.length > 0) {
await this.ctx.model.transaction(async transaction => {
for (const item of successUpdates) {
const warehouseId = Number(item.warehouse_id) || 0;
const orderId = Number(item.order_id) || 0;
const businessKey = Number(item.business_key) || 0;
if (!warehouseId || !orderId || !businessKey) {
continue;
}
await this.ctx.model.OrderExpress.update(item.orderExpressValues, {
where: {
order_id: orderId,
business_key: businessKey,
warehouse_id: warehouseId,
},
transaction,
});
if (item.orderDeliveryValues) {
const orderModel = await this.service.systems.express.getWaybillAsyncOrderDeliveryModel(item.warehouse_id);
await orderModel.update(item.orderDeliveryValues, {
where: {
id: orderId,
},
transaction,
});
}
}
if (storeWarehouseModel
if (storeWarehouseModel
&& typeof storeWarehouseModel.findAll === 'function'
&& settlementRelationMap.size > 0) {
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'],
where: {
[Op.or]: relationList.map(item => ({
store_id: item.store_id,
warehouse_id: item.warehouse_id,
})),
},
raw: true,
transaction,
lock: transaction.LOCK.UPDATE,
});
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' ],
where: {
[Op.or]: relationList.map(item => ({
store_id: item.store_id,
warehouse_id: item.warehouse_id,
})),
},
raw: true,
transaction,
lock: transaction.LOCK.UPDATE,
});
const relationRowMap = new Map();
for (const row of Array.isArray(relationRows) ? relationRows : []) {
const relationKey = `${Number(row && row.store_id) || 0}:${Number(row && row.warehouse_id) || 0}`;
if (relationKey !== '0:0') {
relationRowMap.set(relationKey, row);
}
}
for (const item of relationList) {
const relationKey = `${item.store_id}:${item.warehouse_id}`;
const row = relationRowMap.get(relationKey);
if (!row) {
continue;
}
const currentPrintQuantity = Number(row.print_quantity || 0);
const currentLockedQuantity = Math.max(0, Number(row.print_quantity_locked || 0));
const successCount = Number(item.success_count || 0);
if (successCount <= 0) {
continue;
}
const printDecrement = successCount;
const lockedDecrement = Math.min(currentLockedQuantity, printDecrement);
const nextPrintQuantity = currentPrintQuantity - printDecrement;
const nextLockedQuantity = Math.max(0, currentLockedQuantity - lockedDecrement);
await storeWarehouseModel.update({
print_quantity: nextPrintQuantity,
print_quantity_locked: nextLockedQuantity,
}, {
where: {
id: row.id,
},
transaction,
});
await this.ctx.model.StoreWarehousePrintQuantityLog.create({
contract_id: Number(row.id || 0),
store_id: Number(row.store_id || 0),
warehouse_id: Number(row.warehouse_id || 0),
change_type: 'order_deduct',
business_type: 'order_express',
business_id: null,
change_quantity: -printDecrement,
balance_before: Math.max(0, currentPrintQuantity),
balance_after: Math.max(0, nextPrintQuantity),
reason: '获取快递号成功扣减',
operator_id: null,
created_by: null,
}, {
transaction,
});
}
}
});
for (const item of successUpdates) {
const warehouseId = Number(item.warehouse_id) || 0;
const orderId = Number(item.order_id) || 0;
if (!warehouseId || !orderId) {
continue;
}
await this.service.systems.operationLog.createOperationLog({
businessType: 'order',
businessId: `${orderId}`,
operationCode: 'WAYBILL',
operatorId: this.ctx.user ? this.ctx.user.id : 'system',
operatorName: this.ctx.user ? this.ctx.user.employees_name : '系统',
externalLogType: 'API',
operator: {
id: this.ctx.user ? this.ctx.user.employees_id : '0',
name: this.ctx.user ? this.ctx.user.employees_name : '系统',
},
extras: {
message: `订单${orderId}获取快递单成功,单号:${item.waybill_code}`,
warehouseId,
}
});
}
const relationRowMap = new Map();
for (const row of Array.isArray(relationRows) ? relationRows : []) {
const relationKey = `${Number(row && row.store_id) || 0}:${Number(row && row.warehouse_id) || 0}`;
if (relationKey !== '0:0') {
relationRowMap.set(relationKey, row);
}
}
}
return {
flag: true,
code: 0,
message: '菠萝派平台数据处理成功',
data: result,
};
//throw new Error('菠萝派平台接口未实现');
}
/**
for (const item of relationList) {
const relationKey = `${item.store_id}:${item.warehouse_id}`;
const row = relationRowMap.get(relationKey);
if (!row) {
continue;
}
const currentPrintQuantity = Number(row.print_quantity || 0);
const currentLockedQuantity = Math.max(0, Number(row.print_quantity_locked || 0));
const successCount = Number(item.success_count || 0);
if (successCount <= 0) {
continue;
}
const printDecrement = successCount;
const lockedDecrement = Math.min(currentLockedQuantity, printDecrement);
const nextPrintQuantity = currentPrintQuantity - printDecrement;
const nextLockedQuantity = Math.max(0, currentLockedQuantity - lockedDecrement);
await storeWarehouseModel.update({
print_quantity: nextPrintQuantity,
print_quantity_locked: nextLockedQuantity,
}, {
where: {
id: row.id,
},
transaction,
});
await this.ctx.model.StoreWarehousePrintQuantityLog.create({
contract_id: Number(row.id || 0),
store_id: Number(row.store_id || 0),
warehouse_id: Number(row.warehouse_id || 0),
change_type: 'order_deduct',
business_type: 'order_express',
business_id: null,
change_quantity: -printDecrement,
balance_before: Math.max(0, currentPrintQuantity),
balance_after: Math.max(0, nextPrintQuantity),
reason: '获取快递号成功扣减',
operator_id: null,
created_by: null,
}, {
transaction,
});
}
}
});
for (const item of successUpdates) {
const warehouseId = Number(item.warehouse_id) || 0;
const orderId = Number(item.order_id) || 0;
if (!warehouseId || !orderId) {
continue;
}
await this.service.systems.operationLog.createOperationLog({
businessType: 'order',
businessId: `${orderId}`,
operationCode: 'WAYBILL',
operatorId: this.ctx.user ? this.ctx.user.id : 'system',
operatorName: this.ctx.user ? this.ctx.user.employees_name : '系统',
externalLogType: 'API',
operator: {
id: this.ctx.user ? this.ctx.user.employees_id : '0',
name: this.ctx.user ? this.ctx.user.employees_name : '系统',
},
extras: {
message: `订单${orderId}获取快递单成功,单号:${item.waybill_code}`,
warehouseId,
},
});
}
}
}
return {
flag: true,
code: 0,
message: '菠萝派平台数据处理成功',
data: result,
};
// throw new Error('菠萝派平台接口未实现');
}
/**
* 菜鸟数据处理接口。
*
* @param {Object} [data={}] 平台业务入参。
* @return {Promise<never>} 当前暂未实现,直接抛出异常。
*/
async cainiao(data = {}) {
void data;
console.log('接收到菜鸟平台数据处理请求,入参:', JSON.stringify(data));
throw new Error('菜鸟平台接口未实现');
}
async cainiao(data = {}) {
void data;
console.log('接收到菜鸟平台数据处理请求,入参:', JSON.stringify(data));
throw new Error('菜鸟平台接口未实现');
}
/**
/**
* 拼多多数据处理接口。
*
* @param {Object} [data={}] 平台业务入参。
* @return {Promise<never>} 当前暂未实现,直接抛出异常。
*/
async pdd(data = {}) {
void data;
console.log('接收到拼多多平台数据处理请求,入参:', JSON.stringify(data));
async pdd(data = {}) {
void data;
console.log('接收到拼多多平台数据处理请求,入参:', JSON.stringify(data));
throw new Error('拼多多平台接口未实现');
}
throw new Error('拼多多平台接口未实现');
}
}
module.exports = ExpressPlatformService;

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

@ -3,6 +3,70 @@
const Service = require('egg').Service;
class LocationZoneService extends Service {
async collectZoneSubtree(rootId, transaction) {
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const zoneIds = [ Number(rootId) ];
const zones = [];
let parentIds = [ Number(rootId) ];
while (parentIds.length > 0) {
const children = await ctx.model.LocationZone.findAll({
where: {
parent_id: {
[Op.in]: parentIds,
},
deleted_at: null,
},
raw: true,
transaction,
});
if (!Array.isArray(children) || children.length === 0) {
break;
}
zones.push(...children);
parentIds = children
.map(item => Number(item && item.id))
.filter(childId => Number.isFinite(childId) && childId > 0);
zoneIds.push(...parentIds);
}
return {
zoneIds,
zones,
};
}
async assertSpacesNotOccupied(spaceIds, transaction) {
if (!Array.isArray(spaceIds) || spaceIds.length === 0) {
return;
}
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const stockCount = await ctx.model.Storage.count({
where: {
space_id: {
[Op.in]: spaceIds,
},
delete_at: null,
is_enabled: 1,
[Op.or]: [
{ quantity: { [Op.gt]: 0 } },
{ locked_quantity: { [Op.gt]: 0 } },
{ available_quantity: { [Op.gt]: 0 } },
],
},
transaction,
});
if (stockCount > 0) {
throw new Error('删除范围内库位有库存,禁止删除,请先移库');
}
}
/**
* 获取所有仓库级别的分区列表
* @param {number|string} warehouseId 仓库ID
@ -759,22 +823,57 @@ class LocationZoneService extends Service {
if (!zone) {
throw new Error('分区不存在');
}
// 检查是否有子分区
const childrenCount = await ctx.model.LocationZone.count({
where: {
parent_id: id,
deleted_at: null,
},
await ctx.model.transaction(async transaction => {
const { Op } = ctx.app.Sequelize;
const { zoneIds, zones } = await this.collectZoneSubtree(id, transaction);
const rackZoneIds = [ zone, ...zones ]
.filter(item => item && item.zone_type === 'rack')
.map(item => Number(item.id))
.filter(zoneId => Number.isFinite(zoneId) && zoneId > 0);
const spaceZoneIds = zone.zone_type === 'rack'
? zoneIds
: rackZoneIds;
const spaces = await ctx.model.LocationSpace.findAll({
where: {
zone_id: {
[Op.in]: spaceZoneIds,
},
deleted_at: null,
},
attributes: [ 'id' ],
raw: true,
transaction,
});
const spaceIds = (Array.isArray(spaces) ? spaces : [])
.map(space => Number(space && space.id))
.filter(spaceId => Number.isFinite(spaceId) && spaceId > 0);
await this.assertSpacesNotOccupied(spaceIds, transaction);
if (spaceIds.length > 0) {
await ctx.model.LocationSpace.destroy({
where: {
id: {
[Op.in]: spaceIds,
},
},
transaction,
});
}
await ctx.model.LocationZone.destroy({
where: {
id: {
[Op.in]: zoneIds,
},
},
transaction,
});
});
if (zone.zone_type === 'rack') {
// 货架执行删除需要检测库位是否还有库存
throw new Error('货架XX库位有库存,禁止删除,请先移库');
}
if (childrenCount > 0) {
throw new Error('请先删除或转移所有子分区');
}
// 执行软删除
await zone.destroy();
return {
success: true,
message: '删除成功',
@ -953,35 +1052,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 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 +1105,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 +1114,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 +1127,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

@ -160,6 +160,19 @@ class operationLogService extends Service {
return await this.queryLogsByBusinessType(query, 'order');
}
/**
* 查询收货单操作日志。
* @param {Object} query 查询参数。
* @param {string|number} query.id 收货单ID。
* @param {string|number} query.warehouseId 仓库ID。
* @param {number} [query.page=1] 页码。
* @param {number} [query.pageSize=20] 每页数量。
* @return {Promise<{list: Object[], pagination: Object}>} 分页结果。
*/
async queryReceivingLogs(query = {}) {
return await this.queryLogsByBusinessType(query, 'receiving');
}
async getMessageDetail(data) {
const { id, type } = data;
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: {
@ -1119,4 +1119,4 @@ class OrderAsyncService extends MainService {
}
}
module.exports = OrderAsyncService;
module.exports = OrderAsyncService;

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,12 +3,12 @@
const Service = require('egg').Service;
const result = {
platform:null,
count:0,
datas:[],
platform: null,
count: 0,
datas: [],
};
class PrintDataService extends Service {
async getPrintData({ printType, orderId }) {
const { ctx } = this;
switch (printType) {
@ -22,4 +22,4 @@ class PrintDataService extends Service {
}
}
module.exports = PrintDataService;
module.exports = PrintDataService;

View File

@ -25,4 +25,4 @@ class QimenQueryService extends Service {
}
}
module.exports = QimenQueryService;
module.exports = QimenQueryService;

View File

@ -402,7 +402,7 @@ class SettingExpressInterfaceService extends Service {
express_code: this.normalizeOptionalText(row.express_code, 'express_code', 255),
warehouse_id: row.warehouse_id === undefined || row.warehouse_id === null ? null : Number(row.warehouse_id),
platform_code: this.normalizeOptionalText(row.platform_code, 'platform_code', 20),
sender_name: this.normalizeOptionalText(row.sender_name, 'sender_name', 50),
sender_name: this.normalizeOptionalText(row.sender_name, 'sender_name', 50),
sender_tel: this.normalizeOptionalText(row.sender_tel, 'sender_tel', 11),
weight: row.weight === undefined || row.weight === null ? null : Number(row.weight),
token: this.normalizeOptionalText(row.token, 'token', 500),
@ -801,7 +801,7 @@ class SettingExpressInterfaceService extends Service {
const name = this.normalizeText(data.name, 'name', 255);
const expressCode = this.normalizeText(data.express_code || data.expressCode, 'express_code', 255).toUpperCase();
const platformCode = this.normalizeText(data.platform_code || data.platformCode, 'platform_code', 20).toUpperCase();
if (!name) {
throw this.createError('name 参数不能为空', 400);

View File

@ -425,8 +425,8 @@ class stockStoreService extends Service {
const cacheKey = `storages:${itemId}`;
if (app && typeof app.delCacheAsync === 'function') {
try {
await app.delCacheAsync(cacheKey);
app.logger.debug(`[缓存清理] 商品 ${itemId} 库存缓存已清理`);
await app.delCacheAsync(cacheKey);
app.logger.debug(`[缓存清理] 商品 ${itemId} 库存缓存已清理`);
} catch (error) {
app.logger.warn(`[缓存清理失败] 商品 ${itemId}`, error.message);
}

View File

@ -207,9 +207,10 @@ class InventoryService extends Service {
* 从收货单直接生成入库单并写入库存。
*
* 流程:
* 1. 校验收货单状态(必须 completed)
* 2. 校验所有明细已匹配系统商品(system_product_id 不为空)
* 3. 校验未全部入库(storage_status !== 'all')
* 1. 校验收货单状态(必须 completed)
* 2. 校验收货单已审核(is_review = 1)
* 3. 校验所有明细已匹配系统商品(system_product_id 不为空)
* 4. 校验未全部入库(storage_status !== 'all')
* 4. 事务内:
* a. 创建入库单(EntryOrder)和入库明细(EntryItems)
* b. 逐条锁定 StockWarehouse 行,增加 quantity
@ -257,6 +258,35 @@ class InventoryService extends Service {
await transaction.rollback();
return { code: 400, message: `收货单状态为 ${receiving.status},须完成收货后才能入库`, data: null };
}
if (Number(receiving.is_review) !== 1) {
await transaction.rollback();
return { code: 400, message: '收货单未审核,审核通过后才能入库', data: null };
}
const storeRelation = await ctx.model.StoreWarehouse.findOne({
where: {
warehouse_id: warehouseId,
store_id: Number(receiving.store_id || 0),
use_status: 1,
},
attributes: [ 'id', 'policy_config', 'store_remask' ],
lock: transaction.LOCK.UPDATE,
transaction,
});
if (!storeRelation) {
await transaction.rollback();
return { code: 404, message: '收货单绑定的货主与当前仓库不存在有效签约关系', data: null };
}
const policyConfig = storeRelation.policy_config && typeof storeRelation.policy_config === 'object'
? storeRelation.policy_config
: {};
if (Number(policyConfig.allow_receiving_quick_putaway) !== 1) {
const storeName = String(storeRelation.store_remask || receiving.store_name || receiving.store_id || '当前货主');
await transaction.rollback();
return { code: 400, message: `货主${storeName}不允许快速上架,如需开启请到:货主->策略配置调整`, data: null };
}
if (receiving.storage_status === 'all') {
await transaction.rollback();
@ -640,6 +670,16 @@ class InventoryService extends Service {
return { code: 404, message: '未找到符合条件的收货单', data: null };
}
const unreviewedReceiving = receivings.find(item => Number(item.is_review) !== 1);
if (unreviewedReceiving) {
await transaction.rollback();
return {
code: 400,
message: `收货单 ${unreviewedReceiving.receiving_number || unreviewedReceiving.id} 未审核,审核通过后才能入库`,
data: null,
};
}
// ────────── 4. 查询并锁定入库单 ──────────
const entryOrders = await ctx.model.EntryOrder.findAll({
where: {

File diff suppressed because it is too large Load Diff

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

@ -90,4 +90,4 @@ module.exports = {
);
}
},
};
};

View File

@ -104,4 +104,4 @@ module.exports = {
}
}
},
};
};

View File

@ -6788,6 +6788,93 @@
}
]
},
{
"method": "storage.receiving.rejectReceiving",
"description": "驳回收货单:将已完成(completed)的收货单批量恢复为收货中(receiving),记录驳回人信息和驳回理由。若任意一张收货单状态非 completed,则整批拒绝操作。驳回人信息(reviewer_name、reviewer_employee_id)自动取当前登录用户上下文,无需传入.",
"isNeedAuth": true,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token"
}
],
"params": [
{
"name": "ids",
"type": "array",
"required": true,
"source": "body",
"description": "收货单ID数组,所有收货单必须属于当前仓库且状态为 completed,否则整批拒绝"
},
{
"name": "remark",
"type": "string",
"required": false,
"source": "body",
"description": "驳回理由,覆盖收货单原备注字段;不传则保留原备注"
}
],
"response": [
{
"name": "count",
"type": "number",
"description": "成功驳回的收货单数量"
}
],
"errors": [
{
"code": "0",
"description": "ids 为空、部分单据不存在/无权访问,或存在非 completed 状态的收货单"
},
{
"code": "500",
"description": "服务器错误"
}
]
},
{
"method": "storage.receiving.reviewReceiving",
"description": "批量审核收货单:校验所有单据满足条件(收货完成、全部匹配、未入库、已绑定货主、未审核)后统一审核,任意一张不符合则整批失败回滚。审核人信息自动取当前登录用户上下文,无需传入.",
"isNeedAuth": true,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token"
}
],
"params": [
{
"name": "ids",
"type": "array",
"required": true,
"source": "body",
"description": "收货单ID数组,所有单据必须满足:status=completed、detail_status=all_matched、storage_status=none、store_id 已绑定、is_review=0,否则整批拒绝"
}
],
"response": [
{
"name": "count",
"type": "number",
"description": "成功审核的收货单数量"
}
],
"errors": [
{
"code": "0",
"description": "ids 为空、单据不存在/无权访问,或不满足审核条件(含并发冲突)"
},
{
"code": "500",
"description": "服务器错误,事务已回滚"
}
]
},
{
"method": "storage.receiving.create",
"description": "storage.receiving.create 接口",
@ -7008,7 +7095,7 @@
"errors": [
{
"code": "400",
"description": "用户未绑定仓库、明细ID/商品ID为空,或收货单状态不允许绑定/改绑"
"description": "用户未绑定仓库、明细ID/商品ID为空,收货单状态不允许绑定/改绑,或收货单已审核禁止绑定/改绑"
},
{
"code": "404",
@ -7020,6 +7107,81 @@
}
]
},
{
"method": "storage.receiving.queryReceivingLogs",
"description": "按收货单ID查询操作日志列表(分页),仅返回当前仓库上下文数据",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token"
}
],
"params": [
{
"name": "id",
"type": "number|string",
"required": false,
"source": "body",
"description": "收货单ID(与 receiving_id 二选一)"
},
{
"name": "receiving_id",
"type": "number|string",
"required": false,
"source": "body",
"description": "收货单ID(兼容字段,与 id 二选一)"
},
{
"name": "page",
"type": "number",
"required": false,
"source": "body",
"description": "页码(兼容顶层分页入参)"
},
{
"name": "pageSize",
"type": "number",
"required": false,
"source": "body",
"description": "每页数量(兼容顶层分页入参)"
},
{
"name": "pagination",
"type": "object",
"required": false,
"source": "body",
"description": "分页参数,支持 page / pageSize"
}
],
"response": [
{
"name": "list",
"type": "array",
"required": true,
"description": "日志列表"
},
{
"name": "pagination",
"type": "object",
"required": true,
"description": "分页信息,包含 page、pageSize、total、totalPages"
}
],
"errors": [
{
"code": "400",
"description": "收货单ID为空或仓库上下文缺失"
},
{
"code": "500",
"description": "查询失败"
}
]
},
{
"method": "storage.receiving.addItem",
"description": "storage.receiving.addItem 接口",
@ -7085,8 +7247,8 @@
"errors": []
},
{
"method": "storage.receiving.saveReceiving",
"description": "storage.receiving.saveReceiving 接口",
"method": "storage.receiving.save",
"description": "修改收货单基础信息。按收货单ID更新当前仓库下收货单的基础字段。",
"isNeedAuth": true,
"isNeedLogin": true,
"headers": [
@ -7097,9 +7259,125 @@
"description": "Bearer token"
}
],
"params": [],
"response": [],
"errors": []
"params": [
{
"name": "id",
"type": "number",
"required": true,
"source": "body",
"description": "收货单ID,按该ID修改当前仓库下的收货单"
},
{
"name": "delivery_method",
"type": "string",
"required": false,
"source": "body",
"description": "到货方式:truck/express/air_freight/sea_freight/other;不传则保持原值"
},
{
"name": "loading_method",
"type": "string",
"required": false,
"source": "body",
"description": "装卸方式:with_pallet/without_pallet;不传则保持原值"
},
{
"name": "license_plate",
"type": "string",
"required": false,
"source": "body",
"description": "车牌号;当 delivery_method=truck 时可更新,其他到货方式会被清空或忽略"
},
{
"name": "tracking_number",
"type": "string",
"required": false,
"source": "body",
"description": "物流单号;当 delivery_method 为 express/air_freight/sea_freight 时可更新,truck/other 场景会被清空或忽略"
},
{
"name": "store_id",
"type": "number",
"required": false,
"source": "body",
"description": "货主ID;若传入,会校验当前仓库下签约关系并同步更新货主名称;传 0/null 可清空货主"
},
{
"name": "total_boxes",
"type": "number",
"required": false,
"source": "body",
"description": "总箱数,默认 0"
},
{
"name": "total_pallets",
"type": "number",
"required": false,
"source": "body",
"description": "总托盘数,默认 0"
},
{
"name": "remark",
"type": "string",
"required": false,
"source": "body",
"description": "备注信息"
},
{
"name": "status",
"type": "string",
"required": false,
"source": "body",
"description": "收货单状态;不传则保持原值"
},
{
"name": "video_device_id",
"type": "string",
"required": false,
"source": "body",
"description": "录像设备ID"
}
],
"response": [
{
"name": "code",
"type": "number",
"required": true,
"description": "业务状态码;200 表示修改成功"
},
{
"name": "id",
"type": "number",
"required": true,
"description": "修改的收货单ID"
},
{
"name": "receiving_number",
"type": "string",
"required": true,
"description": "收货单号"
},
{
"name": "message",
"type": "string",
"required": true,
"description": "结果描述;成功时通常为收货单修改成功"
}
],
"errors": [
{
"code": "400",
"description": "收货单ID不能为空、已取消的收货单不允许修改或用户未绑定仓库"
},
{
"code": "404",
"description": "收货单不存在/无权访问,或指定货主不存在/未与当前仓库建立有效签约关系"
},
{
"code": "0",
"description": "修改失败,如字段枚举不合法或数据库写入异常"
}
]
},
{
"method": "storage.receiving.get",
@ -7788,7 +8066,7 @@
"list": [
{
"method": "storage.inventory.quickPutaway",
"description": "收货单快捷入库上架。从收货单直接生成入库单并写入库存表,要求收货单已完成且所有明细已匹配系统商品",
"description": "收货单快捷入库上架。从收货单直接生成入库单并写入库存表,要求收货单已完成、已审核、货主已开启快捷入库策略且所有明细已匹配系统商品",
"isNeedAuth": true,
"isNeedLogin": true,
"params": [
@ -7829,10 +8107,22 @@
"code": 400,
"message": "收货单状态须为已完成"
},
{
"code": 400,
"message": "收货单未审核,审核通过后才能入库"
},
{
"code": 400,
"message": "货主xxxx不允许快速上架,如需开启请到:货主->策略配置调整"
},
{
"code": 400,
"message": "商品未匹配系统商品"
},
{
"code": 404,
"message": "收货单绑定的货主与当前仓库不存在有效签约关系"
},
{
"code": 400,
"message": "已全部入库无需重复操作"
@ -7849,7 +8139,7 @@
},
{
"method": "storage.inventory.matchPutaway",
"description": "收货单与入库单匹配入库。接收多个收货单和入库单,按商品(stock_warehouse_id)进行数量匹配入库,完成后根据入库单来源(QM/API)自动触发回传",
"description": "收货单与入库单匹配入库。接收多个收货单和入库单,按商品(stock_warehouse_id)进行数量匹配入库,要求收货单已完成且已审核,完成后根据入库单来源(QM/API)自动触发回传",
"isNeedAuth": true,
"isNeedLogin": true,
"params": [
@ -7902,6 +8192,10 @@
"code": 404,
"message": "收货单不存在或无权访问"
},
{
"code": 400,
"message": "收货单未审核,审核通过后才能入库"
},
{
"code": 404,
"message": "入库单不存在或无权访问"
@ -9771,129 +10065,6 @@
"response": [],
"errors": []
},
{
"method": "warehouse.createRack",
"description": "warehouse.createRack 接口",
"isNeedAuth": true,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token"
}
],
"params": [
{
"name": "height",
"type": "number",
"required": true,
"source": "body",
"description": "height 参数"
},
{
"name": "length",
"type": "number",
"required": true,
"source": "body",
"description": "length 参数"
},
{
"name": "rack_columns",
"type": "number",
"required": true,
"source": "body",
"description": "rack_columns 参数"
},
{
"name": "rack_levels",
"type": "number",
"required": true,
"source": "body",
"description": "rack_levels 参数"
},
{
"name": "rack_rows",
"type": "number",
"required": true,
"source": "body",
"description": "rack_rows 参数"
},
{
"name": "warehouse_id",
"type": "number",
"required": true,
"source": "body",
"description": "warehouse_id 参数"
},
{
"name": "width",
"type": "number",
"required": true,
"source": "body",
"description": "width 参数"
},
{
"name": "x",
"type": "number",
"required": true,
"source": "body",
"description": "x 参数"
},
{
"name": "y",
"type": "number",
"required": true,
"source": "body",
"description": "y 参数"
},
{
"name": "zone_code",
"type": "string",
"required": true,
"source": "body",
"description": "zone_code 参数"
},
{
"name": "zone_name",
"type": "string",
"required": true,
"source": "body",
"description": "zone_name 参数"
},
{
"name": "color",
"type": "string",
"required": false,
"source": "body",
"description": "color 参数"
},
{
"name": "direction",
"type": "string",
"required": false,
"source": "body",
"description": "direction 参数"
},
{
"name": "parent_id",
"type": "number",
"required": false,
"source": "body",
"description": "parent_id 参数"
},
{
"name": "z",
"type": "number",
"required": false,
"source": "body",
"description": "z 参数"
}
],
"response": [],
"errors": []
},
{
"method": "warehouse.getPickPath",
"description": "warehouse.getPickPath 接口",

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-30T11:15:00.002Z"
}

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 = {};
@ -29,27 +29,27 @@ try {
if (sign !== providedSign) {
console.log('---');
console.log('Mismatch reason analysis:');
// 1. CanonicalQuery check
const expectedCanonicalQuery = 'app_key=APP2024011514301234&method=openapi.index&timestamp=1777222912&v=1.0';
if (canonicalQuery !== expectedCanonicalQuery) {
console.log(`- CanonicalQuery calculation might be incorrect. Expected "${expectedCanonicalQuery}" but got "${canonicalQuery}". This could be due to wrong sorting order or incorrect handling of parameters.`);
console.log(`- CanonicalQuery calculation might be incorrect. Expected "${expectedCanonicalQuery}" but got "${canonicalQuery}". This could be due to wrong sorting order or incorrect handling of parameters.`);
}
// 2. BodySign check
const crypto = require('crypto');
const expectedBodySign = crypto.createHash('md5').update('{}').digest('hex');
if (bodySign !== expectedBodySign) {
console.log(`- BodySign calculation might be incorrect. For an empty object {}, expected "${expectedBodySign}" but got "${bodySign}". This could be due to differences in JSON serialization (e.g., whitespace).`);
if (bodySign !== expectedBodySign) {
console.log(`- BodySign calculation might be incorrect. For an empty object {}, expected "${expectedBodySign}" but got "${bodySign}". This could be due to differences in JSON serialization (e.g., whitespace).`);
}
// 3. Final hash check
const signText = `${canonicalQuery}${self_app_secret}${bodySign}`;
const expectedSign = crypto.createHash('md5').update(signText).digest('hex');
if (sign !== expectedSign) {
console.log(`- The final hash calculation seems to be the issue. The string to be signed was "${canonicalQuery}${self_app_secret}${bodySign}". The resulting hash did not match the provided sign.`);
console.log(`- The final hash calculation seems to be the issue. The string to be signed was "${canonicalQuery}${self_app_secret}${bodySign}". The resulting hash did not match the provided sign.`);
}
console.log('- The most likely reason is an error in the signing logic itself or a discrepancy in how the components (canonical query, body sign, secret) are combined before hashing.');
}

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

@ -146,6 +146,17 @@ async function completeReceiving(token, receivingId) {
assert.equal(res.body.flag, 'success', `完成收货失败: ${res.body.message}`);
}
async function reviewReceiving(token, receivingId) {
const res = await invokeSystemMethod('storage.receiving.reviewReceiving', {
ids: [ receivingId ],
}, token, EXTRA_HEADERS);
assert.equal(res.status, 200, `审核收货单HTTP失败: ${JSON.stringify(res.body)}`);
assert.equal(res.body.flag, 'success', `审核收货单失败: ${res.body.message}`);
const resCode = Number(res.body?.data?.code || res.body?.code || 0);
assert.equal(resCode, 200, `审核收货单业务失败: ${JSON.stringify(res.body)}`);
}
// ──── 创建测试入库单(直接数据库插入) ────
async function createTestEntryOrder(sequelize, { warehouseId, storeId, items }) {
const code = `TEST-ENTRY-${Date.now()}`;
@ -204,7 +215,41 @@ describe('test/app/controller/system.storage.inventory.matchPutaway.test.js', ()
});
// ──────────────────────────────────────────────────────
// 1. 精确匹配:收货量 = 入库计划量
// 1. 未审核拒绝
// ──────────────────────────────────────────────────────
it('should reject matchPutaway for unreviewed receiving', async function() {
this.timeout(60000);
const receivingId = await createReceiving(authToken);
await bindStore(authToken, receivingId);
const detailId = await addAndFillDetail(authToken, receivingId, products[0], 2);
await bindDetailProduct(authToken, detailId, products[0].id);
await completeReceiving(authToken, receivingId);
const entryOrder = await createTestEntryOrder(sequelize, {
warehouseId: TEST_WAREHOUSE_ID,
storeId: TEST_STORE_ID,
items: [{
id: products[0].id,
item_code: products[0].item_code,
quantity: 2,
}],
});
const res = await matchPutaway(authToken, [ receivingId ], [ entryOrder.id ]);
console.log('[UNREVIEWED] matchPutaway 响应:', JSON.stringify(res.body, null, 2));
assert.equal(res.status, 200, `matchPutaway HTTP失败: ${JSON.stringify(res.body)}`);
assert.equal(res.body.flag, 'success', `matchPutaway flag失败: ${res.body.message}`);
const resultData = res.body?.data?.data || res.body?.data || {};
const resCode = Number(resultData.code || res.body?.code || 0);
assert.equal(resCode, 400, `未审核收货单应返回 400, 实际: ${resCode}`);
const message = String(resultData.message || res.body?.message || '');
assert.ok(message.includes('未审核'), `message 应包含"未审核", 实际: ${message}`);
});
// ──────────────────────────────────────────────────────
// 2. 精确匹配:收货量 = 入库计划量
// ──────────────────────────────────────────────────────
it('should match putaway when receiving equals entry order (exact match)', async function() {
this.timeout(60000);
@ -222,6 +267,7 @@ describe('test/app/controller/system.storage.inventory.matchPutaway.test.js', ()
console.log(`[EXACT] 明细 ${i + 1}: detailId=${detailId}, product=${products[i].item_name}, qty=${quantities[i]}`);
}
await completeReceiving(authToken, receivingId);
await reviewReceiving(authToken, receivingId);
// 2. 创建入库单(数量与收货完全一致)
const entryOrder = await createTestEntryOrder(sequelize, {
@ -280,7 +326,7 @@ describe('test/app/controller/system.storage.inventory.matchPutaway.test.js', ()
});
// ──────────────────────────────────────────────────────
// 2. 收货 > 入库计划(部分匹配,有剩余)
// 3. 收货 > 入库计划(部分匹配,有剩余)
// ──────────────────────────────────────────────────────
it('should handle receiving > entry order (partial match with surplus)', async function() {
this.timeout(60000);
@ -299,6 +345,7 @@ describe('test/app/controller/system.storage.inventory.matchPutaway.test.js', ()
console.log(`[SURPLUS] 明细 ${i + 1}: detailId=${detailId}, product=${products[i].item_name}, rcvQty=${rcvQuantities[i]}`);
}
await completeReceiving(authToken, receivingId);
await reviewReceiving(authToken, receivingId);
// 2. 创建入库单(数量 10, 5 — 小于收货量)
const entryOrder = await createTestEntryOrder(sequelize, {
@ -355,7 +402,7 @@ describe('test/app/controller/system.storage.inventory.matchPutaway.test.js', ()
});
// ──────────────────────────────────────────────────────
// 3. 收货 < 入库计划(收货不足)
// 4. 收货 < 入库计划(收货不足)
// ──────────────────────────────────────────────────────
it('should handle receiving < entry order (insufficient receiving)', async function() {
this.timeout(60000);
@ -374,6 +421,7 @@ describe('test/app/controller/system.storage.inventory.matchPutaway.test.js', ()
console.log(`[INSUF] 明细 ${i + 1}: detailId=${detailId}, product=${products[i].item_name}, rcvQty=${rcvQuantities[i]}`);
}
await completeReceiving(authToken, receivingId);
await reviewReceiving(authToken, receivingId);
// 2. 创建入库单(数量 10, 8 — 大于收货量)
const entryOrder = await createTestEntryOrder(sequelize, {

View File

@ -104,6 +104,39 @@ async function bindStore(token, receivingId) {
assert.equal(res.body.flag, 'success', `绑定货主失败: ${res.body.message}`);
}
async function setQuickPutawayPolicy(enabled) {
const [ rows ] = await sequelize.query(
'SELECT id, policy_config FROM wms_store_warehouse WHERE store_id = :storeId AND warehouse_id = :warehouseId AND use_status = 1 LIMIT 1',
{
replacements: {
storeId: TEST_STORE_ID,
warehouseId: TEST_WAREHOUSE_ID,
},
}
);
assert.ok(Array.isArray(rows) && rows.length === 1, '未找到可用的货主仓库签约关系');
let policyConfig = {};
const rawPolicyConfig = rows[0].policy_config;
if (rawPolicyConfig && typeof rawPolicyConfig === 'string') {
policyConfig = JSON.parse(rawPolicyConfig);
} else if (rawPolicyConfig && typeof rawPolicyConfig === 'object') {
policyConfig = { ...rawPolicyConfig };
}
policyConfig.allow_receiving_quick_putaway = enabled ? 1 : 0;
await sequelize.query(
'UPDATE wms_store_warehouse SET policy_config = :policyConfig, updated_at = NOW() WHERE id = :id',
{
replacements: {
id: rows[0].id,
policyConfig: JSON.stringify(policyConfig),
},
}
);
}
// ──── 添加明细 + 修改明细 + 绑定商品 ────
async function addAndFillDetail(token, receivingId, product, qty) {
// addDetail
@ -154,7 +187,7 @@ async function completeReceiving(token, receivingId) {
{
replacements: {
status: 'completed',
storageStatus: 'partial',
storageStatus: 'none',
receivingId,
},
}
@ -162,6 +195,17 @@ async function completeReceiving(token, receivingId) {
}
}
async function reviewReceiving(token, receivingId) {
const res = await invokeSystemMethod('storage.receiving.reviewReceiving', {
ids: [ receivingId ],
}, token, EXTRA_HEADERS);
assert.equal(res.status, 200, `审核收货单HTTP失败: ${JSON.stringify(res.body)}`);
assert.equal(res.body.flag, 'success', `审核收货单失败: ${res.body.message}`);
const resCode = Number(res.body?.data?.code || res.body?.code || 0);
assert.equal(resCode, 200, `审核收货单业务失败: ${JSON.stringify(res.body)}`);
}
// ──── 快捷入库 ────
async function quickPutaway(token, receivingId) {
return invokeSystemMethod('storage.inventory.quickPutaway', {
@ -196,13 +240,63 @@ describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', ()
});
// ──────────────────────────────────────────────────────
// 1. 部分匹配拒绝
// 1. 未审核拒绝
// ──────────────────────────────────────────────────────
it('should reject quickPutaway for unreviewed receiving', async function() {
this.timeout(60000);
const receivingId = await createReceiving(authToken);
await bindStore(authToken, receivingId);
await setQuickPutawayPolicy(false);
const detailId = await addAndFillDetail(authToken, receivingId, products[0], 2);
await bindDetailProduct(authToken, detailId, products[0].id);
await completeReceiving(authToken, receivingId);
const res = await quickPutaway(authToken, receivingId);
console.log('[UNREVIEWED] quickPutaway 响应:', JSON.stringify(res.body, null, 2));
const resCode = Number(res.body?.data?.code || res.body?.code || 0);
assert.equal(resCode, 400, `未审核收货单应返回 400, 实际: ${resCode}`);
const message = String(res.body?.data?.message || res.body?.message || '');
assert.ok(message.includes('未审核'), `message 应包含"未审核", 实际: ${message}`);
});
// ──────────────────────────────────────────────────────
// 2. 货主策略未开启拒绝
// ──────────────────────────────────────────────────────
it('should reject quickPutaway when store policy disallows receiving quick putaway', async function() {
this.timeout(60000);
const receivingId = await createReceiving(authToken);
await bindStore(authToken, receivingId);
await setQuickPutawayPolicy(false);
const detailId = await addAndFillDetail(authToken, receivingId, products[0], 2);
await bindDetailProduct(authToken, detailId, products[0].id);
await completeReceiving(authToken, receivingId);
await reviewReceiving(authToken, receivingId);
const res = await quickPutaway(authToken, receivingId);
console.log('[POLICY] quickPutaway 响应:', JSON.stringify(res.body, null, 2));
const resCode = Number(res.body?.data?.code || res.body?.code || 0);
assert.equal(resCode, 400, `未开启快捷入库策略应返回 400, 实际: ${resCode}`);
const message = String(res.body?.data?.message || res.body?.message || '');
assert.ok(message.includes('货主'), `message 应包含"货主", 实际: ${message}`);
assert.ok(message.includes('不允许快速上架'), `message 应包含"不允许快速上架", 实际: ${message}`);
assert.ok(message.includes('货主->策略配置调整'), `message 应包含"货主->策略配置调整", 实际: ${message}`);
});
// ──────────────────────────────────────────────────────
// 3. 部分匹配拒绝
// ──────────────────────────────────────────────────────
it('should reject quickPutaway for partially matched receiving', async function() {
this.timeout(60000);
const receivingId = await createReceiving(authToken);
await bindStore(authToken, receivingId);
await setQuickPutawayPolicy(true);
console.log(`[PARTIAL] 收货单 ID: ${receivingId}`);
// 添加 3 条明细
@ -221,6 +315,7 @@ describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', ()
// 完成收货
await completeReceiving(authToken, receivingId);
await reviewReceiving(authToken, receivingId);
// 快捷入库 → 应被拒绝
const res = await quickPutaway(authToken, receivingId);
@ -233,13 +328,14 @@ describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', ()
});
// ──────────────────────────────────────────────────────
// 2. 全匹配成功
// 4. 全匹配成功
// ──────────────────────────────────────────────────────
it('should complete quickPutaway for fully matched receiving', async function() {
this.timeout(60000);
const receivingId = await createReceiving(authToken);
await bindStore(authToken, receivingId);
await setQuickPutawayPolicy(true);
console.log(`[FULL] 收货单 ID: ${receivingId}`);
// 添加 2 条明细,全部绑定商品
@ -254,6 +350,7 @@ describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', ()
// 完成收货
await completeReceiving(authToken, receivingId);
await reviewReceiving(authToken, receivingId);
// 快捷入库
const res = await quickPutaway(authToken, receivingId);
@ -302,7 +399,7 @@ describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', ()
});
// ──────────────────────────────────────────────────────
// 3. 数据库行锁冲突 → 409
// 5. 数据库行锁冲突 → 409
// ──────────────────────────────────────────────────────
it('should return 409 when stock row is locked by concurrent transaction', async function() {
this.timeout(120000);
@ -316,9 +413,11 @@ describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', ()
// 先准备好收货单数据
const receivingId = await createReceiving(authToken);
await bindStore(authToken, receivingId);
await setQuickPutawayPolicy(true);
const detailId = await addAndFillDetail(authToken, receivingId, products[0], 1);
await bindDetailProduct(authToken, detailId, products[0].id);
await completeReceiving(authToken, receivingId);
await reviewReceiving(authToken, receivingId);
// 开事务锁行
lockTx = await sequelize.transaction();
@ -356,13 +455,14 @@ describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', ()
});
// ──────────────────────────────────────────────────────
// 4. 无锁冲突正常入库
// 6. 无锁冲突正常入库
// ──────────────────────────────────────────────────────
it('should complete quickPutaway without lock contention', async function() {
this.timeout(60000);
const receivingId = await createReceiving(authToken);
await bindStore(authToken, receivingId);
await setQuickPutawayPolicy(true);
console.log(`[NOLOCK] 收货单 ID: ${receivingId}`);
// 添加 2 条明细,全部绑定
@ -377,6 +477,7 @@ describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', ()
// 完成收货 → 快捷入库
await completeReceiving(authToken, receivingId);
await reviewReceiving(authToken, receivingId);
const res = await quickPutaway(authToken, receivingId);
console.log('[NOLOCK] quickPutaway 响应:', JSON.stringify(res.body, null, 2));
@ -402,13 +503,14 @@ describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', ()
});
// ──────────────────────────────────────────────────────
// 5. 空批次回退 + 批次日期落库存
// 7. 空批次回退 + 批次日期落库存
// ──────────────────────────────────────────────────────
it('should fallback to receiving number when batch is empty and persist batch dates into storage', async function() {
this.timeout(60000);
const receivingId = await createReceiving(authToken);
await bindStore(authToken, receivingId);
await setQuickPutawayPolicy(true);
console.log(`[BATCH] 收货单 ID: ${receivingId}`);
const firstDetailId = await addAndFillDetail(authToken, receivingId, products[0], 2);
@ -428,6 +530,7 @@ describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', ()
await bindDetailProduct(authToken, secondDetailId, products[0].id);
await completeReceiving(authToken, receivingId);
await reviewReceiving(authToken, receivingId);
const detailRes = await invokeSystemMethod('storage.receiving.getReceivingDetail', {
id: receivingId,

View File

@ -336,6 +336,18 @@ describe('test/app/controller/system.storage.receiving.test.js', () => {
const detailId = Number(addDetailRes.body?.data?.data?.selectId || addDetailRes.body?.data?.selectId || 0);
assert.ok(detailId > 0, '新增收货单明细后未返回有效 detail_id');
const detailChangeRes = await invokeSystemMethod('storage.receiving.detailChange', {
id: detailId,
receiving_id: createdId,
product_name: '审核前绑定测试商品',
barcode: `IDR-BC-${Date.now().toString().slice(-6)}`,
actual_quantity: 1,
box_quantity: 1,
pallet_quantity: 0,
}, switched.token, EXTRA_HEADERS);
assert.equal(detailChangeRes.status, 200);
assert.equal(detailChangeRes.body.flag, 'success');
const sortedProducts = [ ...systemProducts ].sort((left, right) => Number(left.id) - Number(right.id));
const firstProduct = sortedProducts[0];
const secondProduct = sortedProducts[1];

View File

@ -16,6 +16,7 @@ const TEST_WAREHOUSE_ID = 100000;
const dbConfig = require('../../../database/config');
const env = process.env.NODE_ENV || 'development';
const config = dbConfig[env] || dbConfig.development || Object.values(dbConfig)[0];
let sequelize;
// ──── switchToWarehouseRole ────
async function switchToWarehouseRole(token) {
@ -103,6 +104,39 @@ async function bindStore(token, receivingId) {
assert.equal(res.body.flag, 'success', `绑定货主失败: ${res.body.message}`);
}
async function setQuickPutawayPolicy(enabled) {
const [ rows ] = await sequelize.query(
'SELECT id, policy_config FROM wms_store_warehouse WHERE store_id = :storeId AND warehouse_id = :warehouseId AND use_status = 1 LIMIT 1',
{
replacements: {
storeId: TEST_STORE_ID,
warehouseId: TEST_WAREHOUSE_ID,
},
}
);
assert.ok(Array.isArray(rows) && rows.length === 1, '未找到可用的货主仓库签约关系');
let policyConfig = {};
const rawPolicyConfig = rows[0].policy_config;
if (rawPolicyConfig && typeof rawPolicyConfig === 'string') {
policyConfig = JSON.parse(rawPolicyConfig);
} else if (rawPolicyConfig && typeof rawPolicyConfig === 'object') {
policyConfig = { ...rawPolicyConfig };
}
policyConfig.allow_receiving_quick_putaway = enabled ? 1 : 0;
await sequelize.query(
'UPDATE wms_store_warehouse SET policy_config = :policyConfig, updated_at = NOW() WHERE id = :id',
{
replacements: {
id: rows[0].id,
policyConfig: JSON.stringify(policyConfig),
},
}
);
}
// ──── 添加明细 + 修改明细 ────
async function addAndFillDetail(token, receivingId, product, qty) {
const addRes = await invokeSystemMethod('storage.receiving.addDetail', {
@ -146,6 +180,16 @@ async function completeReceiving(token, receivingId) {
assert.equal(res.body.flag, 'success', `完成收货失败: ${res.body.message}`);
}
async function reviewReceiving(token, receivingId) {
const res = await invokeSystemMethod('storage.receiving.reviewReceiving', {
ids: [ receivingId ],
}, token, EXTRA_HEADERS);
assert.equal(res.status, 200, `审核收货单HTTP失败: ${JSON.stringify(res.body)}`);
assert.equal(res.body.flag, 'success', `审核收货单失败: ${res.body.message}`);
const resCode = Number(res.body?.data?.code || res.body?.code || 0);
assert.equal(resCode, 200, `审核收货单业务失败: ${JSON.stringify(res.body)}`);
}
// ──── 快捷入库 ────
async function quickPutaway(token, receivingId) {
return invokeSystemMethod('storage.inventory.quickPutaway', {
@ -156,7 +200,6 @@ async function quickPutaway(token, receivingId) {
describe('test/app/controller/system.storage.transaction.test.js', () => {
let authToken;
let products;
let sequelize;
before(async function() {
this.timeout(30000);
@ -191,6 +234,7 @@ describe('test/app/controller/system.storage.transaction.test.js', () => {
// === 准备阶段 ===
const receivingId = await createReceiving(authToken);
await bindStore(authToken, receivingId);
await setQuickPutawayPolicy(true);
console.log(`[TX] 收货单 ID: ${receivingId}`);
const quantities = [ 7, 3 ];
@ -203,6 +247,7 @@ describe('test/app/controller/system.storage.transaction.test.js', () => {
}
await completeReceiving(authToken, receivingId);
await reviewReceiving(authToken, receivingId);
// 记录入库前的 transaction 最大 ID,用于过滤
const [ beforeRows ] = await sequelize.query(

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

View File

@ -0,0 +1,73 @@
'use strict';
const assert = require('node:assert/strict');
const StorageReceivingService = require('../../../../../app/service/systemMethods/storage/receiving');
function createHarness(storeId = 100321) {
const calls = {};
const ctx = {
app: {
config: {},
},
user: {
store_id: storeId,
},
service: {
systems: {
operationLog: {
async queryReceivingLogs(query) {
calls.queryReceivingLogs = query;
return {
list: [{ id: 1 }],
pagination: {
page: Number(query.page || 1),
pageSize: Number(query.pageSize || 20),
total: 1,
totalPages: 1,
},
};
},
},
},
},
};
return {
service: new StorageReceivingService(ctx),
calls,
};
}
describe('test/app/service/systemMethods/storage/queryReceivingLogs.test.js', () => {
it('should inject current store_id and support pagination object', async () => {
const { service, calls } = createHarness(100321);
const result = await service.queryReceivingLogs({
receiving_id: 99,
pagination: {
page: 3,
pageSize: 15,
},
});
assert.deepEqual(calls.queryReceivingLogs, {
id: 99,
page: 3,
pageSize: 15,
warehouseId: 100321,
});
assert.equal(result.flag, 'success');
assert.equal(result.message, 'ok');
assert.equal(result.code, 200);
assert.deepEqual(result.data, {
list: [{ id: 1 }],
pagination: {
page: 3,
pageSize: 15,
total: 1,
totalPages: 1,
},
});
});
});

View File

@ -0,0 +1,198 @@
'use strict';
const assert = require('node:assert/strict');
const { Op } = require('sequelize');
const LocationZoneService = require('../../../../app/service/systems/location_zone');
function createHarness(options = {}) {
const calls = {
transactionCalls: 0,
zoneDestroyQueries: [],
spaceDestroyQueries: [],
storageCountQueries: [],
};
const zoneRows = (options.zones || []).map(item => ({
...item,
deleted_at: item.deleted_at || null,
}));
const spaceRows = (options.spaces || []).map(item => ({
...item,
deleted_at: item.deleted_at || null,
}));
const storageRows = (options.storages || []).map(item => ({
delete_at: null,
is_enabled: 1,
quantity: 0,
locked_quantity: 0,
available_quantity: 0,
...item,
}));
const ctx = {
logger: {
error() {},
},
app: {
Sequelize: {
Op,
},
},
model: {
async transaction(handler) {
calls.transactionCalls += 1;
const transaction = {
async commit() {},
async rollback() {},
};
if (typeof handler === 'function') {
return await handler(transaction);
}
return transaction;
},
LocationZone: {
async findOne({ where = {} }) {
return zoneRows.find(row => (
Number(row.id) === Number(where.id) &&
(where.deleted_at !== null ? row.deleted_at === null : true)
)) || null;
},
async findAll({ where = {}, raw = false }) {
let rows = zoneRows.filter(row => row.deleted_at === null);
if (where.parent_id && where.parent_id[Op.in]) {
const parentIds = where.parent_id[Op.in].map(item => Number(item));
rows = rows.filter(row => parentIds.includes(Number(row.parent_id)));
} else if (Object.prototype.hasOwnProperty.call(where, 'parent_id')) {
rows = rows.filter(row => Number(row.parent_id) === Number(where.parent_id));
}
return raw ? rows.map(row => ({ ...row })) : rows.map(row => ({ ...row }));
},
async destroy({ where = {} }) {
calls.zoneDestroyQueries.push(where);
const ids = where.id && where.id[Op.in]
? where.id[Op.in].map(item => Number(item))
: [];
zoneRows.forEach(row => {
if (ids.includes(Number(row.id))) {
row.deleted_at = new Date();
}
});
return ids.length;
},
},
LocationSpace: {
async findAll({ where = {}, raw = false }) {
let rows = spaceRows.filter(row => row.deleted_at === null);
if (where.zone_id && where.zone_id[Op.in]) {
const zoneIds = where.zone_id[Op.in].map(item => Number(item));
rows = rows.filter(row => zoneIds.includes(Number(row.zone_id)));
} else if (Object.prototype.hasOwnProperty.call(where, 'zone_id')) {
rows = rows.filter(row => Number(row.zone_id) === Number(where.zone_id));
}
return raw ? rows.map(row => ({ ...row })) : rows.map(row => ({ ...row }));
},
async destroy({ where = {} }) {
calls.spaceDestroyQueries.push(where);
const ids = where.id && where.id[Op.in]
? where.id[Op.in].map(item => Number(item))
: [];
spaceRows.forEach(row => {
if (ids.includes(Number(row.id))) {
row.deleted_at = new Date();
}
});
return ids.length;
},
},
Storage: {
async count({ where = {} }) {
calls.storageCountQueries.push(where);
const spaceIds = where.space_id && where.space_id[Op.in]
? where.space_id[Op.in].map(item => Number(item))
: [];
return storageRows.filter(row => {
if (!spaceIds.includes(Number(row.space_id))) {
return false;
}
if (row.delete_at !== null) {
return false;
}
if (Number(row.is_enabled) !== 1) {
return false;
}
return Number(row.quantity) > 0 || Number(row.locked_quantity) > 0 || Number(row.available_quantity) > 0;
}).length;
},
},
},
};
return {
service: new LocationZoneService(ctx),
zoneRows,
spaceRows,
calls,
};
}
describe('test/app/service/systems/location_zone.deleteZone.test.js', () => {
it('should cascade soft delete descendant racks and spaces when deleting an area', async () => {
const { service, zoneRows, spaceRows, calls } = createHarness({
zones: [
{ id: 10, parent_id: 1, zone_type: 'area' },
{ id: 11, parent_id: 10, zone_type: 'rack' },
{ id: 12, parent_id: 11, zone_type: 'obstacle' },
],
spaces: [
{ id: 101, zone_id: 11 },
{ id: 102, zone_id: 11 },
],
});
const result = await service.deleteZone(10);
assert.equal(result.success, true);
assert.equal(result.message, '删除成功');
assert.equal(calls.transactionCalls, 1);
assert.deepEqual(calls.spaceDestroyQueries[0].id[Op.in], [ 101, 102 ]);
assert.deepEqual(calls.zoneDestroyQueries[0].id[Op.in], [ 10, 11, 12 ]);
assert.equal(zoneRows.every(row => row.deleted_at instanceof Date), true);
assert.equal(spaceRows.every(row => row.deleted_at instanceof Date), true);
});
it('should reject deleting a rack when any affected space still has stock', async () => {
const { service, zoneRows, spaceRows, calls } = createHarness({
zones: [
{ id: 20, parent_id: 2, zone_type: 'rack' },
],
spaces: [
{ id: 201, zone_id: 20 },
],
storages: [
{ id: 1, space_id: 201, quantity: 3 },
],
});
await assert.rejects(async () => {
await service.deleteZone(20);
}, /删除范围内库位有库存,禁止删除,请先移库/);
assert.equal(calls.transactionCalls, 1);
assert.equal(calls.spaceDestroyQueries.length, 0);
assert.equal(calls.zoneDestroyQueries.length, 0);
assert.equal(zoneRows[0].deleted_at, null);
assert.equal(spaceRows[0].deleted_at, null);
});
});

View File

@ -106,4 +106,35 @@ describe('test/app/service/systems/operation_log.queryOrderLogs.test.js', () =>
assert.equal(result.list[0].platform_name, 'platform:pda');
assert.equal(result.list[0].created_at, 'formatted:2026-04-19 12:00:00');
});
it('should query receiving logs with business_type receiving', async () => {
const { service, calls } = createServiceHarness({
count: 5,
rows: [{
id: 3,
operation_code: 'RECEIVING_REVIEW',
operator_name: 'Alice',
created_at: '2026-04-19 13:00:00',
external_log_type: 'NONE',
external_log_id: null,
platform_code: 'web',
message: 'reviewed',
}],
});
const result = await service.queryReceivingLogs({
id: 501,
warehouseId: 100000,
page: 1,
pageSize: 20,
});
assert.deepEqual(calls.findAndCountAllArgs.where, {
business_type: 'receiving',
business_id: 501,
warehouse_id: 100000,
});
assert.equal(result.pagination.total, 5);
assert.equal(result.list[0].operation_name, 'name:RECEIVING_REVIEW');
});
});

View File

@ -902,4 +902,4 @@ describe('test/app/service/systems/order_async.syncOrderIds.test.js', () => {
assert.equal(result.status, 'success');
assert.equal(result.success_count, 1);
});
});
});

View File

@ -0,0 +1,102 @@
'use strict';
const assert = require('node:assert/strict');
const ReceivingService = require('../../../../app/service/systems/storage/receiving');
function createHarness(overrides = {}) {
const calls = {
stockWarehouseFindOne: 0,
};
const receivingDetail = {
id: 1001,
receiving_id: 5001,
receiving: {
id: 5001,
warehouse_id: 100000,
store_id: 1000000,
store_name: '测试货主',
status: 'completed',
is_review: 1,
...(overrides.receiving || {}),
},
};
const ctx = {
user: {
store_id: 100000,
employees_id: 9001,
employees_name: '测试员',
id: 9001,
},
logger: {
error() {},
warn() {},
info() {},
},
service: {
systems: {
operationLog: {
async createOperationLog() {},
},
},
},
};
const app = {
model: {
ReceivingDetail: {
async findOne() {
return receivingDetail;
},
},
StockWarehouse: {
async findOne() {
calls.stockWarehouseFindOne += 1;
return null;
},
},
},
};
ctx.app = app;
const service = new ReceivingService(ctx);
return {
service,
calls,
};
}
describe('test/app/service/systems/storage.receiving.bindDetailProduct.test.js', () => {
it('should reject binding when receiving is already reviewed', async () => {
const { service, calls } = createHarness();
const result = await service.bindDetailProduct({
detail_id: 1001,
system_product_id: 2001,
});
assert.equal(result.code, 400);
assert.match(String(result.message || ''), /已审核/);
assert.equal(calls.stockWarehouseFindOne, 0);
});
it('should reject binding when receiving is cancelled', async () => {
const { service, calls } = createHarness({
receiving: {
is_review: 0,
status: 'cancelled',
},
});
const result = await service.bindDetailProduct({
detail_id: 1001,
system_product_id: 2001,
});
assert.equal(result.code, 400);
assert.match(String(result.message || ''), /已作废/);
assert.equal(calls.stockWarehouseFindOne, 0);
});
});

View File

@ -0,0 +1,159 @@
'use strict';
const assert = require('node:assert/strict');
const ReceivingService = require('../../../../app/service/systems/storage/receiving');
function createReceivingRow(overrides = {}) {
return {
id: 501,
warehouse_id: 100000,
receiving_number: 'RCV-501',
status: 'completed',
is_review: 0,
storage_status: 'none',
creator_snapshot: JSON.stringify({
id: 3001,
employees_id: 3001,
name: '创建人A',
}),
...overrides,
};
}
function createHarness(options = {}) {
const rows = (options.rows || []).map(item => ({ ...item }));
const noticeCalls = [];
const operationLogs = [];
const updateCalls = [];
const ctx = {
app: {
config: {},
},
user: {
store_id: 100000,
store_name: '测试仓库',
employees_id: 9001,
employees_name: '审核员A',
id: 9001,
},
logger: {
warn() {},
error() {},
info() {},
},
service: {
systems: {
operationLog: {
async createOperationLog(payload) {
operationLogs.push(payload);
},
},
notice: {
async send(payload) {
noticeCalls.push(payload);
return { success: true };
},
},
},
},
model: {
Sequelize: {
Op: {
in: 'in',
},
},
Receiving: {
async findAll() {
return rows;
},
async update(values) {
updateCalls.push({ ...values });
rows.forEach(row => Object.assign(row, values));
return [ rows.length ];
},
},
},
};
return {
service: new ReceivingService(ctx),
rows,
noticeCalls,
operationLogs,
updateCalls,
};
}
describe('test/app/service/systems/storage.receiving.reject.test.js', () => {
it('should send one reject notice per receiving with creator info and identifiers', async () => {
const { service, noticeCalls, operationLogs, updateCalls } = createHarness({
rows: [
createReceivingRow({ id: 501, receiving_number: 'RCV-501' }),
createReceivingRow({
id: 502,
receiving_number: 'RCV-502',
creator_snapshot: JSON.stringify({
id: 3002,
employees_id: 3002,
name: '创建人B',
}),
}),
],
});
const result = await service.rejectReceiving({
ids: [ 501, 502 ],
remark: '资料不完整',
});
assert.equal(result.code, 200);
assert.equal(result.message, '驳回成功');
assert.equal(updateCalls.length, 1);
assert.equal(Object.prototype.hasOwnProperty.call(updateCalls[0], 'is_review'), false);
assert.equal(operationLogs.length, 2);
assert.equal(noticeCalls.length, 2);
const firstNotice = noticeCalls.find(item => Number(item.businessId) === 501);
const secondNotice = noticeCalls.find(item => Number(item.businessId) === 502);
assert.ok(firstNotice);
assert.ok(secondNotice);
assert.equal(firstNotice.event, 'receiving_rejected');
assert.match(String(firstNotice.title || ''), /RCV-501|501/);
assert.match(String(firstNotice.content || ''), /收货单ID:501/);
assert.match(String(firstNotice.content || ''), /收货单号:RCV-501/);
assert.match(String(firstNotice.content || ''), /收货创建人:创建人A/);
assert.deepEqual(firstNotice.metadata.receiving_ids, [ 501 ]);
assert.deepEqual(firstNotice.metadata.receiving_numbers, [ 'RCV-501' ]);
assert.deepEqual(firstNotice.metadata.receiving_creators, [
{ id: 3001, employees_id: 3001, name: '创建人A' },
]);
assert.deepEqual(firstNotice.metadata.receivings, [
{
id: 501,
receiving_number: 'RCV-501',
creator: { id: 3001, employees_id: 3001, name: '创建人A' },
},
]);
assert.equal(secondNotice.event, 'receiving_rejected');
assert.match(String(secondNotice.title || ''), /RCV-502|502/);
assert.match(String(secondNotice.content || ''), /收货单ID:502/);
assert.match(String(secondNotice.content || ''), /收货单号:RCV-502/);
assert.match(String(secondNotice.content || ''), /收货创建人:创建人B/);
assert.deepEqual(secondNotice.metadata.receiving_ids, [ 502 ]);
assert.deepEqual(secondNotice.metadata.receiving_numbers, [ 'RCV-502' ]);
assert.deepEqual(secondNotice.metadata.receiving_creators, [
{ id: 3002, employees_id: 3002, name: '创建人B' },
]);
assert.deepEqual(secondNotice.metadata.receivings, [
{
id: 502,
receiving_number: 'RCV-502',
creator: { id: 3002, employees_id: 3002, name: '创建人B' },
},
]);
});
});

View File

@ -0,0 +1,151 @@
'use strict';
const assert = require('node:assert/strict');
const { Op } = require('sequelize');
const ReceivingService = require('../../../../app/service/systems/storage/receiving');
function createReceivingRow(overrides = {}) {
return {
id: 101,
warehouse_id: 100000,
receiving_number: 'RCV202604300001',
status: 'completed',
detail_status: 'all_matched',
storage_status: 'none',
store_id: 200001,
is_review: 0,
...overrides,
};
}
function createHarness(options = {}) {
const rows = (options.rows || []).map(item => ({ ...item }));
const calls = {
updateArgs: [],
transactionCommitCount: 0,
transactionRollbackCount: 0,
operationLogs: [],
};
const transaction = {
LOCK: {
UPDATE: 'UPDATE',
},
async commit() {
calls.transactionCommitCount += 1;
},
async rollback() {
calls.transactionRollbackCount += 1;
},
};
const ctx = {
app: {
Sequelize: {
Op,
},
},
user: {
store_id: 100000,
employees_id: 9001,
employees_name: '审核员A',
id: 9001,
},
logger: {
info() {},
warn() {},
error() {},
},
service: {
systems: {
operationLog: {
async createOperationLog(payload) {
calls.operationLogs.push(payload);
},
},
},
},
model: {
Sequelize: {
Op,
},
async transaction() {
return transaction;
},
Receiving: {
async findAll() {
return rows;
},
async update(values, optionsArg = {}) {
calls.updateArgs.push({
values: { ...values },
where: optionsArg.where,
});
const affectedRows = options.updatedRows !== undefined
? Number(options.updatedRows)
: rows.length;
if (affectedRows > 0) {
rows.slice(0, affectedRows).forEach(row => {
Object.assign(row, values);
});
}
return [ affectedRows ];
},
},
},
};
const service = new ReceivingService(ctx);
service.sendReviewNotice = async () => ({ success: true, data: { sentCount: 0, failedCount: 0, matchedHookCount: 0 } });
service.uploadReviewExcelReport = async receiving => ({
fileKey: `${receiving.receiving_number}.xlsx`,
url: `https://cdn.example.com/${receiving.receiving_number}.xlsx`,
});
return {
service,
rows,
calls,
};
}
describe('test/app/service/systems/storage.receiving.review.test.js', () => {
it('should review completed receivings even when legacy is_review is null', async () => {
const { service, rows, calls } = createHarness({
rows: [ createReceivingRow({ id: 201, receiving_number: 'RCV-201', is_review: null }) ],
});
const result = await service.reviewReceiving({ ids: [ 201 ] });
assert.equal(result.code, 200);
assert.equal(result.message, '审核成功');
assert.equal(Number(rows[0].is_review), 1);
assert.equal(rows[0].reviewer_name, '审核员A');
assert.equal(Number(rows[0].reviewer_employee_id), 9001);
assert.equal(calls.transactionCommitCount, 1);
assert.equal(calls.transactionRollbackCount, 0);
assert.equal(calls.updateArgs.length, 1);
assert.deepEqual(calls.updateArgs[0].where[Op.or], [
{ is_review: 0 },
{ is_review: null },
]);
});
it('should fail when affected rows are fewer than requested ids', async () => {
const { service, rows, calls } = createHarness({
rows: [ createReceivingRow({ id: 301, receiving_number: 'RCV-301', is_review: null }) ],
updatedRows: 0,
});
const result = await service.reviewReceiving({ ids: [ 301 ] });
assert.equal(result.code, 0);
assert.match(String(result.message || ''), /审核状态已变化/);
assert.equal(rows[0].is_review, null);
assert.equal(calls.transactionCommitCount, 0);
assert.equal(calls.transactionRollbackCount, 1);
});
});

View File

@ -0,0 +1,162 @@
'use strict';
const assert = require('node:assert/strict');
const ReceivingService = require('../../../../app/service/systems/storage/receiving');
function createReceivingRow(overrides = {}) {
return {
id: 101,
warehouse_id: 100000,
receiving_number: 'RCV202604300001',
status: 'receiving',
delivery_method: 'truck',
license_plate: '粤A12345',
loading_method: 'without_pallet',
remark: 'old remark',
store_id: 200001,
store_name: '旧货主',
total_boxes: 1,
total_pallets: 0,
tracking_number: null,
video_device_id: null,
is_deleted: false,
...overrides,
};
}
function createHarness(options = {}) {
const receivingRow = createReceivingRow(options.receiving || {});
const calls = {
transactionCommitCount: 0,
transactionRollbackCount: 0,
updateArgs: [],
operationLogs: [],
};
const transaction = {
LOCK: {
UPDATE: 'UPDATE',
},
async commit() {
calls.transactionCommitCount += 1;
},
async rollback() {
calls.transactionRollbackCount += 1;
},
};
const storeRelation = options.storeRelation === undefined
? { store_id: 300001, store_remask: '新货主' }
: options.storeRelation;
const ctx = {
app: {
config: {},
},
user: {
store_id: 100000,
employees_id: 9001,
employees_name: '测试员A',
id: 9001,
},
logger: {
warn() {},
error() {},
info() {},
},
service: {
systems: {
operationLog: {
async createOperationLog(payload) {
calls.operationLogs.push(payload);
},
},
},
},
model: {
async transaction() {
return transaction;
},
Receiving: {
async findOne({ where = {} }) {
if (Number(where.id) !== Number(receivingRow.id) || Number(where.warehouse_id) !== Number(receivingRow.warehouse_id) || receivingRow.is_deleted) {
return null;
}
return receivingRow;
},
async update(values, optionsArg = {}) {
calls.updateArgs.push({
values: { ...values },
where: optionsArg.where,
});
Object.assign(receivingRow, values);
return [ 1 ];
},
},
StoreWarehouse: {
async findOne() {
return storeRelation;
},
},
},
};
return {
service: new ReceivingService(ctx),
receivingRow,
calls,
};
}
describe('test/app/service/systems/storage.receiving.save.test.js', () => {
it('should update receiving by id', async () => {
const { service, receivingRow, calls } = createHarness();
const result = await service.save({
id: 101,
delivery_method: 'express',
tracking_number: 'YT123456789',
loading_method: 'with_pallet',
remark: 'new remark',
store_id: 300001,
total_boxes: 8,
total_pallets: 2,
video_device_id: 'CAM-01',
});
assert.equal(result.code, 200);
assert.equal(result.id, 101);
assert.equal(result.receiving_number, 'RCV202604300001');
assert.equal(result.message, '收货单修改成功');
assert.equal(receivingRow.delivery_method, 'express');
assert.equal(receivingRow.license_plate, null);
assert.equal(receivingRow.tracking_number, 'YT123456789');
assert.equal(receivingRow.loading_method, 'with_pallet');
assert.equal(receivingRow.remark, 'new remark');
assert.equal(receivingRow.store_id, 300001);
assert.equal(receivingRow.store_name, '新货主');
assert.equal(receivingRow.total_boxes, 8);
assert.equal(receivingRow.total_pallets, 2);
assert.equal(receivingRow.video_device_id, 'CAM-01');
assert.equal(calls.transactionCommitCount, 1);
assert.equal(calls.transactionRollbackCount, 0);
assert.equal(calls.operationLogs.length, 1);
});
it('should reject invalid store relation', async () => {
const { service, receivingRow, calls } = createHarness({
storeRelation: null,
});
const result = await service.save({
id: 101,
store_id: 999999,
});
assert.equal(result.code, 404);
assert.match(String(result.message || ''), /货主不存在|签约关系/);
assert.equal(receivingRow.store_id, 200001);
assert.equal(calls.transactionCommitCount, 0);
assert.equal(calls.transactionRollbackCount, 1);
});
});