Compare commits

..

33 Commits

Author SHA1 Message Date
01101d422f fix(hjmCar): 调整无坐标分页查询默认限制及状态
- 将无纬度或经度时的分页限制由2000缩减到500
- 设置无坐标查询时默认状态为1,优化数据筛选
- 删除了历史退款订单修复相关的控制器与服务代码
- 移除多个环境配置文件,清理无用资源
- 删除多项测试代码,去除无用单元测试与集成测试代码
2026-04-29 22:14:07 +08:00
4ec637d7f8 refactor(batch-import): 删除 BatchImportSupport 类及相关批处理支持代码
- 移除 credit 模块中的 Excel 导入批处理支持实现
- 删除硬删除及批量硬删除方法
- 删除按企业名称及文本匹配回填 companyId 的相关刷新方法
- 删除多种批量 upsert 实现及带计数器的更新方法
- 移除带降级逐行持久化的批量保存支持
- 删除处理唯一索引冲突的批量插入辅助逻辑
- 清理所有相关导入和依赖内容
2026-04-29 19:49:02 +08:00
30a53e7283 feat(db): 优化ShopDealerApply查询条件支持接待人过滤
- 修改ShopDealerApplyMapper.xml,增加接待人ID和申请用户ID的联合过滤条件
- 支持当接待人ID与申请用户ID都存在时,进行多条件OR查询
- 支持单独存在接待人ID时的过滤条件
- 在ShopDealerApplyParam中新增receptionistId字段,支持接待人用户ID查询参数
- 完善查询条件逻辑,提高业务灵活性和数据筛选能力
2026-04-16 17:42:21 +08:00
9ec44dbe5c refactor(recommendation): 删除推荐记录相关模块,清理代码和数据结构
- 移除推荐记录管理后台控制器LeadReferralAdminController
- 删除小程序端推荐记录控制器LeadReferralController
- 删除推荐记录实体LeadReferral及相关实体ReferralSettlement、ReferrerInfo
- 删除对应的数据访问层Mapper接口
- 删除推荐记录查询参数类LeadReferralParam
- 删除推荐记录服务接口LeadReferralService及其实现LeadReferralServiceImpl
- 清理相关注解、导入及依赖,彻底移除推荐记录功能模块
2026-04-16 17:04:31 +08:00
89ac0d109c fix(recommendation): 修正分页参数的有效性判断逻辑
- 将分页参数的非空判断改为大于0判断以保证参数有效
- 修改参数名统一为current和size以保持一致性
- 修正了LeadReferralServiceImpl中分页相关方法的分页逻辑
- 确保当分页参数无效时使用默认分页值1和10
2026-04-16 16:47:18 +08:00
7095c4bf96 feat(recommendation): 实现推荐客户管理全流程功能
- 新增推荐记录、推荐人信息、推荐费结算实体及数据库表结构
- 实现推荐记录小程序端接口,包括新增报备、获取推荐码、查询我的推荐及统计
- 实现后台管理端推荐记录分页查询、确认有效、作废、结算及批量结算接口
- 实现推荐人信息查询及推荐统计汇总逻辑
- 实现推荐记录导出功能,支持导出推荐详情数据
- 完成推荐状态变更时推荐人统计数据同步更新
- 添加相关Mapper接口和Service接口及实现
- 使用MyBatis Plus分页插件支持分页查询
- 集成Spring Security权限校验和操作日志注解
- 优化推荐码生成和唯一性校验机制
2026-04-16 16:40:08 +08:00
cc2fe7b172 fix(shop-dealer-user): 修复手机号重复添加逻辑并更新用户ID
- 查询手机号是否已存在对应记录
- 如果存在则更新其userId为当前登录用户的userId
- 避免手机号重复添加,改为执行更新操作
- 保证手机号唯一性的同时允许用户信息变更
- 删除原有直接返回失败的逻辑,改为更新并返回成功状态
2026-04-16 14:27:57 +08:00
b6a3d407e4 fix(shop): 修正获取分销商用户记录接口的查询方法
- 将查询方法从getByIdRel修改为getByUserIdRel
- 使用关联查询以确保返回正确的用户数据
- 解决了因使用错误方法导致的数据获取问题
2026-04-16 14:07:19 +08:00
db5ca691d7 feat(customer-lead): 实现完整客资管理系统及全民推荐功能
- 新增客资管理系统数据库变更脚本,扩展客资表及新增派单、推荐关系等多张表
- 实现客资派单、跟进、统计、导出等核心业务逻辑,支持多管理员配置
- 开发Java后端实体、参数、Mapper和服务,实现完整业务流程接口
- 提供客资管理相关REST API,涵盖分页查询、详情、状态更新、派单、跟进和统计等
- 新增全民推荐模块,支持匿名及注册用户报备推荐客户,并提供推荐记录管理
- 开发推荐人相关API接口,支持推荐码生成与查询,推荐确认及结算功能
- Vue后台新增客资管理页面,实现客资列表、派单、跟进、详情查看等功能
- 微信小程序端新增推荐客户页面,支持推荐记录展示和推荐状态跟踪
- 完善数据字典和部署说明,涵盖状态说明、来源类型和跟进方式
- 提出后续优化建议,包括权限细化、数据看板、消息通知以及推荐海报功能等
2026-04-14 11:57:09 +08:00
ad23922a7c feat(entity): 添加接待人相关字段
- 新增receptionistId字段,记录接待人用户ID
- 新增receptionistName字段,记录接待人名称
- 字段均添加了相应的Schema描述信息feat(entity): 新增接待人用户ID及名称字段

- 在ShopDealerApply实体中添加receptionistId字段表示接待人用户ID
- 添加receptionistName字段用于存储接待人名称
- 对新增字段增加Swagger注解描述信息
- 保持原有房号和佣金比例字段不变
2026-04-09 13:59:31 +08:00
1a990087ac Merge remote-tracking branch 'origin/master' 2026-04-04 10:31:46 +08:00
13b4f626aa remove(AI): 移除所有AI相关模块代码
- 删除Ollama客户端及DTO类定义
- 移除AI聊天、分析、知识库控制器
- 清理AI相关数据传输对象
- 删除知识库实体类和映射器
- 移除AI分析服务和提示词模板
- 清理AI相关的XML映射文件
- 移除AI配置属性类定义
- 删除知识库服务实现类
2026-04-04 10:31:32 +08:00
84cd214277 feat(website): 新增应用发布管理功能
- 在CmsWebsite实体中添加发布状态、定价模式、应用描述等相关字段
- 实现应用上架审核流程:提交审核、撤回申请、下架、管理员审批等功能
- 添加审核列表分页查询接口,支持按发布状态筛选
- 更新路由配置,调整开发者资源路径
- 添加数据库表结构变更SQL脚本,增加发布管理相关字段
2026-04-01 01:04:49 +08:00
8a9d779d08 feat(website): 新增应用发布管理功能
- 在CmsWebsite实体中添加发布状态、定价模式、应用描述等相关字段
- 实现应用上架审核流程:提交审核、撤回申请、下架、管理员审批等功能
- 添加审核列表分页查询接口,支持按发布状态筛选
- 更新路由配置,调整开发者资源路径
- 添加数据库表结构变更SQL脚本,增加发布管理相关字段
2026-04-01 00:59:44 +08:00
f1dde97538 feat(website): 新增应用发布管理功能
- 在CmsWebsite实体中添加发布状态、定价模式、应用描述等相关字段
- 实现应用上架审核流程:提交审核、撤回申请、下架、管理员审批等功能
- 添加审核列表分页查询接口,支持按发布状态筛选
- 更新路由配置,调整开发者资源路径
- 添加数据库表结构变更SQL脚本,增加发布管理相关字段
2026-04-01 00:59:06 +08:00
5029be1f1f feat(ticket): 更新工单列表排序逻辑
- 实现工单状态优先级排序:pending > assigned > processing > resolved > closed
- 添加紧急程度优先级排序:urgent > high > normal > low
- 保持相同状态下按创建时间倒序排列
- 使用FIELD函数优化数据库查询排序性能
- 移除原有的简单排序规则并替换为复合排序逻辑
2026-04-01 00:35:07 +08:00
38ee4c65e6 feat(app): 添加开发者资源管理系统
- 创建app_resource数据表,支持服务器/数据库/云存储/域名/SSL证书等资源管理
- 实现AppResource实体类,包含各类资源的特定字段和通用字段
- 开发AppResourceController控制器,提供资源的增删改查和统计功能
- 实现AppResourceService服务层,包含业务逻辑和数据操作方法
- 创建AppResourceMapper数据访问层,支持分页查询和关联查询
- 添加AppResourceParam查询参数类,支持多条件筛选
- 集成MyBatis XML映射文件,实现复杂的关联查询和统计功能
- 实现基于用户权限的资源访问控制和逻辑删除机制
2026-03-31 19:59:24 +08:00
3ea8e652bd feat(app): 添加应用配置管理功能
- 创建应用配置表及实体类
- 实现应用配置的增删改查接口
- 添加配置值加密解密功能
- 支持按应用ID批量获取配置映射
- 实现配置的批量保存和删除功能
- 添加分页查询和列表查询支持
- 集成租户隔离和软删除功能
2026-03-30 19:42:53 +08:00
44e95a7273 feat(ticket): 使用忽略租户拦截器的方法获取用户信息
- 在工单创建时使用 userService.getByIdIgnoreTenant 替代 getById
- 在工单分配时使用 userService.getByIdIgnoreTenant 替代 getById
- 在回复创建时使用 userService.getByIdIgnoreTenant 替代 getById
- 添加注释说明使用 @InterceptorIgnore 绕过租户拦截器跨库查询
- 确保用户信息获取不受租户隔离限制影响
2026-03-30 14:31:52 +08:00
35fdc2dcfc feat(entity): 为工单实体添加附件字段的JSON序列化处理
- 在AppTicket和AppTicketReply实体中添加JsonArrayToStringDeserializer和JsonStringToArraySerializer注解
- 实现附件字段在数据库存储时从数组转换为JSON字符串
- 实现附件字段向前端响应时从JSON字符串转换为数组格式
- 添加JsonArrayToStringDeserializer类处理数组到字符串的反序列化
- 添加JsonStringToArraySerializer类处理字符串到数组的序列化
- 移除CMS网站映射器中的软删除条件过滤
2026-03-30 14:18:03 +08:00
875111d2d8 fix(mapper): 修复网站查询中的表别名引用问题
- 为app_user表添加别名au以避免字段冲突
- 确保website_id字段正确从别名表中引用
- 保持deleted字段的过滤条件一致性
2026-03-30 13:07:26 +08:00
ee2d95da91 feat(website): 添加网站查询中的协作成员筛选功能
- 在CmsWebsiteParam中新增memberUserId参数用于协作成员筛选
- 修改CmsWebsiteMapper.xml添加按memberUserId查询的SQL逻辑
- 实现通过app_user表关联查询指定用户的协作网站列表
- 支持同时查询用户直接创建和作为成员参与的网站
- 保持原有websiteIds和keywords查询条件的兼容性
2026-03-30 12:43:12 +08:00
85e0b062b8 feat(ticket): 实现工单系统并集成企业微信飞书通知
- 在控制器中统一返回格式,修复fail方法调用
- 实现工单提交、查询、回复等核心功能
- 添加工单状态管理(待处理、已分配、处理中、已解决、已关闭)
- 集成企业微信群机器人和飞书群机器人实时通知
- 实现异步推送机制支持四种通知场景:新工单、重新分配、新回复、状态变更
- 添加工单统计功能和用户权限控制
- 创建工单主表和回复表的数据库结构定义
2026-03-30 12:28:27 +08:00
a4d5c86134 feat(app): 添加应用工单系统功能
- 创建AppTicket实体类定义工单数据结构
- 实现AppTicketController提供工单CRUD接口
- 创建AppTicketReply实体支持工单回复功能
- 实现工单提交、查询、状态更新等核心业务逻辑
- 添加工单统计、分配、回复等功能接口
- 集成MyBatis Plus实现数据库操作
- 支持工单分类、优先级、状态流转管理
- 实现自动分配工单给技术成员机制
- 添加工单搜索、分页、权限控制功能
2026-03-30 11:59:41 +08:00
607589d2c5 feat(user): 添加根据手机号查询用户的跨租户功能
- 在 UserMapper 中新增 selectByPhone 方法,支持忽略租户隔离查询
- 更新 UserMapper.xml 中的 selectByPhone 查询语句,实现跨库查询逻辑
- 修改 UserServiceImpl 中的 getByPhone 方法,使用自定义 SQL 避免租户拦截器影响
- 实现跨租户查询,直接访问 gxwebsoft_core.sys_user 表获取用户信息
2026-03-30 11:39:23 +08:00
424929222f feat(contact): 添加联系表单销售线索功能支持
- 新增联系表单数据库表结构设计与实体类定义
- 实现联系表单提交接口,支持公开访问无需登录验证
- 添加后台管理接口,支持线索查询、状态更新和删除操作
- 集成企业微信和飞书机器人通知功能,实时推送新线索
- 在安全配置中开放联系表单提交接口访问权限
- 添加应用配置中的通知机器人Webhook配置项
2026-03-30 11:30:29 +08:00
df7a41f3c4 feat(contact): 添加联系表单销售线索功能支持
- 新增联系表单数据库表结构设计与实体类定义
- 实现联系表单提交接口,支持公开访问无需登录验证
- 添加后台管理接口,支持线索查询、状态更新和删除操作
- 集成企业微信和飞书机器人通知功能,实时推送新线索
- 在安全配置中开放联系表单提交接口访问权限
- 添加应用配置中的通知机器人Webhook配置项
2026-03-30 11:08:12 +08:00
bd2a92d832 feat(website): 完善应用类型管理和标识符唯一性校验
- 移除邀请用户接口的权限注解和操作日志注解
- 更新CmsWebsite实体类中的类型描述,支持多种应用类型
- 在保存和修改网站信息时增加websiteCode唯一性校验逻辑
- 实现create方法中根据应用类型自动设置管理后台地址和类型名称
- 添加generateUniqueCode方法确保websiteCode全局唯一
- 优化代码结构和业务逻辑处理
2026-03-29 02:36:07 +08:00
75c13bada8 refactor(app-user): 移除跨库JOIN依赖,改用冗余字段存储用户信息
- 在AppUser实体中新增nickname和phone冗余字段
- 移除AppUserMapper.xml中的跨库JOIN查询gxwebsoft_core.sys_user表
- 更新搜索条件使用本地冗余字段而非关联表字段
- 注入UserService用于写入冗余用户基础信息
- 邀请成员时查询系统用户信息并冗余存储到本地表
- 日志输出中增加用户名信息便于调试追踪
2026-03-29 01:19:48 +08:00
6aeface82d fix(database): 修复用户表关联查询的数据库模式问题
- 修改 AppUserMapper.xml 中的 LEFT JOIN 语句
- 为 sys_user 表添加 gxwebsoft_core 数据库前缀
- 确保跨数据库关联查询的正确性
- 保持与系统用户表的数据一致性
2026-03-29 00:52:46 +08:00
17352718c5 chore(config): 切换默认激活配置文件为开发环境
- 将 spring.profiles.active 从 ysb2 更改为 dev
- 更新默认运行环境配置以适应开发需求
2026-03-29 00:31:00 +08:00
7dede6f36f feat(app): 完善应用凭证、事件和用户管理功能
- 新增应用密钥凭证的创建、重置和状态管理功能
- 实现AppSecret自动生成功能并添加脱敏显示机制
- 增加应用操作动态的最新记录查询和批量清理功能
- 添加应用成员邀请和角色修改功能
- 优化查询条件支持精确匹配和租户隔离
- 集成网站信息关联查询并完善数据脱敏处理
2026-03-28 21:47:32 +08:00
35cc034af1 feat(generator): 添加代码生成工具及应用实体模块
- 新增 AppGenerator 代码生成工具类,支持多平台模板生成
- 生成 app_credential 应用密钥凭证的完整CRUD功能模块
- 生成 app_event 应用操作动态的完整CRUD功能模块
- 添加对应的 Entity、Controller、Service、Mapper 和 Param 类
- 配置多平台模板支持(Vue、UniApp、移动端页面)
- 实现 app.config.ts 自动更新功能
- 优化后端实现指南文档说明
2026-03-28 21:33:42 +08:00
584 changed files with 12263 additions and 49032 deletions

View File

@@ -0,0 +1,17 @@
{
"version": 2,
"sessions": {
"8b8cdf8cb3404efeac18615f9f419cb1": [
{
"expertId": "SeniorDeveloper",
"name": "吴八哥",
"profession": "高级开发工程师",
"avatarUrl": "https://acc-1258344699.cos.accelerate.myqcloud.com/workbuddy/experts/avatars/02-Engineering/SeniorDeveloper/SeniorDeveloper.png",
"promptUrl": "https://acc-1258344699.cos.accelerate.myqcloud.com/workbuddy/experts/experts/02-Engineering/SeniorDeveloper/SeniorDeveloper_zh.md",
"usedAt": 1776323986694,
"industryId": "02-Engineering"
}
]
},
"lastUpdated": 1776324781452
}

View File

View File

@@ -0,0 +1,230 @@
# 客资管理系统实施总结
> 创建时间2026-04-14
> 作者AI助手
> 状态:实施完成
---
## 一、需求概述
根据客户需求,实现一个完整的**客资管理系统**,具备以下功能:
| 功能 | 描述 |
|------|------|
| 客资派单 | 管理员可以直接派单客资给业务员 |
| 全民推荐 | 任何人都可以推荐客户赚取推荐费 |
| 推荐人报备 | 注册用户可以报备客户(推荐人报备) |
| 实时跟进 | 实时查看跟进情况和成交状态 |
| 多管理员 | 支持多管理员设置 |
| 数据统计导出 | 生成统计报表功能 |
---
## 二、实施成果
### 2.1 Java后端 (`/Users/gxwebsoft/JAVA/mp-java`)
#### 数据库变更
**文件**: `docs/sql/customer_lead_system.sql`
| 表名 | 说明 |
|------|------|
| `cms_contact_lead` | 扩展现有客资表,添加派单、推荐人等字段 |
| `lead_dispatch` | 派单记录表 |
| `lead_follow_log` | 跟进记录表 |
| `lead_referral` | 推荐人关系表(全民推荐) |
| `sys_user_role_extend` | 用户角色扩展表(多管理员) |
| `lead_statistics` | 数据统计汇总表 |
| `lead_referral_settlement` | 推荐费结算记录表 |
| `v_lead_full_info` | 客资完整信息视图 |
#### 新增实体类
| 文件路径 | 说明 |
|----------|------|
| `cms/entity/CustomerLeadEntity.java` | 客资管理扩展实体 |
| `cms/entity/LeadDispatch.java` | 派单记录实体 |
| `cms/entity/LeadFollowLog.java` | 跟进记录实体 |
| `cms/entity/LeadReferral.java` | 推荐关系实体 |
| `cms/entity/LeadStatistics.java` | 统计实体 |
| `common/system/entity/UserRoleExtend.java` | 用户角色扩展实体 |
#### 新增参数类
| 文件路径 | 说明 |
|----------|------|
| `cms/param/CustomerLeadParam.java` | 客资查询参数 |
| `cms/param/LeadDispatchParam.java` | 派单请求参数 |
| `cms/param/LeadFollowParam.java` | 跟进请求参数 |
| `cms/param/LeadReferralParam.java` | 推荐人报备参数 |
#### 新增Mapper
| 文件路径 | 说明 |
|----------|------|
| `cms/mapper/CustomerLeadMapper.java` | 客资管理Mapper |
| `cms/mapper/LeadDispatchMapper.java` | 派单记录Mapper |
| `cms/mapper/LeadFollowLogMapper.java` | 跟进记录Mapper |
| `cms/mapper/LeadReferralMapper.java` | 推荐关系Mapper |
#### 新增Service
| 文件路径 | 说明 |
|----------|------|
| `cms/service/CustomerLeadService.java` | 客资管理服务接口 |
| `cms/service/impl/CustomerLeadServiceImpl.java` | 客资管理服务实现 |
| `cms/service/LeadReferralService.java` | 推荐人服务接口 |
| `cms/service/impl/LeadReferralServiceImpl.java` | 推荐人服务实现 |
#### 新增Controller
| 文件路径 | 说明 |
|----------|------|
| `cms/controller/CustomerLeadController.java` | 客资管理控制器 |
| `cms/controller/LeadReferralController.java` | 推荐人控制器 |
#### API端点
| 接口 | 方法 | 说明 |
|------|------|------|
| `/customer/lead/page` | GET | 分页查询客资列表 |
| `/customer/lead/detail/{leadId}` | GET | 获取客资详情 |
| `/customer/lead/create` | POST | 创建客资 |
| `/customer/lead/update` | PUT | 更新客资信息 |
| `/customer/lead/status/{leadId}` | PUT | 更新客资状态 |
| `/customer/lead/dispatch` | POST | 派单给业务员 |
| `/customer/lead/dispatch/batch` | POST | 批量派单 |
| `/customer/lead/follow` | POST | 添加跟进记录 |
| `/customer/lead/follow/history/{leadId}` | GET | 获取跟进历史 |
| `/customer/lead/statistics` | GET | 获取统计数据 |
| `/customer/lead/export` | GET | 导出客资数据 |
| `/customer/lead/unassigned` | GET | 获取未分配客资 |
| `/lead/referral/anonymous` | POST | 匿名用户报备 |
| `/lead/referral/user` | POST | 注册用户报备 |
| `/lead/referral/page` | GET | 推荐人推荐记录 |
| `/lead/referral/stats/{userId}` | GET | 推荐人统计 |
---
### 2.2 Vue后台管理端 (`/Users/gxwebsoft/VUE/mp-vue`)
#### 新增API
| 文件路径 | 说明 |
|----------|------|
| `api/cms/customerLead/model.ts` | 类型定义 |
| `api/cms/customerLead/index.ts` | API接口 |
#### 新增页面
| 文件路径 | 说明 |
|----------|------|
| `views/cms/customerLead/index.vue` | 客资管理列表页面 |
**功能特性**
- 客资列表(分页、筛选、搜索)
- 统计卡片(总客资、待跟进、已成交、成交金额)
- 新增/编辑客资
- 派单给业务员(支持批量派单)
- 添加跟进记录
- 查看跟进历史
- 客资详情弹窗
---
### 2.3 微信小程序端 (`/Users/gxwebsoft/VUE/template-10582`)
#### 新增API
| 文件路径 | 说明 |
|----------|------|
| `api/shop/referral.ts` | 推荐人API |
#### 新增页面
| 文件路径 | 说明 |
|----------|------|
| `dealer/referral/index.config.ts` | 页面配置 |
| `dealer/referral/index.tsx` | 推荐人报备页面 |
| `dealer/referral/index.scss` | 页面样式 |
**功能特性**
- 推荐人统计(总推荐、待确认、有效、待结算金额)
- 推荐新客户表单
- 推荐记录列表
- 状态追踪
#### 首页入口
在分销商首页 `/dealer/index.tsx` 添加了「推荐客户」入口
---
## 三、数据字典
### 客资状态
| 值 | 文本 | 说明 |
|----|------|------|
| 0 | 待跟进 | 新客资,未分配或未联系 |
| 1 | 跟进中 | 正在跟进 |
| 2 | 已成交 | 客户已付款 |
| 3 | 无效 | 商机流失 |
### 客资来源
| 值 | 文本 | 说明 |
|----|------|------|
| form | 表单 | 网站/小程序表单提交 |
| website | 网站 | 网站表单 |
| miniapp | 小程序 | 小程序表单 |
| referral | 推荐人 | 推荐人报备 |
| admin | 管理员录入 | 后台手动添加 |
### 跟进方式
| 值 | 文本 | 说明 |
|----|------|------|
| 1 | 电话 | 电话沟通 |
| 2 | 微信 | 微信联系 |
| 3 | 上门 | 上门拜访 |
| 4 | 短信 | 短信通知 |
| 5 | 其他 | 其他方式 |
### 推荐状态
| 值 | 文本 | 说明 |
|----|------|------|
| 0 | 待确认 | 等待管理员确认 |
| 1 | 有效 | 推荐有效 |
| 2 | 无效 | 推荐无效 |
| 3 | 已结算 | 推荐费已结算 |
---
## 四、部署说明
### 4.1 数据库部署
```bash
# 执行SQL脚本
mysql -u root -p your_database < docs/sql/customer_lead_system.sql
```
### 4.2 后端部署
1. 重新编译Java项目
2. 部署到应用服务器
3. 确保Mapper XML文件正确部署
### 4.3 前端部署
1. Vue后台`npm run build` 部署dist目录
2. 小程序使用Taro构建并上传
---
## 五、后续优化建议
1. **权限细化**:根据实际业务需求,配置细粒度的按钮权限
2. **数据看板**:开发可视化数据大屏
3. **消息通知**:接入微信模板消息,实时推送派单/跟进通知
4. **小程序入口**:在首页增加「全民推荐」独立入口(非分销商专属)
5. **推荐海报**:生成带参数的推广海报,方便分享传播
6. **佣金结算**:完善佣金提现流程
---
## 六、注意事项
1. **SQL执行顺序**先执行数据库变更SQL再部署后端代码
2. **Mapper XML**需要创建对应的Mapper XML文件
3. **权限配置**:在后台管理系统中配置对应的菜单和按钮权限
4. **推荐费配置**:可后续在配置表中添加推荐费比例等配置项
---
*文档生成时间2026-04-14*

View File

@@ -9,7 +9,8 @@
### 1. 修改 credit_mp_customer 表结构
```sql
-- 为第5-7步添加字段第1-4步字段已存在
-- 为第5-7步添加字段第1-4步基础字段已存在;如未包含审核时间/审核人字段,请先补齐 step1-4 的 approved_at/approved_by
-- 参考docs/sql/credit_mp_customer_step1_4_approval_columns.sql
-- 第5步合同签订
ALTER TABLE credit_mp_customer ADD COLUMN follow_step5_submitted TINYINT DEFAULT 0 COMMENT '是否已提交';
ALTER TABLE credit_mp_customer ADD COLUMN follow_step5_submitted_at VARCHAR(255) COMMENT '提交时间';

19
docs/app_config.sql Normal file
View File

@@ -0,0 +1,19 @@
-- 应用配置表
CREATE TABLE app_config (
config_id INT PRIMARY KEY AUTO_INCREMENT COMMENT '配置ID',
website_id INT NOT NULL COMMENT '应用ID',
config_key VARCHAR(100) NOT NULL COMMENT '配置键',
config_value TEXT NOT NULL COMMENT '配置值JSON或字符串',
config_type VARCHAR(50) NOT NULL DEFAULT 'general' COMMENT '配置类型general/api/callback/wechat/payment/git等',
is_encrypted TINYINT DEFAULT 0 COMMENT '是否加密 0否 1是',
is_secret TINYINT DEFAULT 0 COMMENT '是否敏感信息 0否 1是',
description VARCHAR(500) DEFAULT '' COMMENT '配置说明',
sort_number INT DEFAULT 0 COMMENT '排序号',
tenant_id BIGINT NOT NULL DEFAULT 0 COMMENT '租户id',
created_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
updated_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
deleted TINYINT DEFAULT 0 COMMENT '是否删除 0否 1是',
UNIQUE KEY uk_website_key (website_id, config_key, deleted),
INDEX idx_website_type (website_id, config_type),
INDEX idx_tenant (tenant_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='应用配置表';

View File

@@ -0,0 +1,48 @@
-- 工单主表
CREATE TABLE IF NOT EXISTS `app_ticket` (
`ticket_id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '工单ID',
`ticket_no` VARCHAR(32) NOT NULL COMMENT '工单编号TK-yyyyMMddHHmmss+4位随机',
`title` VARCHAR(200) NOT NULL COMMENT '工单标题',
`content` TEXT NOT NULL COMMENT '工单内容描述',
`website_id` BIGINT DEFAULT NULL COMMENT '关联应用ID',
`website_name` VARCHAR(100) DEFAULT NULL COMMENT '应用名称(冗余)',
`category` VARCHAR(30) NOT NULL DEFAULT 'other' COMMENT '分类: bug/feature/consultation/complaint/other',
`priority` VARCHAR(20) NOT NULL DEFAULT 'normal' COMMENT '优先级: low/normal/high/urgent',
`status` VARCHAR(20) NOT NULL DEFAULT 'pending' COMMENT '状态: pending/assigned/processing/resolved/closed/rejected',
`attachments` TEXT DEFAULT NULL COMMENT '附件JSON数组',
`submit_user_id` INT NOT NULL COMMENT '提交人用户ID',
`submit_user_name` VARCHAR(50) DEFAULT NULL COMMENT '提交人昵称(冗余)',
`submit_user_avatar` VARCHAR(500) DEFAULT NULL COMMENT '提交人头像(冗余)',
`assignee_id` INT DEFAULT NULL COMMENT '处理人用户ID',
`assignee_name` VARCHAR(50) DEFAULT NULL COMMENT '处理人昵称(冗余)',
`assignee_avatar` VARCHAR(500) DEFAULT NULL COMMENT '处理人头像(冗余)',
`reply_count` INT NOT NULL DEFAULT 0 COMMENT '回复数量',
`resolved_time` DATETIME DEFAULT NULL COMMENT '解决时间',
`closed_time` DATETIME DEFAULT NULL COMMENT '关闭时间',
`deleted` TINYINT NOT NULL DEFAULT 0 COMMENT '是否删除: 0否 1是',
`create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`ticket_id`),
UNIQUE KEY `uk_ticket_no` (`ticket_no`),
KEY `idx_submit_user` (`submit_user_id`),
KEY `idx_assignee` (`assignee_id`),
KEY `idx_website_status` (`website_id`, `status`),
KEY `idx_status_create` (`status`, `create_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='应用工单';
-- 工单回复表
CREATE TABLE IF NOT EXISTS `app_ticket_reply` (
`reply_id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '回复ID',
`ticket_id` BIGINT NOT NULL COMMENT '关联工单ID',
`content` TEXT NOT NULL COMMENT '回复内容',
`attachments` TEXT DEFAULT NULL COMMENT '附件JSON数组',
`user_id` INT NOT NULL COMMENT '回复人用户ID',
`user_name` VARCHAR(50) DEFAULT NULL COMMENT '回复人昵称(冗余)',
`user_avatar` VARCHAR(500) DEFAULT NULL COMMENT '回复人头像(冗余)',
`is_staff` TINYINT NOT NULL DEFAULT 0 COMMENT '是否技术人员/客服: 0否 1是',
`deleted` TINYINT NOT NULL DEFAULT 0 COMMENT '是否删除: 0否 1是',
`create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`reply_id`),
KEY `idx_ticket_id` (`ticket_id`),
KEY `idx_user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='工单回复';

View File

@@ -0,0 +1,24 @@
-- 修复:审核接口(updateStepApproval)会写入 follow_step{1..4}_approved_at / follow_step{1..4}_approved_by
-- 若数据库缺少这些列会触发Unknown column 'follow_step1_approved_at' in 'field list'
--
-- 建议先检查:
-- SHOW COLUMNS FROM credit_mp_customer LIKE 'follow_step%_approved%';
--
-- 然后按需执行下面的 ALTER TABLE如果你的 MySQL 版本支持,也可以改为 ADD COLUMN IF NOT EXISTS
-- 第1步案件受理
ALTER TABLE credit_mp_customer ADD COLUMN follow_step1_approved_at VARCHAR(255) NULL COMMENT '第1步审核时间';
ALTER TABLE credit_mp_customer ADD COLUMN follow_step1_approved_by BIGINT NULL COMMENT '第1步审核人ID';
-- 第2步材料准备
ALTER TABLE credit_mp_customer ADD COLUMN follow_step2_approved_at VARCHAR(255) NULL COMMENT '第2步审核时间';
ALTER TABLE credit_mp_customer ADD COLUMN follow_step2_approved_by BIGINT NULL COMMENT '第2步审核人ID';
-- 第3步案件办理
ALTER TABLE credit_mp_customer ADD COLUMN follow_step3_approved_at VARCHAR(255) NULL COMMENT '第3步审核时间';
ALTER TABLE credit_mp_customer ADD COLUMN follow_step3_approved_by BIGINT NULL COMMENT '第3步审核人ID';
-- 第4步送达签收
ALTER TABLE credit_mp_customer ADD COLUMN follow_step4_approved_at VARCHAR(255) NULL COMMENT '第4步审核时间';
ALTER TABLE credit_mp_customer ADD COLUMN follow_step4_approved_by BIGINT NULL COMMENT '第4步审核人ID';

View File

@@ -0,0 +1,178 @@
-- =====================================================
-- 客资管理系统数据库变更脚本
-- 适用于: mp-java 数据库
-- 创建时间: 2026-04-14
-- =====================================================
-- 1. 扩展客资表 - 添加派单、推荐人相关字段
ALTER TABLE cms_contact_lead
ADD COLUMN assigned_user_id INT DEFAULT NULL COMMENT '被分配的业务员用户ID',
ADD COLUMN referrer_user_id INT DEFAULT NULL COMMENT '推荐人用户ID全民推荐',
ADD COLUMN referral_fee DECIMAL(10,2) DEFAULT 0.00 COMMENT '推荐费金额',
ADD COLUMN referral_fee_paid TINYINT DEFAULT 0 COMMENT '推荐费是否已支付 0否 1是',
ADD COLUMN referrer_share DECIMAL(5,2) DEFAULT 0.00 COMMENT '推荐人分成比例%',
ADD COLUMN dispatch_time DATETIME DEFAULT NULL COMMENT '派单时间',
ADD COLUMN dispatch_admin_id INT DEFAULT NULL COMMENT '派单管理员ID',
ADD COLUMN follow_count INT DEFAULT 0 COMMENT '跟进次数',
ADD COLUMN last_follow_time DATETIME DEFAULT NULL COMMENT '最后跟进时间',
ADD COLUMN appointment_time DATETIME DEFAULT NULL COMMENT '预约时间',
ADD COLUMN deal_amount DECIMAL(12,2) DEFAULT NULL COMMENT '成交金额',
ADD COLUMN deal_time DATETIME DEFAULT NULL COMMENT '成交时间',
ADD COLUMN source_type VARCHAR(20) DEFAULT 'form' COMMENT '来源类型: form表单 website网站 miniapp小程序 referral推荐人 admin录入';
-- 创建索引
CREATE INDEX idx_lead_assigned ON cms_contact_lead(assigned_user_id);
CREATE INDEX idx_lead_referrer ON cms_contact_lead(referrer_user_id);
CREATE INDEX idx_lead_status ON cms_contact_lead(status);
CREATE INDEX idx_lead_source ON cms_contact_lead(source_type);
-- 2. 派单记录表
CREATE TABLE IF NOT EXISTS lead_dispatch (
dispatch_id INT PRIMARY KEY AUTO_INCREMENT COMMENT '派单ID',
lead_id INT NOT NULL COMMENT '客资ID',
from_user_id INT DEFAULT NULL COMMENT '原分配用户ID(如果重新分配)',
to_user_id INT NOT NULL COMMENT '新分配用户ID(业务员)',
admin_id INT NOT NULL COMMENT '执行派单的管理员ID',
dispatch_remarks VARCHAR(500) DEFAULT NULL COMMENT '派单备注',
dispatch_type TINYINT DEFAULT 1 COMMENT '派单类型: 1新分配 2重新分配 3抢单',
create_time DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '派单时间',
INDEX idx_dispatch_lead (lead_id),
INDEX idx_dispatch_to_user (to_user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='客资派单记录表';
-- 3. 跟进记录表
CREATE TABLE IF NOT EXISTS lead_follow_log (
follow_id INT PRIMARY KEY AUTO_INCREMENT,
lead_id INT NOT NULL COMMENT '客资ID',
user_id INT NOT NULL COMMENT '跟进人ID',
follow_type TINYINT NOT NULL COMMENT '跟进方式: 1电话 2微信 3上门 4短信 5其他',
follow_content VARCHAR(1000) NOT NULL COMMENT '跟进内容',
next_follow_time DATETIME DEFAULT NULL COMMENT '下次跟进时间',
next_follow_plan VARCHAR(500) DEFAULT NULL COMMENT '下次跟进计划',
attachment_urls VARCHAR(1000) DEFAULT NULL COMMENT '附件URLs(JSON数组)',
create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
INDEX idx_follow_lead (lead_id),
INDEX idx_follow_user (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='客资跟进记录表';
-- 4. 推荐人关系表(全民推荐)
CREATE TABLE IF NOT EXISTS lead_referral (
referral_id INT PRIMARY KEY AUTO_INCREMENT,
referrer_user_id INT NOT NULL COMMENT '推荐人用户ID',
referred_lead_id INT NOT NULL COMMENT '被推荐的客资ID',
referral_code VARCHAR(32) DEFAULT NULL COMMENT '推荐码(用于匿名推荐)',
referral_fee DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '推荐费',
referral_status TINYINT DEFAULT 0 COMMENT '推荐状态: 0待确认 1有效 2无效 3已结算',
customer_name VARCHAR(100) DEFAULT NULL COMMENT '客户姓名(匿名推荐时存储)',
customer_phone VARCHAR(20) DEFAULT NULL COMMENT '客户电话(匿名推荐时存储)',
settlement_time DATETIME DEFAULT NULL COMMENT '结算时间',
create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
INDEX idx_referral_referrer (referrer_user_id),
INDEX idx_referral_lead (referred_lead_id),
INDEX idx_referral_code (referral_code)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='客资推荐关系表';
-- 5. 用户角色扩展表(多管理员支持)
CREATE TABLE IF NOT EXISTS gxwebsoft_core.sys_user_role_extend (
id INT PRIMARY KEY AUTO_INCREMENT,
user_id INT NOT NULL COMMENT '用户ID',
role_type VARCHAR(20) NOT NULL COMMENT '角色类型: admin管理员 salesman业务员 referrer推荐人',
is_primary TINYINT DEFAULT 1 COMMENT '是否主角色 0否 1是',
permissions JSON DEFAULT NULL COMMENT '权限配置(JSON)',
max_leads INT DEFAULT NULL COMMENT '最大客资分配数(业务员)',
commission_rate DECIMAL(5,2) DEFAULT NULL COMMENT '佣金比例%(业务员)',
referral_bonus DECIMAL(10,2) DEFAULT NULL COMMENT '推荐奖金%(推荐人)',
status TINYINT DEFAULT 1 COMMENT '状态: 0禁用 1启用',
create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
update_time DATETIME DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY uk_user_role (user_id, role_type),
INDEX idx_user (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户角色扩展表';
-- 6. 数据统计汇总表(定期生成报表用)
CREATE TABLE IF NOT EXISTS lead_statistics (
stat_id INT PRIMARY KEY AUTO_INCREMENT,
stat_date DATE NOT NULL COMMENT '统计日期',
user_id INT DEFAULT NULL COMMENT '用户ID(Null表示全站)',
role_type VARCHAR(20) DEFAULT NULL COMMENT '角色类型',
total_leads INT DEFAULT 0 COMMENT '总客资数',
new_leads INT DEFAULT 0 COMMENT '新增客资数',
assigned_leads INT DEFAULT 0 COMMENT '已分配客资数',
followed_leads INT DEFAULT 0 COMMENT '已跟进客资数',
dealed_leads INT DEFAULT 0 COMMENT '已成交客资数',
deal_amount DECIMAL(15,2) DEFAULT 0.00 COMMENT '成交总金额',
referral_count INT DEFAULT 0 COMMENT '推荐成功数',
referral_fee DECIMAL(12,2) DEFAULT 0.00 COMMENT '推荐费总额',
create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY uk_stat_date_user (stat_date, user_id, role_type),
INDEX idx_stat_date (stat_date)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='客资数据统计表';
-- 7. 推荐费结算记录表
CREATE TABLE IF NOT EXISTS lead_referral_settlement (
settlement_id INT PRIMARY KEY AUTO_INCREMENT,
referral_id INT NOT NULL COMMENT '推荐关系ID',
referrer_user_id INT NOT NULL COMMENT '推荐人ID',
lead_id INT NOT NULL COMMENT '关联客资ID',
settlement_amount DECIMAL(10,2) NOT NULL COMMENT '结算金额',
settlement_type TINYINT DEFAULT 1 COMMENT '结算方式: 1自动 2手动',
settlement_admin_id INT DEFAULT NULL COMMENT '操作管理员ID',
settlement_remarks VARCHAR(500) DEFAULT NULL COMMENT '结算备注',
status TINYINT DEFAULT 0 COMMENT '状态: 0待确认 1已转账 2已到账',
create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
confirm_time DATETIME DEFAULT NULL COMMENT '确认时间',
INDEX idx_settlement_referrer (referrer_user_id),
INDEX idx_settlement_lead (lead_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='推荐费结算记录表';
-- =====================================================
-- 初始化数据
-- =====================================================
-- 插入默认管理员角色扩展
INSERT INTO gxwebsoft_core.sys_user_role_extend (user_id, role_type, is_primary, permissions, status)
SELECT user_id, 'admin', 1, '{"canDispatch": true, "canManageUsers": true, "canViewStats": true, "canSetCommission": true}', 1
FROM gxwebsoft_core.sys_user WHERE status = 0 AND deleted = 0 LIMIT 1;
-- =====================================================
-- 视图: 客资完整信息视图
-- =====================================================
CREATE OR REPLACE VIEW v_lead_full_info AS
SELECT
l.lead_id,
l.name AS customer_name,
l.phone AS customer_phone,
l.company,
l.need AS requirement,
l.status,
l.source_type,
l.create_time,
l.dispatch_time,
l.deal_amount,
l.deal_time,
l.referral_fee,
l.referral_fee_paid,
au.user_id AS assigned_user_id,
au.nickname AS assigned_user_name,
au.real_name AS assigned_real_name,
au.phone AS assigned_user_phone,
ru.user_id AS referrer_user_id,
ru.nickname AS referrer_name,
ru.phone AS referrer_phone,
admin.user_id AS dispatch_admin_id,
admin.nickname AS dispatch_admin_name,
l.follow_count,
l.last_follow_time,
l.appointment_time,
CASE l.status
WHEN 0 THEN '待跟进'
WHEN 1 THEN '跟进中'
WHEN 2 THEN '已成交'
WHEN 3 THEN '无效'
ELSE '未知'
END AS status_text
FROM cms_contact_lead l
LEFT JOIN gxwebsoft_core.sys_user au ON l.assigned_user_id = au.user_id
LEFT JOIN gxwebsoft_core.sys_user ru ON l.referrer_user_id = ru.user_id
LEFT JOIN gxwebsoft_core.sys_user admin ON l.dispatch_admin_id = admin.user_id
WHERE l.deleted = 0;

View File

@@ -1,194 +0,0 @@
package com.gxwebsoft.ai.client;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxwebsoft.ai.client.dto.*;
import com.gxwebsoft.ai.config.AiOllamaProperties;
import com.gxwebsoft.common.core.exception.BusinessException;
import com.gxwebsoft.common.core.utils.JSONUtil;
import okhttp3.*;
import okio.BufferedSource;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.io.IOException;
import java.time.Duration;
import java.util.Objects;
import java.util.function.Consumer;
/**
* 轻量 Ollama HTTP Client兼容 /api/chat、/api/embeddings、/api/tags
*/
@Component
public class OllamaClient {
@Resource
private AiOllamaProperties props;
@Resource
private ObjectMapper objectMapper;
private volatile OkHttpClient http;
private OkHttpClient http() {
OkHttpClient c = http;
if (c != null) {
return c;
}
synchronized (this) {
if (http == null) {
http = new OkHttpClient.Builder()
.connectTimeout(Duration.ofMillis(props.getConnectTimeoutMs()))
.readTimeout(Duration.ofMillis(props.getReadTimeoutMs()))
.writeTimeout(Duration.ofMillis(props.getWriteTimeoutMs()))
.build();
}
return http;
}
}
public OllamaTagsResponse tags() {
return getJson("/api/tags", OllamaTagsResponse.class);
}
public OllamaChatResponse chat(OllamaChatRequest req) {
if (req.getStream() == null) {
req.setStream(false);
}
return postJson("/api/chat", req, OllamaChatResponse.class);
}
/**
* 流式对话Ollama 会返回按行分隔的 JSON。
*/
public void chatStream(OllamaChatRequest req, Consumer<OllamaChatResponse> onEvent) {
Objects.requireNonNull(onEvent, "onEvent");
if (req.getStream() == null) {
req.setStream(true);
}
Request request = buildPost(baseUrl(), "/api/chat", JSONUtil.toJSONString(req));
try (Response resp = http().newCall(request).execute()) {
if (!resp.isSuccessful()) {
throw new BusinessException("Ollama chat stream failed: HTTP " + resp.code());
}
ResponseBody body = resp.body();
if (body == null) {
throw new BusinessException("Ollama chat stream failed: empty body");
}
BufferedSource source = body.source();
String line;
while ((line = source.readUtf8Line()) != null) {
line = line.trim();
if (line.isEmpty()) {
continue;
}
OllamaChatResponse event = objectMapper.readValue(line, OllamaChatResponse.class);
onEvent.accept(event);
if (Boolean.TRUE.equals(event.getDone())) {
break;
}
}
} catch (IOException e) {
throw new BusinessException("Ollama chat stream IO error: " + e.getMessage());
}
}
public OllamaEmbeddingResponse embedding(String prompt) {
OllamaEmbeddingRequest req = new OllamaEmbeddingRequest();
req.setModel(props.getEmbedModel());
req.setPrompt(prompt);
return postJson("/api/embeddings", req, OllamaEmbeddingResponse.class);
}
private String baseUrl() {
if (props.getBaseUrl() == null || props.getBaseUrl().trim().isEmpty()) {
throw new BusinessException("ai.ollama.base-url 未配置");
}
return props.getBaseUrl().trim();
}
private String fallbackUrl() {
if (props.getFallbackUrl() == null || props.getFallbackUrl().trim().isEmpty()) {
return null;
}
return props.getFallbackUrl().trim();
}
private <T> T getJson(String path, Class<T> clazz) {
try {
return getJsonOnce(baseUrl(), path, clazz);
} catch (Exception e) {
String fb = fallbackUrl();
if (fb == null) {
throw e;
}
return getJsonOnce(fb, path, clazz);
}
}
private <T> T getJsonOnce(String base, String path, Class<T> clazz) {
Request req = new Request.Builder()
.url(join(base, path))
.get()
.build();
try (Response resp = http().newCall(req).execute()) {
if (!resp.isSuccessful()) {
throw new BusinessException("Ollama GET failed: HTTP " + resp.code());
}
ResponseBody body = resp.body();
if (body == null) {
throw new BusinessException("Ollama GET failed: empty body");
}
return objectMapper.readValue(body.string(), clazz);
} catch (IOException e) {
throw new BusinessException("Ollama GET IO error: " + e.getMessage());
}
}
private <T> T postJson(String path, Object payload, Class<T> clazz) {
String json = JSONUtil.toJSONString(payload);
try {
return postJsonOnce(baseUrl(), path, json, clazz);
} catch (Exception e) {
String fb = fallbackUrl();
if (fb == null) {
throw e;
}
return postJsonOnce(fb, path, json, clazz);
}
}
private <T> T postJsonOnce(String base, String path, String json, Class<T> clazz) {
Request req = buildPost(base, path, json);
try (Response resp = http().newCall(req).execute()) {
if (!resp.isSuccessful()) {
throw new BusinessException("Ollama POST failed: HTTP " + resp.code());
}
ResponseBody body = resp.body();
if (body == null) {
throw new BusinessException("Ollama POST failed: empty body");
}
return objectMapper.readValue(body.string(), clazz);
} catch (IOException e) {
throw new BusinessException("Ollama POST IO error: " + e.getMessage());
}
}
private Request buildPost(String base, String path, String json) {
RequestBody body = RequestBody.create(json, MediaType.parse("application/json; charset=utf-8"));
return new Request.Builder()
.url(join(base, path))
.post(body)
.build();
}
private static String join(String base, String path) {
String b = base;
if (b.endsWith("/")) {
b = b.substring(0, b.length() - 1);
}
String p = path.startsWith("/") ? path : ("/" + path);
return b + p;
}
}

View File

@@ -1,19 +0,0 @@
package com.gxwebsoft.ai.client.dto;
import lombok.Data;
import java.util.List;
import java.util.Map;
@Data
public class OllamaChatRequest {
private String model;
private List<OllamaMessage> messages;
private Boolean stream;
/**
* Ollama options例如temperature、top_k、top_p、num_predict...
*/
private Map<String, Object> options;
}

View File

@@ -1,28 +0,0 @@
package com.gxwebsoft.ai.client.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class OllamaChatResponse {
private String model;
@JsonProperty("created_at")
private String createdAt;
private OllamaMessage message;
private Boolean done;
@JsonProperty("total_duration")
private Long totalDuration;
@JsonProperty("prompt_eval_count")
private Integer promptEvalCount;
@JsonProperty("eval_count")
private Integer evalCount;
}

View File

@@ -1,14 +0,0 @@
package com.gxwebsoft.ai.client.dto;
import lombok.Data;
@Data
public class OllamaEmbeddingRequest {
private String model;
/**
* Ollama embeddings 目前常用字段为 prompt。
*/
private String prompt;
}

View File

@@ -1,13 +0,0 @@
package com.gxwebsoft.ai.client.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import java.util.List;
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class OllamaEmbeddingResponse {
private List<Double> embedding;
}

View File

@@ -1,14 +0,0 @@
package com.gxwebsoft.ai.client.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class OllamaMessage {
private String role;
private String content;
}

View File

@@ -1,22 +0,0 @@
package com.gxwebsoft.ai.client.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import java.util.List;
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class OllamaTagsResponse {
private List<Model> models;
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Model {
private String name;
private Long size;
private String digest;
private String modified_at;
}
}

View File

@@ -1,68 +0,0 @@
package com.gxwebsoft.ai.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* Ollama API 配置。
*
* 说明:本项目通过自建 Ollama 网关提供服务,因此这里用 baseUrl + fallbackUrl。
*/
@Data
@Component
@ConfigurationProperties(prefix = "ai.ollama")
public class AiOllamaProperties {
/**
* 主地址例如https://ai-api.websoft.top
*/
private String baseUrl;
/**
* 备用地址例如http://47.119.165.234:11434
*/
private String fallbackUrl;
/**
* 对话模型例如qwen3.5:cloud
*/
private String chatModel;
/**
* 向量模型例如qwen3-embedding:4b
*/
private String embedModel;
/**
* HTTP 超时(毫秒)。
*/
private long connectTimeoutMs = 10_000;
private long readTimeoutMs = 300_000;
private long writeTimeoutMs = 60_000;
/**
* 并发上限(用于 embedding/入库等批处理场景)。
*/
private int maxConcurrency = 4;
/**
* RAG检索候选 chunk 最大数量(避免一次性拉取过多数据导致内存/耗时过高)。
*/
private int ragMaxCandidates = 2000;
/**
* RAG检索返回 topK。
*/
private int ragTopK = 5;
/**
* RAG单个 chunk 最大字符数(用于入库切分)。
*/
private int ragChunkSize = 800;
/**
* RAGchunk 重叠字符数(用于减少语义断裂)。
*/
private int ragChunkOverlap = 120;
}

View File

@@ -1,37 +0,0 @@
package com.gxwebsoft.ai.controller;
import com.gxwebsoft.ai.dto.*;
import com.gxwebsoft.ai.service.AiAnalyticsService;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
@Tag(name = "AI - 订单数据分析")
@RestController
@RequestMapping("/api/ai/analytics")
public class AiAnalyticsController extends BaseController {
@Resource
private AiAnalyticsService analyticsService;
@PreAuthorize("isAuthenticated()")
@Operation(summary = "查询商城订单按天指标(当前租户)")
@PostMapping("/query")
public ApiResult<AiShopMetricsQueryResult> query(@RequestBody AiShopMetricsQueryRequest request) {
Integer tenantId = getTenantId();
return success(analyticsService.queryShopMetrics(tenantId, request));
}
@PreAuthorize("isAuthenticated()")
@Operation(summary = "AI 解析并输出订单分析结论(当前租户)")
@PostMapping("/ask")
public ApiResult<AiAnalyticsAskResult> ask(@RequestBody AiAnalyticsAskRequest request) {
Integer tenantId = getTenantId();
return success(analyticsService.askShopAnalytics(tenantId, request));
}
}

View File

@@ -1,95 +0,0 @@
package com.gxwebsoft.ai.controller;
import com.gxwebsoft.ai.client.OllamaClient;
import com.gxwebsoft.ai.client.dto.OllamaChatResponse;
import com.gxwebsoft.ai.client.dto.OllamaTagsResponse;
import com.gxwebsoft.ai.dto.AiChatRequest;
import com.gxwebsoft.ai.dto.AiChatResult;
import com.gxwebsoft.ai.dto.AiMessage;
import com.gxwebsoft.ai.service.AiChatService;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
@Tag(name = "AI - 对话")
@RestController
@RequestMapping("/api/ai")
public class AiChatController extends BaseController {
@Resource
private OllamaClient ollamaClient;
@Resource
private AiChatService aiChatService;
@PreAuthorize("isAuthenticated()")
@Operation(summary = "获取 Ollama 模型列表")
@GetMapping("/models")
public ApiResult<OllamaTagsResponse> models() {
return success(ollamaClient.tags());
}
@PreAuthorize("isAuthenticated()")
@Operation(summary = "非流式对话")
@PostMapping("/chat")
public ApiResult<AiChatResult> chat(@RequestBody AiChatRequest request) {
return success(aiChatService.chat(request));
}
@PreAuthorize("isAuthenticated()")
@Operation(summary = "流式对话SSE")
@PostMapping("/chat/stream")
public SseEmitter chatStream(@RequestBody AiChatRequest request) {
// 10 分钟超时(可根据前端需要调整)
SseEmitter emitter = new SseEmitter(10 * 60 * 1000L);
CompletableFuture.runAsync(() -> {
try {
aiChatService.chatStream(request,
delta -> {
try {
emitter.send(SseEmitter.event().name("delta").data(delta));
} catch (Exception e) {
// 客户端断开会触发 send 异常,这里直接结束即可
emitter.complete();
}
},
(OllamaChatResponse done) -> {
try {
Map<String, Object> meta = new LinkedHashMap<>();
meta.put("model", done.getModel());
meta.put("prompt_eval_count", done.getPromptEvalCount());
meta.put("eval_count", done.getEvalCount());
meta.put("total_duration", done.getTotalDuration());
emitter.send(SseEmitter.event().name("done").data(meta));
} catch (Exception ignored) {
} finally {
emitter.complete();
}
});
} catch (Exception e) {
emitter.completeWithError(e);
}
});
return emitter;
}
@PreAuthorize("isAuthenticated()")
@Operation(summary = "流式对话SSE, GET 版本,便于 EventSource")
@GetMapping("/chat/stream")
public SseEmitter chatStreamGet(@RequestParam("prompt") String prompt) {
AiChatRequest req = new AiChatRequest();
req.setMessages(Collections.singletonList(new AiMessage("user", prompt)));
return chatStream(req);
}
}

View File

@@ -1,54 +0,0 @@
package com.gxwebsoft.ai.controller;
import com.gxwebsoft.ai.dto.*;
import com.gxwebsoft.ai.service.AiKbRagService;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
@Tag(name = "AI - 知识库(RAG)")
@RestController
@RequestMapping("/api/ai/kb")
public class AiKbController extends BaseController {
@Resource
private AiKbRagService ragService;
@PreAuthorize("isAuthenticated()")
@Operation(summary = "上传文档入库txt/md/html 优先)")
@PostMapping("/upload")
public ApiResult<AiKbIngestResult> upload(@RequestParam("file") MultipartFile file) {
Integer tenantId = getTenantId();
return success(ragService.ingestUpload(tenantId, file));
}
@PreAuthorize("isAuthenticated()")
@Operation(summary = "同步 CMS 文章到知识库(当前租户)")
@PostMapping("/sync/cms")
public ApiResult<AiKbIngestResult> syncCms() {
Integer tenantId = getTenantId();
return success(ragService.syncCms(tenantId));
}
@PreAuthorize("isAuthenticated()")
@Operation(summary = "仅检索(返回 topK 命中)")
@PostMapping("/query")
public ApiResult<AiKbQueryResult> query(@RequestBody AiKbQueryRequest request) {
Integer tenantId = getTenantId();
return success(ragService.query(tenantId, request));
}
@PreAuthorize("isAuthenticated()")
@Operation(summary = "知识库问答RAG 生成 + 返回检索结果)")
@PostMapping("/ask")
public ApiResult<AiKbAskResult> ask(@RequestBody AiKbAskRequest request) {
Integer tenantId = getTenantId();
return success(ragService.ask(tenantId, request));
}
}

View File

@@ -1,13 +0,0 @@
package com.gxwebsoft.ai.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(name = "AiAnalyticsAskRequest", description = "AI 数据分析提问")
public class AiAnalyticsAskRequest {
private String question;
private String startDate;
private String endDate;
}

View File

@@ -1,12 +0,0 @@
package com.gxwebsoft.ai.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(name = "AiAnalyticsAskResult", description = "AI 数据分析结果")
public class AiAnalyticsAskResult {
private String analysis;
private AiShopMetricsQueryResult data;
}

View File

@@ -1,35 +0,0 @@
package com.gxwebsoft.ai.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.List;
@Data
@Schema(name = "AiChatRequest", description = "AI 对话请求")
public class AiChatRequest {
@Schema(description = "可选:直接传一句话。若 messages 为空则使用该字段构造 user message")
private String prompt;
@Schema(description = "可选OpenAI 风格 messagesrole: system/user/assistant")
private List<AiMessage> messages;
@Schema(description = "可选:覆盖默认模型")
private String model;
@Schema(description = "是否流式输出(/chat/stream 端点通常忽略此字段)")
private Boolean stream;
@Schema(description = "temperature")
private Double temperature;
@Schema(description = "top_k")
private Integer topK;
@Schema(description = "top_p")
private Double topP;
@Schema(description = "num_predict类似 max_tokens")
private Integer numPredict;
}

View File

@@ -1,15 +0,0 @@
package com.gxwebsoft.ai.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Schema(name = "AiChatResult", description = "AI 对话结果")
public class AiChatResult {
private String content;
}

View File

@@ -1,12 +0,0 @@
package com.gxwebsoft.ai.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(name = "AiKbAskRequest", description = "知识库问答请求")
public class AiKbAskRequest {
private String question;
private Integer topK;
}

View File

@@ -1,12 +0,0 @@
package com.gxwebsoft.ai.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(name = "AiKbAskResult", description = "知识库问答结果")
public class AiKbAskResult {
private String answer;
private AiKbQueryResult retrieval;
}

View File

@@ -1,15 +0,0 @@
package com.gxwebsoft.ai.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(name = "AiKbHit", description = "知识库命中")
public class AiKbHit {
private String chunkId;
private Integer documentId;
private String title;
private Double score;
private String content;
}

View File

@@ -1,15 +0,0 @@
package com.gxwebsoft.ai.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(name = "AiKbIngestResult", description = "知识库入库结果")
public class AiKbIngestResult {
private Integer documentId;
private String title;
private Integer chunks;
private Integer updatedDocuments;
private Integer skippedDocuments;
}

View File

@@ -1,12 +0,0 @@
package com.gxwebsoft.ai.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(name = "AiKbQueryRequest", description = "知识库检索请求")
public class AiKbQueryRequest {
private String query;
private Integer topK;
}

View File

@@ -1,13 +0,0 @@
package com.gxwebsoft.ai.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.List;
@Data
@Schema(name = "AiKbQueryResult", description = "知识库检索结果")
public class AiKbQueryResult {
private List<AiKbHit> hits;
}

View File

@@ -1,14 +0,0 @@
package com.gxwebsoft.ai.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class AiMessage {
private String role;
private String content;
}

View File

@@ -1,18 +0,0 @@
package com.gxwebsoft.ai.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(name = "AiShopMetricsQueryRequest", description = "商城订单指标查询请求")
public class AiShopMetricsQueryRequest {
@Schema(description = "开始日期(YYYY-MM-DD)")
private String startDate;
@Schema(description = "结束日期(YYYY-MM-DD),包含该天")
private String endDate;
@Schema(description = "是否按天分组,默认 true")
private Boolean groupByDay;
}

View File

@@ -1,16 +0,0 @@
package com.gxwebsoft.ai.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.List;
@Data
@Schema(name = "AiShopMetricsQueryResult", description = "商城订单指标查询结果")
public class AiShopMetricsQueryResult {
private Integer tenantId;
private String startDate;
private String endDate;
private List<AiShopMetricsRow> rows;
}

View File

@@ -1,23 +0,0 @@
package com.gxwebsoft.ai.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.math.BigDecimal;
@Data
@Schema(name = "AiShopMetricsRow", description = "商城订单指标行(按 tenant/day")
public class AiShopMetricsRow {
private Integer tenantId;
private String day;
private Long orderCnt;
private Long paidOrderCnt;
private BigDecimal gmv;
private BigDecimal refundAmt;
private Long payUserCnt;
private BigDecimal aov;
private BigDecimal payRate;
}

View File

@@ -1,57 +0,0 @@
package com.gxwebsoft.ai.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 知识库分段chunk
*/
@Data
@Schema(name = "AiKbChunk", description = "AI 知识库分段")
public class AiKbChunk implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private Integer documentId;
/**
* 外部引用用的唯一 ID便于在答案里引用
*/
private String chunkId;
private Integer chunkIndex;
private String title;
private String content;
private String contentHash;
/**
* embedding JSON数组存成文本便于快速落库。
*/
private String embedding;
/**
* embedding 的 L2 范数,用于余弦相似度。
*/
private Double embeddingNorm;
@TableLogic
private Integer deleted;
private Integer tenantId;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createTime;
}

View File

@@ -1,59 +0,0 @@
package com.gxwebsoft.ai.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 知识库文档来源上传、CMS 等)。
*/
@Data
@Schema(name = "AiKbDocument", description = "AI 知识库文档")
public class AiKbDocument implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "document_id", type = IdType.AUTO)
private Integer documentId;
private String title;
/**
* upload / cms
*/
private String sourceType;
/**
* 例如 CMS article_id
*/
private Integer sourceId;
/**
* 例如文件名、路径等
*/
private String sourceRef;
/**
* 文档文本内容哈希(用于增量同步/去重)。
*/
private String contentHash;
private Integer status;
@TableLogic
private Integer deleted;
private Integer tenantId;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime updateTime;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createTime;
}

View File

@@ -1,10 +0,0 @@
package com.gxwebsoft.ai.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gxwebsoft.ai.entity.AiKbChunk;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface AiKbChunkMapper extends BaseMapper<AiKbChunk> {
}

View File

@@ -1,10 +0,0 @@
package com.gxwebsoft.ai.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gxwebsoft.ai.entity.AiKbDocument;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface AiKbDocumentMapper extends BaseMapper<AiKbDocument> {
}

View File

@@ -1,16 +0,0 @@
package com.gxwebsoft.ai.mapper;
import com.gxwebsoft.ai.dto.AiShopMetricsRow;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.time.LocalDateTime;
import java.util.List;
@Mapper
public interface AiShopAnalyticsMapper {
List<AiShopMetricsRow> queryMetrics(@Param("tenantId") Integer tenantId,
@Param("start") LocalDateTime start,
@Param("end") LocalDateTime end);
}

View File

@@ -1,24 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.gxwebsoft.ai.mapper.AiShopAnalyticsMapper">
<select id="queryMetrics" resultType="com.gxwebsoft.ai.dto.AiShopMetricsRow">
SELECT
tenant_id,
DATE_FORMAT(create_time, '%Y-%m-%d') AS day,
COUNT(1) AS order_cnt,
SUM(CASE WHEN pay_status = 1 THEN 1 ELSE 0 END) AS paid_order_cnt,
SUM(CASE WHEN pay_status = 1 THEN COALESCE(pay_price, 0) ELSE 0 END) AS gmv,
SUM(CASE WHEN COALESCE(refund_money, 0) &gt; 0 THEN COALESCE(refund_money, 0) ELSE 0 END) AS refund_amt,
COUNT(DISTINCT IF(pay_status = 1, user_id, NULL)) AS pay_user_cnt
FROM shop_order
WHERE deleted = 0
AND tenant_id = #{tenantId}
AND create_time &gt;= #{start}
AND create_time &lt; #{end}
GROUP BY tenant_id, DATE_FORMAT(create_time, '%Y-%m-%d')
ORDER BY day ASC
</select>
</mapper>

View File

@@ -1,24 +0,0 @@
package com.gxwebsoft.ai.prompt;
/**
* 统一提示词模板(尽量简短、可控)。
*/
public class AiPrompts {
private AiPrompts() {
}
public static final String SYSTEM_SUPPORT =
"你是 WebSoft 客服AI。规则\n" +
"- 只使用给定的“上下文资料”回答,禁止编造。\n" +
"- 如果资料不足,直接说“资料不足”,并列出需要补充的信息。\n" +
"- 答案末尾必须给引用,格式:[source:chunk_id]。\n" +
"- 输出中文,简洁可执行。\n";
public static final String SYSTEM_ANALYTICS =
"你是商城订单数据分析助手。你将基于提供的按天指标数据给出结论。\n" +
"要求:\n" +
"- 只基于数据陈述,不要编造不存在的数字。\n" +
"- 输出包含:结论、关键指标变化、异常点、建议的下一步核查。\n" +
"- 输出中文,简洁。\n";
}

View File

@@ -1,82 +0,0 @@
package com.gxwebsoft.ai.service;
import cn.hutool.core.util.StrUtil;
import com.gxwebsoft.ai.dto.*;
import com.gxwebsoft.ai.prompt.AiPrompts;
import com.gxwebsoft.common.core.exception.BusinessException;
import com.gxwebsoft.common.core.utils.JSONUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.util.Arrays;
@Service
public class AiAnalyticsService {
@Resource
private AiShopAnalyticsService shopAnalyticsService;
@Resource
private AiChatService aiChatService;
public AiShopMetricsQueryResult queryShopMetrics(Integer tenantId, AiShopMetricsQueryRequest request) {
if (tenantId == null) {
throw new BusinessException("tenantId 不能为空");
}
if (request == null) {
throw new BusinessException("请求不能为空");
}
LocalDate start = parseDate(request.getStartDate(), "startDate");
LocalDate end = parseDate(request.getEndDate(), "endDate");
if (end.isBefore(start)) {
throw new BusinessException("endDate 不能早于 startDate");
}
AiShopMetricsQueryResult r = new AiShopMetricsQueryResult();
r.setTenantId(tenantId);
r.setStartDate(start.toString());
r.setEndDate(end.toString());
r.setRows(shopAnalyticsService.queryTenantDaily(tenantId, start, end));
return r;
}
public AiAnalyticsAskResult askShopAnalytics(Integer tenantId, AiAnalyticsAskRequest request) {
if (request == null || StrUtil.isBlank(request.getQuestion())) {
throw new BusinessException("question 不能为空");
}
AiShopMetricsQueryRequest q = new AiShopMetricsQueryRequest();
q.setStartDate(request.getStartDate());
q.setEndDate(request.getEndDate());
q.setGroupByDay(true);
AiShopMetricsQueryResult data = queryShopMetrics(tenantId, q);
String userPrompt =
"用户问题:\n" + request.getQuestion() + "\n\n" +
"数据JSON字段含义order_cnt=订单数paid_order_cnt=已支付订单数gmv=已支付金额refund_amt=退款金额pay_user_cnt=支付用户数aov=客单价pay_rate=支付率):\n" +
JSONUtil.toJSONString(data, true);
AiChatRequest chat = new AiChatRequest();
chat.setMessages(Arrays.asList(
new AiMessage("system", AiPrompts.SYSTEM_ANALYTICS),
new AiMessage("user", userPrompt)
));
AiChatResult resp = aiChatService.chat(chat);
AiAnalyticsAskResult r = new AiAnalyticsAskResult();
r.setAnalysis(resp.getContent());
r.setData(data);
return r;
}
private static LocalDate parseDate(String s, String field) {
if (StrUtil.isBlank(s)) {
throw new BusinessException(field + " 不能为空,格式 YYYY-MM-DD");
}
try {
return LocalDate.parse(s.trim());
} catch (DateTimeParseException e) {
throw new BusinessException(field + " 格式错误,需 YYYY-MM-DD");
}
}
}

View File

@@ -1,94 +0,0 @@
package com.gxwebsoft.ai.service;
import cn.hutool.core.util.StrUtil;
import com.gxwebsoft.ai.client.OllamaClient;
import com.gxwebsoft.ai.client.dto.OllamaChatRequest;
import com.gxwebsoft.ai.client.dto.OllamaChatResponse;
import com.gxwebsoft.ai.client.dto.OllamaMessage;
import com.gxwebsoft.ai.config.AiOllamaProperties;
import com.gxwebsoft.ai.dto.AiChatRequest;
import com.gxwebsoft.ai.dto.AiChatResult;
import com.gxwebsoft.ai.dto.AiMessage;
import com.gxwebsoft.common.core.exception.BusinessException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.*;
import java.util.function.Consumer;
@Service
public class AiChatService {
@Resource
private AiOllamaProperties props;
@Resource
private OllamaClient ollamaClient;
public AiChatResult chat(AiChatRequest request) {
OllamaChatRequest req = buildChatRequest(request, false);
OllamaChatResponse resp = ollamaClient.chat(req);
String content = resp != null && resp.getMessage() != null ? resp.getMessage().getContent() : null;
return new AiChatResult(content == null ? "" : content);
}
public void chatStream(AiChatRequest request, Consumer<String> onDelta, Consumer<OllamaChatResponse> onFinal) {
Objects.requireNonNull(onDelta, "onDelta");
OllamaChatRequest req = buildChatRequest(request, true);
ollamaClient.chatStream(req, event -> {
String delta = event != null && event.getMessage() != null ? event.getMessage().getContent() : null;
if (StrUtil.isNotBlank(delta)) {
onDelta.accept(delta);
}
if (Boolean.TRUE.equals(event.getDone()) && onFinal != null) {
onFinal.accept(event);
}
});
}
private OllamaChatRequest buildChatRequest(AiChatRequest request, boolean stream) {
if (request == null) {
throw new BusinessException("请求不能为空");
}
List<AiMessage> messages = request.getMessages();
if ((messages == null || messages.isEmpty()) && StrUtil.isBlank(request.getPrompt())) {
throw new BusinessException("prompt 或 messages 不能为空");
}
if (messages == null || messages.isEmpty()) {
messages = Collections.singletonList(new AiMessage("user", request.getPrompt()));
}
List<OllamaMessage> ollamaMessages = new ArrayList<>();
for (AiMessage m : messages) {
if (m == null || StrUtil.isBlank(m.getRole()) || m.getContent() == null) {
continue;
}
ollamaMessages.add(new OllamaMessage(m.getRole(), m.getContent()));
}
if (ollamaMessages.isEmpty()) {
throw new BusinessException("messages 为空或无有效内容");
}
Map<String, Object> options = new HashMap<>();
if (request.getTemperature() != null) {
options.put("temperature", request.getTemperature());
}
if (request.getTopK() != null) {
options.put("top_k", request.getTopK());
}
if (request.getTopP() != null) {
options.put("top_p", request.getTopP());
}
if (request.getNumPredict() != null) {
options.put("num_predict", request.getNumPredict());
}
OllamaChatRequest req = new OllamaChatRequest();
req.setModel(StrUtil.blankToDefault(request.getModel(), props.getChatModel()));
req.setMessages(ollamaMessages);
req.setStream(stream);
req.setOptions(options.isEmpty() ? null : options);
return req;
}
}

View File

@@ -1,8 +0,0 @@
package com.gxwebsoft.ai.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.gxwebsoft.ai.entity.AiKbChunk;
public interface AiKbChunkService extends IService<AiKbChunk> {
}

View File

@@ -1,8 +0,0 @@
package com.gxwebsoft.ai.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.gxwebsoft.ai.entity.AiKbDocument;
public interface AiKbDocumentService extends IService<AiKbDocument> {
}

View File

@@ -1,426 +0,0 @@
package com.gxwebsoft.ai.service;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.ai.client.OllamaClient;
import com.gxwebsoft.ai.client.dto.OllamaEmbeddingResponse;
import com.gxwebsoft.ai.config.AiOllamaProperties;
import com.gxwebsoft.ai.dto.*;
import com.gxwebsoft.ai.entity.AiKbChunk;
import com.gxwebsoft.ai.entity.AiKbDocument;
import com.gxwebsoft.ai.prompt.AiPrompts;
import com.gxwebsoft.ai.util.AiTextUtil;
import com.gxwebsoft.cms.entity.CmsArticle;
import com.gxwebsoft.cms.entity.CmsArticleContent;
import com.gxwebsoft.cms.service.CmsArticleContentService;
import com.gxwebsoft.cms.service.CmsArticleService;
import com.gxwebsoft.common.core.exception.BusinessException;
import com.gxwebsoft.common.core.utils.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.tika.Tika;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;
@Service
public class AiKbRagService {
@Resource
private AiOllamaProperties props;
@Resource
private OllamaClient ollamaClient;
@Resource
private AiKbDocumentService documentService;
@Resource
private AiKbChunkService chunkService;
@Resource
private CmsArticleService cmsArticleService;
@Resource
private CmsArticleContentService cmsArticleContentService;
@Resource
private AiChatService aiChatService;
@Resource
private ObjectMapper objectMapper;
private final Tika tika = new Tika();
private volatile ExecutorService embedPool;
private ExecutorService pool() {
ExecutorService p = embedPool;
if (p != null) {
return p;
}
synchronized (this) {
if (embedPool == null) {
embedPool = Executors.newFixedThreadPool(Math.max(1, props.getMaxConcurrency()));
}
return embedPool;
}
}
public AiKbIngestResult ingestUpload(Integer tenantId, MultipartFile file) {
if (tenantId == null) {
throw new BusinessException("tenantId 不能为空");
}
if (file == null || file.isEmpty()) {
throw new BusinessException("文件不能为空");
}
String title = StrUtil.blankToDefault(file.getOriginalFilename(), "upload");
String text = extractText(file);
if (StrUtil.isBlank(text)) {
throw new BusinessException("无法解析文件内容,请上传 txt/md/html 等可解析文本");
}
String contentHash = AiTextUtil.sha256(text);
AiKbDocument doc = new AiKbDocument();
doc.setTitle(title);
doc.setSourceType("upload");
doc.setSourceRef(title);
doc.setContentHash(contentHash);
doc.setStatus(0);
doc.setTenantId(tenantId);
doc.setCreateTime(LocalDateTime.now());
doc.setUpdateTime(LocalDateTime.now());
documentService.save(doc);
int chunks = ingestChunks(doc, text);
AiKbIngestResult r = new AiKbIngestResult();
r.setDocumentId(doc.getDocumentId());
r.setTitle(doc.getTitle());
r.setChunks(chunks);
r.setUpdatedDocuments(1);
r.setSkippedDocuments(0);
return r;
}
/**
* 同步 CMS仅当前 tenant
*/
public AiKbIngestResult syncCms(Integer tenantId) {
if (tenantId == null) {
throw new BusinessException("tenantId 不能为空");
}
// 仅同步“已发布且未删除”的文章
List<CmsArticle> articles = cmsArticleService.list(new LambdaQueryWrapper<CmsArticle>()
.eq(CmsArticle::getTenantId, tenantId)
.eq(CmsArticle::getDeleted, 0)
.eq(CmsArticle::getStatus, 0));
if (articles == null || articles.isEmpty()) {
AiKbIngestResult r = new AiKbIngestResult();
r.setUpdatedDocuments(0);
r.setSkippedDocuments(0);
r.setChunks(0);
return r;
}
Set<Integer> articleIds = articles.stream().map(CmsArticle::getArticleId).collect(Collectors.toSet());
List<CmsArticleContent> contents = cmsArticleContentService.list(new LambdaQueryWrapper<CmsArticleContent>()
.in(CmsArticleContent::getArticleId, articleIds));
Map<Integer, CmsArticleContent> contentByArticle = contents.stream()
.collect(Collectors.toMap(
CmsArticleContent::getArticleId,
c -> c,
(a, b) -> (a.getCreateTime() != null && b.getCreateTime() != null && a.getCreateTime().isAfter(b.getCreateTime())) ? a : b
));
int updatedDocs = 0;
int skippedDocs = 0;
int totalChunks = 0;
for (CmsArticle a : articles) {
CmsArticleContent c = contentByArticle.get(a.getArticleId());
String raw = "";
if (a.getOverview() != null) {
raw += a.getOverview() + "\n";
}
if (c != null && c.getContent() != null) {
raw += c.getContent();
}
String text = a.getTitle() + "\n" + AiTextUtil.stripHtml(raw);
text = AiTextUtil.normalizeWhitespace(text);
if (StrUtil.isBlank(text)) {
continue;
}
String hash = AiTextUtil.sha256(text);
AiKbDocument existing = documentService.getOne(new LambdaQueryWrapper<AiKbDocument>()
.eq(AiKbDocument::getTenantId, tenantId)
.eq(AiKbDocument::getSourceType, "cms")
.eq(AiKbDocument::getSourceId, a.getArticleId())
.last("limit 1"));
if (existing != null && StrUtil.equals(existing.getContentHash(), hash)) {
skippedDocs++;
continue;
}
AiKbDocument doc;
if (existing == null) {
doc = new AiKbDocument();
doc.setTitle(a.getTitle());
doc.setSourceType("cms");
doc.setSourceId(a.getArticleId());
doc.setSourceRef(a.getCode());
doc.setContentHash(hash);
doc.setStatus(0);
doc.setTenantId(tenantId);
doc.setCreateTime(LocalDateTime.now());
doc.setUpdateTime(LocalDateTime.now());
documentService.save(doc);
} else {
doc = existing;
doc.setTitle(a.getTitle());
doc.setSourceRef(a.getCode());
doc.setContentHash(hash);
doc.setUpdateTime(LocalDateTime.now());
documentService.updateById(doc);
// 重新入库:先删除旧 chunk
chunkService.remove(new LambdaQueryWrapper<AiKbChunk>().eq(AiKbChunk::getDocumentId, doc.getDocumentId()));
}
int chunks = ingestChunks(doc, text);
totalChunks += chunks;
updatedDocs++;
}
AiKbIngestResult r = new AiKbIngestResult();
r.setUpdatedDocuments(updatedDocs);
r.setSkippedDocuments(skippedDocs);
r.setChunks(totalChunks);
return r;
}
public AiKbQueryResult query(Integer tenantId, AiKbQueryRequest request) {
if (tenantId == null) {
throw new BusinessException("tenantId 不能为空");
}
if (request == null || StrUtil.isBlank(request.getQuery())) {
throw new BusinessException("query 不能为空");
}
int topK = request.getTopK() != null ? request.getTopK() : props.getRagTopK();
topK = Math.max(1, Math.min(20, topK));
float[] qEmb = embedding(request.getQuery());
float qNorm = l2(qEmb);
if (qNorm == 0f) {
throw new BusinessException("query embedding 为空");
}
// MVP按 tenant 拉取最新 N 条候选 chunk再做余弦相似度排序
List<AiKbChunk> candidates = chunkService.list(new LambdaQueryWrapper<AiKbChunk>()
.eq(AiKbChunk::getTenantId, tenantId)
.orderByDesc(AiKbChunk::getId)
.last("limit " + props.getRagMaxCandidates()));
PriorityQueue<AiKbHit> pq = new PriorityQueue<>(Comparator.comparingDouble(h -> h.getScore() == null ? -1d : h.getScore()));
for (AiKbChunk c : candidates) {
if (StrUtil.isBlank(c.getEmbedding())) {
continue;
}
float[] cEmb = parseEmbedding(c.getEmbedding());
if (cEmb == null || cEmb.length == 0) {
continue;
}
Double cNormD = c.getEmbeddingNorm();
float cNorm = cNormD == null ? l2(cEmb) : cNormD.floatValue();
if (cNorm == 0f) {
continue;
}
double score = dot(qEmb, cEmb) / (qNorm * cNorm);
AiKbHit hit = new AiKbHit();
hit.setChunkId(c.getChunkId());
hit.setDocumentId(c.getDocumentId());
hit.setTitle(StrUtil.blankToDefault(c.getTitle(), ""));
hit.setScore(score);
// 返回给前端时避免过长
hit.setContent(clip(c.getContent(), 900));
if (pq.size() < topK) {
pq.add(hit);
} else if (hit.getScore() != null && hit.getScore() > pq.peek().getScore()) {
pq.poll();
pq.add(hit);
}
}
List<AiKbHit> hits = new ArrayList<>(pq);
hits.sort((a, b) -> Double.compare(b.getScore(), a.getScore()));
AiKbQueryResult r = new AiKbQueryResult();
r.setHits(hits);
return r;
}
public AiKbAskResult ask(Integer tenantId, AiKbAskRequest request) {
if (request == null || StrUtil.isBlank(request.getQuestion())) {
throw new BusinessException("question 不能为空");
}
AiKbQueryRequest q = new AiKbQueryRequest();
q.setQuery(request.getQuestion());
q.setTopK(request.getTopK());
AiKbQueryResult retrieval = query(tenantId, q);
String context = buildContext(retrieval);
String userPrompt = "上下文资料:\n" + context + "\n\n用户问题\n" + request.getQuestion();
AiChatRequest chatReq = new AiChatRequest();
chatReq.setMessages(Arrays.asList(
new AiMessage("system", AiPrompts.SYSTEM_SUPPORT),
new AiMessage("user", userPrompt)
));
AiChatResult chat = aiChatService.chat(chatReq);
AiKbAskResult r = new AiKbAskResult();
r.setAnswer(chat.getContent());
r.setRetrieval(retrieval);
return r;
}
private int ingestChunks(AiKbDocument doc, String text) {
List<String> chunks = AiTextUtil.chunkText(text, props.getRagChunkSize(), props.getRagChunkOverlap());
if (chunks.isEmpty()) {
return 0;
}
LocalDateTime now = LocalDateTime.now();
List<CompletableFuture<AiKbChunk>> futures = new ArrayList<>(chunks.size());
for (int i = 0; i < chunks.size(); i++) {
final int idx = i;
final String chunkText = chunks.get(i);
futures.add(CompletableFuture.supplyAsync(() -> {
OllamaEmbeddingResponse emb = ollamaClient.embedding(chunkText);
if (emb == null || emb.getEmbedding() == null || emb.getEmbedding().isEmpty()) {
throw new BusinessException("embedding 生成失败");
}
float[] v = toFloat(emb.getEmbedding());
float norm = l2(v);
AiKbChunk c = new AiKbChunk();
c.setDocumentId(doc.getDocumentId());
c.setChunkId(UUID.randomUUID().toString().replace("-", ""));
c.setChunkIndex(idx);
c.setTitle(doc.getTitle());
c.setContent(chunkText);
c.setContentHash(AiTextUtil.sha256(chunkText));
c.setEmbedding(JSONUtil.toJSONString(emb.getEmbedding()));
c.setEmbeddingNorm((double) norm);
c.setTenantId(doc.getTenantId());
c.setCreateTime(now);
c.setDeleted(0);
return c;
}, pool()));
}
List<AiKbChunk> entities = futures.stream().map(f -> {
try {
return f.get(10, TimeUnit.MINUTES);
} catch (Exception e) {
throw new BusinessException("embedding 批处理失败: " + e.getMessage());
}
}).collect(Collectors.toList());
chunkService.saveBatch(entities);
return entities.size();
}
private String extractText(MultipartFile file) {
try {
String contentType = file.getContentType();
String filename = file.getOriginalFilename();
// 优先:对纯文本直接读 UTF-8
if ((contentType != null && contentType.startsWith("text/"))
|| (filename != null && (filename.endsWith(".txt") || filename.endsWith(".md") || filename.endsWith(".html") || filename.endsWith(".htm")))) {
return AiTextUtil.normalizeWhitespace(new String(file.getBytes(), StandardCharsets.UTF_8));
}
// 尝试用 tika 解析(注意:当前依赖为 tika-core解析能力有限
String parsed = tika.parseToString(file.getInputStream());
return AiTextUtil.normalizeWhitespace(parsed);
} catch (Exception e) {
return "";
}
}
private float[] embedding(String text) {
OllamaEmbeddingResponse emb = ollamaClient.embedding(text);
if (emb == null || emb.getEmbedding() == null || emb.getEmbedding().isEmpty()) {
throw new BusinessException("embedding 生成失败");
}
return toFloat(emb.getEmbedding());
}
private float[] parseEmbedding(String json) {
try {
// embedding 是一维数组,存储为 JSON 文本
double[] d = ObjectUtil.isEmpty(json) ? null : objectMapper.readValue(json, double[].class);
if (d == null || d.length == 0) {
return null;
}
float[] f = new float[d.length];
for (int i = 0; i < d.length; i++) {
f[i] = (float) d[i];
}
return f;
} catch (Exception e) {
return null;
}
}
private static float[] toFloat(List<Double> v) {
float[] out = new float[v.size()];
for (int i = 0; i < v.size(); i++) {
Double d = v.get(i);
out[i] = d == null ? 0f : d.floatValue();
}
return out;
}
private static float dot(float[] a, float[] b) {
int n = Math.min(a.length, b.length);
double s = 0d;
for (int i = 0; i < n; i++) {
s += (double) a[i] * (double) b[i];
}
return (float) s;
}
private static float l2(float[] a) {
double s = 0d;
for (float v : a) {
s += (double) v * (double) v;
}
return (float) Math.sqrt(s);
}
private static String clip(String s, int max) {
if (s == null) {
return "";
}
if (s.length() <= max) {
return s;
}
return s.substring(0, max) + "...";
}
private static String buildContext(AiKbQueryResult retrieval) {
if (retrieval == null || retrieval.getHits() == null || retrieval.getHits().isEmpty()) {
return "(无)";
}
StringBuilder sb = new StringBuilder();
for (AiKbHit h : retrieval.getHits()) {
sb.append("[source:").append(h.getChunkId()).append("] ");
if (StrUtil.isNotBlank(h.getTitle())) {
sb.append(h.getTitle()).append("\n");
}
sb.append(h.getContent()).append("\n\n");
}
return sb.toString();
}
}

View File

@@ -1,46 +0,0 @@
package com.gxwebsoft.ai.service;
import com.gxwebsoft.ai.dto.AiShopMetricsRow;
import com.gxwebsoft.ai.mapper.AiShopAnalyticsMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
@Service
public class AiShopAnalyticsService {
@Resource
private AiShopAnalyticsMapper mapper;
public List<AiShopMetricsRow> queryTenantDaily(Integer tenantId, LocalDate startDate, LocalDate endDateInclusive) {
LocalDateTime start = startDate.atStartOfDay();
LocalDateTime endExclusive = endDateInclusive.plusDays(1).atStartOfDay();
List<AiShopMetricsRow> rows = mapper.queryMetrics(tenantId, start, endExclusive);
if (rows == null) {
return null;
}
for (AiShopMetricsRow r : rows) {
long orderCnt = r.getOrderCnt() == null ? 0L : r.getOrderCnt();
long paidCnt = r.getPaidOrderCnt() == null ? 0L : r.getPaidOrderCnt();
BigDecimal gmv = r.getGmv() == null ? BigDecimal.ZERO : r.getGmv();
if (paidCnt > 0) {
r.setAov(gmv.divide(BigDecimal.valueOf(paidCnt), 4, RoundingMode.HALF_UP));
} else {
r.setAov(BigDecimal.ZERO);
}
if (orderCnt > 0) {
r.setPayRate(BigDecimal.valueOf(paidCnt)
.divide(BigDecimal.valueOf(orderCnt), 4, RoundingMode.HALF_UP));
} else {
r.setPayRate(BigDecimal.ZERO);
}
}
return rows;
}
}

View File

@@ -1,12 +0,0 @@
package com.gxwebsoft.ai.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.ai.entity.AiKbChunk;
import com.gxwebsoft.ai.mapper.AiKbChunkMapper;
import com.gxwebsoft.ai.service.AiKbChunkService;
import org.springframework.stereotype.Service;
@Service
public class AiKbChunkServiceImpl extends ServiceImpl<AiKbChunkMapper, AiKbChunk> implements AiKbChunkService {
}

View File

@@ -1,12 +0,0 @@
package com.gxwebsoft.ai.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.ai.entity.AiKbDocument;
import com.gxwebsoft.ai.mapper.AiKbDocumentMapper;
import com.gxwebsoft.ai.service.AiKbDocumentService;
import org.springframework.stereotype.Service;
@Service
public class AiKbDocumentServiceImpl extends ServiceImpl<AiKbDocumentMapper, AiKbDocument> implements AiKbDocumentService {
}

View File

@@ -1,100 +0,0 @@
package com.gxwebsoft.ai.util;
import cn.hutool.core.util.StrUtil;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
public class AiTextUtil {
private AiTextUtil() {
}
public static String sha256(String s) {
if (s == null) {
return null;
}
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] dig = md.digest(s.getBytes(StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder(dig.length * 2);
for (byte b : dig) {
sb.append(String.format("%02x", b));
}
return sb.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 很轻量的 HTML 转纯文本(不追求完美,只用于知识库入库前清洗)。
*/
public static String stripHtml(String html) {
if (StrUtil.isBlank(html)) {
return "";
}
String s = html;
s = s.replaceAll("(?is)<script[^>]*>.*?</script>", " ");
s = s.replaceAll("(?is)<style[^>]*>.*?</style>", " ");
s = s.replaceAll("(?is)<br\\s*/?>", "\n");
s = s.replaceAll("(?is)</p\\s*>", "\n");
s = s.replaceAll("(?is)<[^>]+>", " ");
// 常见 HTML 实体最小处理
s = s.replace("&nbsp;", " ");
s = s.replace("&lt;", "<").replace("&gt;", ">").replace("&amp;", "&").replace("&quot;", "\"");
return normalizeWhitespace(s);
}
public static String normalizeWhitespace(String s) {
if (s == null) {
return "";
}
// 合并空白,保留换行用于 chunking
String x = s.replace("\r", "\n");
x = x.replaceAll("[\\t\\f\\u000B]+", " ");
x = x.replaceAll("[ ]{2,}", " ");
x = x.replaceAll("\\n{3,}", "\n\n");
return x.trim();
}
/**
* 按字符数切分,并做固定 overlap。
*/
public static List<String> chunkText(String text, int chunkSize, int overlap) {
String s = normalizeWhitespace(text);
List<String> out = new ArrayList<>();
if (StrUtil.isBlank(s)) {
return out;
}
if (chunkSize <= 0) {
chunkSize = 800;
}
if (overlap < 0) {
overlap = 0;
}
if (overlap >= chunkSize) {
overlap = Math.max(0, chunkSize / 5);
}
int n = s.length();
int start = 0;
while (start < n) {
int end = Math.min(n, start + chunkSize);
String chunk = s.substring(start, end).trim();
if (!chunk.isEmpty()) {
out.add(chunk);
}
if (end >= n) {
break;
}
start = end - overlap;
if (start < 0) {
start = 0;
}
}
return out;
}
}

View File

@@ -0,0 +1,129 @@
package com.gxwebsoft.app.controller;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.app.entity.AppConfig;
import com.gxwebsoft.app.param.AppConfigParam;
import com.gxwebsoft.app.service.AppConfigService;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
/**
* 应用配置表 Controller
*/
@Slf4j
@Tag(name = "应用配置管理")
@RestController
@RequestMapping("/api/app/app-config")
public class AppConfigController extends BaseController {
@Resource
private AppConfigService appConfigService;
/**
* 分页查询应用配置
*/
@Operation(summary = "分页查询应用配置")
@GetMapping("/page")
public ApiResult<PageResult<AppConfig>> page(AppConfigParam param) {
return success(new PageResult<>(appConfigService.page(param)));
}
/**
* 获取应用配置列表
*/
@Operation(summary = "获取应用配置列表")
@GetMapping()
public ApiResult<List<AppConfig>> list(AppConfigParam param) {
return success(appConfigService.list(param));
}
/**
* 根据应用ID获取配置映射
*/
@Operation(summary = "根据应用ID获取配置映射")
@GetMapping("/map/{websiteId}")
public ApiResult<Map<String, Object>> getConfigsByWebsiteId(@PathVariable Integer websiteId) {
return success(appConfigService.getConfigsByWebsiteId(websiteId));
}
/**
* 获取单个配置值
*/
@Operation(summary = "获取单个配置值")
@GetMapping("/value")
public ApiResult<String> getConfigValue(@RequestParam Integer websiteId, @RequestParam String configKey) {
return success(appConfigService.getConfigValue(websiteId, configKey),null);
}
/**
* 保存配置
*/
@Operation(summary = "保存配置")
@PostMapping()
public ApiResult<?> save(@RequestBody AppConfig config) {
appConfigService.saveConfig(config);
return success("保存成功");
}
/**
* 批量保存配置
*/
@Operation(summary = "批量保存配置")
@PostMapping("/batch")
public ApiResult<?> batchSave(@RequestBody BatchSaveRequest request) {
appConfigService.batchSaveConfig(request.getWebsiteId(), request.getConfigs());
return success("保存成功");
}
/**
* 更新配置
*/
@Operation(summary = "更新配置")
@PutMapping()
public ApiResult<?> update(@RequestBody AppConfig config) {
appConfigService.updateConfig(config);
return success("更新成功");
}
/**
* 删除配置
*/
@Operation(summary = "删除配置")
@DeleteMapping("/{configId}")
public ApiResult<?> delete(@PathVariable Integer configId) {
appConfigService.deleteConfig(configId);
return success("删除成功");
}
/**
* 批量保存请求对象
*/
public static class BatchSaveRequest {
private Integer websiteId;
private List<AppConfig> configs;
public Integer getWebsiteId() {
return websiteId;
}
public void setWebsiteId(Integer websiteId) {
this.websiteId = websiteId;
}
public List<AppConfig> getConfigs() {
return configs;
}
public void setConfigs(List<AppConfig> configs) {
this.configs = configs;
}
}
}

View File

@@ -0,0 +1,151 @@
package com.gxwebsoft.app.controller;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.app.service.AppCredentialService;
import com.gxwebsoft.app.entity.AppCredential;
import com.gxwebsoft.app.param.AppCredentialParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.system.entity.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* 应用密钥凭证控制器
*
* @author 科技小王子
* @since 2026-03-28 21:29:44
*/
@Slf4j
@Tag(name = "应用密钥凭证管理")
@RestController
@RequestMapping("/api/app/app-credential")
public class AppCredentialController extends BaseController {
@Resource
private AppCredentialService appCredentialService;
@Operation(summary = "分页查询应用密钥凭证")
@GetMapping("/page")
public ApiResult<PageResult<AppCredential>> page(AppCredentialParam param) {
return success(appCredentialService.pageRel(param));
}
@Operation(summary = "查询全部应用密钥凭证")
@GetMapping()
public ApiResult<List<AppCredential>> list(AppCredentialParam param) {
return success(appCredentialService.listRel(param));
}
@Operation(summary = "根据id查询应用密钥凭证")
@GetMapping("/{id}")
public ApiResult<AppCredential> get(@PathVariable("id") Integer id) {
return success(appCredentialService.getByIdRel(id));
}
@PreAuthorize("hasAuthority('app:appCredential:save')")
@OperationLog
@Operation(summary = "创建应用密钥凭证(自动生成 AppID 和 AppSecret")
@PostMapping()
public ApiResult<?> save(@RequestBody AppCredential appCredential) {
User loginUser = getLoginUser();
if (loginUser == null) {
return fail("请先登录");
}
appCredential.setUserId(loginUser.getUserId());
// 创建并生成密钥
AppCredential result = appCredentialService.createCredential(appCredential);
return success("创建成功,请保存 AppSecret该信息仅展示一次", result);
}
@PreAuthorize("hasAuthority('app:appCredential:update')")
@OperationLog
@Operation(summary = "修改应用密钥凭证(名称/类型/备注等,不含密钥)")
@PutMapping()
public ApiResult<?> update(@RequestBody AppCredential appCredential) {
// 防止通过此接口直接修改 appId/appSecret
appCredential.setAppId(null);
appCredential.setAppSecret(null);
if (appCredentialService.updateById(appCredential)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('app:appCredential:update')")
@OperationLog
@Operation(summary = "重置 AppSecret重新生成密钥")
@PostMapping("/resetSecret/{id}")
public ApiResult<?> resetSecret(@PathVariable("id") Long id) {
try {
AppCredential result = appCredentialService.resetSecret(id);
return success("重置成功,请保存新 AppSecret该信息仅展示一次", result);
} catch (RuntimeException e) {
return fail(e.getMessage());
}
}
@PreAuthorize("hasAuthority('app:appCredential:update')")
@OperationLog
@Operation(summary = "禁用/启用凭证")
@PutMapping("/status/{id}/{status}")
public ApiResult<?> updateStatus(@PathVariable("id") Long id, @PathVariable("status") Integer status) {
if (appCredentialService.updateStatus(id, status)) {
return success(status == 0 ? "已启用" : "已禁用");
}
return fail("操作失败");
}
@PreAuthorize("hasAuthority('app:appCredential:remove')")
@OperationLog
@Operation(summary = "删除应用密钥凭证")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (appCredentialService.removeById(id)) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('app:appCredential:save')")
@OperationLog
@Operation(summary = "批量添加应用密钥凭证")
@PostMapping("/batch")
public ApiResult<?> saveBatch(@RequestBody List<AppCredential> list) {
if (appCredentialService.saveBatch(list)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('app:appCredential:update')")
@OperationLog
@Operation(summary = "批量修改应用密钥凭证")
@PutMapping("/batch")
public ApiResult<?> updateBatch(@RequestBody BatchParam<AppCredential> batchParam) {
if (batchParam.update(appCredentialService, "id")) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('app:appCredential:remove')")
@OperationLog
@Operation(summary = "批量删除应用密钥凭证")
@DeleteMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
if (appCredentialService.removeByIds(ids)) {
return success("删除成功");
}
return fail("删除失败");
}
}

View File

@@ -0,0 +1,133 @@
package com.gxwebsoft.app.controller;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.app.service.AppEventService;
import com.gxwebsoft.app.entity.AppEvent;
import com.gxwebsoft.app.param.AppEventParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.system.entity.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* 应用操作动态控制器
*
* @author 科技小王子
* @since 2026-03-28 21:29:44
*/
@Slf4j
@Tag(name = "应用操作动态管理")
@RestController
@RequestMapping("/api/app/app-event")
public class AppEventController extends BaseController {
@Resource
private AppEventService appEventService;
@Operation(summary = "分页查询操作动态")
@GetMapping("/page")
public ApiResult<PageResult<AppEvent>> page(AppEventParam param) {
return success(appEventService.pageRel(param));
}
@Operation(summary = "查询全部操作动态")
@GetMapping()
public ApiResult<List<AppEvent>> list(AppEventParam param) {
return success(appEventService.listRel(param));
}
@Operation(summary = "根据id查询操作动态")
@GetMapping("/{id}")
public ApiResult<AppEvent> get(@PathVariable("id") Integer id) {
return success(appEventService.getByIdRel(id));
}
@Operation(summary = "获取应用最新一条动态(用于卡片展示)")
@GetMapping("/latest/{websiteId}")
public ApiResult<AppEvent> getLatest(@PathVariable("websiteId") Long websiteId) {
return success(appEventService.getLatestEvent(websiteId));
}
@PreAuthorize("hasAuthority('app:appEvent:save')")
@OperationLog
@Operation(summary = "手动记录操作动态")
@PostMapping()
public ApiResult<?> save(@RequestBody AppEvent appEvent) {
User loginUser = getLoginUser();
if (loginUser != null) {
appEvent.setUserId(loginUser.getUserId());
appEvent.setTenantId(loginUser.getTenantId());
if (appEvent.getOperatorId() == null) {
appEvent.setOperatorId(loginUser.getUserId().longValue());
}
if (appEvent.getOperator() == null) {
appEvent.setOperator(loginUser.getNickname());
}
}
if (appEventService.save(appEvent)) {
return success("记录成功");
}
return fail("记录失败");
}
@PreAuthorize("hasAuthority('app:appEvent:update')")
@OperationLog
@Operation(summary = "修改操作动态")
@PutMapping()
public ApiResult<?> update(@RequestBody AppEvent appEvent) {
if (appEventService.updateById(appEvent)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('app:appEvent:remove')")
@OperationLog
@Operation(summary = "删除操作动态")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (appEventService.removeById(id)) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('app:appEvent:remove')")
@OperationLog
@Operation(summary = "清空应用所有动态记录")
@DeleteMapping("/clear/{websiteId}")
public ApiResult<?> clearByWebsiteId(@PathVariable("websiteId") Long websiteId) {
// 只清空当前租户下的数据
AppEventParam param = new AppEventParam();
param.setWebsiteId(websiteId);
List<AppEvent> list = appEventService.listRel(param);
if (list.isEmpty()) {
return success("暂无动态记录");
}
List<Long> ids = list.stream().map(AppEvent::getId).collect(java.util.stream.Collectors.toList());
if (appEventService.removeByIds(ids)) {
return success("已清空 " + ids.size() + " 条动态记录");
}
return fail("清空失败");
}
@PreAuthorize("hasAuthority('app:appEvent:remove')")
@OperationLog
@Operation(summary = "批量删除操作动态")
@DeleteMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
if (appEventService.removeByIds(ids)) {
return success("删除成功");
}
return fail("删除失败");
}
}

View File

@@ -0,0 +1,145 @@
package com.gxwebsoft.app.controller;
import com.gxwebsoft.app.entity.AppResource;
import com.gxwebsoft.app.param.AppResourceParam;
import com.gxwebsoft.app.service.AppResourceService;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
/**
* 开发者资源管理控制器(服务器/数据库/云存储/域名/SSL
*
* @author 科技小王子
* @since 2026-03-31
*/
@Slf4j
@Tag(name = "开发者资源管理")
@RestController
@RequestMapping("/api/app/developer-resource")
public class AppResourceController extends BaseController {
@Resource
private AppResourceService appResourceService;
// ─── 查询接口 ─────────────────────────────────────────────────
@Operation(summary = "分页查询资源列表")
@GetMapping("/page")
public ApiResult<PageResult<AppResource>> page(AppResourceParam param) {
User loginUser = getLoginUser();
if (loginUser == null) return fail("请先登录", null);
// 普通开发者只能查自己的资源
param.setUserId(loginUser.getUserId());
param.setTenantId(loginUser.getTenantId());
return success(appResourceService.pageRel(param));
}
@Operation(summary = "查询资源列表(不分页)")
@GetMapping
public ApiResult<List<AppResource>> list(AppResourceParam param) {
User loginUser = getLoginUser();
if (loginUser == null) return fail("请先登录", null);
param.setUserId(loginUser.getUserId());
param.setTenantId(loginUser.getTenantId());
return success(appResourceService.listRel(param));
}
@Operation(summary = "获取资源详情")
@GetMapping("/{resourceId}")
public ApiResult<AppResource> get(@PathVariable Long resourceId) {
User loginUser = getLoginUser();
if (loginUser == null) return fail("请先登录", null);
AppResource resource = appResourceService.getByIdRel(resourceId);
if (resource == null) return fail("资源不存在", null);
if (!resource.getUserId().equals(loginUser.getUserId())) return fail("无权访问此资源", null);
return success(resource);
}
@Operation(summary = "统计各类型资源数量")
@GetMapping("/stats")
public ApiResult<Map<String, Long>> stats() {
User loginUser = getLoginUser();
if (loginUser == null) return fail("请先登录", null);
return success(appResourceService.countByType(loginUser.getUserId(), loginUser.getTenantId()));
}
// ─── 新增/修改接口 ────────────────────────────────────────────
@OperationLog
@Operation(summary = "新增资源")
@PostMapping
public ApiResult<AppResource> save(@RequestBody AppResource resource) {
User loginUser = getLoginUser();
if (loginUser == null) return fail("请先登录", null);
if (resource.getResourceType() == null || resource.getResourceType().isEmpty()) {
return fail("资源类型不能为空", null);
}
if (resource.getName() == null || resource.getName().isEmpty()) {
return fail("资源名称不能为空", null);
}
resource.setTenantId(loginUser.getTenantId());
try {
AppResource result = appResourceService.addResource(resource, loginUser.getUserId());
return success("添加成功", result);
} catch (Exception e) {
return fail(e.getMessage(), null);
}
}
@OperationLog
@Operation(summary = "修改资源")
@PutMapping
public ApiResult<AppResource> update(@RequestBody AppResource resource) {
User loginUser = getLoginUser();
if (loginUser == null) return fail("请先登录", null);
try {
AppResource result = appResourceService.updateResource(resource);
return success("修改成功", result);
} catch (Exception e) {
return fail(e.getMessage(), null);
}
}
// ─── 删除接口 ─────────────────────────────────────────────────
@OperationLog
@Operation(summary = "删除资源(逻辑删除)")
@DeleteMapping("/{resourceId}")
public ApiResult<?> remove(@PathVariable Long resourceId) {
User loginUser = getLoginUser();
if (loginUser == null) return fail("请先登录");
try {
appResourceService.removeResource(resourceId, loginUser.getUserId());
return success("删除成功");
} catch (Exception e) {
return fail(e.getMessage());
}
}
@OperationLog
@Operation(summary = "批量删除资源")
@DeleteMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody List<Long> ids) {
User loginUser = getLoginUser();
if (loginUser == null) return fail("请先登录");
try {
for (Long id : ids) {
appResourceService.removeResource(id, loginUser.getUserId());
}
return success("批量删除成功");
} catch (Exception e) {
return fail(e.getMessage());
}
}
}

View File

@@ -0,0 +1,150 @@
package com.gxwebsoft.app.controller;
import com.gxwebsoft.app.entity.AppTicket;
import com.gxwebsoft.app.entity.AppTicketReply;
import com.gxwebsoft.app.param.AppTicketParam;
import com.gxwebsoft.app.service.AppTicketService;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
/**
* 应用工单控制器
*
* @author 科技小王子
* @since 2026-03-30
*/
@Slf4j
@Tag(name = "应用工单管理")
@RestController
@RequestMapping("/api/app/ticket")
public class AppTicketController extends BaseController {
@Resource
private AppTicketService appTicketService;
// ─── 客户端接口 ────────────────────────────────────────────────
@Operation(summary = "查询我的工单(分页)")
@GetMapping("/my")
public ApiResult<PageResult<AppTicket>> myTickets(AppTicketParam param) {
User loginUser = getLoginUser();
if (loginUser == null) return fail("请先登录",null);
return success(appTicketService.myPage(param, loginUser.getUserId()));
}
@Operation(summary = "提交工单")
@PostMapping("/submit")
public ApiResult<AppTicket> submit(@RequestBody AppTicket ticket) {
User loginUser = getLoginUser();
if (loginUser == null) return fail("请先登录",null);
try {
AppTicket result = appTicketService.submit(ticket, loginUser.getUserId());
return success("工单提交成功", result);
} catch (Exception e) {
return fail(e.getMessage(),null);
}
}
@Operation(summary = "关闭工单(提交人)")
@PutMapping("/{ticketId}/close")
public ApiResult<?> close(@PathVariable Long ticketId) {
User loginUser = getLoginUser();
if (loginUser == null) return fail("请先登录");
try {
appTicketService.closeByUser(ticketId, loginUser.getUserId());
return success("工单已关闭");
} catch (Exception e) {
return fail(e.getMessage());
}
}
// ─── 技术端接口 ────────────────────────────────────────────────
@Operation(summary = "查询所有工单(技术人员)")
@GetMapping("/list")
public ApiResult<PageResult<AppTicket>> allTickets(AppTicketParam param) {
User loginUser = getLoginUser();
if (loginUser == null) return fail("请先登录",null);
return success(appTicketService.allPage(param));
}
@Operation(summary = "获取工单详情")
@GetMapping("/{ticketId}")
public ApiResult<AppTicket> detail(@PathVariable Long ticketId) {
return success(appTicketService.getById(ticketId));
}
@Operation(summary = "更新工单状态(技术人员)")
@PutMapping("/status")
public ApiResult<?> updateStatus(@RequestBody Map<String, Object> body) {
User loginUser = getLoginUser();
if (loginUser == null) return fail("请先登录");
Long ticketId = Long.valueOf(body.get("ticketId").toString());
String status = body.get("status").toString();
appTicketService.updateStatus(ticketId, status, loginUser.getUserId());
return success("状态已更新");
}
@Operation(summary = "分配处理人(管理员)")
@PutMapping("/assign")
public ApiResult<?> assign(@RequestBody Map<String, Object> body) {
User loginUser = getLoginUser();
if (loginUser == null) return fail("请先登录");
Long ticketId = Long.valueOf(body.get("ticketId").toString());
Integer assigneeId = Integer.valueOf(body.get("assigneeId").toString());
appTicketService.assign(ticketId, assigneeId);
return success("分配成功");
}
// ─── 回复接口 ─────────────────────────────────────────────────
@Operation(summary = "获取工单回复列表")
@GetMapping("/{ticketId}/replies")
public ApiResult<List<AppTicketReply>> replies(@PathVariable Long ticketId) {
return success(appTicketService.getReplies(ticketId));
}
@Operation(summary = "提交工单回复")
@PostMapping("/reply")
public ApiResult<AppTicketReply> reply(@RequestBody AppTicketReply reply) {
User loginUser = getLoginUser();
if (loginUser == null) return fail("请先登录",null);
if (reply.getContent() == null || reply.getContent().trim().isEmpty()) {
return fail("回复内容不能为空",null);
}
try {
AppTicketReply result = appTicketService.addReply(reply, loginUser.getUserId());
return success("回复成功", result);
} catch (Exception e) {
return fail(e.getMessage(),null);
}
}
// ─── 统计 & 辅助 ─────────────────────────────────────────────
@Operation(summary = "工单统计数据")
@GetMapping("/stats")
public ApiResult<Map<String, Long>> stats(
@RequestParam(required = false) Long websiteId) {
User loginUser = getLoginUser();
if (loginUser == null) return fail("请先登录",null);
// 技术端不限制用户维度;客户端通过路由区分
return success(appTicketService.stats(websiteId, null));
}
@Operation(summary = "获取技术人员列表(用于分配)")
@GetMapping("/staff-list")
public ApiResult<List<Map<String, Object>>> staffList() {
return success(appTicketService.getTechStaffList());
}
}

View File

@@ -0,0 +1,167 @@
package com.gxwebsoft.app.controller;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.app.service.AppUserService;
import com.gxwebsoft.app.entity.AppUser;
import com.gxwebsoft.app.param.AppUserParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.system.entity.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* 应用成员控制器
*
* @author 科技小王子
* @since 2026-03-28 21:29:44
*/
@Slf4j
@Tag(name = "应用成员管理")
@RestController
@RequestMapping("/api/app/app-user")
public class AppUserController extends BaseController {
@Resource
private AppUserService appUserService;
@Operation(summary = "分页查询应用成员")
@GetMapping("/page")
public ApiResult<PageResult<AppUser>> page(AppUserParam param) {
return success(appUserService.pageRel(param));
}
@Operation(summary = "查询全部应用成员")
@GetMapping()
public ApiResult<List<AppUser>> list(AppUserParam param) {
return success(appUserService.listRel(param));
}
@Operation(summary = "根据id查询应用成员")
@GetMapping("/{id}")
public ApiResult<AppUser> get(@PathVariable("id") Integer id) {
return success(appUserService.getByIdRel(id));
}
@PreAuthorize("hasAuthority('app:appUser:save')")
@OperationLog
@Operation(summary = "添加应用成员(手动添加)")
@PostMapping()
public ApiResult<?> save(@RequestBody AppUser appUser) {
User loginUser = getLoginUser();
if (loginUser != null) {
appUser.setUserId(loginUser.getUserId());
appUser.setTenantId(loginUser.getTenantId());
}
if (appUserService.save(appUser)) {
return success("添加成功");
}
return fail("添加失败");
}
@Operation(summary = "邀请用户成为应用成员支持用户ID或手机号")
@PostMapping("/invite")
public ApiResult<?> invite(@RequestBody AppUser appUser) {
User loginUser = getLoginUser();
if (loginUser == null) {
return fail("请先登录");
}
// 支持手机号邀请:若 userId 为空但传了 phone则先按手机号查出用户
if (appUser.getUserId() == null && appUser.getPhone() != null && !appUser.getPhone().isEmpty()) {
User targetUser = appUserService.findUserByPhone(appUser.getPhone());
if (targetUser == null) {
return fail("手机号未注册,请确认后再试");
}
appUser.setUserId(targetUser.getUserId());
}
if (appUser.getUserId() == null) {
return fail("请输入用户ID或手机号");
}
try {
AppUser result = appUserService.inviteUser(
appUser.getWebsiteId(),
appUser.getUserId(),
appUser.getRole(),
loginUser.getUserId()
);
return success("邀请成功", result);
} catch (RuntimeException e) {
return fail(e.getMessage());
}
}
@PreAuthorize("hasAuthority('app:appUser:update')")
@OperationLog
@Operation(summary = "修改应用成员信息")
@PutMapping()
public ApiResult<?> update(@RequestBody AppUser appUser) {
if (appUserService.updateById(appUser)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('app:appUser:update')")
@OperationLog
@Operation(summary = "修改成员角色")
@PutMapping("/role/{id}/{role}")
public ApiResult<?> updateRole(@PathVariable("id") Long id, @PathVariable("role") String role) {
if (appUserService.updateRole(id, role)) {
return success("角色修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('app:appUser:remove')")
@OperationLog
@Operation(summary = "移除应用成员")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (appUserService.removeById(id)) {
return success("已移除");
}
return fail("移除失败");
}
@PreAuthorize("hasAuthority('app:appUser:save')")
@OperationLog
@Operation(summary = "批量添加应用成员")
@PostMapping("/batch")
public ApiResult<?> saveBatch(@RequestBody List<AppUser> list) {
if (appUserService.saveBatch(list)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('app:appUser:update')")
@OperationLog
@Operation(summary = "批量修改应用成员")
@PutMapping("/batch")
public ApiResult<?> updateBatch(@RequestBody BatchParam<AppUser> batchParam) {
if (batchParam.update(appUserService, "id")) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('app:appUser:remove')")
@OperationLog
@Operation(summary = "批量移除应用成员")
@DeleteMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
if (appUserService.removeByIds(ids)) {
return success("移除成功");
}
return fail("移除失败");
}
}

View File

@@ -0,0 +1,173 @@
package com.gxwebsoft.app.controller;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.app.service.AppVersionService;
import com.gxwebsoft.app.entity.AppVersion;
import com.gxwebsoft.app.param.AppVersionParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.system.entity.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* 应用版本发布记录控制器
*
* @author 科技小王子
* @since 2026-03-28 21:29:44
*/
@Slf4j
@Tag(name = "应用版本发布管理")
@RestController
@RequestMapping("/api/app/app-version")
public class AppVersionController extends BaseController {
@Resource
private AppVersionService appVersionService;
@Operation(summary = "分页查询版本记录")
@GetMapping("/page")
public ApiResult<PageResult<AppVersion>> page(AppVersionParam param) {
return success(appVersionService.pageRel(param));
}
@Operation(summary = "查询全部版本记录")
@GetMapping()
public ApiResult<List<AppVersion>> list(AppVersionParam param) {
return success(appVersionService.listRel(param));
}
@Operation(summary = "根据id查询版本")
@GetMapping("/{id}")
public ApiResult<AppVersion> get(@PathVariable("id") Integer id) {
return success(appVersionService.getByIdRel(id));
}
@Operation(summary = "获取应用当前版本")
@GetMapping("/current/{websiteId}")
public ApiResult<AppVersion> getCurrentVersion(@PathVariable("websiteId") Long websiteId) {
return success(appVersionService.getCurrentVersion(websiteId));
}
@PreAuthorize("hasAuthority('app:appVersion:save')")
@OperationLog
@Operation(summary = "新增版本(构建中状态)")
@PostMapping()
public ApiResult<?> save(@RequestBody AppVersion appVersion) {
User loginUser = getLoginUser();
if (loginUser != null) {
appVersion.setUserId(loginUser.getUserId());
appVersion.setTenantId(loginUser.getTenantId());
}
// 默认为构建中状态
if (appVersion.getStatus() == null) {
appVersion.setStatus(0);
}
if (appVersion.getEnv() == null) {
appVersion.setEnv("production");
}
appVersion.setIsCurrent(false);
if (appVersionService.save(appVersion)) {
return success("创建成功");
}
return fail("创建失败");
}
@PreAuthorize("hasAuthority('app:appVersion:update')")
@OperationLog
@Operation(summary = "修改版本信息")
@PutMapping()
public ApiResult<?> update(@RequestBody AppVersion appVersion) {
if (appVersionService.updateById(appVersion)) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('app:appVersion:update')")
@OperationLog
@Operation(summary = "发布版本(将此版本设为当前运行版本)")
@PostMapping("/publish/{id}")
public ApiResult<?> publish(@PathVariable("id") Long id) {
User loginUser = getLoginUser();
if (loginUser == null) {
return fail("请先登录");
}
try {
appVersionService.publish(id, loginUser.getUserId());
return success("发布成功");
} catch (RuntimeException e) {
return fail(e.getMessage());
}
}
@PreAuthorize("hasAuthority('app:appVersion:update')")
@OperationLog
@Operation(summary = "回滚到指定版本")
@PostMapping("/rollback/{id}")
public ApiResult<?> rollback(@PathVariable("id") Long id) {
User loginUser = getLoginUser();
if (loginUser == null) {
return fail("请先登录");
}
try {
appVersionService.rollback(id, loginUser.getUserId());
return success("回滚成功");
} catch (RuntimeException e) {
return fail(e.getMessage());
}
}
@PreAuthorize("hasAuthority('app:appVersion:remove')")
@OperationLog
@Operation(summary = "删除版本记录")
@DeleteMapping("/{id}")
public ApiResult<?> remove(@PathVariable("id") Integer id) {
if (appVersionService.removeById(id)) {
return success("删除成功");
}
return fail("删除失败");
}
@PreAuthorize("hasAuthority('app:appVersion:save')")
@OperationLog
@Operation(summary = "批量添加版本")
@PostMapping("/batch")
public ApiResult<?> saveBatch(@RequestBody List<AppVersion> list) {
if (appVersionService.saveBatch(list)) {
return success("添加成功");
}
return fail("添加失败");
}
@PreAuthorize("hasAuthority('app:appVersion:update')")
@OperationLog
@Operation(summary = "批量修改版本")
@PutMapping("/batch")
public ApiResult<?> updateBatch(@RequestBody BatchParam<AppVersion> batchParam) {
if (batchParam.update(appVersionService, "id")) {
return success("修改成功");
}
return fail("修改失败");
}
@PreAuthorize("hasAuthority('app:appVersion:remove')")
@OperationLog
@Operation(summary = "批量删除版本记录")
@DeleteMapping("/batch")
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
if (appVersionService.removeByIds(ids)) {
return success("删除成功");
}
return fail("删除失败");
}
}

View File

@@ -0,0 +1,87 @@
package com.gxwebsoft.app.entity;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
/**
* 应用配置表
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("app_config")
public class AppConfig implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 配置ID
*/
@TableId(value = "config_id", type = IdType.AUTO)
private Integer configId;
/**
* 应用ID
*/
private Integer websiteId;
/**
* 配置键
*/
private String configKey;
/**
* 配置值JSON或字符串
*/
private String configValue;
/**
* 配置类型general/api/callback/wechat/payment/git等
*/
private String configType;
/**
* 是否加密 0否 1是
*/
private Integer isEncrypted;
/**
* 是否敏感信息 0否 1是
*/
private Integer isSecret;
/**
* 配置说明
*/
private String description;
/**
* 排序号
*/
private Integer sortNumber;
/**
* 租户id
*/
private Long tenantId;
/**
* 创建时间
*/
@TableField(fill = FieldFill.INSERT)
private Long createdTime;
/**
* 更新时间
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private Long updatedTime;
/**
* 是否删除 0否 1是
*/
@TableLogic
private Integer deleted;
}

View File

@@ -1,63 +1,57 @@
package com.gxwebsoft.credit.entity;
package com.gxwebsoft.app.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.TableLogic;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 历史法定代表人
* 应用密钥凭证
*
* @author 科技小王子
* @since 2026-01-07 13:52:14
* @since 2026-03-28 21:29:43
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Schema(name = "CreditHistoricalLegalPerson对象", description = "历史法定代表人")
public class CreditHistoricalLegalPerson implements Serializable {
@Schema(name = "AppCredential对象", description = "应用密钥凭证")
public class AppCredential implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(description = "ID")
@Schema(description = "自增ID")
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private Long id;
@Schema(description = "名称")
@Schema(description = "关联应用ID")
private Long websiteId;
@Schema(description = "凭证名称,如生产环境密钥")
private String name;
@Schema(description = "任职日期")
private String registerDate;
@Schema(description = "App ID公开")
private String appId;
@Schema(description = "卸任日期")
private String publicDate;
@Schema(description = "App Secret加密存储")
private String appSecret;
@Schema(description = "链接")
private String url;
@Schema(description = "凭证类型: server/client/webhook")
private String type;
@Schema(description = "是否有数据")
private Boolean hasData;
@Schema(description = "权限范围,空格分隔")
private String scopes;
@Schema(description = "备注")
private String comments;
@Schema(description = "到期时间NULL=永不过期")
private LocalDateTime expireTime;
@Schema(description = "企业ID")
private Integer companyId;
@Schema(description = "最后使用时间")
private LocalDateTime lastUsedAt;
@Schema(description = "企业别名")
private String companyAlias;
@Schema(description = "主体企业")
@TableField(exist = false)
private String companyName;
@Schema(description = "是否推荐")
private Integer recommend;
private String remark;
@Schema(description = "排序(数字越小越靠前)")
private Integer sortNumber;
@@ -72,10 +66,6 @@ public class CreditHistoricalLegalPerson implements Serializable {
@Schema(description = "用户ID")
private Integer userId;
@Schema(description = "真实姓名")
@TableField(exist = false)
private String realName;
@Schema(description = "租户id")
private Integer tenantId;

View File

@@ -0,0 +1,76 @@
package com.gxwebsoft.app.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 应用操作动态
*
* @author 科技小王子
* @since 2026-03-28 21:29:44
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Schema(name = "AppEvent对象", description = "应用操作动态")
public class AppEvent implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(description = "自增ID")
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@Schema(description = "关联应用ID")
private Long websiteId;
@Schema(description = "事件类型: created/published/updated/domain_bound/member_added/status_changed")
private String eventType;
@Schema(description = "事件标题,如已发布")
private String title;
@Schema(description = "详细描述")
private String content;
@Schema(description = "操作人用户ID")
private Long operatorId;
@Schema(description = "操作人名称(冗余)")
private String operator;
@Schema(description = "关联ID如版本ID")
private Long refId;
@Schema(description = "关联类型")
private String refType;
@Schema(description = "扩展数据")
private String extra;
@Schema(description = "排序(数字越小越靠前)")
private Integer sortNumber;
@Schema(description = "状态, 0正常, 1冻结")
private Integer status;
@Schema(description = "用户ID")
private Integer userId;
@Schema(description = "租户id")
private Integer tenantId;
@Schema(description = "创建时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createTime;
@Schema(description = "修改时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime updateTime;
}

View File

@@ -0,0 +1,121 @@
package com.gxwebsoft.app.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime;
/**
* 开发者资源(服务器/数据库/云存储/域名/SSL证书
*
* @author 科技小王子
* @since 2026-03-31
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("app_resource")
@Schema(name = "AppResource对象", description = "开发者资源")
public class AppResource implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(description = "资源ID")
@TableId(value = "resource_id", type = IdType.AUTO)
private Long resourceId;
@Schema(description = "资源类型: server/database/storage/domain/ssl")
private String resourceType;
@Schema(description = "资源名称")
private String name;
@Schema(description = "服务商: tencent/aliyun/huawei/other")
private String provider;
@Schema(description = "关联应用ID可选")
private Long websiteId;
@Schema(description = "关联应用名称(冗余)")
private String websiteName;
// ─── 服务器字段 ───────────────────────────────────────
@Schema(description = "IP地址服务器用")
private String ip;
// ─── 数据库字段 ───────────────────────────────────────
@Schema(description = "数据库类型: MySQL/PostgreSQL/Redis/MongoDB数据库用")
private String dbType;
@Schema(description = "连接主机地址(数据库用)")
private String host;
@Schema(description = "连接端口(数据库用)")
private Integer port;
// ─── 云存储字段 ───────────────────────────────────────
@Schema(description = "地区/Region云存储用")
private String region;
@Schema(description = "访问权限: public-read/private云存储用")
private String acl;
@Schema(description = "已用空间(字节,云存储用)")
private Long usedBytes;
// ─── 域名字段 ─────────────────────────────────────────
@Schema(description = "域名(域名用)")
private String domain;
@Schema(description = "注册商(域名用)")
private String registrar;
@Schema(description = "是否已备案(域名用)")
private Boolean icp;
@Schema(description = "ICP备案号域名用")
private String icpNo;
@Schema(description = "是否已绑定SSL域名用冗余")
private Boolean sslBound;
// ─── SSL证书字段 ──────────────────────────────────────
@Schema(description = "证书类型: DV/OV/EVSSL用")
private String certType;
@Schema(description = "颁发机构SSL用")
private String issuer;
// ─── 通用字段 ─────────────────────────────────────────
@Schema(description = "状态: running/stopped/expired/pending")
private String status;
@Schema(description = "到期时间")
@JsonFormat(pattern = "yyyy-MM-dd")
private LocalDate expireAt;
@Schema(description = "备注")
private String remark;
@Schema(description = "所属用户ID")
private Integer userId;
@Schema(description = "租户ID")
private Integer tenantId;
@Schema(description = "是否删除: 0否 1是")
private Integer deleted;
@Schema(description = "创建时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createTime;
@Schema(description = "更新时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime updateTime;
}

View File

@@ -0,0 +1,103 @@
package com.gxwebsoft.app.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.gxwebsoft.common.core.config.JsonArrayToStringDeserializer;
import com.gxwebsoft.common.core.config.JsonStringToArraySerializer;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 应用工单
*
* @author 科技小王子
* @since 2026-03-30
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("app_ticket")
@Schema(name = "AppTicket对象", description = "应用工单")
public class AppTicket implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(description = "工单ID")
@TableId(value = "ticket_id", type = IdType.AUTO)
private Long ticketId;
@Schema(description = "工单编号TK-yyyyMMddHHmmss+4位随机")
private String ticketNo;
@Schema(description = "工单标题")
private String title;
@Schema(description = "工单内容描述")
private String content;
@Schema(description = "关联应用ID")
private Long websiteId;
@Schema(description = "应用名称(冗余)")
private String websiteName;
@Schema(description = "工单分类: bug/feature/consultation/complaint/other")
private String category;
@Schema(description = "优先级: low/normal/high/urgent")
private String priority;
@Schema(description = "状态: pending/assigned/processing/resolved/closed/rejected")
private String status;
@Schema(description = "附件JSON数组")
@JsonDeserialize(using = JsonArrayToStringDeserializer.class)
@JsonSerialize(using = JsonStringToArraySerializer.class)
private String attachments;
@Schema(description = "提交人用户ID")
private Integer submitUserId;
@Schema(description = "提交人昵称(冗余)")
private String submitUserName;
@Schema(description = "提交人头像(冗余)")
private String submitUserAvatar;
@Schema(description = "分配的处理人用户ID")
private Integer assigneeId;
@Schema(description = "处理人昵称(冗余)")
private String assigneeName;
@Schema(description = "处理人头像(冗余)")
private String assigneeAvatar;
@Schema(description = "回复数量")
private Integer replyCount;
@Schema(description = "解决时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime resolvedTime;
@Schema(description = "关闭时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime closedTime;
@Schema(description = "是否删除: 0否 1是")
private Integer deleted;
@Schema(description = "创建时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createTime;
@Schema(description = "更新时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime updateTime;
}

View File

@@ -0,0 +1,64 @@
package com.gxwebsoft.app.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.gxwebsoft.common.core.config.JsonArrayToStringDeserializer;
import com.gxwebsoft.common.core.config.JsonStringToArraySerializer;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 工单回复
*
* @author 科技小王子
* @since 2026-03-30
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("app_ticket_reply")
@Schema(name = "AppTicketReply对象", description = "工单回复")
public class AppTicketReply implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(description = "回复ID")
@TableId(value = "reply_id", type = IdType.AUTO)
private Long replyId;
@Schema(description = "关联工单ID")
private Long ticketId;
@Schema(description = "回复内容")
private String content;
@Schema(description = "附件JSON数组")
@JsonDeserialize(using = JsonArrayToStringDeserializer.class)
@JsonSerialize(using = JsonStringToArraySerializer.class)
private String attachments;
@Schema(description = "回复人用户ID")
private Integer userId;
@Schema(description = "回复人昵称(冗余)")
private String userName;
@Schema(description = "回复人头像(冗余)")
private String userAvatar;
@Schema(description = "是否是技术人员/客服: 0否 1是")
private Integer isStaff;
@Schema(description = "是否删除: 0否 1是")
private Integer deleted;
@Schema(description = "创建时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createTime;
}

View File

@@ -1,66 +1,64 @@
package com.gxwebsoft.glt.entity;
package com.gxwebsoft.app.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.TableLogic;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import com.fasterxml.jackson.annotation.JsonFormat;
/**
* 水票释放
* 应用成员
*
* @author 科技小王子
* @since 2026-02-03 18:55:55
* @since 2026-03-28 21:29:44
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Schema(name = "GltUserTicketRelease对象", description = "水票释放")
public class GltUserTicketRelease implements Serializable {
@Schema(name = "AppUser对象", description = "应用成员")
public class AppUser implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(description = "自增ID")
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@Schema(description = "水票ID")
private Long userTicketId;
@Schema(description = "关联应用ID")
private Long websiteId;
@Schema(description = "用户ID")
private Integer userId;
@Schema(description = "用户昵称")
@TableField(exist = false)
@Schema(description = "用户名(冗余)")
private String username;
@Schema(description = "昵称(冗余)")
private String nickname;
@Schema(description = "用户头像")
@TableField(exist = false)
@Schema(description = "头像(冗余)")
private String avatar;
@Schema(description = "用户手机号")
@TableField(exist = false)
@Schema(description = "手机号(冗余,脱敏存储)")
private String phone;
@Schema(description = "周期编号")
private Integer periodNo;
@Schema(description = "角色: owner/admin/developer/viewer")
private String role;
@Schema(description = "释放数量")
private Integer releaseQty;
@Schema(description = "邀请人用户ID")
private Long inviteBy;
@Schema(description = "释放时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime releaseTime;
@Schema(description = "加入时间")
private LocalDateTime inviteTime;
@Schema(description = "状态")
@Schema(description = "排序(数字越小越靠前)")
private Integer sortNumber;
@Schema(description = "状态, 0正常, 1冻结")
private Integer status;
@Schema(description = "是否删除, 0否, 1是")
@TableLogic
private Integer deleted;
@Schema(description = "租户id")
private Integer tenantId;

View File

@@ -0,0 +1,85 @@
package com.gxwebsoft.app.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 应用版本发布记录
*
* @author 科技小王子
* @since 2026-03-28 21:29:44
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Schema(name = "AppVersion对象", description = "应用版本发布记录")
public class AppVersion implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(description = "自增ID")
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@Schema(description = "关联应用ID")
private Long websiteId;
@Schema(description = "版本号,如 1.0.0")
private String versionNo;
@Schema(description = "版本名称")
private String versionName;
@Schema(description = "版本更新说明")
private String changelog;
@Schema(description = "安装包地址")
private String packageUrl;
@Schema(description = "包大小(字节)")
private Long packageSize;
@Schema(description = "包MD5/SHA256")
private String packageHash;
@Schema(description = "环境: development/staging/production")
private String env;
@Schema(description = "状态 0=构建中 1=已发布 2=已回滚 3=构建失败")
private Integer status;
@Schema(description = "是否为当前版本")
private Boolean isCurrent;
@Schema(description = "发布人用户ID")
private Long publishBy;
@Schema(description = "发布时间")
private LocalDateTime publishTime;
@Schema(description = "备注")
private String remark;
@Schema(description = "排序(数字越小越靠前)")
private Integer sortNumber;
@Schema(description = "用户ID")
private Integer userId;
@Schema(description = "租户id")
private Integer tenantId;
@Schema(description = "创建时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createTime;
@Schema(description = "修改时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime updateTime;
}

View File

@@ -0,0 +1,43 @@
package com.gxwebsoft.app.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gxwebsoft.app.entity.AppConfig;
import com.gxwebsoft.app.param.AppConfigParam;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* 应用配置表 Mapper
*
* @author 科技小王子
*/
@Mapper
public interface AppConfigMapper extends BaseMapper<AppConfig> {
/**
* 批量获取应用配置
*/
List<Map<String, Object>> selectConfigsByWebsiteId(Integer websiteId);
/**
* 分页查询
*
* @param page 分页对象
* @param param 查询参数
* @return List<AppConfig>
*/
List<AppConfig> selectPageRel(@Param("page") IPage<AppConfig> page,
@Param("param") AppConfigParam param);
/**
* 查询全部
*
* @param param 查询参数
* @return List<AppConfig>
*/
List<AppConfig> selectListRel(@Param("param") AppConfigParam param);
}

View File

@@ -0,0 +1,37 @@
package com.gxwebsoft.app.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gxwebsoft.app.entity.AppCredential;
import com.gxwebsoft.app.param.AppCredentialParam;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 应用密钥凭证Mapper
*
* @author 科技小王子
* @since 2026-03-28 21:29:43
*/
public interface AppCredentialMapper extends BaseMapper<AppCredential> {
/**
* 分页查询
*
* @param page 分页对象
* @param param 查询参数
* @return List<AppCredential>
*/
List<AppCredential> selectPageRel(@Param("page") IPage<AppCredential> page,
@Param("param") AppCredentialParam param);
/**
* 查询全部
*
* @param param 查询参数
* @return List<User>
*/
List<AppCredential> selectListRel(@Param("param") AppCredentialParam param);
}

View File

@@ -0,0 +1,37 @@
package com.gxwebsoft.app.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gxwebsoft.app.entity.AppEvent;
import com.gxwebsoft.app.param.AppEventParam;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 应用操作动态Mapper
*
* @author 科技小王子
* @since 2026-03-28 21:29:44
*/
public interface AppEventMapper extends BaseMapper<AppEvent> {
/**
* 分页查询
*
* @param page 分页对象
* @param param 查询参数
* @return List<AppEvent>
*/
List<AppEvent> selectPageRel(@Param("page") IPage<AppEvent> page,
@Param("param") AppEventParam param);
/**
* 查询全部
*
* @param param 查询参数
* @return List<User>
*/
List<AppEvent> selectListRel(@Param("param") AppEventParam param);
}

View File

@@ -0,0 +1,35 @@
package com.gxwebsoft.app.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gxwebsoft.app.entity.AppResource;
import com.gxwebsoft.app.param.AppResourceParam;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 开发者资源 Mapper
*
* @author 科技小王子
* @since 2026-03-31
*/
public interface AppResourceMapper extends BaseMapper<AppResource> {
/**
* 分页查询(关联应用名称)
*/
List<AppResource> selectPageRel(@Param("page") IPage<AppResource> page,
@Param("param") AppResourceParam param);
/**
* 查询全部列表(关联应用名称)
*/
List<AppResource> selectListRel(@Param("param") AppResourceParam param);
/**
* 统计各类型资源数量,返回 [{resourceType, cnt}]
*/
List<java.util.Map<String, Object>> countByType(@Param("userId") Integer userId,
@Param("tenantId") Integer tenantId);
}

View File

@@ -0,0 +1,11 @@
package com.gxwebsoft.app.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gxwebsoft.app.entity.AppTicket;
import org.apache.ibatis.annotations.Param;
/**
* 应用工单 Mapper
*/
public interface AppTicketMapper extends BaseMapper<AppTicket> {
}

View File

@@ -0,0 +1,10 @@
package com.gxwebsoft.app.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gxwebsoft.app.entity.AppTicketReply;
/**
* 工单回复 Mapper
*/
public interface AppTicketReplyMapper extends BaseMapper<AppTicketReply> {
}

View File

@@ -0,0 +1,37 @@
package com.gxwebsoft.app.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gxwebsoft.app.entity.AppUser;
import com.gxwebsoft.app.param.AppUserParam;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 应用成员Mapper
*
* @author 科技小王子
* @since 2026-03-28 21:29:44
*/
public interface AppUserMapper extends BaseMapper<AppUser> {
/**
* 分页查询
*
* @param page 分页对象
* @param param 查询参数
* @return List<AppUser>
*/
List<AppUser> selectPageRel(@Param("page") IPage<AppUser> page,
@Param("param") AppUserParam param);
/**
* 查询全部
*
* @param param 查询参数
* @return List<User>
*/
List<AppUser> selectListRel(@Param("param") AppUserParam param);
}

View File

@@ -0,0 +1,37 @@
package com.gxwebsoft.app.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gxwebsoft.app.entity.AppVersion;
import com.gxwebsoft.app.param.AppVersionParam;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 应用版本发布记录Mapper
*
* @author 科技小王子
* @since 2026-03-28 21:29:44
*/
public interface AppVersionMapper extends BaseMapper<AppVersion> {
/**
* 分页查询
*
* @param page 分页对象
* @param param 查询参数
* @return List<AppVersion>
*/
List<AppVersion> selectPageRel(@Param("page") IPage<AppVersion> page,
@Param("param") AppVersionParam param);
/**
* 查询全部
*
* @param param 查询参数
* @return List<User>
*/
List<AppVersion> selectListRel(@Param("param") AppVersionParam param);
}

View File

@@ -0,0 +1,66 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.gxwebsoft.app.mapper.AppConfigMapper">
<!-- 关联查询sql -->
<sql id="selectSql">
SELECT a.*
FROM app_config a
<where>
a.deleted = 0
<if test="param.configId != null">
AND a.config_id = #{param.configId}
</if>
<if test="param.websiteId != null">
AND a.website_id = #{param.websiteId}
</if>
<if test="param.configKey != null and param.configKey != ''">
AND a.config_key LIKE CONCAT('%', #{param.configKey}, '%')
</if>
<if test="param.configType != null and param.configType != ''">
AND a.config_type = #{param.configType}
</if>
<if test="param.isSecret != null">
AND a.is_secret = #{param.isSecret}
</if>
<if test="param.tenantId != null">
AND a.tenant_id = #{param.tenantId}
</if>
<if test="param.createTimeStart != null">
AND a.create_time &gt;= #{param.createTimeStart}
</if>
<if test="param.createTimeEnd != null">
AND a.create_time &lt;= #{param.createTimeEnd}
</if>
<if test="param.keywords != null and param.keywords != ''">
AND a.config_key LIKE CONCAT('%', #{param.keywords}, '%')
</if>
</where>
</sql>
<!-- 分页查询 -->
<select id="selectPageRel" resultType="com.gxwebsoft.app.entity.AppConfig">
<include refid="selectSql"></include>
</select>
<!-- 查询全部 -->
<select id="selectListRel" resultType="com.gxwebsoft.app.entity.AppConfig">
<include refid="selectSql"></include>
</select>
<!-- 批量获取应用配置(自动解密) -->
<select id="selectConfigsByWebsiteId" resultType="java.util.HashMap">
SELECT
config_key as configKey,
config_value as configValue,
config_type as configType,
is_encrypted as isEncrypted,
is_secret as isSecret,
description
FROM app_config
WHERE website_id = #{websiteId}
AND deleted = 0
ORDER BY config_type, sort_number, config_id
</select>
</mapper>

View File

@@ -0,0 +1,71 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.gxwebsoft.app.mapper.AppCredentialMapper">
<!-- 关联查询sql -->
<sql id="selectSql">
SELECT a.*, w.website_name, w.website_code, w.website_icon
FROM app_credential a
LEFT JOIN cms_website w ON a.website_id = w.website_id AND w.deleted = 0
<where>
<if test="param.id != null">
AND a.id = #{param.id}
</if>
<if test="param.websiteId != null">
AND a.website_id = #{param.websiteId}
</if>
<if test="param.name != null and param.name != ''">
AND a.name LIKE CONCAT('%', #{param.name}, '%')
</if>
<if test="param.appId != null and param.appId != ''">
AND a.app_id = #{param.appId}
</if>
<if test="param.type != null and param.type != ''">
AND a.type = #{param.type}
</if>
<if test="param.scopes != null and param.scopes != ''">
AND a.scopes LIKE CONCAT('%', #{param.scopes}, '%')
</if>
<if test="param.remark != null and param.remark != ''">
AND a.remark LIKE CONCAT('%', #{param.remark}, '%')
</if>
<if test="param.sortNumber != null">
AND a.sort_number = #{param.sortNumber}
</if>
<if test="param.status != null">
AND a.status = #{param.status}
</if>
<if test="param.deleted != null">
AND a.deleted = #{param.deleted}
</if>
<if test="param.deleted == null">
AND a.deleted = 0
</if>
<if test="param.userId != null">
AND a.user_id = #{param.userId}
</if>
<if test="param.createTimeStart != null">
AND a.create_time &gt;= #{param.createTimeStart}
</if>
<if test="param.createTimeEnd != null">
AND a.create_time &lt;= #{param.createTimeEnd}
</if>
<if test="param.keywords != null and param.keywords != ''">
AND (a.name LIKE CONCAT('%', #{param.keywords}, '%')
OR a.app_id LIKE CONCAT('%', #{param.keywords}, '%')
)
</if>
</where>
</sql>
<!-- 分页查询 -->
<select id="selectPageRel" resultType="com.gxwebsoft.app.entity.AppCredential">
<include refid="selectSql"></include>
</select>
<!-- 查询全部 -->
<select id="selectListRel" resultType="com.gxwebsoft.app.entity.AppCredential">
<include refid="selectSql"></include>
</select>
</mapper>

View File

@@ -0,0 +1,66 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.gxwebsoft.app.mapper.AppEventMapper">
<!-- 关联查询sql -->
<sql id="selectSql">
SELECT a.*, w.website_name, w.website_code, w.website_icon
FROM app_event a
LEFT JOIN cms_website w ON a.website_id = w.website_id AND w.deleted = 0
<where>
<if test="param.id != null">
AND a.id = #{param.id}
</if>
<if test="param.websiteId != null">
AND a.website_id = #{param.websiteId}
</if>
<if test="param.eventType != null and param.eventType != ''">
AND a.event_type = #{param.eventType}
</if>
<if test="param.title != null and param.title != ''">
AND a.title LIKE CONCAT('%', #{param.title}, '%')
</if>
<if test="param.operatorId != null">
AND a.operator_id = #{param.operatorId}
</if>
<if test="param.refId != null">
AND a.ref_id = #{param.refId}
</if>
<if test="param.refType != null and param.refType != ''">
AND a.ref_type = #{param.refType}
</if>
<if test="param.status != null">
AND a.status = #{param.status}
</if>
<if test="param.userId != null">
AND a.user_id = #{param.userId}
</if>
<if test="param.tenantId != null">
AND a.tenant_id = #{param.tenantId}
</if>
<if test="param.createTimeStart != null">
AND a.create_time &gt;= #{param.createTimeStart}
</if>
<if test="param.createTimeEnd != null">
AND a.create_time &lt;= #{param.createTimeEnd}
</if>
<if test="param.keywords != null and param.keywords != ''">
AND (a.title LIKE CONCAT('%', #{param.keywords}, '%')
OR a.content LIKE CONCAT('%', #{param.keywords}, '%')
)
</if>
</where>
ORDER BY a.create_time DESC
</sql>
<!-- 分页查询 -->
<select id="selectPageRel" resultType="com.gxwebsoft.app.entity.AppEvent">
<include refid="selectSql"></include>
</select>
<!-- 查询全部 -->
<select id="selectListRel" resultType="com.gxwebsoft.app.entity.AppEvent">
<include refid="selectSql"></include>
</select>
</mapper>

View File

@@ -0,0 +1,75 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.gxwebsoft.app.mapper.AppResourceMapper">
<!-- 关联查询 SQL -->
<sql id="selectSql">
SELECT a.*, w.website_name
FROM app_resource a
LEFT JOIN cms_website w ON a.website_id = w.website_id AND w.deleted = 0
<where>
a.deleted = 0
<if test="param.resourceId != null">
AND a.resource_id = #{param.resourceId}
</if>
<if test="param.resourceType != null and param.resourceType != ''">
AND a.resource_type = #{param.resourceType}
</if>
<if test="param.websiteId != null">
AND a.website_id = #{param.websiteId}
</if>
<if test="param.provider != null and param.provider != ''">
AND a.provider = #{param.provider}
</if>
<if test="param.status != null and param.status != ''">
AND a.status = #{param.status}
</if>
<if test="param.userId != null">
AND a.user_id = #{param.userId}
</if>
<if test="param.tenantId != null">
AND a.tenant_id = #{param.tenantId}
</if>
<if test="param.keywords != null and param.keywords != ''">
AND (
a.name LIKE CONCAT('%', #{param.keywords}, '%')
OR a.ip LIKE CONCAT('%', #{param.keywords}, '%')
OR a.domain LIKE CONCAT('%', #{param.keywords}, '%')
OR a.host LIKE CONCAT('%', #{param.keywords}, '%')
)
</if>
<if test="param.createTimeStart != null">
AND a.create_time &gt;= #{param.createTimeStart}
</if>
<if test="param.createTimeEnd != null">
AND a.create_time &lt;= #{param.createTimeEnd}
</if>
</where>
ORDER BY a.create_time DESC
</sql>
<!-- 分页查询 -->
<select id="selectPageRel" resultType="com.gxwebsoft.app.entity.AppResource">
<include refid="selectSql"/>
</select>
<!-- 查询全部 -->
<select id="selectListRel" resultType="com.gxwebsoft.app.entity.AppResource">
<include refid="selectSql"/>
</select>
<!-- 按类型统计数量 -->
<select id="countByType" resultType="java.util.Map">
SELECT resource_type AS resourceType, COUNT(*) AS cnt
FROM app_resource
WHERE deleted = 0
<if test="userId != null">
AND user_id = #{userId}
</if>
<if test="tenantId != null">
AND tenant_id = #{tenantId}
</if>
GROUP BY resource_type
</select>
</mapper>

View File

@@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.gxwebsoft.app.mapper.AppUserMapper">
<!-- 关联查询sql已移除跨库 JOIN gxwebsoft_core.sys_user用户信息从冗余字段读取 -->
<sql id="selectSql">
SELECT a.*, w.website_name, w.website_code, w.website_icon
FROM app_user a
LEFT JOIN cms_website w ON a.website_id = w.website_id AND w.deleted = 0
<where>
<if test="param.id != null">
AND a.id = #{param.id}
</if>
<if test="param.websiteId != null">
AND a.website_id = #{param.websiteId}
</if>
<if test="param.userId != null">
AND a.user_id = #{param.userId}
</if>
<if test="param.username != null and param.username != ''">
AND (a.username LIKE CONCAT('%', #{param.username}, '%')
OR a.nickname LIKE CONCAT('%', #{param.username}, '%'))
</if>
<if test="param.role != null and param.role != ''">
AND a.role = #{param.role}
</if>
<if test="param.inviteBy != null">
AND a.invite_by = #{param.inviteBy}
</if>
<if test="param.sortNumber != null">
AND a.sort_number = #{param.sortNumber}
</if>
<if test="param.status != null">
AND a.status = #{param.status}
</if>
<if test="param.tenantId != null">
AND a.tenant_id = #{param.tenantId}
</if>
<if test="param.createTimeStart != null">
AND a.create_time &gt;= #{param.createTimeStart}
</if>
<if test="param.createTimeEnd != null">
AND a.create_time &lt;= #{param.createTimeEnd}
</if>
<if test="param.keywords != null and param.keywords != ''">
AND (a.username LIKE CONCAT('%', #{param.keywords}, '%')
OR a.nickname LIKE CONCAT('%', #{param.keywords}, '%'))
</if>
</where>
</sql>
<!-- 分页查询 -->
<select id="selectPageRel" resultType="com.gxwebsoft.app.entity.AppUser">
<include refid="selectSql"></include>
</select>
<!-- 查询全部 -->
<select id="selectListRel" resultType="com.gxwebsoft.app.entity.AppUser">
<include refid="selectSql"></include>
</select>
</mapper>

View File

@@ -0,0 +1,66 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.gxwebsoft.app.mapper.AppVersionMapper">
<!-- 关联查询sql -->
<sql id="selectSql">
SELECT a.*, w.website_name, w.website_code, w.website_icon
FROM app_version a
LEFT JOIN cms_website w ON a.website_id = w.website_id AND w.deleted = 0
<where>
<if test="param.id != null">
AND a.id = #{param.id}
</if>
<if test="param.websiteId != null">
AND a.website_id = #{param.websiteId}
</if>
<if test="param.versionNo != null and param.versionNo != ''">
AND a.version_no = #{param.versionNo}
</if>
<if test="param.versionName != null and param.versionName != ''">
AND a.version_name LIKE CONCAT('%', #{param.versionName}, '%')
</if>
<if test="param.env != null and param.env != ''">
AND a.env = #{param.env}
</if>
<if test="param.status != null">
AND a.status = #{param.status}
</if>
<if test="param.isCurrent != null">
AND a.is_current = #{param.isCurrent}
</if>
<if test="param.publishBy != null">
AND a.publish_by = #{param.publishBy}
</if>
<if test="param.userId != null">
AND a.user_id = #{param.userId}
</if>
<if test="param.tenantId != null">
AND a.tenant_id = #{param.tenantId}
</if>
<if test="param.createTimeStart != null">
AND a.create_time &gt;= #{param.createTimeStart}
</if>
<if test="param.createTimeEnd != null">
AND a.create_time &lt;= #{param.createTimeEnd}
</if>
<if test="param.keywords != null and param.keywords != ''">
AND (a.version_no LIKE CONCAT('%', #{param.keywords}, '%')
OR a.version_name LIKE CONCAT('%', #{param.keywords}, '%')
OR a.changelog LIKE CONCAT('%', #{param.keywords}, '%')
)
</if>
</where>
</sql>
<!-- 分页查询 -->
<select id="selectPageRel" resultType="com.gxwebsoft.app.entity.AppVersion">
<include refid="selectSql"></include>
</select>
<!-- 查询全部 -->
<select id="selectListRel" resultType="com.gxwebsoft.app.entity.AppVersion">
<include refid="selectSql"></include>
</select>
</mapper>

View File

@@ -0,0 +1,38 @@
package com.gxwebsoft.app.param;
import com.gxwebsoft.common.core.web.BaseParam;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 应用配置表查询参数
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class AppConfigParam extends BaseParam {
/**
* 配置ID
*/
private Integer configId;
/**
* 应用ID
*/
private Integer websiteId;
/**
* 配置键
*/
private String configKey;
/**
* 配置类型
*/
private String configType;
/**
* 是否敏感信息
*/
private Integer isSecret;
}

View File

@@ -1,52 +1,50 @@
package com.gxwebsoft.credit.param;
package com.gxwebsoft.app.param;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.gxwebsoft.common.core.annotation.QueryField;
import com.gxwebsoft.common.core.annotation.QueryType;
import com.gxwebsoft.common.core.web.BaseParam;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 历史法定代表人查询参数
* 应用密钥凭证查询参数
*
* @author 科技小王子
* @since 2026-01-07 13:52:14
* @since 2026-03-28 21:29:43
*/
@Data
@EqualsAndHashCode(callSuper = false)
@JsonInclude(JsonInclude.Include.NON_NULL)
@Schema(name = "CreditHistoricalLegalPersonParam对象", description = "历史法定代表人查询参数")
public class CreditHistoricalLegalPersonParam extends BaseParam {
@Schema(name = "AppCredentialParam对象", description = "应用密钥凭证查询参数")
public class AppCredentialParam extends BaseParam {
private static final long serialVersionUID = 1L;
@Schema(description = "ID")
@Schema(description = "自增ID")
@QueryField(type = QueryType.EQ)
private Integer id;
private Long id;
@Schema(description = "名称")
@Schema(description = "关联应用ID")
@QueryField(type = QueryType.EQ)
private Long websiteId;
@Schema(description = "凭证名称,如生产环境密钥")
private String name;
@Schema(description = "任职日期")
private String registerDate;
@Schema(description = "App ID公开")
@QueryField(type = QueryType.EQ)
private String appId;
@Schema(description = "卸任日期")
private String publicDate;
@Schema(description = "凭证类型: server/client/webhook")
@QueryField(type = QueryType.EQ)
private String type;
@Schema(description = "链接")
private String url;
@Schema(description = "权限范围,空格分隔")
private String scopes;
@Schema(description = "备注")
private String comments;
@Schema(description = "企业ID")
@QueryField(type = QueryType.EQ)
private Integer companyId;
@Schema(description = "是否推荐")
@QueryField(type = QueryType.EQ)
private Integer recommend;
private String remark;
@Schema(description = "排序(数字越小越靠前)")
@QueryField(type = QueryType.EQ)

View File

@@ -0,0 +1,63 @@
package com.gxwebsoft.app.param;
import com.gxwebsoft.common.core.annotation.QueryField;
import com.gxwebsoft.common.core.annotation.QueryType;
import com.gxwebsoft.common.core.web.BaseParam;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 应用操作动态查询参数
*
* @author 科技小王子
* @since 2026-03-28 21:29:44
*/
@Data
@EqualsAndHashCode(callSuper = false)
@JsonInclude(JsonInclude.Include.NON_NULL)
@Schema(name = "AppEventParam对象", description = "应用操作动态查询参数")
public class AppEventParam extends BaseParam {
private static final long serialVersionUID = 1L;
@Schema(description = "自增ID")
@QueryField(type = QueryType.EQ)
private Long id;
@Schema(description = "关联应用ID")
@QueryField(type = QueryType.EQ)
private Long websiteId;
@Schema(description = "事件类型: created/published/updated/domain_bound/member_added/status_changed")
@QueryField(type = QueryType.EQ)
private String eventType;
@Schema(description = "事件标题(模糊)")
private String title;
@Schema(description = "操作人用户ID")
@QueryField(type = QueryType.EQ)
private Long operatorId;
@Schema(description = "关联ID如版本ID")
@QueryField(type = QueryType.EQ)
private Long refId;
@Schema(description = "关联类型")
@QueryField(type = QueryType.EQ)
private String refType;
@Schema(description = "状态, 0正常, 1冻结")
@QueryField(type = QueryType.EQ)
private Integer status;
@Schema(description = "用户ID")
@QueryField(type = QueryType.EQ)
private Integer userId;
@Schema(description = "租户ID")
@QueryField(type = QueryType.EQ)
private Integer tenantId;
}

View File

@@ -1,54 +1,54 @@
package com.gxwebsoft.glt.param;
package com.gxwebsoft.app.param;
import java.math.BigDecimal;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.gxwebsoft.common.core.annotation.QueryField;
import com.gxwebsoft.common.core.annotation.QueryType;
import com.gxwebsoft.common.core.web.BaseParam;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 水票释放查询参数
* 开发者资源查询参数
*
* @author 科技小王子
* @since 2026-02-03 18:55:55
* @since 2026-03-31
*/
@Data
@EqualsAndHashCode(callSuper = false)
@JsonInclude(JsonInclude.Include.NON_NULL)
@Schema(name = "GltUserTicketReleaseParam对象", description = "水票释放查询参数")
public class GltUserTicketReleaseParam extends BaseParam {
@Schema(name = "AppResourceParam对象", description = "开发者资源查询参数")
public class AppResourceParam extends BaseParam {
private static final long serialVersionUID = 1L;
@Schema(description = "资源ID")
@QueryField(type = QueryType.EQ)
private Integer id;
private Long resourceId;
@Schema(description = "水票ID")
private Integer userTicketId;
@Schema(description = "用户ID")
@Schema(description = "资源类型: server/database/storage/domain/ssl")
@QueryField(type = QueryType.EQ)
private Integer userId;
private String resourceType;
@Schema(description = "周期编号")
@Schema(description = "关联应用ID")
@QueryField(type = QueryType.EQ)
private Integer periodNo;
private Long websiteId;
@Schema(description = "释放数量")
@Schema(description = "服务商")
@QueryField(type = QueryType.EQ)
private Integer releaseQty;
@Schema(description = "释放时间")
private String releaseTime;
private String provider;
@Schema(description = "状态")
@QueryField(type = QueryType.EQ)
private Integer status;
private String status;
@Schema(description = "是否删除, 0否, 1是")
@Schema(description = "所属用户ID")
@QueryField(type = QueryType.EQ)
private Integer deleted;
private Integer userId;
@Schema(description = "租户ID")
@QueryField(type = QueryType.EQ)
private Integer tenantId;
@Schema(description = "关键词(名称/IP/域名/Host模糊搜索")
private String keywords;
}

View File

@@ -0,0 +1,33 @@
package com.gxwebsoft.app.param;
import com.gxwebsoft.common.core.web.PageParam;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 工单查询参数
*/
@Data
@EqualsAndHashCode(callSuper = true)
@Schema(description = "工单查询参数")
public class AppTicketParam extends PageParam {
@Schema(description = "关联应用ID")
private Long websiteId;
@Schema(description = "工单状态")
private String status;
@Schema(description = "工单分类")
private String category;
@Schema(description = "优先级")
private String priority;
@Schema(description = "处理人ID传0=未分配)")
private Integer assigneeId;
@Schema(description = "关键词(标题/工单编号)")
private String keywords;
}

View File

@@ -1,6 +1,5 @@
package com.gxwebsoft.dormitory.param;
package com.gxwebsoft.app.param;
import java.math.BigDecimal;
import com.gxwebsoft.common.core.annotation.QueryField;
import com.gxwebsoft.common.core.annotation.QueryType;
import com.gxwebsoft.common.core.web.BaseParam;
@@ -10,53 +9,51 @@ import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 宿舍记录查询参数
* 应用成员查询参数
*
* @author 科技小王子
* @since 2025-10-03 10:49:27
* @since 2026-03-28 21:29:44
*/
@Data
@EqualsAndHashCode(callSuper = false)
@JsonInclude(JsonInclude.Include.NON_NULL)
@Schema(description = "宿舍记录查询参数")
public class DormitoryRecordParam extends BaseParam {
@Schema(name = "AppUserParam对象", description = "应用成员查询参数")
public class AppUserParam extends BaseParam {
private static final long serialVersionUID = 1L;
@Schema(description = "ID")
@Schema(description = "自增ID")
@QueryField(type = QueryType.EQ)
private Integer id;
private Long id;
@Schema(description = "宿舍名称")
private String name;
@Schema(description = "编号")
private String code;
@Schema(description = "楼栋ID")
@Schema(description = "关联应用ID")
@QueryField(type = QueryType.EQ)
private Integer buildingId;
private Long websiteId;
@Schema(description = "楼层ID")
@Schema(description = "用户ID")
@QueryField(type = QueryType.EQ)
private Integer floorId;
private Integer userId;
@Schema(description = "床位数")
@QueryField(type = QueryType.EQ)
private Integer beds;
@Schema(description = "用户名(模糊搜索)")
private String username;
@Schema(description = "独立卫生间")
@Schema(description = "角色: owner/admin/developer/viewer")
@QueryField(type = QueryType.EQ)
private Boolean toilet;
private String role;
@Schema(description = "邀请人用户ID")
@QueryField(type = QueryType.EQ)
private Long inviteBy;
@Schema(description = "排序(数字越小越靠前)")
@QueryField(type = QueryType.EQ)
private Integer sortNumber;
@Schema(description = "备注")
private String comments;
@Schema(description = "状态, 0正常, 1冻结")
@QueryField(type = QueryType.EQ)
private Integer status;
@Schema(description = "租户ID")
@QueryField(type = QueryType.EQ)
private Integer tenantId;
}

View File

@@ -0,0 +1,63 @@
package com.gxwebsoft.app.param;
import com.gxwebsoft.common.core.annotation.QueryField;
import com.gxwebsoft.common.core.annotation.QueryType;
import com.gxwebsoft.common.core.web.BaseParam;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 应用版本发布记录查询参数
*
* @author 科技小王子
* @since 2026-03-28 21:29:44
*/
@Data
@EqualsAndHashCode(callSuper = false)
@JsonInclude(JsonInclude.Include.NON_NULL)
@Schema(name = "AppVersionParam对象", description = "应用版本发布记录查询参数")
public class AppVersionParam extends BaseParam {
private static final long serialVersionUID = 1L;
@Schema(description = "自增ID")
@QueryField(type = QueryType.EQ)
private Long id;
@Schema(description = "关联应用ID")
@QueryField(type = QueryType.EQ)
private Long websiteId;
@Schema(description = "版本号,如 1.0.0")
@QueryField(type = QueryType.EQ)
private String versionNo;
@Schema(description = "版本名称(模糊)")
private String versionName;
@Schema(description = "环境: development/staging/production")
@QueryField(type = QueryType.EQ)
private String env;
@Schema(description = "状态 0=构建中 1=已发布 2=已回滚 3=构建失败")
@QueryField(type = QueryType.EQ)
private Integer status;
@Schema(description = "是否为当前版本")
@QueryField(type = QueryType.EQ)
private Boolean isCurrent;
@Schema(description = "发布人用户ID")
@QueryField(type = QueryType.EQ)
private Long publishBy;
@Schema(description = "用户ID")
@QueryField(type = QueryType.EQ)
private Integer userId;
@Schema(description = "租户ID")
@QueryField(type = QueryType.EQ)
private Integer tenantId;
}

View File

@@ -0,0 +1,58 @@
package com.gxwebsoft.app.service;
import com.gxwebsoft.app.entity.AppConfig;
import com.gxwebsoft.app.param.AppConfigParam;
import java.util.List;
import java.util.Map;
/**
* 应用配置表 Service
*/
public interface AppConfigService {
/**
* 分页查询应用配置
*/
List<AppConfig> page(AppConfigParam param);
/**
* 获取应用配置列表
*/
List<AppConfig> list(AppConfigParam param);
/**
* 根据应用ID获取配置映射自动解密
*/
Map<String, Object> getConfigsByWebsiteId(Integer websiteId);
/**
* 获取单个配置值
*/
String getConfigValue(Integer websiteId, String configKey);
/**
* 保存配置
*/
void saveConfig(AppConfig config);
/**
* 批量保存配置
*/
void batchSaveConfig(Integer websiteId, List<AppConfig> configs);
/**
* 更新配置
*/
void updateConfig(AppConfig config);
/**
* 删除配置
*/
void deleteConfig(Integer configId);
/**
* 根据应用ID删除所有配置
*/
void deleteByWebsiteId(Integer websiteId);
}

View File

@@ -0,0 +1,57 @@
package com.gxwebsoft.app.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.app.entity.AppCredential;
import com.gxwebsoft.app.param.AppCredentialParam;
import java.util.List;
/**
* 应用密钥凭证Service
*
* @author 科技小王子
* @since 2026-03-28 21:29:43
*/
public interface AppCredentialService extends IService<AppCredential> {
/**
* 分页关联查询
*/
PageResult<AppCredential> pageRel(AppCredentialParam param);
/**
* 关联查询全部
*/
List<AppCredential> listRel(AppCredentialParam param);
/**
* 根据id查询
*/
AppCredential getByIdRel(Integer id);
/**
* 创建凭证(自动生成 appId 和 appSecret
*
* @param credential 凭证基础信息
* @return 包含明文 appSecret 的凭证对象(仅此次返回,之后不再展示)
*/
AppCredential createCredential(AppCredential credential);
/**
* 重置密钥(重新生成 appSecret
*
* @param id 凭证ID
* @return 包含新明文 appSecret 的凭证对象
*/
AppCredential resetSecret(Long id);
/**
* 禁用/启用凭证
*
* @param id 凭证ID
* @param status 0=正常 1=冻结
*/
boolean updateStatus(Long id, Integer status);
}

View File

@@ -0,0 +1,60 @@
package com.gxwebsoft.app.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.app.entity.AppEvent;
import com.gxwebsoft.app.param.AppEventParam;
import java.util.List;
/**
* 应用操作动态Service
*
* @author 科技小王子
* @since 2026-03-28 21:29:44
*/
public interface AppEventService extends IService<AppEvent> {
/**
* 分页关联查询
*/
PageResult<AppEvent> pageRel(AppEventParam param);
/**
* 关联查询全部
*/
List<AppEvent> listRel(AppEventParam param);
/**
* 根据id查询
*/
AppEvent getByIdRel(Integer id);
/**
* 记录应用事件(便捷方法,供其他模块调用)
*
* @param websiteId 应用ID
* @param eventType 事件类型created/published/updated/domain_bound/member_added/status_changed 等)
* @param title 事件标题
* @param content 详细描述
* @param operatorId 操作人用户ID
* @param operatorName 操作人名称
* @param refId 关联记录ID如版本ID
* @param refType 关联记录类型
*/
void logEvent(Long websiteId, String eventType, String title, String content,
Long operatorId, String operatorName, Long refId, String refType);
/**
* 快捷记录事件(无关联记录)
*/
void logEvent(Long websiteId, String eventType, String title, Long operatorId, String operatorName);
/**
* 获取指定应用的最新一条事件(用于卡片"最新动态"展示)
*
* @param websiteId 应用ID
*/
AppEvent getLatestEvent(Long websiteId);
}

View File

@@ -0,0 +1,39 @@
package com.gxwebsoft.app.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.gxwebsoft.app.entity.AppResource;
import com.gxwebsoft.app.param.AppResourceParam;
import com.gxwebsoft.common.core.web.PageResult;
import java.util.List;
import java.util.Map;
/**
* 开发者资源 Service
*
* @author 科技小王子
* @since 2026-03-31
*/
public interface AppResourceService extends IService<AppResource> {
/** 分页查询(关联应用名称) */
PageResult<AppResource> pageRel(AppResourceParam param);
/** 列表查询 */
List<AppResource> listRel(AppResourceParam param);
/** 详情(关联查询) */
AppResource getByIdRel(Long resourceId);
/** 新增资源 */
AppResource addResource(AppResource resource, Integer userId);
/** 更新资源 */
AppResource updateResource(AppResource resource);
/** 删除资源(逻辑删除) */
void removeResource(Long resourceId, Integer userId);
/** 按资源类型统计数量 [{resourceType, cnt}] */
Map<String, Long> countByType(Integer userId, Integer tenantId);
}

View File

@@ -0,0 +1,46 @@
package com.gxwebsoft.app.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.gxwebsoft.app.entity.AppTicket;
import com.gxwebsoft.app.entity.AppTicketReply;
import com.gxwebsoft.app.param.AppTicketParam;
import com.gxwebsoft.common.core.web.PageResult;
import java.util.List;
import java.util.Map;
/**
* 应用工单 Service
*/
public interface AppTicketService extends IService<AppTicket> {
/** 客户端:查自己提交的工单(分页) */
PageResult<AppTicket> myPage(AppTicketParam param, Integer userId);
/** 技术端:查询所有工单(分页) */
PageResult<AppTicket> allPage(AppTicketParam param);
/** 提交工单(自动分配) */
AppTicket submit(AppTicket ticket, Integer userId);
/** 更新状态(技术人员操作) */
void updateStatus(Long ticketId, String status, Integer operatorId);
/** 分配处理人 */
void assign(Long ticketId, Integer assigneeId);
/** 关闭工单(提交人操作) */
void closeByUser(Long ticketId, Integer userId);
/** 获取工单回复列表 */
List<AppTicketReply> getReplies(Long ticketId);
/** 添加回复 */
AppTicketReply addReply(AppTicketReply reply, Integer userId);
/** 统计数据 */
Map<String, Long> stats(Long websiteId, Integer userId);
/** 获取技术人员列表角色developer/admin 的应用成员) */
List<Map<String, Object>> getTechStaffList();
}

View File

@@ -0,0 +1,68 @@
package com.gxwebsoft.app.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.app.entity.AppUser;
import com.gxwebsoft.app.param.AppUserParam;
import java.util.List;
/**
* 应用成员Service
*
* @author 科技小王子
* @since 2026-03-28 21:29:44
*/
public interface AppUserService extends IService<AppUser> {
/**
* 分页关联查询
*/
PageResult<AppUser> pageRel(AppUserParam param);
/**
* 关联查询全部
*/
List<AppUser> listRel(AppUserParam param);
/**
* 根据id查询
*/
AppUser getByIdRel(Integer id);
/**
* 邀请成员加入应用
*
* @param websiteId 应用ID
* @param userId 被邀请的用户ID
* @param role 分配的角色
* @param inviteBy 邀请人用户ID
* @return 成员记录
*/
AppUser inviteUser(Long websiteId, Integer userId, String role, Integer inviteBy);
/**
* 修改成员角色
*
* @param id 成员记录ID
* @param role 新角色
*/
boolean updateRole(Long id, String role);
/**
* 检查用户是否已是应用成员
*
* @param websiteId 应用ID
* @param userId 用户ID
*/
boolean isMember(Long websiteId, Integer userId);
/**
* 根据手机号查找系统用户(用于手机号邀请)
*
* @param phone 手机号
* @return 系统用户,不存在返回 null
*/
com.gxwebsoft.common.system.entity.User findUserByPhone(String phone);
}

View File

@@ -0,0 +1,56 @@
package com.gxwebsoft.app.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.app.entity.AppVersion;
import com.gxwebsoft.app.param.AppVersionParam;
import java.util.List;
/**
* 应用版本发布记录Service
*
* @author 科技小王子
* @since 2026-03-28 21:29:44
*/
public interface AppVersionService extends IService<AppVersion> {
/**
* 分页关联查询
*/
PageResult<AppVersion> pageRel(AppVersionParam param);
/**
* 关联查询全部
*/
List<AppVersion> listRel(AppVersionParam param);
/**
* 根据id查询
*/
AppVersion getByIdRel(Integer id);
/**
* 发布版本(将此版本设为当前版本,其他版本 isCurrent=false
*
* @param id 版本ID
* @param publishBy 发布人用户ID
*/
boolean publish(Long id, Integer publishBy);
/**
* 回滚到指定版本(将此版本设为当前版本,当前版本标为已回滚)
*
* @param id 要回滚到的版本ID
* @param publishBy 操作人用户ID
*/
boolean rollback(Long id, Integer publishBy);
/**
* 获取指定应用的当前版本
*
* @param websiteId 应用ID
*/
AppVersion getCurrentVersion(Long websiteId);
}

View File

@@ -0,0 +1,270 @@
package com.gxwebsoft.app.service.impl;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.app.entity.AppConfig;
import com.gxwebsoft.app.mapper.AppConfigMapper;
import com.gxwebsoft.app.param.AppConfigParam;
import com.gxwebsoft.app.service.AppConfigService;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 应用配置表 Service 实现类
*
* @author 科技小王子
*/
@Slf4j
@Service
public class AppConfigServiceImpl extends ServiceImpl<AppConfigMapper, AppConfig> implements AppConfigService {
@Resource
private UserService userService;
/**
* 配置加密密钥(从配置文件读取)
*/
@Value("${app.config.encrypt-key:GXWebsoft2024!@#$}")
private String encryptKey;
/**
* 分页查询应用配置
*/
@Override
public List<AppConfig> page(AppConfigParam param) {
PageParam<AppConfig, AppConfigParam> page = new PageParam<>(param);
page.setDefaultOrder("sort_number asc, config_id asc");
List<AppConfig> list = baseMapper.selectPageRel(page, param);
return page.sortRecords(list);
}
/**
* 分页查询应用配置返回PageResult
*/
public PageResult<AppConfig> pageRel(AppConfigParam param) {
PageParam<AppConfig, AppConfigParam> page = new PageParam<>(param);
page.setDefaultOrder("sort_number asc, config_id asc");
List<AppConfig> list = baseMapper.selectPageRel(page, param);
return new PageResult<>(list, page.getTotal());
}
/**
* 获取应用配置列表
*/
@Override
public List<AppConfig> list(AppConfigParam param) {
List<AppConfig> list = baseMapper.selectListRel(param);
PageParam<AppConfig, AppConfigParam> page = new PageParam<>();
page.setDefaultOrder("sort_number asc, config_id asc");
return page.sortRecords(list);
}
/**
* 根据应用ID获取配置映射自动解密
*/
@Override
public Map<String, Object> getConfigsByWebsiteId(Integer websiteId) {
List<Map<String, Object>> configs = baseMapper.selectConfigsByWebsiteId(websiteId);
Map<String, Object> result = new HashMap<>();
for (Map<String, Object> config : configs) {
String configKey = (String) config.get("configKey");
Object configValue = config.get("configValue");
Integer isEncrypted = (Integer) config.get("isEncrypted");
// 解密
if (isEncrypted != null && isEncrypted == 1 && configValue != null) {
try {
configValue = decrypt((String) configValue);
} catch (Exception e) {
log.error("配置解密失败: {}", configKey, e);
}
}
result.put(configKey, configValue);
}
return result;
}
/**
* 获取单个配置值
*/
@Override
public String getConfigValue(Integer websiteId, String configKey) {
LambdaQueryWrapper<AppConfig> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(AppConfig::getWebsiteId, websiteId);
wrapper.eq(AppConfig::getConfigKey, configKey);
AppConfig config = getOne(wrapper);
if (config == null || config.getConfigValue() == null) {
return null;
}
// 解密
if (config.getIsEncrypted() != null && config.getIsEncrypted() == 1) {
return decrypt(config.getConfigValue());
}
return config.getConfigValue();
}
/**
* 保存配置
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void saveConfig(AppConfig config) {
// 设置租户ID
Integer tenantId = getCurrentTenantId();
if (tenantId != null) {
config.setTenantId(Long.valueOf(tenantId));
}
// 加密敏感信息
if (config.getIsEncrypted() != null && config.getIsEncrypted() == 1 && config.getConfigValue() != null) {
config.setConfigValue(encrypt(config.getConfigValue()));
}
save(config);
}
/**
* 批量保存配置
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void batchSaveConfig(Integer websiteId, List<AppConfig> configs) {
// 设置租户ID
Integer tenantId = getCurrentTenantId();
if (tenantId != null) {
for (AppConfig config : configs) {
config.setTenantId(Long.valueOf(tenantId));
}
}
// 先删除该应用的所有配置
remove(new LambdaQueryWrapper<AppConfig>()
.eq(AppConfig::getWebsiteId, websiteId));
// 批量插入新配置
for (AppConfig config : configs) {
config.setWebsiteId(websiteId);
// 加密敏感信息
if (config.getIsEncrypted() != null && config.getIsEncrypted() == 1 && config.getConfigValue() != null) {
config.setConfigValue(encrypt(config.getConfigValue()));
}
save(config);
}
}
/**
* 更新配置
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void updateConfig(AppConfig config) {
// 加密敏感信息
if (config.getIsEncrypted() != null && config.getIsEncrypted() == 1 && config.getConfigValue() != null) {
config.setConfigValue(encrypt(config.getConfigValue()));
}
updateById(config);
}
/**
* 删除配置
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteConfig(Integer configId) {
removeById(configId);
}
/**
* 根据应用ID删除所有配置
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteByWebsiteId(Integer websiteId) {
remove(new LambdaQueryWrapper<AppConfig>()
.eq(AppConfig::getWebsiteId, websiteId));
}
/**
* 构建查询条件
*/
private LambdaQueryWrapper<AppConfig> buildQueryWrapper(AppConfigParam param) {
LambdaQueryWrapper<AppConfig> wrapper = new LambdaQueryWrapper<>();
if (param.getConfigId() != null) {
wrapper.eq(AppConfig::getConfigId, param.getConfigId());
}
if (param.getWebsiteId() != null) {
wrapper.eq(AppConfig::getWebsiteId, param.getWebsiteId());
}
if (param.getConfigKey() != null) {
wrapper.like(AppConfig::getConfigKey, param.getConfigKey());
}
if (param.getConfigType() != null) {
wrapper.eq(AppConfig::getConfigType, param.getConfigType());
}
if (param.getIsSecret() != null) {
wrapper.eq(AppConfig::getIsSecret, param.getIsSecret());
}
wrapper.orderByAsc(AppConfig::getConfigType)
.orderByAsc(AppConfig::getSortNumber)
.orderByAsc(AppConfig::getConfigId);
return wrapper;
}
/**
* AES 加密
*/
private String encrypt(String plainText) {
AES aes = SecureUtil.aes(encryptKey.getBytes());
return aes.encryptBase64(plainText);
}
/**
* AES 解密
*/
private String decrypt(String cipherText) {
AES aes = SecureUtil.aes(encryptKey.getBytes());
return aes.decryptStr(cipherText);
}
/**
* 获取当前登录用户的租户ID
*/
private Integer getCurrentTenantId() {
try {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getPrincipal() instanceof User) {
return ((User) authentication.getPrincipal()).getTenantId();
}
} catch (Exception e) {
log.error("获取当前用户租户ID失败", e);
}
return null;
}
}

View File

@@ -0,0 +1,125 @@
package com.gxwebsoft.app.service.impl;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.app.mapper.AppCredentialMapper;
import com.gxwebsoft.app.service.AppCredentialService;
import com.gxwebsoft.app.entity.AppCredential;
import com.gxwebsoft.app.param.AppCredentialParam;
import com.gxwebsoft.common.core.utils.CommonUtil;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 应用密钥凭证Service实现
*
* @author 科技小王子
* @since 2026-03-28 21:29:43
*/
@Slf4j
@Service
public class AppCredentialServiceImpl extends ServiceImpl<AppCredentialMapper, AppCredential> implements AppCredentialService {
@Override
public PageResult<AppCredential> pageRel(AppCredentialParam param) {
PageParam<AppCredential, AppCredentialParam> page = new PageParam<>(param);
page.setDefaultOrder("sort_number asc, create_time desc");
List<AppCredential> list = baseMapper.selectPageRel(page, param);
// 脱敏处理appSecret 不对外展示(仅创建/重置时返回明文)
list.forEach(this::maskSecret);
return new PageResult<>(list, page.getTotal());
}
@Override
public List<AppCredential> listRel(AppCredentialParam param) {
List<AppCredential> list = baseMapper.selectListRel(param);
PageParam<AppCredential, AppCredentialParam> page = new PageParam<>();
page.setDefaultOrder("sort_number asc, create_time desc");
list = page.sortRecords(list);
list.forEach(this::maskSecret);
return list;
}
@Override
public AppCredential getByIdRel(Integer id) {
AppCredentialParam param = new AppCredentialParam();
param.setId(id.longValue());
AppCredential credential = param.getOne(baseMapper.selectListRel(param));
if (credential != null) {
maskSecret(credential);
}
return credential;
}
@Override
public AppCredential createCredential(AppCredential credential) {
// 生成 AppIDapp_ + 16位随机字符串
String appId = "app_" + CommonUtil.randomUUID16();
// 生成 AppSecret32位随机字符串大小写字母+数字)
String appSecret = generateSecretValue();
credential.setAppId(appId);
credential.setAppSecret(appSecret);
// 默认状态正常
if (credential.getStatus() == null) {
credential.setStatus(0);
}
if (StrUtil.isBlank(credential.getType())) {
credential.setType("server");
}
save(credential);
log.info("创建凭证成功websiteId={}, appId={}", credential.getWebsiteId(), appId);
// 返回含明文 secret 的对象(仅此一次)
return credential;
}
@Override
public AppCredential resetSecret(Long id) {
AppCredential credential = getById(id);
if (credential == null) {
throw new RuntimeException("凭证不存在");
}
String newSecret = generateSecretValue();
credential.setAppSecret(newSecret);
updateById(credential);
log.info("重置凭证密钥成功id={}", id);
return credential;
}
@Override
public boolean updateStatus(Long id, Integer status) {
return update(new LambdaUpdateWrapper<AppCredential>()
.eq(AppCredential::getId, id)
.set(AppCredential::getStatus, status));
}
/**
* 生成32位随机 AppSecret
*/
private String generateSecretValue() {
// 格式8位-8位-8位-8位类似 UUID 格式,便于复制)
return RandomUtil.randomString(8) + "-"
+ RandomUtil.randomString(8) + "-"
+ RandomUtil.randomString(8) + "-"
+ RandomUtil.randomString(8);
}
/**
* 脱敏处理:将 appSecret 替换为掩码
*/
private void maskSecret(AppCredential credential) {
if (StrUtil.isNotBlank(credential.getAppSecret())) {
// 只保留前4位其余用 * 替代
String secret = credential.getAppSecret();
credential.setAppSecret(secret.substring(0, Math.min(4, secret.length())) + "**********************");
}
}
}

View File

@@ -0,0 +1,86 @@
package com.gxwebsoft.app.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.app.mapper.AppEventMapper;
import com.gxwebsoft.app.service.AppEventService;
import com.gxwebsoft.app.entity.AppEvent;
import com.gxwebsoft.app.param.AppEventParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 应用操作动态Service实现
*
* @author 科技小王子
* @since 2026-03-28 21:29:44
*/
@Slf4j
@Service
public class AppEventServiceImpl extends ServiceImpl<AppEventMapper, AppEvent> implements AppEventService {
@Override
public PageResult<AppEvent> pageRel(AppEventParam param) {
PageParam<AppEvent, AppEventParam> page = new PageParam<>(param);
page.setDefaultOrder("create_time desc");
List<AppEvent> list = baseMapper.selectPageRel(page, param);
return new PageResult<>(list, page.getTotal());
}
@Override
public List<AppEvent> listRel(AppEventParam param) {
List<AppEvent> list = baseMapper.selectListRel(param);
PageParam<AppEvent, AppEventParam> page = new PageParam<>();
page.setDefaultOrder("create_time desc");
return page.sortRecords(list);
}
@Override
public AppEvent getByIdRel(Integer id) {
AppEventParam param = new AppEventParam();
param.setId(id.longValue());
return param.getOne(baseMapper.selectListRel(param));
}
@Override
@Async
public void logEvent(Long websiteId, String eventType, String title, String content,
Long operatorId, String operatorName, Long refId, String refType) {
try {
AppEvent event = new AppEvent();
event.setWebsiteId(websiteId);
event.setEventType(eventType);
event.setTitle(title);
event.setContent(content);
event.setOperatorId(operatorId);
event.setOperator(operatorName);
event.setRefId(refId);
event.setRefType(refType);
event.setStatus(0);
save(event);
log.debug("记录事件成功websiteId={}, eventType={}, title={}", websiteId, eventType, title);
} catch (Exception e) {
log.warn("记录事件失败websiteId={}, eventType={}: {}", websiteId, eventType, e.getMessage());
}
}
@Override
@Async
public void logEvent(Long websiteId, String eventType, String title, Long operatorId, String operatorName) {
logEvent(websiteId, eventType, title, null, operatorId, operatorName, null, null);
}
@Override
public AppEvent getLatestEvent(Long websiteId) {
return getOne(new LambdaQueryWrapper<AppEvent>()
.eq(AppEvent::getWebsiteId, websiteId)
.orderByDesc(AppEvent::getCreateTime)
.last("LIMIT 1"));
}
}

View File

@@ -0,0 +1,109 @@
package com.gxwebsoft.app.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.app.entity.AppResource;
import com.gxwebsoft.app.mapper.AppResourceMapper;
import com.gxwebsoft.app.param.AppResourceParam;
import com.gxwebsoft.app.service.AppResourceService;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 开发者资源 Service 实现
*
* @author 科技小王子
* @since 2026-03-31
*/
@Slf4j
@Service
public class AppResourceServiceImpl extends ServiceImpl<AppResourceMapper, AppResource>
implements AppResourceService {
@Override
public PageResult<AppResource> pageRel(AppResourceParam param) {
PageParam<AppResource, AppResourceParam> page = new PageParam<>(param);
page.setDefaultOrder("create_time desc");
List<AppResource> list = baseMapper.selectPageRel(page, param);
return new PageResult<>(list, page.getTotal());
}
@Override
public List<AppResource> listRel(AppResourceParam param) {
return baseMapper.selectListRel(param);
}
@Override
public AppResource getByIdRel(Long resourceId) {
AppResourceParam param = new AppResourceParam();
param.setResourceId(resourceId);
List<AppResource> list = baseMapper.selectListRel(param);
return list.isEmpty() ? null : list.get(0);
}
@Override
@Transactional(rollbackFor = Exception.class)
public AppResource addResource(AppResource resource, Integer userId) {
resource.setUserId(userId);
resource.setDeleted(0);
resource.setCreateTime(LocalDateTime.now());
resource.setUpdateTime(LocalDateTime.now());
// 默认状态
if (resource.getStatus() == null) {
resource.setStatus("running");
}
save(resource);
log.info("新增资源成功, type={}, name={}, userId={}", resource.getResourceType(), resource.getName(), userId);
return resource;
}
@Override
@Transactional(rollbackFor = Exception.class)
public AppResource updateResource(AppResource resource) {
if (resource.getResourceId() == null) {
throw new RuntimeException("资源ID不能为空");
}
resource.setUpdateTime(LocalDateTime.now());
updateById(resource);
return getByIdRel(resource.getResourceId());
}
@Override
@Transactional(rollbackFor = Exception.class)
public void removeResource(Long resourceId, Integer userId) {
AppResource resource = getById(resourceId);
if (resource == null) {
throw new RuntimeException("资源不存在");
}
if (!resource.getUserId().equals(userId)) {
throw new RuntimeException("无权操作此资源");
}
resource.setDeleted(1);
resource.setUpdateTime(LocalDateTime.now());
updateById(resource);
log.info("删除资源成功, resourceId={}, userId={}", resourceId, userId);
}
@Override
public Map<String, Long> countByType(Integer userId, Integer tenantId) {
List<Map<String, Object>> raw = baseMapper.countByType(userId, tenantId);
Map<String, Long> result = new HashMap<>();
// 初始化所有类型为 0
for (String type : new String[]{"server", "database", "storage", "domain", "ssl"}) {
result.put(type, 0L);
}
for (Map<String, Object> row : raw) {
String type = (String) row.get("resourceType");
Long cnt = ((Number) row.get("cnt")).longValue();
result.put(type, cnt);
}
return result;
}
}

View File

@@ -0,0 +1,579 @@
package com.gxwebsoft.app.service.impl;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.app.entity.AppTicket;
import com.gxwebsoft.app.entity.AppTicketReply;
import com.gxwebsoft.app.entity.AppUser;
import com.gxwebsoft.app.mapper.AppTicketMapper;
import com.gxwebsoft.app.mapper.AppTicketReplyMapper;
import com.gxwebsoft.app.param.AppTicketParam;
import com.gxwebsoft.app.service.AppTicketService;
import com.gxwebsoft.app.service.AppUserService;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
/**
* 应用工单 Service 实现
*
* @author 科技小王子
* @since 2026-03-30
*/
@Slf4j
@Service
public class AppTicketServiceImpl extends ServiceImpl<AppTicketMapper, AppTicket> implements AppTicketService {
/** 企业微信群机器人 Webhook留空则不发送 */
@Value("${notify.wecom-webhook:}")
private String wecomWebhook;
/** 飞书群机器人 Webhook留空则不发送 */
@Value("${notify.feishu-webhook:}")
private String feishuWebhook;
@Resource
private AppTicketReplyMapper replyMapper;
@Resource
private AppUserService appUserService;
@Resource
private UserService userService;
// ─── 生成工单编号 ─────────────────────────────────────────────
private String generateTicketNo() {
String ts = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
String rand = String.format("%04d", new Random().nextInt(10000));
return "TK-" + ts + rand;
}
// ─── 客户端:查自己的工单 ─────────────────────────────────────
@Override
public PageResult<AppTicket> myPage(AppTicketParam param, Integer userId) {
// 用 PageParam 包装分页参数getCurrent/getSize 来自父类 Page<T>
Page<AppTicket> page = new Page<>(param.getCurrent(), param.getSize() > 0 ? param.getSize() : 15);
LambdaQueryWrapper<AppTicket> wrapper = new LambdaQueryWrapper<AppTicket>()
.eq(AppTicket::getDeleted, 0)
.eq(AppTicket::getSubmitUserId, userId)
.eq(ObjectUtil.isNotNull(param.getWebsiteId()), AppTicket::getWebsiteId, param.getWebsiteId())
.eq(ObjectUtil.isNotEmpty(param.getStatus()), AppTicket::getStatus, param.getStatus())
.eq(ObjectUtil.isNotEmpty(param.getCategory()), AppTicket::getCategory, param.getCategory())
.and(ObjectUtil.isNotEmpty(param.getKeywords()), q ->
q.like(AppTicket::getTitle, param.getKeywords())
.or().like(AppTicket::getTicketNo, param.getKeywords()))
// 状态优先级pending > assigned > processing > resolved > closed同状态内最新的排前
.last("ORDER BY FIELD(status,'pending','assigned','processing','resolved','closed','rejected'), create_time DESC");
baseMapper.selectPage(page, wrapper);
return new PageResult<>(page.getRecords(), page.getTotal());
}
// ─── 技术端:查所有工单 ───────────────────────────────────────
@Override
public PageResult<AppTicket> allPage(AppTicketParam param) {
Page<AppTicket> page = new Page<>(param.getCurrent(), param.getSize() > 0 ? param.getSize() : 20);
LambdaQueryWrapper<AppTicket> wrapper = new LambdaQueryWrapper<AppTicket>()
.eq(AppTicket::getDeleted, 0)
.eq(ObjectUtil.isNotNull(param.getWebsiteId()), AppTicket::getWebsiteId, param.getWebsiteId())
.eq(ObjectUtil.isNotEmpty(param.getStatus()), AppTicket::getStatus, param.getStatus())
.eq(ObjectUtil.isNotEmpty(param.getCategory()), AppTicket::getCategory, param.getCategory())
.eq(ObjectUtil.isNotEmpty(param.getPriority()), AppTicket::getPriority, param.getPriority())
.and(ObjectUtil.isNotNull(param.getAssigneeId()) && param.getAssigneeId() == 0,
q -> q.isNull(AppTicket::getAssigneeId))
.eq(ObjectUtil.isNotNull(param.getAssigneeId()) && param.getAssigneeId() > 0,
AppTicket::getAssigneeId, param.getAssigneeId())
.and(ObjectUtil.isNotEmpty(param.getKeywords()), q ->
q.like(AppTicket::getTitle, param.getKeywords())
.or().like(AppTicket::getTicketNo, param.getKeywords()))
// 状态优先级 > 紧急程度 > 最新提交时间
.last("ORDER BY FIELD(status,'pending','assigned','processing','resolved','closed','rejected'), FIELD(priority,'urgent','high','normal','low'), create_time DESC");
baseMapper.selectPage(page, wrapper);
return new PageResult<>(page.getRecords(), page.getTotal());
}
// ─── 提交工单(自动分配) ─────────────────────────────────────
@Override
@Transactional(rollbackFor = Exception.class)
public AppTicket submit(AppTicket ticket, Integer userId) {
// 补充提交人信息
ticket.setSubmitUserId(userId);
ticket.setTicketNo(generateTicketNo());
ticket.setStatus("pending");
ticket.setReplyCount(0);
ticket.setDeleted(0);
ticket.setCreateTime(LocalDateTime.now());
ticket.setUpdateTime(LocalDateTime.now());
// 从用户服务取昵称/头像冗余存储(@InterceptorIgnore 绕过租户拦截器跨库查询)
try {
User user = userService.getByIdIgnoreTenant(userId);
if (user != null) {
ticket.setSubmitUserName(user.getNickname() != null ? user.getNickname() : user.getUsername());
ticket.setSubmitUserAvatar(user.getAvatar());
}
} catch (Exception e) {
log.warn("获取提交人信息失败", e);
}
// 自动分配:查找该应用的 admin/developer 成员,随机分配
autoAssign(ticket);
save(ticket);
// 异步推送:新工单通知(通知分配到的技术人员)
sendTicketCreatedAsync(ticket);
return ticket;
}
/** 自动分配工单给应用的技术成员 */
private void autoAssign(AppTicket ticket) {
if (ticket.getWebsiteId() == null) return;
try {
List<AppUser> members = appUserService.list(
new LambdaQueryWrapper<AppUser>()
.eq(AppUser::getWebsiteId, ticket.getWebsiteId())
.eq(AppUser::getStatus, 0)
.in(AppUser::getRole, "admin", "developer", "owner"));
if (!members.isEmpty()) {
// 简单轮询:按工单数最少分配(此处随机)
AppUser assigned = members.get(new Random().nextInt(members.size()));
ticket.setAssigneeId(assigned.getUserId());
ticket.setAssigneeName(assigned.getNickname() != null ? assigned.getNickname() : assigned.getUsername());
ticket.setAssigneeAvatar(assigned.getAvatar());
ticket.setStatus("assigned");
}
} catch (Exception e) {
log.warn("自动分配工单失败,保持 pending 状态", e);
}
}
// ─── 更新状态 ─────────────────────────────────────────────────
@Override
public void updateStatus(Long ticketId, String status, Integer operatorId) {
LambdaUpdateWrapper<AppTicket> wrapper = new LambdaUpdateWrapper<AppTicket>()
.eq(AppTicket::getTicketId, ticketId)
.set(AppTicket::getStatus, status)
.set(AppTicket::getUpdateTime, LocalDateTime.now());
if ("resolved".equals(status)) {
wrapper.set(AppTicket::getResolvedTime, LocalDateTime.now());
// 如果没有分配人,自动将操作人设为处理人
AppTicket t = getById(ticketId);
if (t != null && t.getAssigneeId() == null) {
wrapper.set(AppTicket::getAssigneeId, operatorId);
}
}
update(wrapper);
// 异步推送:状态变更通知提交人(已解决/已关闭)
if ("resolved".equals(status) || "closed".equals(status)) {
AppTicket t = getById(ticketId);
if (t != null) sendStatusChangedAsync(t, status);
}
}
// ─── 分配处理人 ───────────────────────────────────────────────
@Override
public void assign(Long ticketId, Integer assigneeId) {
User user = userService.getByIdIgnoreTenant(assigneeId);
LambdaUpdateWrapper<AppTicket> wrapper = new LambdaUpdateWrapper<AppTicket>()
.eq(AppTicket::getTicketId, ticketId)
.set(AppTicket::getAssigneeId, assigneeId)
.set(user != null, AppTicket::getAssigneeName,
user != null ? (user.getNickname() != null ? user.getNickname() : user.getUsername()) : null)
.set(user != null, AppTicket::getAssigneeAvatar, user != null ? user.getAvatar() : null)
.set(AppTicket::getStatus, "assigned")
.set(AppTicket::getUpdateTime, LocalDateTime.now());
update(wrapper);
// 异步推送:通知新分配到的技术人员
AppTicket t = getById(ticketId);
if (t != null) sendTicketAssignedAsync(t);
}
// ─── 用户关闭工单 ─────────────────────────────────────────────
@Override
public void closeByUser(Long ticketId, Integer userId) {
AppTicket ticket = getById(ticketId);
if (ticket == null || !ticket.getSubmitUserId().equals(userId)) {
throw new RuntimeException("无权操作该工单");
}
update(new LambdaUpdateWrapper<AppTicket>()
.eq(AppTicket::getTicketId, ticketId)
.set(AppTicket::getStatus, "closed")
.set(AppTicket::getClosedTime, LocalDateTime.now())
.set(AppTicket::getUpdateTime, LocalDateTime.now()));
}
// ─── 获取回复列表 ─────────────────────────────────────────────
@Override
public List<AppTicketReply> getReplies(Long ticketId) {
return replyMapper.selectList(
new LambdaQueryWrapper<AppTicketReply>()
.eq(AppTicketReply::getTicketId, ticketId)
.eq(AppTicketReply::getDeleted, 0)
.orderByAsc(AppTicketReply::getCreateTime));
}
// ─── 添加回复 ─────────────────────────────────────────────────
@Override
@Transactional(rollbackFor = Exception.class)
public AppTicketReply addReply(AppTicketReply reply, Integer userId) {
reply.setUserId(userId);
reply.setDeleted(0);
reply.setCreateTime(LocalDateTime.now());
// 补充用户信息(@InterceptorIgnore 绕过租户拦截器跨库查询)
try {
User user = userService.getByIdIgnoreTenant(userId);
if (user != null) {
reply.setUserName(user.getNickname() != null ? user.getNickname() : user.getUsername());
reply.setUserAvatar(user.getAvatar());
}
} catch (Exception e) {
log.warn("获取回复人信息失败", e);
}
// 判断是否是技术人员(该应用的 admin/developer/owner
AppTicket ticket = getById(reply.getTicketId());
if (ticket != null) {
boolean isStaff = appUserService.count(new LambdaQueryWrapper<AppUser>()
.eq(AppUser::getWebsiteId, ticket.getWebsiteId())
.eq(AppUser::getUserId, userId)
.in(AppUser::getRole, "owner", "admin", "developer")
.eq(AppUser::getStatus, 0)) > 0;
reply.setIsStaff(isStaff ? 1 : 0);
} else {
reply.setIsStaff(0);
}
replyMapper.insert(reply);
// 更新工单回复数 & 更新时间,若状态是 assigned 则推进为 processing
update(new LambdaUpdateWrapper<AppTicket>()
.eq(AppTicket::getTicketId, reply.getTicketId())
.setSql("reply_count = reply_count + 1")
.set(AppTicket::getUpdateTime, LocalDateTime.now())
.eq(AppTicket::getStatus, "assigned")
.set(AppTicket::getStatus, "processing"));
// 异步推送:有新回复时通知对方
if (ticket != null) sendReplyNotifyAsync(ticket, reply);
return reply;
}
// ─── 统计 ─────────────────────────────────────────────────────
@Override
public Map<String, Long> stats(Long websiteId, Integer userId) {
LambdaQueryWrapper<AppTicket> base = new LambdaQueryWrapper<AppTicket>()
.eq(AppTicket::getDeleted, 0)
.eq(ObjectUtil.isNotNull(websiteId), AppTicket::getWebsiteId, websiteId)
.eq(ObjectUtil.isNotNull(userId), AppTicket::getSubmitUserId, userId);
Map<String, Long> result = new HashMap<>();
result.put("total", (long) count(base.clone()));
result.put("pending", (long) count(base.clone().in(AppTicket::getStatus, "pending", "assigned")));
result.put("processing", (long) count(base.clone().eq(AppTicket::getStatus, "processing")));
result.put("resolved", (long) count(base.clone().eq(AppTicket::getStatus, "resolved")));
result.put("closed", (long) count(base.clone().eq(AppTicket::getStatus, "closed")));
return result;
}
// ─── 获取技术人员列表 ─────────────────────────────────────────
@Override
public List<Map<String, Object>> getTechStaffList() {
List<AppUser> members = appUserService.list(
new LambdaQueryWrapper<AppUser>()
.eq(AppUser::getStatus, 0)
.in(AppUser::getRole, "owner", "admin", "developer")
.select(AppUser::getUserId, AppUser::getNickname, AppUser::getAvatar));
// 去重(一个用户可能在多个应用里)
Map<Integer, AppUser> dedupMap = new LinkedHashMap<>();
for (AppUser m : members) {
dedupMap.put(m.getUserId(), m);
}
return dedupMap.values().stream().map(m -> {
Map<String, Object> map = new HashMap<>();
map.put("userId", m.getUserId());
map.put("nickname", m.getNickname() != null ? m.getNickname() : "用户" + m.getUserId());
map.put("avatar", m.getAvatar());
return map;
}).collect(Collectors.toList());
}
// ════════════════════════════════════════════════════════════
// 异步消息推送
// ════════════════════════════════════════════════════════════
/**
* 场景1新工单提交 → 通知分配到的技术人员
*/
@Async
public void sendTicketCreatedAsync(AppTicket ticket) {
String now = now();
String title = String.format("🎫 新工单待处理(%s", now);
String assigneeLine = StrUtil.isNotBlank(ticket.getAssigneeName())
? "**处理人:** " + ticket.getAssigneeName()
: "**处理人:** 待分配";
String wecomContent = String.format(
"## %s\n" +
"> **工单号:** %s\n" +
"> **标题:** %s\n" +
"> **分类:** %s **优先级:** %s\n" +
"> **提交人:** %s\n" +
"> %s\n" +
"> **描述:** %s",
title,
nullSafe(ticket.getTicketNo()),
nullSafe(ticket.getTitle()),
categoryLabel(ticket.getCategory()), priorityLabel(ticket.getPriority()),
nullSafe(ticket.getSubmitUserName()),
assigneeLine,
truncate(ticket.getContent(), 120)
);
List<String[]> feishuLines = Arrays.asList(
new String[]{"工单号:" + nullSafe(ticket.getTicketNo())},
new String[]{"标 题:" + nullSafe(ticket.getTitle())},
new String[]{"分 类:" + categoryLabel(ticket.getCategory()) + " 优先级:" + priorityLabel(ticket.getPriority())},
new String[]{"提交人:" + nullSafe(ticket.getSubmitUserName())},
new String[]{assigneeLine.replace("**", "")},
new String[]{"描 述:" + truncate(ticket.getContent(), 120)}
);
doSend(title, wecomContent, feishuLines, "ticket_created");
}
/**
* 场景2工单被重新分配 → 通知新处理人
*/
@Async
public void sendTicketAssignedAsync(AppTicket ticket) {
String now = now();
String title = String.format("📋 工单已分配给您(%s", now);
String wecomContent = String.format(
"## %s\n" +
"> **工单号:** %s\n" +
"> **标题:** %s\n" +
"> **分配给:** <font color=\"warning\">%s</font>\n" +
"> **分类:** %s **优先级:** %s\n" +
"> **描述:** %s",
title,
nullSafe(ticket.getTicketNo()),
nullSafe(ticket.getTitle()),
nullSafe(ticket.getAssigneeName()),
categoryLabel(ticket.getCategory()), priorityLabel(ticket.getPriority()),
truncate(ticket.getContent(), 100)
);
List<String[]> feishuLines = Arrays.asList(
new String[]{"工单号:" + nullSafe(ticket.getTicketNo())},
new String[]{"标 题:" + nullSafe(ticket.getTitle())},
new String[]{"分配给:" + nullSafe(ticket.getAssigneeName())},
new String[]{"分 类:" + categoryLabel(ticket.getCategory()) + " 优先级:" + priorityLabel(ticket.getPriority())},
new String[]{"描 述:" + truncate(ticket.getContent(), 100)}
);
doSend(title, wecomContent, feishuLines, "ticket_assigned");
}
/**
* 场景3有新回复 → 技术人员回复则通知客户,客户回复则通知技术人员
*/
@Async
public void sendReplyNotifyAsync(AppTicket ticket, AppTicketReply reply) {
boolean isStaff = Integer.valueOf(1).equals(reply.getIsStaff());
String now = now();
String who = isStaff ? "技术人员" : "用户";
String notifyRole = isStaff ? "您的工单有新回复" : "工单有用户新回复";
String title = String.format("💬 %s%s", notifyRole, now);
String wecomContent = String.format(
"## %s\n" +
"> **工单号:** %s\n" +
"> **标题:** %s\n" +
"> **回复人:** %s%s\n" +
"> **回复内容:** %s",
title,
nullSafe(ticket.getTicketNo()),
nullSafe(ticket.getTitle()),
nullSafe(reply.getUserName()), who,
truncate(reply.getContent(), 200)
);
List<String[]> feishuLines = Arrays.asList(
new String[]{"工单号:" + nullSafe(ticket.getTicketNo())},
new String[]{"标 题:" + nullSafe(ticket.getTitle())},
new String[]{"回复人:" + nullSafe(reply.getUserName()) + "" + who + ""},
new String[]{"回复内容:" + truncate(reply.getContent(), 200)}
);
doSend(title, wecomContent, feishuLines, "ticket_reply");
}
/**
* 场景4状态变更已解决/已关闭)→ 通知提交人
*/
@Async
public void sendStatusChangedAsync(AppTicket ticket, String status) {
String now = now();
String emoji = "resolved".equals(status) ? "" : "🔒";
String statusLabel = "resolved".equals(status) ? "已解决" : "已关闭";
String title = String.format("%s 工单%s%s", emoji, statusLabel, now);
String wecomContent = String.format(
"## %s\n" +
"> **工单号:** %s\n" +
"> **标题:** %s\n" +
"> **提交人:** %s\n" +
"> **处理人:** %s\n" +
"> **状态:** <font color=\"%s\">%s</font>",
title,
nullSafe(ticket.getTicketNo()),
nullSafe(ticket.getTitle()),
nullSafe(ticket.getSubmitUserName()),
nullSafe(ticket.getAssigneeName()),
"resolved".equals(status) ? "info" : "comment",
statusLabel
);
List<String[]> feishuLines = Arrays.asList(
new String[]{"工单号:" + nullSafe(ticket.getTicketNo())},
new String[]{"标 题:" + nullSafe(ticket.getTitle())},
new String[]{"提交人:" + nullSafe(ticket.getSubmitUserName())},
new String[]{"处理人:" + nullSafe(ticket.getAssigneeName())},
new String[]{"状 态:" + statusLabel}
);
doSend(title, wecomContent, feishuLines, "ticket_status");
}
/**
* 统一发送入口:企业微信 + 飞书
*/
private void doSend(String title, String wecomContent, List<String[]> feishuLines, String scene) {
if (StrUtil.isNotBlank(wecomWebhook)) {
try {
sendWecom(wecomContent);
} catch (Exception e) {
log.warn("[工单通知][{}] 企业微信发送失败: {}", scene, e.getMessage());
}
}
if (StrUtil.isNotBlank(feishuWebhook)) {
try {
sendFeishu(title, feishuLines);
} catch (Exception e) {
log.warn("[工单通知][{}] 飞书发送失败: {}", scene, e.getMessage());
}
}
}
/**
* 企业微信群机器人 - markdown 消息
* 文档https://developer.work.weixin.qq.com/document/path/91770
*/
private void sendWecom(String content) {
Map<String, Object> textMap = new HashMap<>();
textMap.put("content", content);
Map<String, Object> payload = new HashMap<>();
payload.put("msgtype", "markdown");
payload.put("markdown", textMap);
String resp = HttpUtil.post(wecomWebhook, JSON.toJSONString(payload));
log.info("[工单通知] 企业微信推送结果: {}", resp);
}
/**
* 飞书群机器人 - 富文本post消息
* 文档https://open.feishu.cn/document/client-docs/bot-v3/add-custom-bot
*/
private void sendFeishu(String title, List<String[]> lines) {
List<List<Map<String, String>>> content = new ArrayList<>();
for (String[] line : lines) {
Map<String, String> node = new HashMap<>();
node.put("tag", "text");
node.put("text", line[0]);
content.add(Collections.singletonList(node));
}
Map<String, Object> zhCn = new HashMap<>();
zhCn.put("title", title);
zhCn.put("content", content);
Map<String, Object> postContent = new HashMap<>();
postContent.put("zh_cn", zhCn);
Map<String, Object> post = new HashMap<>();
post.put("content", postContent);
Map<String, Object> payload = new HashMap<>();
payload.put("msg_type", "post");
payload.put("content", post);
String resp = HttpUtil.post(feishuWebhook, JSON.toJSONString(payload));
log.info("[工单通知] 飞书推送结果: {}", resp);
}
// ════════════════════════════════════════════════════════════
// 工具方法
// ════════════════════════════════════════════════════════════
private String now() {
return LocalDateTime.now().format(DateTimeFormatter.ofPattern("MM-dd HH:mm"));
}
private String nullSafe(String s) {
return StrUtil.isBlank(s) ? "" : s;
}
private String truncate(String s, int max) {
if (StrUtil.isBlank(s)) return "";
return s.length() > max ? s.substring(0, max) + "" : s;
}
private String categoryLabel(String category) {
if (category == null) return "其他";
return switch (category) {
case "bug" -> "Bug反馈";
case "feature" -> "功能需求";
case "config" -> "配置问题";
case "performance" -> "性能问题";
case "security" -> "安全问题";
default -> category;
};
}
private String priorityLabel(String priority) {
if (priority == null) return "普通";
return switch (priority) {
case "urgent" -> "🔴 紧急";
case "high" -> "🟠 高";
case "normal" -> "🟡 普通";
case "low" -> "🟢 低";
default -> priority;
};
}
}

View File

@@ -0,0 +1,112 @@
package com.gxwebsoft.app.service.impl;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.app.mapper.AppUserMapper;
import com.gxwebsoft.app.service.AppUserService;
import com.gxwebsoft.app.entity.AppUser;
import com.gxwebsoft.app.param.AppUserParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
/**
* 应用成员Service实现
*
* @author 科技小王子
* @since 2026-03-28 21:29:44
*/
@Slf4j
@Service
public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, AppUser> implements AppUserService {
/** 注入同 jar 包内的 UserService用于写入冗余用户信息不做跨库 JOIN */
@Resource
private UserService userService;
@Override
public PageResult<AppUser> pageRel(AppUserParam param) {
PageParam<AppUser, AppUserParam> page = new PageParam<>(param);
page.setDefaultOrder("sort_number asc, create_time asc");
List<AppUser> list = baseMapper.selectPageRel(page, param);
return new PageResult<>(list, page.getTotal());
}
@Override
public List<AppUser> listRel(AppUserParam param) {
List<AppUser> list = baseMapper.selectListRel(param);
PageParam<AppUser, AppUserParam> page = new PageParam<>();
page.setDefaultOrder("sort_number asc, create_time asc");
return page.sortRecords(list);
}
@Override
public AppUser getByIdRel(Integer id) {
AppUserParam param = new AppUserParam();
param.setId(id.longValue());
return param.getOne(baseMapper.selectListRel(param));
}
@Override
public AppUser inviteUser(Long websiteId, Integer userId, String role, Integer inviteBy) {
// 检查是否已经是成员
if (isMember(websiteId, userId)) {
throw new RuntimeException("该用户已经是应用成员");
}
// 查询用户基础信息并冗余写入,避免跨库 JOIN
User sysUser = userService.getByIdIgnoreTenant(userId);
if (sysUser == null) {
throw new RuntimeException("用户不存在userId=" + userId);
}
AppUser appUser = new AppUser();
appUser.setWebsiteId(websiteId);
appUser.setUserId(userId);
appUser.setRole(role != null ? role : "developer");
appUser.setInviteBy(inviteBy.longValue());
appUser.setInviteTime(LocalDateTime.now());
appUser.setStatus(0);
appUser.setSortNumber(0);
// 冗余写入用户基础信息,彻底解除跨库 JOIN 依赖
appUser.setUsername(sysUser.getUsername());
appUser.setNickname(sysUser.getNickname());
appUser.setAvatar(sysUser.getAvatar());
appUser.setPhone(sysUser.getPhone());
save(appUser);
log.info("邀请成员成功websiteId={}, userId={}, username={}, role={}", websiteId, userId, sysUser.getUsername(), role);
return appUser;
}
@Override
public boolean updateRole(Long id, String role) {
return update(new LambdaUpdateWrapper<AppUser>()
.eq(AppUser::getId, id)
.set(AppUser::getRole, role));
}
@Override
public boolean isMember(Long websiteId, Integer userId) {
long count = count(new LambdaQueryWrapper<AppUser>()
.eq(AppUser::getWebsiteId, websiteId)
.eq(AppUser::getUserId, userId)
.eq(AppUser::getStatus, 0));
return count > 0;
}
@Override
public User findUserByPhone(String phone) {
return userService.getByPhone(phone);
}
}

View File

@@ -0,0 +1,112 @@
package com.gxwebsoft.app.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.app.mapper.AppVersionMapper;
import com.gxwebsoft.app.service.AppVersionService;
import com.gxwebsoft.app.entity.AppVersion;
import com.gxwebsoft.app.param.AppVersionParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;
/**
* 应用版本发布记录Service实现
*
* @author 科技小王子
* @since 2026-03-28 21:29:44
*/
@Slf4j
@Service
public class AppVersionServiceImpl extends ServiceImpl<AppVersionMapper, AppVersion> implements AppVersionService {
@Override
public PageResult<AppVersion> pageRel(AppVersionParam param) {
PageParam<AppVersion, AppVersionParam> page = new PageParam<>(param);
page.setDefaultOrder("create_time desc");
List<AppVersion> list = baseMapper.selectPageRel(page, param);
return new PageResult<>(list, page.getTotal());
}
@Override
public List<AppVersion> listRel(AppVersionParam param) {
List<AppVersion> list = baseMapper.selectListRel(param);
PageParam<AppVersion, AppVersionParam> page = new PageParam<>();
page.setDefaultOrder("create_time desc");
return page.sortRecords(list);
}
@Override
public AppVersion getByIdRel(Integer id) {
AppVersionParam param = new AppVersionParam();
param.setId(id.longValue());
return param.getOne(baseMapper.selectListRel(param));
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean publish(Long id, Integer publishBy) {
AppVersion version = getById(id);
if (version == null) {
throw new RuntimeException("版本不存在");
}
Long websiteId = version.getWebsiteId();
// 1. 将该应用下所有版本的 isCurrent 设为 false
update(new LambdaUpdateWrapper<AppVersion>()
.eq(AppVersion::getWebsiteId, websiteId)
.set(AppVersion::getIsCurrent, false));
// 2. 将当前版本设为已发布+当前版本
version.setStatus(1);
version.setIsCurrent(true);
version.setPublishBy(publishBy.longValue());
version.setPublishTime(LocalDateTime.now());
boolean result = updateById(version);
log.info("发布版本成功id={}, versionNo={}", id, version.getVersionNo());
return result;
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean rollback(Long id, Integer publishBy) {
AppVersion targetVersion = getById(id);
if (targetVersion == null) {
throw new RuntimeException("目标版本不存在");
}
Long websiteId = targetVersion.getWebsiteId();
// 1. 将当前版本标记为已回滚
update(new LambdaUpdateWrapper<AppVersion>()
.eq(AppVersion::getWebsiteId, websiteId)
.eq(AppVersion::getIsCurrent, true)
.set(AppVersion::getStatus, 2) // 2=已回滚
.set(AppVersion::getIsCurrent, false));
// 2. 将目标版本设为当前版本
targetVersion.setStatus(1);
targetVersion.setIsCurrent(true);
targetVersion.setPublishBy(publishBy.longValue());
targetVersion.setPublishTime(LocalDateTime.now());
boolean result = updateById(targetVersion);
log.info("回滚版本成功id={}, versionNo={}", id, targetVersion.getVersionNo());
return result;
}
@Override
public AppVersion getCurrentVersion(Long websiteId) {
return getOne(new LambdaQueryWrapper<AppVersion>()
.eq(AppVersion::getWebsiteId, websiteId)
.eq(AppVersion::getIsCurrent, true)
.last("LIMIT 1"));
}
}

View File

@@ -0,0 +1,54 @@
-- ----------------------------
-- 开发者资源管理表
-- 统一存放服务器/数据库/云存储/域名/SSL证书等开发基础设施资源
-- ----------------------------
CREATE TABLE IF NOT EXISTS `app_resource` (
`resource_id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '资源ID',
`resource_type` VARCHAR(20) NOT NULL COMMENT '资源类型: server/database/storage/domain/ssl',
`name` VARCHAR(100) NOT NULL COMMENT '资源名称',
`provider` VARCHAR(30) DEFAULT NULL COMMENT '服务商: tencent/aliyun/huawei/other',
-- 服务器字段
`ip` VARCHAR(50) DEFAULT NULL COMMENT 'IP地址服务器用',
-- 数据库字段
`db_type` VARCHAR(30) DEFAULT NULL COMMENT '数据库类型: MySQL/PostgreSQL/Redis/MongoDB',
`host` VARCHAR(200) DEFAULT NULL COMMENT '连接主机地址(数据库用)',
`port` INT DEFAULT NULL COMMENT '连接端口(数据库用)',
-- 云存储字段
`region` VARCHAR(50) DEFAULT NULL COMMENT '地区/Region云存储用',
`acl` VARCHAR(30) DEFAULT 'private' COMMENT '访问权限: public-read/private云存储用',
`used_bytes` BIGINT DEFAULT 0 COMMENT '已用空间(字节,云存储用)',
-- 域名字段
`domain` VARCHAR(200) DEFAULT NULL COMMENT '域名(域名/SSL用',
`registrar` VARCHAR(100) DEFAULT NULL COMMENT '注册商(域名用)',
`icp` TINYINT(1) DEFAULT 0 COMMENT '是否已备案: 0否 1是域名用',
`icp_no` VARCHAR(100) DEFAULT NULL COMMENT 'ICP备案号域名用',
`ssl_bound` TINYINT(1) DEFAULT 0 COMMENT '是否已绑定SSL域名冗余标记',
-- SSL证书字段
`cert_type` VARCHAR(10) DEFAULT NULL COMMENT '证书类型: DV/OV/EVSSL用',
`issuer` VARCHAR(100) DEFAULT NULL COMMENT '颁发机构SSL用',
-- 通用字段
`status` VARCHAR(20) NOT NULL DEFAULT 'running' COMMENT '状态: running/stopped/expired/pending',
`website_id` BIGINT DEFAULT NULL COMMENT '关联应用ID可选',
`expire_at` DATE DEFAULT NULL COMMENT '到期时间',
`remark` VARCHAR(500) DEFAULT NULL COMMENT '备注',
`user_id` INT NOT NULL COMMENT '所属用户ID',
`tenant_id` INT DEFAULT NULL COMMENT '租户ID',
`deleted` TINYINT NOT NULL DEFAULT 0 COMMENT '是否删除: 0否 1是',
`create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`resource_id`),
KEY `idx_resource_type` (`resource_type`),
KEY `idx_user_id` (`user_id`),
KEY `idx_tenant_id` (`tenant_id`),
KEY `idx_website_id` (`website_id`),
KEY `idx_status` (`status`),
KEY `idx_expire_at` (`expire_at`),
KEY `idx_deleted` (`deleted`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='开发者资源管理(服务器/数据库/云存储/域名/SSL';

Some files were not shown because too many files have changed in this diff Show More