505 lines
14 KiB
JavaScript
505 lines
14 KiB
JavaScript
'use strict';
|
||
|
||
const { Service } = require('egg');
|
||
|
||
const DEFAULT_CACHE_TTL_SECONDS = 600;
|
||
const DEFAULT_EXPRESS_PRODUCT_TYPE_CACHE_TTL_SECONDS = 60 * 60;
|
||
|
||
class ExpressService extends Service {
|
||
/**
|
||
* 生成快递列表缓存键。
|
||
*
|
||
* @param {number|string} warehouseId 仓库ID
|
||
* @return {string} 缓存键
|
||
*/
|
||
getExpressListCacheKey(warehouseId = 0) {
|
||
const normalizedWarehouseId = Number(warehouseId || 0);
|
||
|
||
if (Number.isFinite(normalizedWarehouseId) && normalizedWarehouseId > 0) {
|
||
return `express:list:${normalizedWarehouseId}`;
|
||
}
|
||
|
||
return 'express:list';
|
||
}
|
||
|
||
/**
|
||
* 获取当前上下文中的仓库ID。
|
||
*
|
||
* @return {number} 仓库ID,未获取到时返回 0
|
||
*/
|
||
getCurrentWarehouseId() {
|
||
const warehouseId = Number(this.ctx && this.ctx.user && this.ctx.user.store_id || 0);
|
||
|
||
if (Number.isFinite(warehouseId) && warehouseId > 0) {
|
||
return warehouseId;
|
||
}
|
||
|
||
return 0;
|
||
}
|
||
|
||
/**
|
||
* 生成合并后的快递项展示名称。
|
||
*
|
||
* @param {string} settingCode 快递设置编码
|
||
* @param {Object} expressItem 系统快递项
|
||
* @return {string} 展示名称
|
||
*/
|
||
buildMergedExpressLabel(settingCode, expressItem) {
|
||
const normalizedSettingCode = String(settingCode || '').trim();
|
||
const expressName = String(expressItem && (expressItem.name || expressItem.label || expressItem.code || expressItem.value) || '').trim();
|
||
|
||
if (!normalizedSettingCode) {
|
||
return expressName;
|
||
}
|
||
|
||
if (!expressName) {
|
||
return normalizedSettingCode;
|
||
}
|
||
|
||
return `${normalizedSettingCode} (${expressName})`;
|
||
}
|
||
|
||
/**
|
||
* 规范化快递设置记录。
|
||
*
|
||
* @param {Object} row 数据库记录
|
||
* @param {Map<string, Object>} expressMap 系统快递映射
|
||
* @return {Object|null} 规范化后的记录
|
||
*/
|
||
normalizeExpressSettingRow(row, expressMap) {
|
||
if (!row || typeof row !== 'object') {
|
||
return null;
|
||
}
|
||
|
||
const code = String(row.code || '').trim();
|
||
if (!code) {
|
||
return null;
|
||
}
|
||
|
||
const expressCode = String(row.express_code || '').trim();
|
||
const expressItem = expressMap instanceof Map ? expressMap.get(expressCode) : null;
|
||
const label = this.buildMergedExpressLabel(code, expressItem);
|
||
|
||
return {
|
||
code,
|
||
name: label,
|
||
value: code,
|
||
label,
|
||
is_system_setting: true,
|
||
id: row.id === undefined || row.id === null ? null : row.id,
|
||
alias: String(row.name || '').trim(),
|
||
express_code: String((expressItem && (expressItem.code || expressItem.value)) || expressCode || '').trim(),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 从数据库加载快递设置列表。
|
||
*
|
||
* @param {number|string} warehouseId 仓库ID
|
||
* @return {Promise<Array>} 快递设置列表
|
||
*/
|
||
async loadExpressSettingListFromDatabase(warehouseId = 0) {
|
||
const normalizedWarehouseId = Number(warehouseId || 0);
|
||
if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
|
||
return [];
|
||
}
|
||
|
||
const expressSettingModel = this.ctx.model && this.ctx.model.ExpressSetting;
|
||
if (!expressSettingModel || typeof expressSettingModel.findAll !== 'function') {
|
||
return [];
|
||
}
|
||
|
||
const rows = await expressSettingModel.findAll({
|
||
attributes: [ 'id', 'code', 'name', 'express_code' ],
|
||
where: {
|
||
warehouse_id: normalizedWarehouseId,
|
||
},
|
||
order: [[ 'code', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
|
||
if (!Array.isArray(rows)) {
|
||
return [];
|
||
}
|
||
|
||
return rows;
|
||
}
|
||
|
||
/**
|
||
* 合并系统快递和快递设置列表。
|
||
*
|
||
* @param {Array<Object>} expressList 系统快递列表
|
||
* @param {Array<Object>} expressSettingList 快递设置列表
|
||
* @return {Array<Object>} 合并后的快递列表
|
||
*/
|
||
buildMergedExpressList(expressList, expressSettingList) {
|
||
const mergedList = [];
|
||
const seenCodeMap = new Set();
|
||
const normalizedExpressList = Array.isArray(expressList) ? expressList : [];
|
||
const expressMap = new Map();
|
||
|
||
for (const expressItem of normalizedExpressList) {
|
||
if (!expressItem || typeof expressItem !== 'object') {
|
||
continue;
|
||
}
|
||
|
||
const code = String(expressItem.code || expressItem.value || '').trim();
|
||
if (!code) {
|
||
continue;
|
||
}
|
||
|
||
if (!expressMap.has(code)) {
|
||
expressMap.set(code, expressItem);
|
||
}
|
||
}
|
||
|
||
for (const expressItem of normalizedExpressList) {
|
||
if (!expressItem || typeof expressItem !== 'object') {
|
||
continue;
|
||
}
|
||
|
||
const code = String(expressItem.code || expressItem.value || '').trim();
|
||
if (!code || seenCodeMap.has(code)) {
|
||
continue;
|
||
}
|
||
|
||
mergedList.push(expressItem);
|
||
seenCodeMap.add(code);
|
||
}
|
||
|
||
for (const row of Array.isArray(expressSettingList) ? expressSettingList : []) {
|
||
const mergedItem = this.normalizeExpressSettingRow(row, expressMap);
|
||
if (!mergedItem || seenCodeMap.has(mergedItem.code)) {
|
||
continue;
|
||
}
|
||
|
||
mergedList.push(mergedItem);
|
||
seenCodeMap.add(mergedItem.code);
|
||
}
|
||
|
||
return mergedList;
|
||
}
|
||
|
||
/**
|
||
* 生成快递产品类型列表缓存键。
|
||
*
|
||
* @param {string} expressCode 快递公司编码
|
||
* @return {string} 缓存键
|
||
*/
|
||
getExpressProductTypeListCacheKey(expressCode = '') {
|
||
const normalizedExpressCode = String(expressCode || '').trim();
|
||
|
||
if (!normalizedExpressCode) {
|
||
return 'express:product-type:list';
|
||
}
|
||
|
||
return `express:product-type:list:${normalizedExpressCode}`;
|
||
}
|
||
|
||
/**
|
||
* 规范化快递产品类型记录。
|
||
*
|
||
* @param {Object} row 数据库记录
|
||
* @return {Object|null} 规范化后的记录
|
||
*/
|
||
normalizeExpressProductTypeRow(row) {
|
||
if (!row || typeof row !== 'object') {
|
||
return null;
|
||
}
|
||
|
||
const code = String(row.code || '').trim();
|
||
if (!code) {
|
||
return null;
|
||
}
|
||
|
||
const name = String(row.name || '').trim();
|
||
|
||
return {
|
||
code,
|
||
express_code: String(row.express_code || '').trim(),
|
||
name,
|
||
value: code,
|
||
label: name || code,
|
||
};
|
||
}
|
||
|
||
normalizeExpressRow(row) {
|
||
if (!row || typeof row !== 'object') {
|
||
return null;
|
||
}
|
||
|
||
const code = String(row.code || '').trim();
|
||
if (!code) {
|
||
return null;
|
||
}
|
||
|
||
return {
|
||
code,
|
||
name: String(row.name || '').trim(),
|
||
value: code,
|
||
label: String(row.name || code).trim(),
|
||
is_system_setting: false,
|
||
id: null,
|
||
alias: null,
|
||
};
|
||
}
|
||
|
||
async loadExpressListFromDatabase() {
|
||
const rows = await this.ctx.model.Express.findAll({
|
||
attributes: [ 'code', 'name' ],
|
||
order: [[ 'code', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
|
||
if (!Array.isArray(rows)) {
|
||
return [];
|
||
}
|
||
|
||
return rows
|
||
.map(row => this.normalizeExpressRow(row))
|
||
.filter(Boolean);
|
||
}
|
||
|
||
/**
|
||
* 获取系统快递编码和名称列表。
|
||
*
|
||
* 该接口只返回系统基础快递数据,不合并仓库自定义映射。
|
||
*
|
||
* @return {Promise<Array>} 系统快递编码和名称列表
|
||
*/
|
||
async getSystemExpressList() {
|
||
return await this.loadExpressListFromDatabase();
|
||
}
|
||
|
||
/**
|
||
* 从数据库加载快递产品类型列表。
|
||
*
|
||
* @param {string} expressCode 快递公司编码
|
||
* @return {Promise<Array>} 快递产品类型列表
|
||
*/
|
||
async loadExpressProductTypeListFromDatabase(expressCode = '') {
|
||
const normalizedExpressCode = String(expressCode || '').trim();
|
||
const query = {
|
||
attributes: [ 'code', 'name', 'express_code' ],
|
||
order: [[ 'express_code', 'ASC' ], [ 'code', 'ASC' ]],
|
||
raw: true,
|
||
};
|
||
|
||
if (normalizedExpressCode) {
|
||
query.where = {
|
||
express_code: normalizedExpressCode,
|
||
};
|
||
}
|
||
|
||
const rows = await this.ctx.model.ExpressProductType.findAll(query);
|
||
|
||
if (!Array.isArray(rows)) {
|
||
return [];
|
||
}
|
||
|
||
return rows
|
||
.map(row => this.normalizeExpressProductTypeRow(row))
|
||
.filter(Boolean);
|
||
}
|
||
|
||
/**
|
||
* 获取快递列表。
|
||
*
|
||
* 先读取系统快递,再按当前仓库合并快递设置;同一编码只保留一条记录。
|
||
*
|
||
* @return {Promise<Array>} 快递列表
|
||
*/
|
||
async getExpressList() {
|
||
const warehouseId = this.getCurrentWarehouseId();
|
||
const cacheKey = this.getExpressListCacheKey(warehouseId);
|
||
|
||
try {
|
||
const cachedList = await this.app.getCacheAsync(cacheKey);
|
||
if (cachedList !== null && cachedList !== undefined) {
|
||
return Array.isArray(cachedList) ? cachedList : [];
|
||
}
|
||
|
||
const [ expressList, expressSettingList ] = await Promise.all([
|
||
this.loadExpressListFromDatabase(),
|
||
this.loadExpressSettingListFromDatabase(warehouseId),
|
||
]);
|
||
|
||
const mergedList = this.buildMergedExpressList(expressList, expressSettingList);
|
||
await this.app.setCacheAsync(cacheKey, mergedList, DEFAULT_CACHE_TTL_SECONDS);
|
||
|
||
return mergedList;
|
||
} catch (error) {
|
||
this.ctx.logger.error('[ExpressService.getExpressList] 获取快递列表失败', {
|
||
error: error.message,
|
||
stack: error.stack,
|
||
});
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 获取快递产品类型列表。
|
||
*
|
||
* @param {string} expressCode 快递公司编码
|
||
* @return {Promise<Array>} 快递产品类型列表
|
||
*/
|
||
async getExpressProductTypeList(expressCode = '') {
|
||
const cacheKey = this.getExpressProductTypeListCacheKey(expressCode);
|
||
const normalizedExpressCode = String(expressCode || '').trim();
|
||
|
||
try {
|
||
const cachedList = await this.app.getCacheAsync(cacheKey);
|
||
if (cachedList !== null && cachedList !== undefined) {
|
||
return Array.isArray(cachedList) ? cachedList : [];
|
||
}
|
||
|
||
const expressProductTypeList = await this.loadExpressProductTypeListFromDatabase(normalizedExpressCode);
|
||
await this.app.setCacheAsync(cacheKey, expressProductTypeList, DEFAULT_EXPRESS_PRODUCT_TYPE_CACHE_TTL_SECONDS);
|
||
|
||
return expressProductTypeList;
|
||
} catch (error) {
|
||
this.ctx.logger.error('[ExpressService.getExpressProductTypeList] 获取快递产品类型失败', {
|
||
error: error.message,
|
||
stack: error.stack,
|
||
expressCode: normalizedExpressCode,
|
||
});
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 处理订单快递记录。
|
||
* 先按订单ID和业务键筛选 wms_order_express,再排除已存在且状态不为 0 的记录,
|
||
* 对可重试记录重置 retry_count,并为缺失记录补插状态为 0 的快递记录。
|
||
*
|
||
* @param {Array<Object>} orders 订单与业务键列表。
|
||
* @param {number} orders[].order_id 订单ID。
|
||
* @param {number} orders[].business_key 业务键。
|
||
* @return {Promise<Object>} 处理后的订单列表与运单号列表。
|
||
*/
|
||
async createWaybillCode(orders = []) {
|
||
const { app, ctx } = this;
|
||
const { Op } = app.Sequelize;
|
||
const orderExpressModel = ctx.model && ctx.model.OrderExpress;
|
||
if (!orderExpressModel
|
||
|| typeof orderExpressModel.findAll !== 'function'
|
||
|| typeof orderExpressModel.update !== 'function'
|
||
|| typeof orderExpressModel.bulkCreate !== 'function') {
|
||
throw new Error('订单快递模型未初始化');
|
||
}
|
||
|
||
// orders 入参去重归一化。
|
||
const normalizedOrderMap = new Map();
|
||
for (const order of Array.isArray(orders) ? orders : []) {
|
||
const orderId = Number(order && order.order_id);
|
||
const businessKey = Number(order && order.business_key);
|
||
|
||
if (!Number.isFinite(orderId) || orderId <= 0 || !Number.isInteger(businessKey)) {
|
||
continue;
|
||
}
|
||
|
||
const orderKey = `${orderId}:${businessKey}`;
|
||
if (!normalizedOrderMap.has(orderKey)) {
|
||
normalizedOrderMap.set(orderKey, {
|
||
order_id: orderId,
|
||
business_key: businessKey,
|
||
});
|
||
}
|
||
}
|
||
|
||
const normalizedOrders = Array.from(normalizedOrderMap.values());
|
||
if (normalizedOrders.length === 0) {
|
||
return {
|
||
orders: [],
|
||
waybill_codes: [],
|
||
};
|
||
}
|
||
|
||
// 事务开始。
|
||
return await app.model.transaction(async transaction => {
|
||
// 事务内批量查询已有记录。
|
||
const existingRows = await orderExpressModel.findAll({
|
||
where: {
|
||
[Op.or]: normalizedOrders.map(order => ({
|
||
order_id: order.order_id,
|
||
business_key: order.business_key,
|
||
})),
|
||
},
|
||
attributes: [ 'id', 'order_id', 'business_key', 'status', 'retry_count' ],
|
||
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);
|
||
}
|
||
}
|
||
|
||
// 重置可重试记录 retry_count=0。
|
||
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 rowsToCreate = [];
|
||
for (const order of normalizedOrders) {
|
||
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,
|
||
});
|
||
}
|
||
|
||
// 批量插入 status=0 的新记录。
|
||
if (rowsToCreate.length > 0) {
|
||
await orderExpressModel.bulkCreate(rowsToCreate, {
|
||
transaction,
|
||
});
|
||
}
|
||
|
||
return {
|
||
orders: normalizedOrders,
|
||
waybill_codes: [],
|
||
};
|
||
});
|
||
}
|
||
}
|
||
|
||
module.exports = ExpressService;
|