1
Co-authored-by: Copilot <copilot@github.com>
This commit is contained in:
parent
ea8c6ebe82
commit
b7f980188f
@ -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('&');
|
||||
}
|
||||
|
||||
|
||||
@ -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));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -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,
|
||||
|
||||
@ -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);
|
||||
|
||||
@ -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;
|
||||
|
||||
@ -118,7 +118,7 @@ module.exports = app => {
|
||||
allowNull: true,
|
||||
comment: '平台店铺',
|
||||
},
|
||||
address:{
|
||||
address: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '地址',
|
||||
|
||||
@ -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' ],
|
||||
},
|
||||
// 状态机索引
|
||||
{
|
||||
|
||||
@ -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);
|
||||
|
||||
@ -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,
|
||||
|
||||
@ -55,11 +55,11 @@ module.exports = app => {
|
||||
allowNull: true,
|
||||
comment: '店铺类型',
|
||||
},
|
||||
ordersource:{
|
||||
ordersource: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '订单来源',
|
||||
}
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_platform',
|
||||
freezeTableName: true,
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@ -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 });
|
||||
}
|
||||
/**
|
||||
* 获取快递列表。
|
||||
*
|
||||
|
||||
@ -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 审核状态。
|
||||
|
||||
@ -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);
|
||||
// ========== 库存检查逻辑结束 ==========
|
||||
|
||||
// 所有检查通过,准备订单行数据
|
||||
|
||||
@ -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,
|
||||
|
||||
@ -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;
|
||||
|
||||
@ -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,
|
||||
|
||||
@ -767,8 +767,39 @@ class LocationZoneService extends Service {
|
||||
},
|
||||
});
|
||||
if (zone.zone_type === 'rack') {
|
||||
// 货架执行删除需要检测库位是否还有库存
|
||||
throw new Error('货架XX库位有库存,禁止删除,请先移库');
|
||||
// 货架执行删除前,按真实库存判断是否可删。
|
||||
const { Op } = ctx.app.Sequelize;
|
||||
const spaces = await ctx.model.LocationSpace.findAll({
|
||||
where: {
|
||||
zone_id: id,
|
||||
deleted_at: null,
|
||||
},
|
||||
attributes: [ 'id' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const spaceIds = (Array.isArray(spaces) ? spaces : [])
|
||||
.map(space => Number(space && space.id))
|
||||
.filter(spaceId => Number.isFinite(spaceId) && spaceId > 0);
|
||||
|
||||
if (spaceIds.length > 0) {
|
||||
const stockCount = await ctx.model.Storage.count({
|
||||
where: {
|
||||
space_id: {
|
||||
[Op.in]: spaceIds,
|
||||
},
|
||||
delete_at: null,
|
||||
is_enabled: 1,
|
||||
quantity: {
|
||||
[Op.gt]: 0,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (stockCount > 0) {
|
||||
throw new Error('货架库位有库存,禁止删除,请先移库');
|
||||
}
|
||||
}
|
||||
}
|
||||
if (childrenCount > 0) {
|
||||
throw new Error('请先删除或转移所有子分区');
|
||||
@ -953,35 +984,42 @@ class LocationZoneService extends Service {
|
||||
}
|
||||
|
||||
async generateSpacesForRack(rackId, rack, transaction = null) {
|
||||
const { app } = this;
|
||||
const { app, ctx } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
const { rack_columns, rack_rows, rack_levels, direction, x, y, z } = rack;
|
||||
const expectedSpaceCount = Number(rack_columns || 0) * Number(rack_rows || 0) * Number(rack_levels || 0);
|
||||
|
||||
// 读取已有仓位编码,用于差量补齐。
|
||||
const existingSpaces = await ctx.model.LocationSpace.findAll({
|
||||
where: {
|
||||
zone_id: rackId,
|
||||
deleted_at: null,
|
||||
},
|
||||
attributes: [ 'id', 'space_code' ],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
const existingSpaceCodeSet = new Set(
|
||||
(Array.isArray(existingSpaces) ? existingSpaces : [])
|
||||
.map(item => String(item && item.space_code || '').trim())
|
||||
.filter(Boolean)
|
||||
);
|
||||
|
||||
const rackWidth = rack.width;
|
||||
const rackLength = rack.length;
|
||||
const prelativeX = x;
|
||||
const prelativeY = y;
|
||||
const prelativeZ = z;
|
||||
const cellLength = rackLength / rack_columns / rack_levels;
|
||||
const cellWidth = rackWidth;
|
||||
const cellHeight = rack.height / rack_rows;
|
||||
|
||||
const spaces = [];
|
||||
let rackWidth = 0;
|
||||
let rackLength = 0;
|
||||
let cellLength = 0;
|
||||
let cellWidth = 0;
|
||||
let cellHeight = 0;
|
||||
let prelativeX = 0;
|
||||
let prelativeY = 0;
|
||||
let prelativeZ = 0;
|
||||
|
||||
rackWidth = rack.width;
|
||||
rackLength = rack.length;
|
||||
prelativeX = x;
|
||||
prelativeY = y;
|
||||
prelativeZ = z;
|
||||
// 计算每个仓位的尺寸
|
||||
cellLength = rackLength / rack_columns / rack_levels;
|
||||
cellWidth = rackWidth;
|
||||
cellHeight = rack.height / rack_rows;
|
||||
|
||||
// 生成所有仓位
|
||||
for (let column = 1; column <= rack_columns; column++) {
|
||||
for (let row = 1; row <= rack_rows; row++) {
|
||||
for (let row = 1; row <= rack_rows; row++) {
|
||||
for (let column = 1; column <= rack_columns; column++) {
|
||||
for (let level = 1; level <= rack_levels; level++) {
|
||||
const spaceCode = `${rack.zone_code}-${column.toString().padStart(2, '0')}-${row.toString().padStart(2, '0')}-${level.toString().padStart(2, '0')}`;
|
||||
|
||||
// 计算相对坐标
|
||||
let relativeX = 0;
|
||||
let relativeY = 0;
|
||||
let relativeZ = (level - 1) * cellWidth + prelativeZ;
|
||||
@ -999,7 +1037,7 @@ class LocationZoneService extends Service {
|
||||
spaces.push({
|
||||
warehouse_id: rack.warehouse_id,
|
||||
zone_id: rackId,
|
||||
location_type_id: row === 1 ? 1 : 2, // 默认第一层为分拣,其他层为存储
|
||||
location_type_id: row === 1 ? 1 : 2,
|
||||
space_code: spaceCode,
|
||||
row_no: row.toString(),
|
||||
column_no: column.toString(),
|
||||
@ -1008,8 +1046,8 @@ class LocationZoneService extends Service {
|
||||
length: cellLength,
|
||||
width: cellWidth,
|
||||
height: cellHeight,
|
||||
volume: cellLength * cellWidth * cellHeight / 1000000, // cm³转m³
|
||||
max_weight: 100, // 默认100kg
|
||||
volume: cellLength * cellWidth * cellHeight / 1000000,
|
||||
max_weight: 100,
|
||||
space_status: 'AVAILABLE',
|
||||
is_enabled: true,
|
||||
relative_x: relativeX,
|
||||
@ -1021,11 +1059,104 @@ class LocationZoneService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
// 批量插入仓位
|
||||
if (spaces.length > 0) {
|
||||
await app.model.LocationSpace.bulkCreate(spaces, { transaction });
|
||||
const expectedSpaceCodeSet = new Set(spaces.map(space => String(space.space_code || '').trim()).filter(Boolean));
|
||||
const spacesNeedDelete = (Array.isArray(existingSpaces) ? existingSpaces : []).filter(space => {
|
||||
const spaceCode = String(space && space.space_code || '').trim();
|
||||
return spaceCode && !expectedSpaceCodeSet.has(spaceCode);
|
||||
});
|
||||
|
||||
if (spacesNeedDelete.length > 0) {
|
||||
const extraSpaceIds = spacesNeedDelete
|
||||
.map(space => Number(space && space.id))
|
||||
.filter(spaceId => Number.isFinite(spaceId) && spaceId > 0);
|
||||
|
||||
if (extraSpaceIds.length > 0) {
|
||||
const storages = await ctx.model.Storage.findAll({
|
||||
where: {
|
||||
space_id: {
|
||||
[Op.in]: extraSpaceIds,
|
||||
},
|
||||
delete_at: null,
|
||||
is_enabled: 1,
|
||||
[Op.or]: [
|
||||
{ quantity: { [Op.gt]: 0 } },
|
||||
{ locked_quantity: { [Op.gt]: 0 } },
|
||||
{ available_quantity: { [Op.gt]: 0 } },
|
||||
],
|
||||
},
|
||||
attributes: [ 'space_id', 'quantity', 'locked_quantity', 'available_quantity' ],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
|
||||
if (Array.isArray(storages) && storages.length > 0) {
|
||||
const occupiedSpaceIdSet = new Set(storages.map(item => Number(item && item.space_id)).filter(Boolean));
|
||||
const occupiedSpaceCodes = spacesNeedDelete
|
||||
.filter(space => occupiedSpaceIdSet.has(Number(space && space.id)))
|
||||
.map(space => String(space && space.space_code || '').trim())
|
||||
.filter(Boolean);
|
||||
|
||||
throw new Error(`发现 ${spacesNeedDelete.length} 个多余库位,其中 ${occupiedSpaceCodes.length} 个存在库存,禁止自动删除:${occupiedSpaceCodes.slice(0, 10).join(',')}`);
|
||||
}
|
||||
|
||||
await ctx.model.LocationSpace.destroy({
|
||||
where: {
|
||||
id: {
|
||||
[Op.in]: extraSpaceIds,
|
||||
},
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const missingSpaces = spaces.filter(space => !existingSpaceCodeSet.has(String(space.space_code || '').trim()));
|
||||
const existingSpaceCount = existingSpaceCodeSet.size;
|
||||
|
||||
if (missingSpaces.length === 0 && spacesNeedDelete.length === 0) {
|
||||
return `货架 ${rack.zone_code} 已完整存在 ${existingSpaceCount} 个仓位,无需补齐`;
|
||||
}
|
||||
|
||||
if (missingSpaces.length === 0) {
|
||||
return `货架 ${rack.zone_code} 已删除 ${spacesNeedDelete.length} 个多余库位,当前总数 ${expectedSpaceCount}/${expectedSpaceCount}`;
|
||||
}
|
||||
|
||||
try {
|
||||
await app.model.LocationSpace.bulkCreate(missingSpaces, { transaction });
|
||||
const finalSpaceCount = existingSpaceCount - spacesNeedDelete.length + missingSpaces.length;
|
||||
if (spacesNeedDelete.length > 0) {
|
||||
return `为货架 ${rack.zone_code} 删除 ${spacesNeedDelete.length} 个多余库位并补齐 ${missingSpaces.length} 个仓位(总数 ${finalSpaceCount}/${expectedSpaceCount})`;
|
||||
}
|
||||
return `为货架 ${rack.zone_code} 补齐 ${missingSpaces.length} 个仓位(总数 ${finalSpaceCount}/${expectedSpaceCount})`;
|
||||
} catch (error) {
|
||||
// 并发场景:再次按编码回查后补齐剩余缺口。
|
||||
const latestSpaces = await ctx.model.LocationSpace.findAll({
|
||||
where: {
|
||||
zone_id: rackId,
|
||||
deleted_at: null,
|
||||
},
|
||||
attributes: [ 'space_code' ],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
const latestSpaceCodeSet = new Set(
|
||||
(Array.isArray(latestSpaces) ? latestSpaces : [])
|
||||
.map(item => String(item && item.space_code || '').trim())
|
||||
.filter(Boolean)
|
||||
);
|
||||
const retryMissingSpaces = spaces.filter(space => !latestSpaceCodeSet.has(String(space.space_code || '').trim()));
|
||||
|
||||
if (retryMissingSpaces.length === 0) {
|
||||
return `货架 ${rack.zone_code} 已完整存在 ${latestSpaceCodeSet.size} 个仓位,无需补齐`;
|
||||
}
|
||||
|
||||
await app.model.LocationSpace.bulkCreate(retryMissingSpaces, { transaction });
|
||||
const finalSpaceCount = latestSpaceCodeSet.size + retryMissingSpaces.length;
|
||||
if (spacesNeedDelete.length > 0) {
|
||||
return `为货架 ${rack.zone_code} 删除 ${spacesNeedDelete.length} 个多余库位并补齐 ${retryMissingSpaces.length} 个仓位(总数 ${finalSpaceCount}/${expectedSpaceCount})`;
|
||||
}
|
||||
return `为货架 ${rack.zone_code} 补齐 ${retryMissingSpaces.length} 个仓位(总数 ${finalSpaceCount}/${expectedSpaceCount})`;
|
||||
}
|
||||
return `为货架 ${rack.zone_code} 生成了 ${spaces.length} 个仓位`;
|
||||
}
|
||||
async getSpaceInfo(id) {
|
||||
const { ctx } = this;
|
||||
|
||||
@ -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;
|
||||
|
||||
@ -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)) {
|
||||
|
||||
@ -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,
|
||||
});
|
||||
}
|
||||
/**
|
||||
|
||||
@ -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;
|
||||
|
||||
@ -25,4 +25,4 @@ class QimenQueryService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = QimenQueryService;
|
||||
module.exports = QimenQueryService;
|
||||
|
||||
@ -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);
|
||||
|
||||
@ -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);
|
||||
}
|
||||
|
||||
@ -69,7 +69,7 @@ class ReceivingService extends Service {
|
||||
},
|
||||
order: [],
|
||||
attributes: {
|
||||
exclude: ['deleted_at'],
|
||||
exclude: [ 'deleted_at' ],
|
||||
},
|
||||
};
|
||||
|
||||
@ -115,7 +115,7 @@ class ReceivingService extends Service {
|
||||
parsedResult = parsed.result;
|
||||
}
|
||||
|
||||
const dynamicConditions = [...(parsedResult.dynamicConditions || [])];
|
||||
const dynamicConditions = [ ...(parsedResult.dynamicConditions || []) ];
|
||||
const quickWhereRaw = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere)
|
||||
|| normalizedWhere.quickWhere;
|
||||
|
||||
@ -153,14 +153,14 @@ class ReceivingService extends Service {
|
||||
];
|
||||
const actualSortField = validSortFields.includes(sortField) ? sortField : 'create_at';
|
||||
const actualSortOrder = sortOrder.toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
|
||||
queryOptions.order.push([actualSortField, actualSortOrder]);
|
||||
queryOptions.order.push([ actualSortField, actualSortOrder ]);
|
||||
|
||||
const offset = (page - 1) * pageSize;
|
||||
const include = [
|
||||
{
|
||||
model: ctx.model.StoreWarehouse,
|
||||
as: 'store',
|
||||
attributes: ['store_remask'],
|
||||
attributes: [ 'store_remask' ],
|
||||
where: {
|
||||
use_status: 1,
|
||||
warehouse_id: ctx.user.store_id,
|
||||
@ -170,12 +170,12 @@ class ReceivingService extends Service {
|
||||
{
|
||||
model: ctx.model.AccountStoreEmployee,
|
||||
as: 'creator',
|
||||
attributes: ['real_name'],
|
||||
attributes: [ 'real_name' ],
|
||||
required: true,
|
||||
},
|
||||
];
|
||||
|
||||
const [total, data] = await Promise.all([
|
||||
const [ total, data ] = await Promise.all([
|
||||
ctx.model.Receiving.count({
|
||||
where: queryOptions.where,
|
||||
include,
|
||||
@ -209,7 +209,7 @@ class ReceivingService extends Service {
|
||||
{
|
||||
model: ctx.model.File,
|
||||
as: 'file',
|
||||
attributes: ['file_url'],
|
||||
attributes: [ 'file_url' ],
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
@ -341,7 +341,7 @@ class ReceivingService extends Service {
|
||||
include: [{
|
||||
model: ctx.model.File,
|
||||
as: 'file',
|
||||
attributes: ['file_url'],
|
||||
attributes: [ 'file_url' ],
|
||||
required: true,
|
||||
}],
|
||||
});
|
||||
@ -372,7 +372,7 @@ class ReceivingService extends Service {
|
||||
include: [{
|
||||
model: ctx.model.File,
|
||||
as: 'file',
|
||||
attributes: ['file_url'],
|
||||
attributes: [ 'file_url' ],
|
||||
required: true,
|
||||
}],
|
||||
});
|
||||
@ -671,7 +671,7 @@ class ReceivingService extends Service {
|
||||
case 'daterange':
|
||||
// 处理日期范围:数组的第一个元素是开始时间,第二个元素是结束时间
|
||||
if (Array.isArray(value) && value.length === 2) {
|
||||
const [startDate, endDate] = value;
|
||||
const [ startDate, endDate ] = value;
|
||||
return [
|
||||
startDate ? service.main.normalizeDate(startDate, false) : null, // 开始时间设为00:00:00
|
||||
endDate ? service.main.normalizeDate(endDate, true) : null, // 结束时间设为23:59:59
|
||||
@ -680,10 +680,10 @@ class ReceivingService extends Service {
|
||||
return value;
|
||||
|
||||
case 'number':
|
||||
{
|
||||
const num = parseFloat(value);
|
||||
return isNaN(num) ? value : num;
|
||||
}
|
||||
{
|
||||
const num = parseFloat(value);
|
||||
return isNaN(num) ? value : num;
|
||||
}
|
||||
case 'text':
|
||||
if (typeof value === 'string') {
|
||||
return value.split(',').map(item => item.trim());
|
||||
@ -705,15 +705,15 @@ class ReceivingService extends Service {
|
||||
const suffixStartIndex = prefix.length + 1;
|
||||
|
||||
const maxReceiving = await app.model.Receiving.findOne({
|
||||
attributes: ['receiving_number'],
|
||||
attributes: [ 'receiving_number' ],
|
||||
where: {
|
||||
receiving_number: {
|
||||
[app.Sequelize.Op.like]: `${prefix}%`,
|
||||
},
|
||||
},
|
||||
order: [
|
||||
[app.Sequelize.literal(`CAST(SUBSTRING(receiving_number, ${suffixStartIndex}) AS UNSIGNED)`), 'DESC'],
|
||||
['receiving_number', 'DESC'],
|
||||
[ app.Sequelize.literal(`CAST(SUBSTRING(receiving_number, ${suffixStartIndex}) AS UNSIGNED)`), 'DESC' ],
|
||||
[ 'receiving_number', 'DESC' ],
|
||||
],
|
||||
});
|
||||
|
||||
@ -943,7 +943,7 @@ class ReceivingService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
if (['receiving', 'completed'].includes(receiving.status) && Number(receiving.store_id || 0) > 0) {
|
||||
if ([ 'receiving', 'completed' ].includes(receiving.status) && Number(receiving.store_id || 0) > 0) {
|
||||
await transaction.rollback();
|
||||
return {
|
||||
code: 400,
|
||||
@ -957,7 +957,7 @@ class ReceivingService extends Service {
|
||||
store_id: storeId,
|
||||
use_status: 1,
|
||||
},
|
||||
attributes: ['store_id', 'store_remask'],
|
||||
attributes: [ 'store_id', 'store_remask' ],
|
||||
transaction,
|
||||
});
|
||||
|
||||
@ -1053,7 +1053,7 @@ class ReceivingService extends Service {
|
||||
include: [{
|
||||
model: ctx.model.StoreWarehouse,
|
||||
as: 'store',
|
||||
attributes: ['store_remask'],
|
||||
attributes: [ 'store_remask' ],
|
||||
where: {
|
||||
use_status: 1,
|
||||
warehouse_id: warehouseId,
|
||||
@ -1062,7 +1062,7 @@ class ReceivingService extends Service {
|
||||
}, {
|
||||
model: ctx.model.AccountStoreEmployee,
|
||||
as: 'creator',
|
||||
attributes: ['real_name'],
|
||||
attributes: [ 'real_name' ],
|
||||
required: false,
|
||||
}],
|
||||
// 不需要order,因为根据id查询已经是唯一的
|
||||
@ -1080,10 +1080,10 @@ class ReceivingService extends Service {
|
||||
{
|
||||
model: ctx.model.LocationSpace,
|
||||
as: 'receiving_space',
|
||||
attributes: ['space_code', 'custom_barcode', 'custom_name'],
|
||||
attributes: [ 'space_code', 'custom_barcode', 'custom_name' ],
|
||||
},
|
||||
],
|
||||
order: [['id', 'DESC']], // 保持倒序,最新在前
|
||||
order: [[ 'id', 'DESC' ]], // 保持倒序,最新在前
|
||||
});
|
||||
|
||||
// 3. 获取明细ID数组
|
||||
@ -1102,7 +1102,7 @@ class ReceivingService extends Service {
|
||||
include: [{
|
||||
model: ctx.model.File,
|
||||
as: 'file',
|
||||
attributes: ['file_url'],
|
||||
attributes: [ 'file_url' ],
|
||||
required: true,
|
||||
}],
|
||||
});
|
||||
@ -1136,7 +1136,7 @@ class ReceivingService extends Service {
|
||||
include: [{
|
||||
model: ctx.model.File,
|
||||
as: 'file',
|
||||
attributes: ['file_url'],
|
||||
attributes: [ 'file_url' ],
|
||||
required: true,
|
||||
}],
|
||||
});
|
||||
@ -1216,7 +1216,7 @@ class ReceivingService extends Service {
|
||||
// 获取更新后的明细列表
|
||||
const allDetails = await ctx.model.ReceivingDetail.findAll({
|
||||
where: { receiving_id },
|
||||
order: [['id', 'DESC']],
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
});
|
||||
|
||||
// 格式化返回数据
|
||||
@ -1322,7 +1322,7 @@ class ReceivingService extends Service {
|
||||
{
|
||||
model: app.model.Receiving,
|
||||
as: 'receiving',
|
||||
attributes: ['id', 'warehouse_id', 'store_id', 'store_name', 'status'],
|
||||
attributes: [ 'id', 'warehouse_id', 'store_id', 'store_name', 'status' ],
|
||||
where: {
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
@ -1347,12 +1347,12 @@ class ReceivingService extends Service {
|
||||
app.model.StoreWarehouse.buildStoreStockInclude({
|
||||
warehouseId,
|
||||
required: false,
|
||||
attributes: ['store_id', 'store_remask'],
|
||||
attributes: [ 'store_id', 'store_remask' ],
|
||||
}),
|
||||
{
|
||||
model: app.model.StockBarcode,
|
||||
as: 'barcodes',
|
||||
attributes: ['barcode'],
|
||||
attributes: [ 'barcode' ],
|
||||
required: false,
|
||||
},
|
||||
],
|
||||
@ -1511,7 +1511,7 @@ class ReceivingService extends Service {
|
||||
{
|
||||
model: ctx.model.Receiving,
|
||||
as: 'receiving',
|
||||
attributes: ['id', 'status'],
|
||||
attributes: [ 'id', 'status' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
@ -1604,7 +1604,7 @@ class ReceivingService extends Service {
|
||||
}
|
||||
|
||||
// 更新明细
|
||||
const [affectedRows] = await ctx.model.ReceivingDetail.update(updateData, {
|
||||
const [ affectedRows ] = await ctx.model.ReceivingDetail.update(updateData, {
|
||||
where: { id },
|
||||
});
|
||||
|
||||
@ -1627,7 +1627,7 @@ class ReceivingService extends Service {
|
||||
{
|
||||
model: ctx.model.StockWarehouse,
|
||||
as: 'system_product',
|
||||
attributes: ['id', 'name', 'barcode', 'spec', 'unit', 'images'],
|
||||
attributes: [ 'id', 'name', 'barcode', 'spec', 'unit', 'images' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
@ -1676,7 +1676,7 @@ class ReceivingService extends Service {
|
||||
ctx.model.StoreWarehouse.buildStoreStockInclude({
|
||||
warehouseId: ctx.user.store_id,
|
||||
required: false,
|
||||
attributes: ['store_id', 'store_remask'],
|
||||
attributes: [ 'store_id', 'store_remask' ],
|
||||
}),
|
||||
],
|
||||
});
|
||||
@ -1759,8 +1759,8 @@ class ReceivingService extends Service {
|
||||
const stats = await ctx.model.ReceivingDetail.findAll({
|
||||
where: { receiving_id: receivingId },
|
||||
attributes: [
|
||||
[ctx.model.fn('COUNT', ctx.model.col('id')), 'total_items'],
|
||||
[ctx.model.fn('SUM', ctx.model.col('actual_quantity')), 'total_quantity'],
|
||||
[ ctx.model.fn('COUNT', ctx.model.col('id')), 'total_items' ],
|
||||
[ ctx.model.fn('SUM', ctx.model.col('actual_quantity')), 'total_quantity' ],
|
||||
],
|
||||
raw: true,
|
||||
transaction,
|
||||
@ -1843,7 +1843,7 @@ class ReceivingService extends Service {
|
||||
{
|
||||
model: ctx.model.Receiving,
|
||||
as: 'receiving',
|
||||
attributes: ['id', 'status'],
|
||||
attributes: [ 'id', 'status' ],
|
||||
where: {
|
||||
warehouse_id,
|
||||
},
|
||||
@ -1894,7 +1894,7 @@ class ReceivingService extends Service {
|
||||
// 获取删除后的所有明细
|
||||
const remainingDetails = await ctx.model.ReceivingDetail.findAll({
|
||||
where: { receiving_id },
|
||||
order: [['id', 'DESC']],
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
});
|
||||
|
||||
// 格式化返回数据
|
||||
@ -2013,7 +2013,7 @@ class ReceivingService extends Service {
|
||||
{
|
||||
model: app.model.Receiving,
|
||||
as: 'receiving',
|
||||
attributes: ['id', 'warehouse_id', 'store_id', 'store_name'],
|
||||
attributes: [ 'id', 'warehouse_id', 'store_id', 'store_name' ],
|
||||
where: {
|
||||
warehouse_id: warehouseId,
|
||||
id: receiving_id,
|
||||
@ -2090,12 +2090,12 @@ class ReceivingService extends Service {
|
||||
app.model.StoreWarehouse.buildStoreStockInclude({
|
||||
warehouseId,
|
||||
required: false,
|
||||
attributes: ['store_id', 'store_remask'],
|
||||
attributes: [ 'store_id', 'store_remask' ],
|
||||
}),
|
||||
{
|
||||
model: app.model.StockBarcode,
|
||||
as: 'barcodes',
|
||||
attributes: ['barcode'],
|
||||
attributes: [ 'barcode' ],
|
||||
required: false,
|
||||
},
|
||||
],
|
||||
@ -2390,11 +2390,11 @@ class ReceivingService extends Service {
|
||||
const deliveryMethod = String((receiving && receiving.delivery_method) || '').trim();
|
||||
|
||||
if (deliveryMethod === 'truck') {
|
||||
return [['车牌号', receiving && receiving.license_plate]];
|
||||
return [[ '车牌号', receiving && receiving.license_plate ]];
|
||||
}
|
||||
|
||||
if (deliveryMethod === 'express') {
|
||||
return [['物流单号', receiving && receiving.tracking_number]];
|
||||
return [[ '物流单号', receiving && receiving.tracking_number ]];
|
||||
}
|
||||
|
||||
return [];
|
||||
@ -2448,7 +2448,7 @@ class ReceivingService extends Service {
|
||||
);
|
||||
|
||||
const buildLinkCell = urls => {
|
||||
const normalizedUrls = (Array.isArray(urls) ? urls : [urls])
|
||||
const normalizedUrls = (Array.isArray(urls) ? urls : [ urls ])
|
||||
.map(item => String(item || '').trim())
|
||||
.filter(Boolean);
|
||||
|
||||
@ -2484,22 +2484,22 @@ class ReceivingService extends Service {
|
||||
pushReportRow([]);
|
||||
|
||||
[
|
||||
['收货单ID', receiving && receiving.id],
|
||||
['收货单号', receiving && receiving.receiving_number],
|
||||
['货主', receiving && receiving.store_name],
|
||||
['来货方式', this.formatDeliveryMethod(receiving && receiving.delivery_method)],
|
||||
[ '收货单ID', receiving && receiving.id ],
|
||||
[ '收货单号', receiving && receiving.receiving_number ],
|
||||
[ '货主', receiving && receiving.store_name ],
|
||||
[ '来货方式', this.formatDeliveryMethod(receiving && receiving.delivery_method) ],
|
||||
...this.getCompletionContactFields(receiving),
|
||||
['总明细数', stats.total_details || details.length],
|
||||
['已匹配明细数', stats.matched_details || 0],
|
||||
['未匹配明细数', stats.unmatched_details || 0],
|
||||
['总数量', stats.total_quantity || 0],
|
||||
['总箱数', receiving && receiving.total_boxes],
|
||||
['总托盘数', receiving && receiving.total_pallets],
|
||||
['完成人', operator.employees_name || operator.real_name || operator.name || ''],
|
||||
['完成时间', this.formatReportDate(receiving && receiving.receiving_end_time)],
|
||||
['备注', receiving && receiving.remark],
|
||||
].forEach(([field, value]) => {
|
||||
pushReportRow([field, value], {
|
||||
[ '总明细数', stats.total_details || details.length ],
|
||||
[ '已匹配明细数', stats.matched_details || 0 ],
|
||||
[ '未匹配明细数', stats.unmatched_details || 0 ],
|
||||
[ '总数量', stats.total_quantity || 0 ],
|
||||
[ '总箱数', receiving && receiving.total_boxes ],
|
||||
[ '总托盘数', receiving && receiving.total_pallets ],
|
||||
[ '完成人', operator.employees_name || operator.real_name || operator.name || '' ],
|
||||
[ '完成时间', this.formatReportDate(receiving && receiving.receiving_end_time) ],
|
||||
[ '备注', receiving && receiving.remark ],
|
||||
].forEach(([ field, value ]) => {
|
||||
pushReportRow([ field, value ], {
|
||||
toCol: 2,
|
||||
style: {
|
||||
alignment: { vertical: 'top', wrapText: true },
|
||||
@ -2508,7 +2508,7 @@ class ReceivingService extends Service {
|
||||
});
|
||||
|
||||
if (mainImageUrls.length === 0) {
|
||||
pushReportRow(['收货图片', '无'], {
|
||||
pushReportRow([ '收货图片', '无' ], {
|
||||
toCol: 2,
|
||||
style: {
|
||||
alignment: { vertical: 'top', wrapText: true },
|
||||
@ -2517,7 +2517,7 @@ class ReceivingService extends Service {
|
||||
} else {
|
||||
const summaryLinkCell = buildLinkCell(mainImageUrls);
|
||||
const imagePlaceholders = Array(Math.max(mainImageUrls.length, 1)).fill('');
|
||||
const firstImageRowIndex = pushReportRow(['收货图片', summaryLinkCell, ...imagePlaceholders], {
|
||||
const firstImageRowIndex = pushReportRow([ '收货图片', summaryLinkCell, ...imagePlaceholders ], {
|
||||
toCol: 2 + imagePlaceholders.length,
|
||||
height: 88,
|
||||
style: {
|
||||
@ -2554,7 +2554,7 @@ class ReceivingService extends Service {
|
||||
});
|
||||
|
||||
if (details.length === 0) {
|
||||
pushReportRow(['', '', '无明细'], {
|
||||
pushReportRow([ '', '', '无明细' ], {
|
||||
toCol: detailColumns.length,
|
||||
style: {
|
||||
alignment: { vertical: 'top', wrapText: true },
|
||||
@ -2703,7 +2703,7 @@ class ReceivingService extends Service {
|
||||
(completionReport && (completionReport.filename || completionReport.fileKey || completionReport.key)) || `收货完成_${receivingNumber}.xlsx`
|
||||
).trim();
|
||||
const title = `收货单${receivingNumber}已完成`;
|
||||
const contactLines = this.getCompletionContactFields(receiving).map(([field, value]) => `${field}:${value || '无'}`);
|
||||
const contactLines = this.getCompletionContactFields(receiving).map(([ field, value ]) => `${field}:${value || '无'}`);
|
||||
const content = [
|
||||
`收货单号:${receivingNumber} 已完成`,
|
||||
`货主:${receiving.store_name || '未知'}`,
|
||||
@ -2957,7 +2957,7 @@ class ReceivingService extends Service {
|
||||
include: [{
|
||||
model: ctx.model.File,
|
||||
as: 'file',
|
||||
attributes: ['file_url'],
|
||||
attributes: [ 'file_url' ],
|
||||
required: false,
|
||||
}],
|
||||
transaction,
|
||||
@ -2985,7 +2985,7 @@ class ReceivingService extends Service {
|
||||
include: [{
|
||||
model: ctx.model.File,
|
||||
as: 'file',
|
||||
attributes: ['file_url'],
|
||||
attributes: [ 'file_url' ],
|
||||
required: false,
|
||||
}],
|
||||
transaction,
|
||||
@ -3209,7 +3209,7 @@ class ReceivingService extends Service {
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async _syncProductDataFromReceiving({ receivingId, warehouseId, details }) {
|
||||
console.log("_syncProductDataFromReceiving异步执行中..."); // 调试日志
|
||||
console.log('_syncProductDataFromReceiving异步执行中...'); // 调试日志
|
||||
const { ctx, app } = this;
|
||||
|
||||
// 只处理已绑定系统商品的明细
|
||||
@ -3229,7 +3229,7 @@ class ReceivingService extends Service {
|
||||
warehouse_id: warehouseId,
|
||||
deleted_at: null,
|
||||
},
|
||||
attributes: ['id', 'is_images', 'gross_weight'],
|
||||
attributes: [ 'id', 'is_images', 'gross_weight' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
@ -3242,7 +3242,7 @@ class ReceivingService extends Service {
|
||||
business_id: String(detail.id),
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
attributes: ['file_id'],
|
||||
attributes: [ 'file_id' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
@ -3254,7 +3254,7 @@ class ReceivingService extends Service {
|
||||
business_id: String(systemProductId),
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
attributes: ['file_id'],
|
||||
attributes: [ 'file_id' ],
|
||||
raw: true,
|
||||
}).then(rows => rows.map(r => r.file_id));
|
||||
|
||||
|
||||
@ -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,
|
||||
});
|
||||
|
||||
|
||||
@ -167,7 +167,7 @@ module.exports = appInfo => {
|
||||
deletedAt: 'deleted_at', // 软删除字段名
|
||||
},
|
||||
pool: {
|
||||
max: 5,
|
||||
max: 20,
|
||||
min: 1,
|
||||
idle: 10000,
|
||||
acquire: 30000,
|
||||
|
||||
@ -90,4 +90,4 @@ module.exports = {
|
||||
);
|
||||
}
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
@ -104,4 +104,4 @@ module.exports = {
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
@ -1 +1 @@
|
||||
{"startedAt":1777218488523,"recordCount":1}
|
||||
{"startedAt":1777304067412,"recordCount":8}
|
||||
|
||||
1
runtime/file-writer/.write-window-counter-4.json
Normal file
1
runtime/file-writer/.write-window-counter-4.json
Normal file
@ -0,0 +1 @@
|
||||
{"startedAt":1777304050565,"recordCount":67}
|
||||
@ -1,7 +1,7 @@
|
||||
{
|
||||
"filePath": "D:\\wms\\runtime\\file-writer\\qimen-logs\\2026\\04\\12\\qimen-logs-MINGREN-worker-p38224-0001.log",
|
||||
"offset": 1713,
|
||||
"processedCount": 1,
|
||||
"completedAt": "2026-04-12T14:54:22.636Z",
|
||||
"updatedAt": "2026-04-17T12:02:32.964Z"
|
||||
"filePath": "D:\\wms\\runtime\\file-writer\\qimen-logs\\2026\\04\\27\\qimen-logs-MINGREN-worker-p17872-0001.log",
|
||||
"offset": 18973,
|
||||
"processedCount": 7,
|
||||
"completedAt": "2026-04-27T13:30:41.800Z",
|
||||
"updatedAt": "2026-04-29T09:42:51.811Z"
|
||||
}
|
||||
|
||||
@ -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=×tamp=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}
|
||||
@ -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"
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@ -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"
|
||||
}
|
||||
@ -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×tamp=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.');
|
||||
|
||||
}
|
||||
|
||||
@ -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\(\/\^\?\//);
|
||||
|
||||
@ -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>/);
|
||||
});
|
||||
|
||||
@ -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,
|
||||
|
||||
146
test/app/service/systemMethods/order/detail.images.test.js
Normal file
146
test/app/service/systemMethods/order/detail.images.test.js
Normal 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: [],
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
99
test/app/service/systemMethods/order/detail.logs.test.js
Normal file
99
test/app/service/systemMethods/order/detail.logs.test.js
Normal 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);
|
||||
});
|
||||
});
|
||||
@ -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);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user