'use strict'; const Service = require('egg').Service; const { parseWhereConditions } = require('../../../lib/query_condition_parser'); class SettingPackageMaterialService 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 {string} fieldName 字段名称 * @param {number|null} [min=null] 最小值 * @return {number|null} 规范化结果 */ normalizeOptionalDecimal(value, fieldName, min = null) { if (value === undefined || value === null || value === '') { return null; } const normalized = Number(value); if (!Number.isFinite(normalized)) { throw this.createError(fieldName + ' 参数不合法', 400); } if (min !== null && normalized < min) { throw this.createError(fieldName + ' 参数不合法', 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, material_id: materialId, materialId: camelMaterialId, } = data || {}; const rawIds = ids !== undefined ? ids : (id !== undefined ? id : (materialId !== undefined ? materialId : camelMaterialId)); 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', }, material_code: { field: 'material_code', }, material_name: { field: 'material_name', }, material_type: { field: 'material_type', }, 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} 规范化结果 */ normalizeMaterialRow(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), material_code: String(row.material_code || '').trim(), material_name: String(row.material_name || '').trim(), material_type: row.material_type === undefined || row.material_type === null ? '' : String(row.material_type).trim(), spec: row.spec === undefined || row.spec === null ? '' : String(row.spec).trim(), length: row.length === undefined || row.length === null ? null : Number(row.length), width: row.width === undefined || row.width === null ? null : Number(row.width), height: row.height === undefined || row.height === null ? null : Number(row.height), weight: row.weight === undefined || row.weight === null ? null : Number(row.weight), cost_price: row.cost_price === undefined || row.cost_price === null ? null : Number(row.cost_price), 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} materialCode 包材编码 * @param {number|null} [excludeId=null] 排除 ID * @return {Promise} 无返回值 */ async ensureMaterialCodeUnique(warehouseId, materialCode, excludeId = null) { const { ctx, app } = this; const { Op } = app.Sequelize; const where = { warehouse_id: warehouseId, material_code: materialCode, }; const normalizedExcludeId = Number(excludeId || 0); if (Number.isFinite(normalizedExcludeId) && normalizedExcludeId > 0) { where.id = { [Op.ne]: normalizedExcludeId, }; } const existing = await ctx.model.PackageMaterial.findOne({ where, attributes: [ 'id', 'material_code' ], }); if (existing) { throw this.createError('material_code 已被当前仓库使用', 409); } } /** * 按 ID 查找包材。 * * @param {number} id 包材 ID * @param {number} warehouseId 仓库 ID * @return {Promise} 包材记录 */ async findMaterialById(id, warehouseId) { const material = await this.ctx.model.PackageMaterial.findOne({ where: { id, warehouse_id: warehouseId, }, }); if (!material) { throw this.createError('包材不存在或无权限操作', 404); } return material; } /** * 创建包材。 * * @param {Object} data 请求参数 * @return {Promise} 创建结果 */ async create(data = {}) { const warehouseId = this.getCurrentStoreId(); const { material_code: materialCode, material_name: materialName, material_type: materialType, spec, length, width, height, weight, cost_price: costPrice, status, } = data || {}; const normalizedMaterialCode = this.normalizeRequiredText(materialCode, 'material_code', 64).toUpperCase(); const normalizedMaterialName = this.normalizeRequiredText(materialName, 'material_name', 128); const normalizedMaterialType = this.normalizeOptionalText(materialType, 'material_type', 32); const normalizedSpec = this.normalizeOptionalText(spec, 'spec', 128); const normalizedStatus = this.normalizeStatus(status, 1); await this.ensureMaterialCodeUnique(warehouseId, normalizedMaterialCode); const createdRow = await this.ctx.model.PackageMaterial.create({ warehouse_id: warehouseId, material_code: normalizedMaterialCode, material_name: normalizedMaterialName, material_type: normalizedMaterialType, spec: normalizedSpec, length: this.normalizeOptionalDecimal(length, 'length', 0), width: this.normalizeOptionalDecimal(width, 'width', 0), height: this.normalizeOptionalDecimal(height, 'height', 0), weight: this.normalizeOptionalDecimal(weight, 'weight', 0), cost_price: this.normalizeOptionalDecimal(costPrice, 'cost_price', 0), status: normalizedStatus, }); return this.normalizeMaterialRow(createdRow && typeof createdRow.get === 'function' ? createdRow.get({ plain: true }) : createdRow); } /** * 更新包材。 * * @param {Object} data 请求参数 * @return {Promise} 更新结果 */ async update(data = {}) { const warehouseId = this.getCurrentStoreId(); const { id, material_id: materialId, materialId: camelMaterialId, material_code: materialCode, material_name: materialName, material_type: materialType, spec, length, width, height, weight, cost_price: costPrice, status, } = data || {}; const resolvedId = Number(id !== undefined ? id : (materialId !== undefined ? materialId : camelMaterialId)); if (!Number.isInteger(resolvedId) || resolvedId <= 0) { throw this.createError('id 参数不合法', 400); } const material = await this.findMaterialById(resolvedId, warehouseId); const updates = {}; if (materialCode !== undefined) { const normalizedMaterialCode = this.normalizeRequiredText(materialCode, 'material_code', 64).toUpperCase(); await this.ensureMaterialCodeUnique(warehouseId, normalizedMaterialCode, resolvedId); updates.material_code = normalizedMaterialCode; } if (materialName !== undefined) { updates.material_name = this.normalizeRequiredText(materialName, 'material_name', 128); } if (materialType !== undefined) { updates.material_type = this.normalizeOptionalText(materialType, 'material_type', 32); } if (spec !== undefined) { updates.spec = this.normalizeOptionalText(spec, 'spec', 128); } if (length !== undefined) { updates.length = this.normalizeOptionalDecimal(length, 'length', 0); } if (width !== undefined) { updates.width = this.normalizeOptionalDecimal(width, 'width', 0); } if (height !== undefined) { updates.height = this.normalizeOptionalDecimal(height, 'height', 0); } if (weight !== undefined) { updates.weight = this.normalizeOptionalDecimal(weight, 'weight', 0); } if (costPrice !== undefined) { updates.cost_price = this.normalizeOptionalDecimal(costPrice, 'cost_price', 0); } if (status !== undefined) { updates.status = this.normalizeStatus(status, 1); } if (Object.keys(updates).length > 0) { await material.update(updates); } return this.normalizeMaterialRow(material && typeof material.get === 'function' ? material.get({ plain: true }) : material); } /** * 删除包材。 * * @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.PackageMaterial.findAll({ where: { id: { [Op.in]: ids, }, warehouse_id: warehouseId, }, attributes: [ 'id', 'material_code' ], raw: true, }); if (!Array.isArray(rows) || rows.length !== ids.length) { throw this.createError('存在包材不存在或无权限删除', 404); } const refCount = await ctx.model.OrderExpress.count({ where: { warehouse_id: warehouseId, package_material_id: { [Op.in]: ids, }, }, }); if (Number(refCount) > 0) { throw this.createError('包材已被订单快递使用,无法删除', 409); } const affectedRows = await ctx.model.PackageMaterial.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]: [ { material_code: { [Op.like]: '%' + quickWhereValue + '%', }, }, { material_name: { [Op.like]: '%' + quickWhereValue + '%', }, }, { material_type: { [Op.like]: '%' + quickWhereValue + '%', }, }, { spec: { [Op.like]: '%' + quickWhereValue + '%', }, }, ], }); } const { rows, count } = await ctx.model.PackageMaterial.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.normalizeMaterialRow(item && typeof item.get === 'function' ? item.get({ plain: true }) : item)) .filter(Boolean), }; } /** * 快捷搜索包材,按关键词模糊匹配编码和名称。 * * @param {Object} [data={}] 请求参数 * @param {string} [data.keyword] 搜索关键词,匹配 material_code 和 material_name * @return {Promise} 返回对象包含 data 属性,值为匹配结果数组,最多 50 条 */ async search(data = {}) { const { app } = this; const { Op } = app.Sequelize; const warehouseId = this.getCurrentStoreId(); const { keyword } = data || {}; const whereCondition = { warehouse_id: warehouseId, status: 1, }; if (keyword && String(keyword).trim()) { const kw = String(keyword).trim(); const like = `%${kw}%`; whereCondition[Op.or] = [ { material_code: { [Op.like]: like } }, { material_name: { [Op.like]: like } }, ]; } const rows = await app.model.PackageMaterial.findAll({ where: whereCondition, attributes: [ 'id', 'material_code', 'material_name', 'material_type', 'spec', 'status' ], order: [[ 'id', 'DESC' ]], limit: 50, raw: true, }); return { data: rows, }; } } module.exports = SettingPackageMaterialService;