'use strict'; const Service = require('egg').Service; const { parseWhereConditions } = require('../../../lib/query_condition_parser'); class SettingExpressInterfaceService 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 字段名称 * @param {number} [maxLength=255] 最大长度 * @return {string|null} 规范化后的文本 */ normalizeOptionalText(value, fieldName, maxLength = 255) { if (value === undefined || value === null) { return null; } const normalized = String(value).trim(); if (normalized.length > maxLength) { throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400); } return normalized; } /** * 规范化整数值。 * * @param {number|string} value 原始值 * @param {string} fieldName 字段名称 * @param {Object} [options] 额外选项 * @param {boolean} [options.allowEmpty=false] 是否允许空值 * @param {number|null} [options.min=null] 最小值 * @param {number|null} [options.max=null] 最大值 * @return {number|null} 规范化后的整数 */ normalizeInteger(value, fieldName, options = {}) { const { allowEmpty = false, min = null, max = null, } = options; if (value === undefined || value === null || value === '') { if (allowEmpty) { return null; } throw this.createError(`${fieldName} 参数不能为空`, 400); } const normalized = Number(value); if (!Number.isInteger(normalized)) { throw this.createError(`${fieldName} 参数不合法`, 400); } if (min !== null && normalized < min) { throw this.createError(`${fieldName} 参数不合法`, 400); } if (max !== null && normalized > max) { throw this.createError(`${fieldName} 参数不合法`, 400); } return normalized; } /** * 规范化布尔标记。 * * @param {number|string} value 原始值 * @param {string} fieldName 字段名称 * @param {number|null} [defaultValue=null] 默认值 * @return {number|null} 规范化后的标记 */ normalizeFlag(value, fieldName, defaultValue = null) { if (value === undefined || value === null || value === '') { return defaultValue; } const normalized = Number(value); if (normalized === 0 || normalized === 1) { return normalized; } throw this.createError(`${fieldName} 参数不合法`, 400); } /** * 规范化分页参数。 * * @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 normalized = Number(value); if (!Number.isFinite(normalized) || normalized <= 0) { throw this.createError(`${fieldName} 参数不合法`, 400); } return Math.min(Math.floor(normalized), maxValue); } /** * 获取列表查询字段映射。 * * @return {Object} 字段映射 */ getListWhereSpecialFieldMap() { return { id: { field: 'id', }, name: { field: 'name', }, express_code: { field: 'express_code', }, platform_code: { field: 'platform_code', }, express_platform_id: { field: 'express_platform_id', }, sender_name: { field: 'sender_name', }, sender_tel: { field: 'sender_tel', }, viewer: { field: 'viewer', }, client_id: { field: 'client_id', }, share_id: { field: 'share_id', }, site_code: { field: 'site_code', }, product_type: { field: 'product_type', }, shop_name: { field: 'shop_name', }, quickWhere: { bucket: 'quick', }, }; } /** * 解析列表查询条件。 * * @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} row 数据库记录 * @return {Object|null} 规范化后的记录 */ normalizeInterfaceRow(row) { if (!row || typeof row !== 'object') { return null; } return { id: row.id === undefined || row.id === null ? null : Number(row.id), name: this.normalizeOptionalText(row.name, 'name', 255), 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), express_platform_id: row.express_platform_id === undefined || row.express_platform_id === null ? null : Number(row.express_platform_id), 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), viewer: this.normalizeOptionalText(row.viewer, 'viewer', 50), client_id: this.normalizeOptionalText(row.client_id, 'client_id', 50), is_share: row.is_share === undefined || row.is_share === null ? null : Number(row.is_share), share_id: row.share_id === undefined || row.share_id === null ? null : Number(row.share_id), can_use_count: row.can_use_count === undefined || row.can_use_count === null ? null : Number(row.can_use_count), province_name: this.normalizeOptionalText(row.province_name, 'province_name', 255), city_name: this.normalizeOptionalText(row.city_name, 'city_name', 255), district_name: this.normalizeOptionalText(row.district_name, 'district_name', 255), site_code: this.normalizeOptionalText(row.site_code, 'site_code', 255), product_type: this.normalizeOptionalText(row.product_type, 'product_type', 50), shop_name: this.normalizeOptionalText(row.shop_name, 'shop_name', 255), }; } /** * 查找当前仓库下的快递接口记录。 * * @param {number} id 接口 ID * @return {Promise} 接口记录 */ async findInterfaceById(id) { const { ctx } = this; const currentStoreId = this.getCurrentStoreId(); const setting = await ctx.model.ExpressInterface.findOne({ where: { id, warehouse_id: currentStoreId, }, }); if (!setting) { throw this.createError('快递接口不存在或无权限操作', 404); } return setting; } /** * 查找同仓下的快递编码冲突记录。 * * @param {string} expressCode 快递编码 * @param {number|null} [excludeId=null] 排除的记录 ID * @return {Promise} 冲突记录 */ async findCodeConflict(expressCode, excludeId = null) { const { ctx, app } = this; const { Op } = app.Sequelize; const where = { warehouse_id: this.getCurrentStoreId(), express_code: expressCode, }; const normalizedExcludeId = Number(excludeId || 0); if (Number.isInteger(normalizedExcludeId) && normalizedExcludeId > 0) { where.id = { [Op.ne]: normalizedExcludeId, }; } return await ctx.model.ExpressInterface.findOne({ where, attributes: [ 'id', 'express_code' ], }); } /** * 查找同仓下的平台接口冲突记录。 * * @param {string} platformCode 平台代码 * @param {number} expressPlatformId 快递接口 ID * @param {number|null} [excludeId=null] 排除的记录 ID * @return {Promise} 冲突记录 */ async findInterfaceConflict(platformCode, expressPlatformId, excludeId = null) { const { ctx, app } = this; const { Op } = app.Sequelize; const where = { warehouse_id: this.getCurrentStoreId(), platform_code: platformCode, express_platform_id: expressPlatformId, }; const normalizedExcludeId = Number(excludeId || 0); if (Number.isInteger(normalizedExcludeId) && normalizedExcludeId > 0) { where.id = { [Op.ne]: normalizedExcludeId, }; } return await ctx.model.ExpressInterface.findOne({ where, attributes: [ 'id', 'platform_code', 'express_platform_id' ], }); } /** * 校验快递编码是否可用。 * * @param {string} expressCode 快递编码 * @param {number|null} [excludeId=null] 排除的记录 ID * @return {Promise} 是否可用 */ async ensureCodeAvailable(expressCode, excludeId = null) { const conflict = await this.findCodeConflict(expressCode, excludeId); if (conflict) { throw this.createError('快递编码已被当前仓库使用', 409); } return true; } /** * 校验平台接口组合是否可用。 * * @param {string} platformCode 平台代码 * @param {number} expressPlatformId 快递接口 ID * @param {number|null} [excludeId=null] 排除的记录 ID * @return {Promise} 是否可用 */ async ensureInterfaceAvailable(platformCode, expressPlatformId, excludeId = null) { const conflict = await this.findInterfaceConflict(platformCode, expressPlatformId, excludeId); if (conflict) { throw this.createError('当前平台和快递接口组合已被使用', 409); } return true; } /** * 获取快递接口列表。 * * @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]: [ { name: { [Op.like]: `%${keyword}%` } }, { express_code: { [Op.like]: `%${keyword}%` } }, { platform_code: { [Op.like]: `%${keyword}%` } }, { sender_name: { [Op.like]: `%${keyword}%` } }, { sender_tel: { [Op.like]: `%${keyword}%` } }, { viewer: { [Op.like]: `%${keyword}%` } }, { client_id: { [Op.like]: `%${keyword}%` } }, { province_name: { [Op.like]: `%${keyword}%` } }, { city_name: { [Op.like]: `%${keyword}%` } }, { district_name: { [Op.like]: `%${keyword}%` } }, { site_code: { [Op.like]: `%${keyword}%` } }, { product_type: { [Op.like]: `%${keyword}%` } }, { shop_name: { [Op.like]: `%${keyword}%` } }, ], }); } const result = await ctx.model.ExpressInterface.findAndCountAll({ where: { [Op.and]: andConditions, }, attributes: [ 'id', 'name', 'express_code', 'warehouse_id', 'platform_code', 'express_platform_id', 'sender_name', 'sender_tel', 'weight', 'token', 'viewer', 'client_id', 'is_share', 'share_id', 'can_use_count', 'province_name', 'city_name', 'district_name', 'site_code', 'product_type', 'shop_name', ], order: [[ 'id', 'DESC' ]], offset, limit: pageSize, raw: true, }); const list = Array.isArray(result && result.rows) ? result.rows.map(row => this.normalizeInterfaceRow(row)).filter(Boolean) : []; return { code: 200, data: { list, total: Number(result && result.count ? result.count : 0), page, page_size: pageSize, }, }; } /** * 创建快递接口。 * * @param {Object} data 请求参数 * @return {Promise} 创建结果 */ async create(data = {}) { const { ctx } = this; const currentStoreId = this.getCurrentStoreId(); 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(); const expressPlatformId = this.normalizeInteger(data.express_platform_id || data.expressPlatformId, 'express_platform_id', { min: 1, }); if (!name) { throw this.createError('name 参数不能为空', 400); } if (!expressCode) { throw this.createError('express_code 参数不能为空', 400); } if (!platformCode) { throw this.createError('platform_code 参数不能为空', 400); } if (!expressPlatformId) { throw this.createError('express_platform_id 参数不能为空', 400); } await this.ensureCodeAvailable(expressCode); await this.ensureInterfaceAvailable(platformCode, expressPlatformId); const payload = { warehouse_id: currentStoreId, name, express_code: expressCode, platform_code: platformCode, express_platform_id: expressPlatformId, sender_name: this.normalizeOptionalText(data.sender_name || data.senderName, 'sender_name', 50), sender_tel: this.normalizeOptionalText(data.sender_tel || data.senderTel, 'sender_tel', 11), weight: this.normalizeInteger(data.weight, 'weight', { allowEmpty: true, }), token: this.normalizeOptionalText(data.token, 'token', 500), viewer: this.normalizeOptionalText(data.viewer, 'viewer', 50), client_id: this.normalizeOptionalText(data.client_id || data.clientId, 'client_id', 50), is_share: this.normalizeFlag(data.is_share !== undefined ? data.is_share : data.isShare, 'is_share', 0), share_id: this.normalizeInteger(data.share_id || data.shareId, 'share_id', { allowEmpty: true, min: 1, }), can_use_count: this.normalizeInteger(data.can_use_count !== undefined ? data.can_use_count : data.canUseCount, 'can_use_count', { allowEmpty: true, min: 0, }), province_name: this.normalizeOptionalText(data.province_name || data.provinceName, 'province_name', 255), city_name: this.normalizeOptionalText(data.city_name || data.cityName, 'city_name', 255), district_name: this.normalizeOptionalText(data.district_name || data.districtName, 'district_name', 255), site_code: this.normalizeOptionalText(data.site_code || data.siteCode, 'site_code', 255), product_type: this.normalizeOptionalText(data.product_type || data.productType, 'product_type', 50), shop_name: this.normalizeOptionalText(data.shop_name || data.shopName, 'shop_name', 255), }; const created = await ctx.model.ExpressInterface.create(payload); const plainCreated = created && typeof created.get === 'function' ? created.get({ plain: true }) : created; return { code: 200, data: this.normalizeInterfaceRow(plainCreated), }; } /** * 修改快递接口。 * * @param {Object} data 请求参数 * @return {Promise} 修改结果 */ async update(data = {}) { const id = Number(data.id || data.interface_id || data.interfaceId || 0); if (!Number.isInteger(id) || id <= 0) { throw this.createError('id 参数不能为空', 400); } const setting = await this.findInterfaceById(id); const hasName = Object.prototype.hasOwnProperty.call(data, 'name'); const hasExpressCode = Object.prototype.hasOwnProperty.call(data, 'express_code') || Object.prototype.hasOwnProperty.call(data, 'expressCode'); const hasPlatformCode = Object.prototype.hasOwnProperty.call(data, 'platform_code') || Object.prototype.hasOwnProperty.call(data, 'platformCode'); const hasExpressPlatformId = Object.prototype.hasOwnProperty.call(data, 'express_platform_id') || Object.prototype.hasOwnProperty.call(data, 'expressPlatformId'); const hasSenderName = Object.prototype.hasOwnProperty.call(data, 'sender_name') || Object.prototype.hasOwnProperty.call(data, 'senderName'); const hasSenderTel = Object.prototype.hasOwnProperty.call(data, 'sender_tel') || Object.prototype.hasOwnProperty.call(data, 'senderTel'); const hasWeight = Object.prototype.hasOwnProperty.call(data, 'weight'); const hasToken = Object.prototype.hasOwnProperty.call(data, 'token'); const hasViewer = Object.prototype.hasOwnProperty.call(data, 'viewer'); const hasClientId = Object.prototype.hasOwnProperty.call(data, 'client_id') || Object.prototype.hasOwnProperty.call(data, 'clientId'); const hasIsShare = Object.prototype.hasOwnProperty.call(data, 'is_share') || Object.prototype.hasOwnProperty.call(data, 'isShare'); const hasShareId = Object.prototype.hasOwnProperty.call(data, 'share_id') || Object.prototype.hasOwnProperty.call(data, 'shareId'); const hasCanUseCount = Object.prototype.hasOwnProperty.call(data, 'can_use_count') || Object.prototype.hasOwnProperty.call(data, 'canUseCount'); const hasProvinceName = Object.prototype.hasOwnProperty.call(data, 'province_name') || Object.prototype.hasOwnProperty.call(data, 'provinceName'); const hasCityName = Object.prototype.hasOwnProperty.call(data, 'city_name') || Object.prototype.hasOwnProperty.call(data, 'cityName'); const hasDistrictName = Object.prototype.hasOwnProperty.call(data, 'district_name') || Object.prototype.hasOwnProperty.call(data, 'districtName'); const hasSiteCode = Object.prototype.hasOwnProperty.call(data, 'site_code') || Object.prototype.hasOwnProperty.call(data, 'siteCode'); const hasProductType = Object.prototype.hasOwnProperty.call(data, 'product_type') || Object.prototype.hasOwnProperty.call(data, 'productType'); const hasShopName = Object.prototype.hasOwnProperty.call(data, 'shop_name') || Object.prototype.hasOwnProperty.call(data, 'shopName'); if (!hasName && !hasExpressCode && !hasPlatformCode && !hasExpressPlatformId && !hasSenderName && !hasSenderTel && !hasWeight && !hasToken && !hasViewer && !hasClientId && !hasIsShare && !hasShareId && !hasCanUseCount && !hasProvinceName && !hasCityName && !hasDistrictName && !hasSiteCode && !hasProductType && !hasShopName) { throw this.createError('至少需要提供一个可更新字段', 400); } const updates = {}; let nextExpressCode = setting.express_code || ''; let nextPlatformCode = setting.platform_code || ''; let nextExpressPlatformId = setting.express_platform_id === undefined || setting.express_platform_id === null ? null : Number(setting.express_platform_id); if (hasName) { const name = this.normalizeText(data.name, 'name', 255); if (!name) { throw this.createError('name 参数不能为空', 400); } updates.name = name; } if (hasExpressCode) { const expressCode = this.normalizeText(data.express_code || data.expressCode, 'express_code', 255).toUpperCase(); if (!expressCode) { throw this.createError('express_code 参数不能为空', 400); } nextExpressCode = expressCode; updates.express_code = expressCode; } if (hasPlatformCode) { const platformCode = this.normalizeText(data.platform_code || data.platformCode, 'platform_code', 20).toUpperCase(); if (!platformCode) { throw this.createError('platform_code 参数不能为空', 400); } nextPlatformCode = platformCode; updates.platform_code = platformCode; } if (hasExpressPlatformId) { const expressPlatformId = this.normalizeInteger(data.express_platform_id || data.expressPlatformId, 'express_platform_id', { min: 1, }); if (!expressPlatformId) { throw this.createError('express_platform_id 参数不能为空', 400); } nextExpressPlatformId = expressPlatformId; updates.express_platform_id = expressPlatformId; } if (hasSenderName) { updates.sender_name = this.normalizeOptionalText(data.sender_name || data.senderName, 'sender_name', 50); } if (hasSenderTel) { updates.sender_tel = this.normalizeOptionalText(data.sender_tel || data.senderTel, 'sender_tel', 11); } if (hasWeight) { updates.weight = this.normalizeInteger(data.weight, 'weight', { allowEmpty: true, }); } if (hasToken) { updates.token = this.normalizeOptionalText(data.token, 'token', 500); } if (hasViewer) { updates.viewer = this.normalizeOptionalText(data.viewer, 'viewer', 50); } if (hasClientId) { updates.client_id = this.normalizeOptionalText(data.client_id || data.clientId, 'client_id', 50); } if (hasIsShare) { updates.is_share = this.normalizeFlag(data.is_share !== undefined ? data.is_share : data.isShare, 'is_share', 0); } if (hasShareId) { updates.share_id = this.normalizeInteger(data.share_id || data.shareId, 'share_id', { allowEmpty: true, min: 1, }); } if (hasCanUseCount) { updates.can_use_count = this.normalizeInteger(data.can_use_count !== undefined ? data.can_use_count : data.canUseCount, 'can_use_count', { allowEmpty: true, min: 0, }); } if (hasProvinceName) { updates.province_name = this.normalizeOptionalText(data.province_name || data.provinceName, 'province_name', 255); } if (hasCityName) { updates.city_name = this.normalizeOptionalText(data.city_name || data.cityName, 'city_name', 255); } if (hasDistrictName) { updates.district_name = this.normalizeOptionalText(data.district_name || data.districtName, 'district_name', 255); } if (hasSiteCode) { updates.site_code = this.normalizeOptionalText(data.site_code || data.siteCode, 'site_code', 255); } if (hasProductType) { updates.product_type = this.normalizeOptionalText(data.product_type || data.productType, 'product_type', 50); } if (hasShopName) { updates.shop_name = this.normalizeOptionalText(data.shop_name || data.shopName, 'shop_name', 255); } if (Object.prototype.hasOwnProperty.call(updates, 'express_code')) { await this.ensureCodeAvailable(nextExpressCode, id); } if (Object.prototype.hasOwnProperty.call(updates, 'platform_code') || Object.prototype.hasOwnProperty.call(updates, 'express_platform_id')) { await this.ensureInterfaceAvailable(nextPlatformCode, nextExpressPlatformId, id); } await setting.update(updates); const plainSetting = setting && typeof setting.get === 'function' ? setting.get({ plain: true }) : setting; return { code: 200, data: this.normalizeInterfaceRow(plainSetting), }; } /** * 删除快递接口。 * * @param {Object} data 请求参数 * @return {Promise} 删除结果 */ async delete(data = {}) { const id = Number(data.id || data.interface_id || data.interfaceId || 0); if (!Number.isInteger(id) || id <= 0) { throw this.createError('id 参数不能为空', 400); } const setting = await this.findInterfaceById(id); const plainSetting = setting && typeof setting.get === 'function' ? setting.get({ plain: true }) : setting; await setting.destroy(); return { code: 200, data: { id: Number(plainSetting.id), warehouse_id: Number(plainSetting.warehouse_id), deleted: true, }, }; } } module.exports = SettingExpressInterfaceService;