'use strict'; const Service = require('egg').Service; class StoreService extends Service { normalizeSubjectConfigInput(data = {}) { const rawSubjectConfig = data.subject_config !== undefined ? data.subject_config : data.subjectConfig; if (this.app.model.Store && typeof this.app.model.Store.normalizeSubjectConfig === 'function') { return this.app.model.Store.normalizeSubjectConfig(rawSubjectConfig); } return { max_notice_webhook_count: 5, default_express_code: 'STO', default_platform_code: 'TB', }; } validateStoreData(data = {}) { const errors = []; const requiredFields = [ 'company_name', 'contact_person', 'contact_phone' ]; for (const field of requiredFields) { if (!data[field]) { errors.push(`${field} 不能为空`); } } if (data.company_name && (data.company_name.length < 1 || data.company_name.length > 200)) { errors.push('公司名称长度应在1-200个字符之间'); } if (data.contact_email && data.contact_email.trim() !== '') { const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if (!emailRegex.test(data.contact_email)) { errors.push('联系邮箱格式不正确'); } } if (data.subject_config !== undefined || data.subjectConfig !== undefined) { try { this.normalizeSubjectConfigInput(data); } catch (error) { errors.push(error.message); } } return errors; } async checkCompanyNameExists(companyName, excludeId = null) { const where = { company_name: companyName, }; if (excludeId) { where.id = { [this.app.Sequelize.Op.ne]: excludeId, }; } const store = await this.app.model.Store.findOne({ where }); return !!store; } async findByAccountId(accountId) { return await this.app.model.Store.findOne({ where: { account_id: accountId, status: 1, }, }); } async findAllEnabled() { return await this.app.model.Store.findAll({ where: { status: 1, }, order: [[ 'company_name', 'ASC' ]], }); } async findAllWarehouses() { return await this.app.model.Store.findAll({ where: { status: 1, project: 'warehouse', }, order: [[ 'company_name', 'ASC' ]], }); } /** * 根据ID获取商家信息。 * @param {number|string} storeId 商家ID * @return {Promise} 查询结果 */ async getStoreName(storeId) { try { const store = await this.app.model.Store.findByPk(storeId, { attributes: [ 'id', 'company_name', 'status' ], }); if (!store) { return { code: 404, message: '商家不存在', data: null, }; } return { code: 200, message: '获取成功', data: store, }; } catch (error) { this.ctx.logger.error('获取商家信息失败:', error); return { code: 500, message: '获取商家信息失败', data: null, }; } } /** * 获取商家仓库备注名。 * @param {number|string} storeId 商家ID * @param {number|string} warehouseId 仓库ID * @return {Promise} 查询结果 */ async getStoreRemaskName(storeId, warehouseId) { try { const relation = await this.app.model.StoreWarehouse.findOne({ where: { store_id: storeId, warehouse_id: warehouseId, }, }); if (!relation) { return { code: 404, message: '商家仓库关系不存在', data: null, }; } return { code: 200, message: '获取成功', data: relation, }; } catch (error) { this.ctx.logger.error('获取商家仓库关系失败:', error); return { code: 500, message: '获取商家仓库关系失败', data: null, }; } } /** * 创建商家(不需要审核)。 * @param {Object} data 请求参数 * @return {Promise} 创建结果 */ async createStore(data) { const { ctx, } = this; const transaction = await ctx.model.transaction(); try { const userId = ctx.userId || (ctx.user && ctx.user.id); if (!userId) { return { code: 401, message: '用户未登录', data: null, }; } // 验证必填字段 const requiredFields = [ 'company_name', 'business_license', 'contact_person', 'contact_phone' ]; for (const field of requiredFields) { if (!data[field]) { return { code: 400, message: `字段 ${field} 不能为空`, data: null, }; } } // 检查公司名称是否已存在 const existingStore = await ctx.model.Store.findOne({ where: { company_name: data.company_name, }, }); if (existingStore) { return { code: 409, message: '公司名称已存在', data: null, }; } let subjectConfig = null; try { subjectConfig = this.normalizeSubjectConfigInput(data); } catch (error) { await transaction.rollback(); return { code: 400, message: error.message, data: null, }; } // 创建商家 const storeData = { company_name: data.company_name, business_license: data.business_license, legal_person: data.legal_person, contact_phone: data.contact_phone, contact_email: data.contact_email, contact_person: data.contact_person, address: data.address, industry: data.industry, account_id: userId, // 商家管理员 status: 1, // 直接启用 created_by: userId, is_warehouse: 0, // 默认不是仓库 logo_url: data.logo_url, domain: data.domain, auth_start: data.auth_start, auth_end: data.auth_end, subject_config: subjectConfig, }; const store = await ctx.model.Store.create(storeData, { transaction, }); // 为创建者自动分配商家管理员角色 const role_id = await this.assignAdminRoleToCreator(store.id, userId, data.contact_person, transaction); await transaction.commit(); // 记录操作日志 try { await ctx.service.systems.operationLog.createOperationLog({ businessType: 'store', businessId: store.id, operationCode: 'STORE_CREATE', operator: { id: ctx.user?.employees_id || ctx.user?.id, name: ctx.user?.employees_name || '', }, extras: {}, beforeChanges: null, }); } catch (logErr) { ctx.logger.warn('[store.createStore] 写入操作日志失败,不影响业务', logErr); } return { code: 200, message: '商家创建成功', data: { store_id: store.id, company_name: store.company_name, role_id: role_id.id, }, }; } catch (error) { await transaction.rollback(); this.ctx.logger.error('创建商家失败:', error); if (error.name === 'SequelizeUniqueConstraintError') { return { code: 409, message: '商家信息已存在', data: null, }; } return { code: 500, message: '创建商家失败', data: null, }; } } /** * 创建仓库(需要审核)。 * @param {Object} data 请求参数 * @return {Promise} 创建结果 */ async createWarehouse(data) { const { ctx, } = this; const transaction = await ctx.model.transaction(); try { const userId = ctx.userId || (ctx.user && ctx.user.id); if (!userId) { return { code: 401, message: '用户未登录', data: null, }; } // 验证必填字段 const requiredFields = [ 'company_name', 'contact_person', 'contact_phone' ]; for (const field of requiredFields) { if (!data[field]) { return { code: 400, message: `字段 ${field} 不能为空`, data: null, }; } } // 检查公司名称是否已存在 const existingStore = await ctx.model.Store.findOne({ where: { company_name: data.company_name, }, }); if (existingStore) { return { code: 409, message: '公司名称已存在', data: null, }; } let subjectConfig = null; try { subjectConfig = this.normalizeSubjectConfigInput(data); } catch (error) { await transaction.rollback(); return { code: 400, message: error.message, data: null, }; } // 创建仓库(也是商家,但 is_warehouse = 1) const warehouseData = { company_name: data.company_name, business_license: data.business_license, legal_person: data.legal_person, contact_phone: data.contact_phone, contact_email: data.contact_email, contact_person: data.contact_person, address: data.address, industry: data.industry, account_id: userId, status: 1, // 直接通过 created_by: userId, is_warehouse: 1, // 标记为仓库 logo_url: data.logo_url, domain: data.domain, auth_start: new Date(), // 设置当前时间为授权开始时间 auth_end: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // 默认授权7天试用 subject_config: subjectConfig, }; const warehouse = await ctx.model.Store.create(warehouseData, { transaction, }); // 为创建者自动分配商家管理员角色 const role_id = await this.assignAdminRoleToCreator(warehouse.id, userId, data.contact_person, transaction, false); await transaction.commit(); // 记录操作日志 try { await ctx.service.systems.operationLog.createOperationLog({ businessType: 'store', businessId: warehouse.id, operationCode: 'STORE_CREATE_WAREHOUSE', operator: { id: ctx.user?.employees_id || ctx.user?.id, name: ctx.user?.employees_name || '', }, extras: {}, beforeChanges: null, }); } catch (logErr) { ctx.logger.warn('[store.createWarehouse] 写入操作日志失败,不影响业务', logErr); } return { code: 200, message: '仓库创建申请已提交,等待审核', data: { store_id: warehouse.id, company_name: warehouse.company_name, role_id: role_id.id, }, }; } catch (error) { await transaction.rollback(); this.ctx.logger.error('创建仓库申请失败:', error); if (error.name === 'SequelizeUniqueConstraintError') { return { code: 409, message: '仓库信息已存在', data: null, }; } return { code: 500, message: '提交申请失败', data: null, }; } } /** * 加入商家。 * @param {Object} data 请求参数 * @return {Promise} 创建结果 */ async joinStore(data) { const { ctx, } = this; const transaction = await ctx.model.transaction(); try { const userId = ctx.userId || (ctx.user && ctx.user.id); // 验证必填字段 if (!data.employees_name) { return { code: 400, message: '真实姓名不能为空', data: null, }; } // 删除用户的其他待审核申请 await ctx.model.StoreJoin.destroy({ where: { account_id: userId, audit_status: 'pending', }, transaction, }); // 生成加入链接(用于分享给管理员) const joinToken = this.generateJoinToken(userId, data.store_id); // 创建加入申请 const applyData = { account_id: userId, real_name: data.employees_name, warehouse: 0, apply_time: new Date(), apply_username: ctx.username || '', audit_status: 'pending', remark: data.remark, join_token: joinToken, }; const applyRecord = await ctx.model.StoreJoin.create(applyData, { transaction, }); await transaction.commit(); return { code: 200, message: '加入申请已提交', data: { apply_id: applyRecord.id, joinToken, }, }; } catch (error) { await transaction.rollback(); return { code: 500, message: '创建申请链接失败', data: null, }; } } /** * 加入仓库。 * @param {Object} data 请求参数 * @return {Promise} 创建结果 */ async joinWarehouse(data) { const { ctx, } = this; const transaction = await ctx.model.transaction(); try { const userId = ctx.userId || (ctx.user && ctx.user.id); // 验证必填字段 if (!data.employees_name) { return { code: 400, message: '真实姓名不能为空', data: null, }; } // 删除用户的其他待审核申请 await ctx.model.StoreJoin.destroy({ where: { account_id: userId, audit_status: 'pending', }, transaction, }); // 生成加入链接(用于分享给管理员) const joinToken = this.generateJoinToken(userId, data.store_id); // 创建加入申请 const applyData = { account_id: userId, real_name: data.employees_name, warehouse: 1, apply_time: new Date(), apply_username: ctx.username || '', audit_status: 'pending', remark: data.remark, join_token: joinToken, }; const applyRecord = await ctx.model.StoreJoin.create(applyData, { transaction, }); await transaction.commit(); return { code: 200, message: '加入申请已提交', data: { apply_id: applyRecord.id, joinToken, }, }; } catch (error) { await transaction.rollback(); return { code: 500, message: '创建申请链接失败', data: null, }; } } // ==================== 辅助方法 ==================== /** * 确保工号与角色已绑定。 * @param {Object} options 绑定参数 * @param {number|string} options.accountId 账号ID * @param {number|string} options.storeId 主体ID * @param {number|string} options.roleId 角色ID * @param {string} [options.realName] 真实姓名 * @param {Object} options.transaction 事务对象 * @return {Promise} 绑定结果 */ async ensureEmployeeRoleBinding({ accountId, storeId, roleId, realName = '', transaction }) { const { ctx } = this; const [ employee ] = await ctx.model.AccountStoreEmployee.findOrCreate({ where: { account_id: accountId, store_id: storeId, }, defaults: { account_id: accountId, store_id: storeId, status: 1, real_name: realName || '', }, transaction, }); const shouldRefreshEmployee = Number(employee.status) !== 1 || (realName && employee.real_name !== realName); if (shouldRefreshEmployee) { await employee.update({ status: 1, real_name: realName || employee.real_name || '', }, { transaction }); } const [ employeeRole ] = await ctx.model.EmployeeRole.findOrCreate({ where: { employee_id: employee.id, role_id: roleId, }, defaults: { employee_id: employee.id, role_id: roleId, }, transaction, }); return { employee, employeeRole }; } /** * 为创建者分配管理员角色。 * @param {number|string} storeId 主体ID * @param {number|string} userId 账号ID * @param {string} realName 真实姓名 * @param {Object} transaction 事务对象 * @param {boolean} [isStore=true] 是否为商家主体 * @return {Promise} 工号实例 */ async assignAdminRoleToCreator(storeId, userId, realName, transaction, isStore = true) { const { ctx, } = this; // 创建或获取管理员角色 const role_code = isStore ? 'store_admin_default' : 'warehouse_admin_default'; const adminRole = await ctx.model.Role.findOne({ where: { store_id: null, role_code, }, }); if (!adminRole) { throw new Error(`未初始化${role_code}管理员角色`); } const { employee } = await this.ensureEmployeeRoleBinding({ accountId: userId, storeId, roleId: adminRole.id, realName: realName || '', transaction, }); return employee; } /** * 生成加入令牌。 * @param {number|string} userId 账号ID * @param {number|string} storeId 主体ID * @param {string} [type='store'] 令牌类型 * @return {string} 加入令牌 */ generateJoinToken(userId, storeId, type = 'store') { const crypto = require('crypto'); const timestamp = Date.now(); const randomStr = Math.random().toString(36).substring(2, 10); const data = `${userId}_${storeId}_${type}_${timestamp}_${randomStr}`; return crypto.createHash('sha256').update(data).digest('hex') .substring(0, 32); } /** * 发送通知。 * @param {Object} notificationData 通知数据 * @return {Promise} */ async sendNotification(notificationData) { const { ctx, } = this; try { await ctx.model.Notification.create({ ...notificationData, is_read: 0, created_at: new Date(), }); } catch (error) { this.ctx.logger.error('发送通知失败:', error); } } /** * 发送通知给系统管理员。 * @param {Object} notificationData 通知数据 * @return {Promise} */ async sendNotificationToAdmins(notificationData) { const { ctx, } = this; try { // 获取所有系统管理员 const admins = await ctx.model.Account.findAll({ where: { status: 1, // 这里可以根据角色筛选系统管理员 }, attributes: [ 'id' ], }); for (const admin of admins) { await this.sendNotification({ ...notificationData, account_id: admin.id, }); } } catch (error) { this.ctx.logger.error('发送管理员通知失败:', error); } } async getStoreRoles(data) { const { ctx, } = this; try { const storeId = ctx.user.store_id; // 验证必填字段 if (!data.code) { return { code: 400, message: '参数错误', data: null, }; } const code = data.code; const applyData = await ctx.model.StoreJoin.findOne({ where: { join_token: code, audit_status: 'pending', }, attributes: [ 'account_id', 'real_name', 'remark', 'audit_status', 'apply_time' ], }); const store = await ctx.model.Store.findOne({ where: { id: storeId, status: 1, }, attributes: [ 'company_name', 'id' ], }); const Roles = await ctx.model.Role.findAll({ where: { store_id: storeId, deleted_at: null, }, }); return { code: 200, message: '获取成功', data: { info: applyData, store, roles: Roles, }, }; } catch (error) { return { code: 500, message: '请求失败', data: null, }; } } async auditApply(data) { const { ctx } = this; const transaction = await ctx.model.transaction(); try { // 1. 验证必填字段 - 修复逻辑错误 if (!data.audit_status || !data.code || !data.store_id || !data.role_ids || data.role_ids.length === 0) { await transaction.rollback(); return { code: 400, message: '参数错误:audit_status、code和role_ids为必填字段', data: null, }; } // 2. 验证store_id if (ctx.user.store_id !== data.store_id) { await transaction.rollback(); return { code: 400, message: '参数错误:审批角色与访问接口不一致', data: null, }; } const { code, audit_status, role_ids } = data; const store_id = ctx.user.store_id; // 3. 查找申请记录 const applyData = await ctx.model.StoreJoin.findOne({ where: { join_token: code, audit_status: 'pending', }, attributes: [ 'id', 'account_id', 'real_name', 'remark', 'audit_status', 'apply_time' ], transaction, }); if (!applyData) { await transaction.rollback(); return { code: 400, message: '没有找到对应的申请信息,可能已被他人审核或者申请者重新提交了申请资料', data: null, }; } // 4. 查询角色信息 const roles = await ctx.model.Role.findAll({ where: { store_id, deleted_at: null, id: role_ids, // in查询 }, transaction, }); // 5. 验证role_ids是否都存在 if (roles.length !== role_ids.length) { await transaction.rollback(); const foundRoleIds = roles.map(role => role.id); const missingRoleIds = role_ids.filter(id => !foundRoleIds.includes(id)); return { code: 400, message: `角色ID不存在或无权限:${missingRoleIds.join(',')}`, data: null, }; } // 6. 根据审核状态处理不同的逻辑 if (audit_status === 'approved') { // 审核通过:分配角色并更新申请状态 const { account_id, real_name } = applyData; for (const role of roles) { await this.ensureEmployeeRoleBinding({ accountId: account_id, storeId: store_id, roleId: role.id, realName: real_name || '', transaction, }); } // 更新申请记录状态 await ctx.model.StoreJoin.update({ audit_status: 'approved', audit_time: new Date(), auditor_id: ctx.user.account_id, auditor_name: ctx.user.real_name || ctx.user.username, }, { where: { id: applyData.id }, transaction, }); await this.ctx.Service.systems.auth.user.clearUserCache(ctx.user.account_id);// 立即清理用户缓存 await transaction.commit(); const result = await this.getStoreRoles({ code }); return { code: 200, message: '审批通过成功', data: result.data, }; } else if (audit_status === 'rejected') { // 审核拒绝:只更新申请状态 await ctx.model.StoreJoin.update({ audit_status: 'rejected', audit_time: new Date(), auditor_id: ctx.user.account_id, auditor_name: ctx.user.real_name || ctx.user.username, reject_reason: data.reject_reason || '审核不通过', }, { where: { id: applyData.id }, transaction, }); await transaction.commit(); return { code: 200, message: '审批拒绝成功', data: null, }; } await transaction.rollback(); return { code: 400, message: 'audit_status参数错误,只能为approved或rejected', data: null, }; } catch (error) { await transaction.rollback(); console.error('审核申请出错:', error); // 根据错误类型返回更详细的错误信息 let errorMessage = '请求失败'; if (error.name === 'SequelizeValidationError') { errorMessage = '数据验证失败'; } else if (error.name === 'SequelizeUniqueConstraintError') { errorMessage = '数据已存在'; } return { code: 500, message: errorMessage, data: null, error: process.env.NODE_ENV === 'development' ? error.message : undefined, }; } } async loadStores() { const { ctx } = this; try { const rows = await ctx.model.StoreWarehouse.findAll({ where: { warehouse_use_status: 1, warehouse_id: ctx.user.store_id, }, attributes: [ 'store_id', 'store_remask' ], include: [ { model: ctx.model.Store, as: 'store', attributes: [ 'company_name' ], required: false, }, ], raw: true, }); return rows.map(row => ({ value: row.store_id, label: row.store_remask || (row['store.company_name'] || ''), })); } catch (error) { ctx.logger.error('[Service.loadStores] 查询失败:', error); throw error; } } async loadWarehouses() { const { ctx } = this; try { const rows = await ctx.model.StoreWarehouse.findAll({ where: { store_use_status: 1, store_id: ctx.user.store_id, }, attributes: [ 'warehouse_id', 'warehouse_remask' ], include: [ { model: ctx.model.Store, as: 'warehouse', attributes: [ 'company_name' ], required: false, }, ], raw: true, }); return rows.map(row => ({ value: row.warehouse_id, label: row.warehouse_remask || (row['warehouse.company_name'] || ''), })); } catch (error) { ctx.logger.error('[Service.loadWarehouses] 查询失败:', error); throw error; } } /** * 生成货主绑群码。 * 查询货主与仓库的有效合约,生成 12 位随机码并存入缓存(5分钟有效)。 * * @param {Object} data 请求数据。 * @param {number} data.storeId 货主ID(必填)。 * @param {number} data.warehouseId 仓库ID(必填,由 systemMethods 层注入)。 * @param {string} [data.subType] 群子类型:after_sales / finance / receiving。 * @return {Promise} { code: 绑群码 }。 */ async bindCode(data = {}) { const { ctx } = this; const storeId = Number(data.storeId); const warehouseId = Number(data.warehouseId); if (!Number.isFinite(storeId) || storeId <= 0) { throw new Error('storeId 无效'); } if (!Number.isFinite(warehouseId) || warehouseId <= 0) { throw new Error('缺少仓库信息,请确认已登录并选择了仓库'); } const contract = await ctx.model.StoreWarehouse.findOne({ attributes: [ 'id', 'store_id', 'warehouse_id', 'initiator_subject_id' ], where: { store_id: storeId, warehouse_id: warehouseId, auth_status: 2, warehouse_use_status: 1, }, raw: true, }); if (!contract) { throw new Error(`货主 ${storeId} 在仓库 ${warehouseId} 无有效合约`); } const subType = String(data.subType || '').trim(); const VALID_SUB_TYPES = [ 'after_sales', 'finance', 'receiving' ]; if (subType && !VALID_SUB_TYPES.includes(subType)) { throw new Error(`无效的子类型: ${subType},可选值: ${VALID_SUB_TYPES.join(' / ')}`); } const code = Math.random().toString(36).slice(2, 8) .toUpperCase() + Math.random().toString(36).slice(2, 8) .toUpperCase(); const cacheKey = `chat:bind:${warehouseId}:${code}`; const cacheValue = { store_id: contract.store_id, initiator_subject_id: contract.initiator_subject_id || null, warehouse_id: contract.warehouse_id, group_type: 'store', sub_type: subType || null, }; await ctx.app.setCacheAsync(cacheKey, cacheValue, 300); ctx.logger.info( `[store bindCode] 生成绑群码 code=${code} ` + `store_id=${contract.store_id} warehouse_id=${warehouseId}` ); return { code }; } } module.exports = StoreService;