'use strict'; const Service = require('egg').Service; const { parseWhereConditions } = require('../../../lib/query_condition_parser'); class SettingPackageSupplierService 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 {*} value 原始值 * @param {string} fieldName 字段名称 * @param {number} maxLength 最大长度 * @return {string} 规范化结果 */ normalizeRequiredText(value, fieldName, maxLength) { if (value === undefined || value === null) { throw this.createError(fieldName + ' 参数不能为空', 400); } const normalized = String(value).trim(); if (!normalized) { throw this.createError(fieldName + ' 参数不能为空', 400); } if (normalized.length > maxLength) { throw this.createError(fieldName + ' 长度不能超过 ' + maxLength, 400); } return normalized; } /** * 规范化可选文本。 * * @param {*} value 原始值 * @param {string} fieldName 字段名称 * @param {number} maxLength 最大长度 * @return {string|null} 规范化结果 */ normalizeOptionalText(value, fieldName, maxLength) { if (value === undefined || value === null) { return null; } const normalized = String(value).trim(); if (!normalized) { return null; } if (normalized.length > maxLength) { throw this.createError(fieldName + ' 长度不能超过 ' + maxLength, 400); } return normalized; } /** * 规范化可选状态值。 * * @param {*} value 原始值 * @param {number} defaultValue 默认值 * @return {number} 规范化结果 */ normalizeStatus(value, defaultValue = 1) { if (value === undefined || value === null || value === '') { return defaultValue; } const normalized = Number(value); if (!Number.isInteger(normalized) || ![ 0, 1 ].includes(normalized)) { throw this.createError('status 参数不合法', 400); } return normalized; } /** * 规范化分页参数。 * * @param {*} 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); } /** * 规范化删除 ID 列表。 * * @param {Object} data 请求参数 * @return {Array} 删除 ID 列表 */ normalizeDeleteIds(data = {}) { const { ids, id, supplier_id: supplierId, supplierId: camelSupplierId, } = data || {}; const rawIds = ids !== undefined ? ids : (id !== undefined ? id : (supplierId !== undefined ? supplierId : camelSupplierId)); 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; } /** * 列表 where 字段映射。 * * @return {Object} 字段映射 */ getListWhereSpecialFieldMap() { return { id: { field: 'id', }, supplier_code: { field: 'supplier_code', }, supplier_name: { field: 'supplier_name', }, contact_name: { field: 'contact_name', }, contact_phone: { field: 'contact_phone', }, status: { field: 'status', }, quickWhere: { bucket: 'quick', }, }; } /** * 解析列表查询 where。 * * @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} 规范化结果 */ normalizeSupplierRow(row) { if (!row || typeof row !== 'object') { return 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), supplier_code: String(row.supplier_code || '').trim(), supplier_name: String(row.supplier_name || '').trim(), contact_name: row.contact_name === undefined || row.contact_name === null ? '' : String(row.contact_name).trim(), contact_phone: row.contact_phone === undefined || row.contact_phone === null ? '' : String(row.contact_phone).trim(), status: row.status === undefined || row.status === null ? 1 : Number(row.status), version: row.version === undefined || row.version === null ? null : Number(row.version), created_at: row.created_at || null, updated_at: row.updated_at || null, }; } /** * 校验供应商编码在当前仓库内唯一。 * * @param {number} warehouseId 仓库 ID * @param {string} supplierCode 供应商编码 * @param {number|null} [excludeId=null] 排除 ID * @return {Promise} 无返回值 */ async ensureSupplierCodeUnique(warehouseId, supplierCode, excludeId = null) { const { ctx, app } = this; const { Op } = app.Sequelize; const where = { warehouse_id: warehouseId, supplier_code: supplierCode, }; const normalizedExcludeId = Number(excludeId || 0); if (Number.isFinite(normalizedExcludeId) && normalizedExcludeId > 0) { where.id = { [Op.ne]: normalizedExcludeId, }; } const existing = await ctx.model.PackageSupplier.findOne({ where, attributes: [ 'id', 'supplier_code' ], }); if (existing) { throw this.createError('supplier_code 已被当前仓库使用', 409); } } /** * 按 ID 查找供应商。 * * @param {number} id 供应商 ID * @param {number} warehouseId 仓库 ID * @return {Promise} 供应商记录 */ async findSupplierById(id, warehouseId) { const supplier = await this.ctx.model.PackageSupplier.findOne({ where: { id, warehouse_id: warehouseId, }, }); if (!supplier) { throw this.createError('供应商不存在或无权限操作', 404); } return supplier; } /** * 创建供应商。 * * @param {Object} data 请求参数 * @return {Promise} 创建结果 */ async create(data = {}) { const warehouseId = this.getCurrentStoreId(); const { supplier_code: supplierCode, supplier_name: supplierName, contact_name: contactName, contact_phone: contactPhone, status, } = data || {}; const normalizedSupplierCode = this.normalizeRequiredText(supplierCode, 'supplier_code', 64).toUpperCase(); const normalizedSupplierName = this.normalizeRequiredText(supplierName, 'supplier_name', 128); await this.ensureSupplierCodeUnique(warehouseId, normalizedSupplierCode); const createdRow = await this.ctx.model.PackageSupplier.create({ warehouse_id: warehouseId, supplier_code: normalizedSupplierCode, supplier_name: normalizedSupplierName, contact_name: this.normalizeOptionalText(contactName, 'contact_name', 64), contact_phone: this.normalizeOptionalText(contactPhone, 'contact_phone', 32), status: this.normalizeStatus(status, 1), }); return this.normalizeSupplierRow(createdRow && typeof createdRow.get === 'function' ? createdRow.get({ plain: true }) : createdRow); } /** * 更新供应商。 * * @param {Object} data 请求参数 * @return {Promise} 更新结果 */ async update(data = {}) { const warehouseId = this.getCurrentStoreId(); const { id, supplier_id: supplierId, supplierId: camelSupplierId, supplier_code: supplierCode, supplier_name: supplierName, contact_name: contactName, contact_phone: contactPhone, status, } = data || {}; const resolvedId = Number(id !== undefined ? id : (supplierId !== undefined ? supplierId : camelSupplierId)); if (!Number.isInteger(resolvedId) || resolvedId <= 0) { throw this.createError('id 参数不合法', 400); } const supplier = await this.findSupplierById(resolvedId, warehouseId); const updates = {}; if (supplierCode !== undefined) { const normalizedSupplierCode = this.normalizeRequiredText(supplierCode, 'supplier_code', 64).toUpperCase(); await this.ensureSupplierCodeUnique(warehouseId, normalizedSupplierCode, resolvedId); updates.supplier_code = normalizedSupplierCode; } if (supplierName !== undefined) { updates.supplier_name = this.normalizeRequiredText(supplierName, 'supplier_name', 128); } if (contactName !== undefined) { updates.contact_name = this.normalizeOptionalText(contactName, 'contact_name', 64); } if (contactPhone !== undefined) { updates.contact_phone = this.normalizeOptionalText(contactPhone, 'contact_phone', 32); } if (status !== undefined) { updates.status = this.normalizeStatus(status, 1); } if (Object.keys(updates).length > 0) { await supplier.update(updates); } return this.normalizeSupplierRow(supplier && typeof supplier.get === 'function' ? supplier.get({ plain: true }) : supplier); } /** * 删除供应商。 * * @param {Object} data 请求参数 * @return {Promise} 删除结果 */ async delete(data = {}) { const { app, ctx } = this; const { Op } = app.Sequelize; const warehouseId = this.getCurrentStoreId(); const ids = this.normalizeDeleteIds(data); if (!Array.isArray(ids) || ids.length === 0) { throw this.createError('ids 参数不能为空', 400); } const rows = await ctx.model.PackageSupplier.findAll({ where: { id: { [Op.in]: ids, }, warehouse_id: warehouseId, }, attributes: [ 'id', 'supplier_code' ], raw: true, }); if (!Array.isArray(rows) || rows.length !== ids.length) { throw this.createError('存在供应商不存在或无权限删除', 404); } const affectedRows = await ctx.model.PackageSupplier.destroy({ where: { id: { [Op.in]: ids, }, warehouse_id: warehouseId, }, }); return { deleted: true, warehouse_id: warehouseId, ids, affected_rows: Number(affectedRows || 0), }; } /** * 查询供应商列表。 * * @param {Object} data 请求参数 * @return {Promise} 分页结果 */ async get(data = {}) { const { app, ctx } = this; const { Op } = app.Sequelize; const warehouseId = 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: warehouseId, }, ...(Array.isArray(parsedResult.dynamicConditions) ? parsedResult.dynamicConditions : []), ]; const quickWhereField = parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere ? parsedResult.rawConditionsByField.quickWhere : null; const quickWhereValue = quickWhereField && quickWhereField.value !== undefined ? String(quickWhereField.value || '').trim() : ''; if (quickWhereValue) { andConditions.push({ [Op.or]: [ { supplier_code: { [Op.like]: '%' + quickWhereValue + '%', }, }, { supplier_name: { [Op.like]: '%' + quickWhereValue + '%', }, }, { contact_name: { [Op.like]: '%' + quickWhereValue + '%', }, }, { contact_phone: { [Op.like]: '%' + quickWhereValue + '%', }, }, ], }); } const { rows, count } = await ctx.model.PackageSupplier.findAndCountAll({ where: { [Op.and]: andConditions, }, order: [[ 'id', 'DESC' ]], limit: pageSize, offset, }); return { page, page_size: pageSize, total: Number(count || 0), where: normalizedWhere, list: (Array.isArray(rows) ? rows : []) .map(item => this.normalizeSupplierRow(item && typeof item.get === 'function' ? item.get({ plain: true }) : item)) .filter(Boolean), }; } } module.exports = SettingPackageSupplierService;