'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 {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} 系统快递列表 */ 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>} 系统快递映射表 */ 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} 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} 映射记录 */ async findSettingById(id) { const { ctx } = this; const setting = await ctx.model.ExpressSetting.findOne({ where: { id, warehouse_id: this.getCurrentStoreId(), }, }); if (!setting) { throw this.createError('快递映射不存在或无权限操作', 404); } return setting; } /** * 查找同仓下的编码冲突记录。 * * @param {string} code 映射编码 * @param {number|null} [excludeId=null] 排除的记录ID * @return {Promise} 冲突记录 */ async findCodeConflict(code, excludeId = null) { const { ctx, app } = this; const { Op } = app.Sequelize; const where = { warehouse_id: this.getCurrentStoreId(), code, }; 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} [expressMap] 系统快递映射表 * @return {Promise} 系统快递信息 */ 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} 是否可用 */ 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} 分页结果 */ 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, }, ]; 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} 系统快递列表 */ 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} 唯一性校验结果 */ 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} 创建结果 */ 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, }); return { code: 200, data: this.normalizeSettingRow(created.get ? created.get({ plain: true }) : created, expressMap), }; } /** * 修改快递映射。 * * @param {Object} data 请求参数 * @return {Promise} 修改结果 */ async update(data = {}) { const { ctx } = this; 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); if (!expressMap) { expressMap = await this.getSystemExpressMap(); } return { code: 200, data: this.normalizeSettingRow(setting.get ? setting.get({ plain: true }) : setting, expressMap), }; } } module.exports = SettingExpressService;