2026-04-27 16:09:26 +08:00

777 lines
21 KiB
JavaScript

'use strict';
const Service = require('egg').Service;
const { parseWhereConditions } = require('../../../lib/query_condition_parser');
class SettingExpressService extends Service {
/**
* 创建业务错误对象。
*
* @param {string} message 错误信息
* @param {number} [code=500] 错误码
* @return {Error} 错误对象
*/
createError(message, code = 500) {
const error = new Error(message);
error.code = code;
return error;
}
/**
* 获取当前仓库主体ID。
*
* @return {number} 当前仓库主体ID
*/
getCurrentStoreId() {
const storeId = Number(this.ctx.user && this.ctx.user.store_id);
if (!Number.isFinite(storeId) || storeId <= 0) {
throw this.createError('未识别到当前主体,无法操作快递映射', 400);
}
return storeId;
}
/**
* 生成当前仓库快递列表缓存键。
*
* @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';
}
/**
* 删除指定缓存键。
*
* @param {string} cacheKey 缓存键
* @return {Promise<void>}
*/
async deleteCacheByKey(cacheKey) {
if (!cacheKey) {
return;
}
const { app } = this;
if (app && typeof app.delCacheAsync === 'function') {
await app.delCacheAsync(cacheKey);
return;
}
if (app && typeof app.setCacheAsync === 'function') {
await app.setCacheAsync(cacheKey, null, 0);
}
}
/**
* 清理当前仓库快递列表缓存。
*
* @param {number|string} warehouseId 仓库主体ID
* @return {Promise<void>}
*/
async clearExpressListCache(warehouseId) {
await this.deleteCacheByKey(this.getExpressListCacheKey(warehouseId));
}
/**
* 规范化删除 ID 列表。
*
* 优先读取 `ids`,其次兼容单个 `id`、`setting_id`、`settingId`。
*
* @param {Object} data 请求参数
* @return {Array<number>} 删除 ID 列表
*/
normalizeDeleteIds(data = {}) {
const {
ids,
id,
setting_id: settingId,
settingId: camelSettingId,
} = data || {};
const rawIds = ids !== undefined
? ids
: (id !== undefined ? id : (settingId !== undefined ? settingId : camelSettingId));
const values = Array.isArray(rawIds)
? rawIds
: String(rawIds || '')
.split(',')
.map(item => item.trim())
.filter(Boolean);
const normalizedIds = [];
const seenIds = new Set();
for (const value of values) {
const normalized = Number(value);
if (!Number.isInteger(normalized) || normalized <= 0 || seenIds.has(normalized)) {
continue;
}
seenIds.add(normalized);
normalizedIds.push(normalized);
}
return normalizedIds;
}
/**
* 规范化文本值。
*
* @param {string} value 原始值
* @param {string} fieldName 字段名称
* @param {number} [maxLength=255] 最大长度
* @return {string} 规范化后的文本
*/
normalizeText(value, fieldName, maxLength = 255) {
if (value === undefined || value === null) {
return '';
}
const normalized = String(value).trim();
if (normalized.length > maxLength) {
throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400);
}
return normalized;
}
/**
* 规范化编码值。
*
* @param {string} value 原始值
* @param {string} [fieldName='code'] 字段名称
* @param {number} [maxLength=50] 最大长度
* @return {string} 规范化后的编码
*/
normalizeCode(value, fieldName = 'code', maxLength = 50) {
return this.normalizeText(value, fieldName, maxLength).toUpperCase();
}
/**
* 规范化分页参数。
*
* @param {number|string} value 原始值
* @param {string} fieldName 字段名称
* @param {number} defaultValue 默认值
* @param {number} maxValue 最大值
* @return {number} 规范化后的分页值
*/
normalizePage(value, fieldName, defaultValue, maxValue) {
if (value === undefined || value === null || value === '') {
return defaultValue;
}
const num = Number(value);
if (!Number.isFinite(num) || num <= 0) {
throw this.createError(`${fieldName} 参数不合法`, 400);
}
return Math.min(Math.floor(num), maxValue);
}
/**
* 返回 where 字段映射。
*
* @return {Object} where 字段映射
*/
getListWhereSpecialFieldMap() {
return {
id: {
field: 'id',
},
code: {
field: 'code',
},
name: {
field: 'name',
},
express_code: {
field: 'express_code',
},
quickWhere: {
bucket: 'quick',
},
};
}
/**
* 获取系统快递列表。
*
* @return {Promise<Array>} 系统快递列表
*/
async getSystemExpressList() {
const systemExpressService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.express;
if (!systemExpressService || typeof systemExpressService.getSystemExpressList !== 'function') {
return [];
}
return await systemExpressService.getSystemExpressList();
}
/**
* 构建系统快递映射表。
*
* @return {Promise<Map<string, Object>>} 系统快递映射表
*/
async getSystemExpressMap() {
const expressList = await this.getSystemExpressList();
const expressMap = new Map();
for (const expressItem of Array.isArray(expressList) ? expressList : []) {
if (!expressItem || typeof expressItem !== 'object') {
continue;
}
const code = String(expressItem.code || expressItem.value || '').trim().toUpperCase();
if (!code) {
continue;
}
if (!expressMap.has(code)) {
expressMap.set(code, {
code,
name: String(expressItem.name || expressItem.label || '').trim(),
});
}
}
return expressMap;
}
/**
* 规范化映射记录。
*
* @param {Object} row 数据库记录
* @param {Map<string, Object>} expressMap 系统快递映射表
* @return {Object|null} 规范化后的记录
*/
normalizeSettingRow(row, expressMap) {
if (!row || typeof row !== 'object') {
return null;
}
const code = String(row.code || '').trim().toUpperCase();
if (!code) {
return null;
}
const expressCode = String(row.express_code || '').trim().toUpperCase();
const expressInfo = expressMap instanceof Map ? expressMap.get(expressCode) : null;
return {
id: row.id === undefined || row.id === null ? null : Number(row.id),
warehouse_id: row.warehouse_id === undefined || row.warehouse_id === null ? null : Number(row.warehouse_id),
code,
name: String(row.name || '').trim(),
express_code: expressCode,
express_name: expressInfo ? expressInfo.name : '',
express_label: expressInfo ? expressInfo.name : '',
};
}
/**
* 查找当前仓库下的映射记录。
*
* @param {number} id 映射ID
* @return {Promise<Object>} 映射记录
*/
async findSettingById(id) {
const { ctx } = this;
const setting = await ctx.model.ExpressSetting.findOne({
where: {
id,
warehouse_id: this.getCurrentStoreId(),
deleted_at: null,
},
});
if (!setting) {
throw this.createError('快递映射不存在或无权限操作', 404);
}
return setting;
}
/**
* 查找同仓下的编码冲突记录。
*
* @param {string} code 映射编码
* @param {number|null} [excludeId=null] 排除的记录ID
* @return {Promise<Object|null>} 冲突记录
*/
async findCodeConflict(code, excludeId = null) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const where = {
warehouse_id: this.getCurrentStoreId(),
code,
deleted_at: null,
};
const normalizedExcludeId = Number(excludeId || 0);
if (Number.isFinite(normalizedExcludeId) && normalizedExcludeId > 0) {
where.id = {
[Op.ne]: normalizedExcludeId,
};
}
return await ctx.model.ExpressSetting.findOne({
where,
attributes: [ 'id', 'code' ],
});
}
/**
* 校验系统快递编码是否存在。
*
* @param {string} expressCode 系统快递编码
* @param {Map<string, Object>} [expressMap] 系统快递映射表
* @return {Promise<Object>} 系统快递信息
*/
async ensureSystemExpressExists(expressCode, expressMap = null) {
const normalizedExpressCode = this.normalizeCode(expressCode, 'express_code');
const resolvedMap = expressMap instanceof Map ? expressMap : await this.getSystemExpressMap();
const expressInfo = resolvedMap.get(normalizedExpressCode);
if (!expressInfo) {
throw this.createError('系统快递编码不存在', 400);
}
return expressInfo;
}
/**
* 校验同仓编码是否可用。
*
* @param {string} code 映射编码
* @param {number|null} [excludeId=null] 排除的记录ID
* @return {Promise<boolean>} 是否可用
*/
async ensureCodeAvailable(code, excludeId = null) {
const conflict = await this.findCodeConflict(code, excludeId);
if (conflict) {
throw this.createError('快递编码已被当前仓库使用', 409);
}
return true;
}
/**
* 解析列表查询条件。
*
* @param {Object} data 请求参数
* @return {Object} 查询条件信息
*/
resolveListWhere(data = {}) {
const { ctx, app } = this;
const normalizedWhere = ctx.where && typeof ctx.where === 'object'
? { ...ctx.where }
: (data.where && typeof data.where === 'object' ? { ...data.where } : {});
let parsedResult = ctx.whereParsed;
if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) {
const parsed = parseWhereConditions({
where: normalizedWhere,
app,
specialFieldMap: this.getListWhereSpecialFieldMap(),
});
if (!parsed.ok) {
throw this.createError(`where 参数解析失败: ${parsed.reason}`, 400);
}
parsedResult = parsed.result;
}
return {
normalizedWhere,
parsedResult,
};
}
/**
* 查询映射列表。
*
* @param {Object} data 请求参数
* @param {Object} [data.pagination] 分页参数
* @return {Promise<Object>} 分页结果
*/
async list(data = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const currentStoreId = this.getCurrentStoreId();
const pagination = data.pagination && typeof data.pagination === 'object' ? data.pagination : {};
const pageSource = pagination.page !== undefined ? pagination.page : data.page;
const pageSizeSource = pagination.pageSize !== undefined
? pagination.pageSize
: (pagination.page_size !== undefined ? pagination.page_size : (data.page_size !== undefined ? data.page_size : data.pageSize));
const page = this.normalizePage(pageSource, 'page', 1, 1000000);
const pageSize = this.normalizePage(pageSizeSource, 'page_size', 20, 200);
const offset = (page - 1) * pageSize;
const { normalizedWhere, parsedResult } = this.resolveListWhere(data);
const andConditions = [
{
warehouse_id: currentStoreId,
},
{
deleted_at: null,
},
];
const dynamicConditions = Array.isArray(parsedResult.dynamicConditions) ? parsedResult.dynamicConditions : [];
if (dynamicConditions.length > 0) {
andConditions.push({ [Op.and]: dynamicConditions });
}
const quickWhereInput = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere)
|| normalizedWhere.quickWhere
|| null;
const quickWhereValue = quickWhereInput && typeof quickWhereInput === 'object'
? quickWhereInput.value
: quickWhereInput;
if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') {
const keyword = String(quickWhereValue).trim();
andConditions.push({
[Op.or]: [
{ code: { [Op.like]: `%${keyword}%` } },
{ name: { [Op.like]: `%${keyword}%` } },
{ express_code: { [Op.like]: `%${keyword}%` } },
],
});
}
const [ expressMap, result ] = await Promise.all([
this.getSystemExpressMap(),
ctx.model.ExpressSetting.findAndCountAll({
where: {
[Op.and]: andConditions,
},
attributes: [ 'id', 'warehouse_id', 'code', 'name', 'express_code' ],
order: [[ 'id', 'DESC' ]],
offset,
limit: pageSize,
raw: true,
}),
]);
const list = Array.isArray(result && result.rows)
? result.rows.map(row => this.normalizeSettingRow(row, expressMap)).filter(Boolean)
: [];
return {
code: 200,
data: {
list,
total: Number(result && result.count ? result.count : 0),
page,
page_size: pageSize,
},
};
}
/**
* 查询系统快递编码和名称列表。
*
* @return {Promise<Object>} 系统快递列表
*/
async listBase() {
const list = await this.getSystemExpressList();
return {
code: 200,
data: list,
};
}
/**
* 检查编码是否已被占用。
*
* @param {Object} data 请求参数
* @param {number} [data.id] 编辑时的映射ID
* @param {string} data.code 映射编码
* @return {Promise<Object>} 唯一性校验结果
*/
async checkCodeUnique(data = {}) {
const code = this.normalizeCode(data.code, 'code');
if (!code) {
throw this.createError('code 参数不能为空', 400);
}
const excludeId = Number(data.id || 0);
const conflict = await this.findCodeConflict(code, excludeId);
return {
code: 200,
data: {
isUnique: !conflict,
message: conflict ? '快递编码已被当前仓库使用' : 'ok',
},
};
}
/**
* 创建快递映射。
*
* @param {Object} data 请求参数
* @return {Promise<Object>} 创建结果
*/
async create(data = {}) {
const { ctx } = this;
const currentStoreId = this.getCurrentStoreId();
const expressMap = await this.getSystemExpressMap();
const code = this.normalizeCode(data.code, 'code');
const name = this.normalizeText(data.name, 'name', 50);
const expressCode = this.normalizeCode(data.express_code || data.expressCode, 'express_code');
if (!code) {
throw this.createError('code 参数不能为空', 400);
}
if (!name) {
throw this.createError('name 参数不能为空', 400);
}
if (!expressCode) {
throw this.createError('express_code 参数不能为空', 400);
}
const expressInfo = await this.ensureSystemExpressExists(expressCode, expressMap);
await this.ensureCodeAvailable(code);
const created = await ctx.model.ExpressSetting.create({
warehouse_id: currentStoreId,
code,
name,
express_code: expressInfo.code,
});
await this.clearExpressListCache(currentStoreId);
return {
code: 200,
data: this.normalizeSettingRow(created.get ? created.get({ plain: true }) : created, expressMap),
};
}
/**
* 修改快递映射。
*
* @param {Object} data 请求参数
* @return {Promise<Object>} 修改结果
*/
async update(data = {}) {
const id = Number(data.id || data.setting_id || data.settingId || 0);
if (!Number.isFinite(id) || id <= 0) {
throw this.createError('id 参数不能为空', 400);
}
const setting = await this.findSettingById(id);
const hasCode = Object.prototype.hasOwnProperty.call(data, 'code');
const hasName = Object.prototype.hasOwnProperty.call(data, 'name');
const hasExpressCode = Object.prototype.hasOwnProperty.call(data, 'express_code')
|| Object.prototype.hasOwnProperty.call(data, 'expressCode');
if (!hasCode && !hasName && !hasExpressCode) {
throw this.createError('至少需要提供一个可更新字段', 400);
}
const updates = {};
let expressMap = null;
if (hasCode) {
const code = this.normalizeCode(data.code, 'code');
if (!code) {
throw this.createError('code 参数不能为空', 400);
}
await this.ensureCodeAvailable(code, id);
updates.code = code;
}
if (hasName) {
const name = this.normalizeText(data.name, 'name', 50);
if (!name) {
throw this.createError('name 参数不能为空', 400);
}
updates.name = name;
}
if (hasExpressCode) {
expressMap = await this.getSystemExpressMap();
const expressCode = this.normalizeCode(data.express_code || data.expressCode, 'express_code');
if (!expressCode) {
throw this.createError('express_code 参数不能为空', 400);
}
const expressInfo = await this.ensureSystemExpressExists(expressCode, expressMap);
updates.express_code = expressInfo.code;
}
await setting.update(updates);
await this.clearExpressListCache(this.getCurrentStoreId());
if (!expressMap) {
expressMap = await this.getSystemExpressMap();
}
return {
code: 200,
data: this.normalizeSettingRow(setting.get ? setting.get({ plain: true }) : setting, expressMap),
};
}
/**
* 查询批量删除目标记录。
*
* @param {Array<number>} ids 删除ID列表
* @return {Promise<Array<Object>>} 目标记录列表
*/
async findSettingsForDelete(ids) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
return await ctx.model.ExpressSetting.findAll({
where: {
warehouse_id: this.getCurrentStoreId(),
id: {
[Op.in]: ids,
},
},
attributes: [ 'id', 'code', 'deleted_at' ],
raw: true,
});
}
/**
* 检查待删除快递编码是否被当前仓库快递接口引用。
*
* @param {Array<string>} codes 快递设置编码列表
* @return {Promise<void>}
*/
async ensureDeleteCodesNotReferenced(codes) {
const uniqueCodes = Array.from(new Set(
Array.isArray(codes)
? codes.map(code => String(code || '').trim()).filter(Boolean)
: []
));
if (uniqueCodes.length === 0) {
return;
}
const { ctx, app } = this;
const { Op } = app.Sequelize;
const referencedRows = await ctx.model.ExpressInterface.findAll({
where: {
warehouse_id: this.getCurrentStoreId(),
express_code: {
[Op.in]: uniqueCodes,
},
},
attributes: [ 'id', 'express_code' ],
raw: true,
});
if (Array.isArray(referencedRows) && referencedRows.length > 0) {
const referencedCodes = Array.from(new Set(
referencedRows
.map(row => String(row && row.express_code || '').trim())
.filter(Boolean)
));
throw this.createError(`存在快递接口引用的快递编码,无法删除:${referencedCodes.join('、')}`, 409);
}
}
/**
* 删除快递映射。
*
* @param {Object} data 请求参数
* @return {Promise<Object>} 删除结果
*/
async delete(data = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const ids = this.normalizeDeleteIds(data);
if (ids.length === 0) {
throw this.createError('ids 参数不能为空', 400);
}
const settings = await this.findSettingsForDelete(ids);
if (!Array.isArray(settings) || settings.length !== ids.length) {
throw this.createError('快递映射不存在或无权限操作', 404);
}
const settingMap = new Map();
for (const setting of settings) {
if (!setting || typeof setting !== 'object') {
continue;
}
const settingId = Number(setting.id);
if (Number.isInteger(settingId) && settingId > 0) {
settingMap.set(settingId, setting);
}
}
const deletedIds = [];
const alreadyDeletedIds = [];
const targetCodes = [];
for (const id of ids) {
const setting = settingMap.get(id);
if (!setting) {
throw this.createError('快递映射不存在或无权限操作', 404);
}
targetCodes.push(String(setting.code || '').trim());
if (setting.deleted_at) {
alreadyDeletedIds.push(id);
continue;
}
deletedIds.push(id);
}
await this.ensureDeleteCodesNotReferenced(targetCodes);
if (deletedIds.length > 0) {
await ctx.model.transaction(async transaction => {
await ctx.model.ExpressSetting.update({
deleted_at: new Date(),
}, {
where: {
warehouse_id: this.getCurrentStoreId(),
id: {
[Op.in]: deletedIds,
},
deleted_at: null,
},
transaction,
});
});
await this.clearExpressListCache(this.getCurrentStoreId());
}
return {
code: 200,
data: {
ids,
deleted_ids: deletedIds,
already_deleted_ids: alreadyDeletedIds,
status: 'deleted',
},
};
}
}
module.exports = SettingExpressService;