Compare commits
31 Commits
7dede6f36f
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 01101d422f | |||
| 4ec637d7f8 | |||
| 30a53e7283 | |||
| 9ec44dbe5c | |||
| 89ac0d109c | |||
| 7095c4bf96 | |||
| cc2fe7b172 | |||
| b6a3d407e4 | |||
| db5ca691d7 | |||
| ad23922a7c | |||
| 1a990087ac | |||
| 13b4f626aa | |||
| 84cd214277 | |||
| 8a9d779d08 | |||
| f1dde97538 | |||
| 5029be1f1f | |||
| 38ee4c65e6 | |||
| 3ea8e652bd | |||
| 44e95a7273 | |||
| 35fdc2dcfc | |||
| 875111d2d8 | |||
| ee2d95da91 | |||
| 85e0b062b8 | |||
| a4d5c86134 | |||
| 607589d2c5 | |||
| 424929222f | |||
| df7a41f3c4 | |||
| bd2a92d832 | |||
| 75c13bada8 | |||
| 6aeface82d | |||
| 17352718c5 |
17
.workbuddy/expert-history.json
Normal file
17
.workbuddy/expert-history.json
Normal 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
|
||||
}
|
||||
0
.workbuddy/memory/MEMORY.md
Normal file
0
.workbuddy/memory/MEMORY.md
Normal file
230
docs/ai/customer-lead-system-summary.md
Normal file
230
docs/ai/customer-lead-system-summary.md
Normal 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*
|
||||
19
docs/app_config.sql
Normal file
19
docs/app_config.sql
Normal 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='应用配置表';
|
||||
48
docs/sql/2026-03-30_app_ticket_tables.sql
Normal file
48
docs/sql/2026-03-30_app_ticket_tables.sql
Normal 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='工单回复';
|
||||
178
docs/sql/customer_lead_system.sql
Normal file
178
docs/sql/customer_lead_system.sql
Normal 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;
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
/**
|
||||
* RAG:chunk 重叠字符数(用于减少语义断裂)。
|
||||
*/
|
||||
private int ragChunkOverlap = 120;
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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 风格 messages(role: 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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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> {
|
||||
}
|
||||
|
||||
@@ -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> {
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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) > 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 >= #{start}
|
||||
AND create_time < #{end}
|
||||
GROUP BY tenant_id, DATE_FORMAT(create_time, '%Y-%m-%d')
|
||||
ORDER BY day ASC
|
||||
</select>
|
||||
|
||||
</mapper>
|
||||
|
||||
@@ -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";
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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> {
|
||||
}
|
||||
|
||||
@@ -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> {
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
}
|
||||
|
||||
@@ -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(" ", " ");
|
||||
s = s.replace("<", "<").replace(">", ">").replace("&", "&").replace(""", "\"");
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -67,15 +67,24 @@ public class AppUserController extends BaseController {
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('app:appUser:save')")
|
||||
@OperationLog
|
||||
@Operation(summary = "邀请用户成为应用成员")
|
||||
@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(),
|
||||
|
||||
87
src/main/java/com/gxwebsoft/app/entity/AppConfig.java
Normal file
87
src/main/java/com/gxwebsoft/app/entity/AppConfig.java
Normal 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;
|
||||
}
|
||||
121
src/main/java/com/gxwebsoft/app/entity/AppResource.java
Normal file
121
src/main/java/com/gxwebsoft/app/entity/AppResource.java
Normal 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/EV(SSL用)")
|
||||
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;
|
||||
}
|
||||
103
src/main/java/com/gxwebsoft/app/entity/AppTicket.java
Normal file
103
src/main/java/com/gxwebsoft/app/entity/AppTicket.java
Normal 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;
|
||||
}
|
||||
64
src/main/java/com/gxwebsoft/app/entity/AppTicketReply.java
Normal file
64
src/main/java/com/gxwebsoft/app/entity/AppTicketReply.java
Normal 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;
|
||||
}
|
||||
@@ -35,9 +35,15 @@ public class AppUser implements Serializable {
|
||||
@Schema(description = "用户名(冗余)")
|
||||
private String username;
|
||||
|
||||
@Schema(description = "昵称(冗余)")
|
||||
private String nickname;
|
||||
|
||||
@Schema(description = "头像(冗余)")
|
||||
private String avatar;
|
||||
|
||||
@Schema(description = "手机号(冗余,脱敏存储)")
|
||||
private String phone;
|
||||
|
||||
@Schema(description = "角色: owner/admin/developer/viewer")
|
||||
private String role;
|
||||
|
||||
|
||||
43
src/main/java/com/gxwebsoft/app/mapper/AppConfigMapper.java
Normal file
43
src/main/java/com/gxwebsoft/app/mapper/AppConfigMapper.java
Normal 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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
11
src/main/java/com/gxwebsoft/app/mapper/AppTicketMapper.java
Normal file
11
src/main/java/com/gxwebsoft/app/mapper/AppTicketMapper.java
Normal 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> {
|
||||
}
|
||||
@@ -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> {
|
||||
}
|
||||
@@ -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 >= #{param.createTimeStart}
|
||||
</if>
|
||||
<if test="param.createTimeEnd != null">
|
||||
AND a.create_time <= #{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>
|
||||
@@ -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 >= #{param.createTimeStart}
|
||||
</if>
|
||||
<if test="param.createTimeEnd != null">
|
||||
AND a.create_time <= #{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>
|
||||
@@ -2,13 +2,11 @@
|
||||
<!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 -->
|
||||
<!-- 关联查询sql(已移除跨库 JOIN gxwebsoft_core.sys_user,用户信息从冗余字段读取) -->
|
||||
<sql id="selectSql">
|
||||
SELECT a.*, w.website_name, w.website_code, w.website_icon,
|
||||
u.nickname, u.avatar AS user_avatar, u.phone
|
||||
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
|
||||
LEFT JOIN sys_user u ON a.user_id = u.user_id
|
||||
<where>
|
||||
<if test="param.id != null">
|
||||
AND a.id = #{param.id}
|
||||
@@ -21,7 +19,7 @@
|
||||
</if>
|
||||
<if test="param.username != null and param.username != ''">
|
||||
AND (a.username LIKE CONCAT('%', #{param.username}, '%')
|
||||
OR u.nickname 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}
|
||||
@@ -46,8 +44,7 @@
|
||||
</if>
|
||||
<if test="param.keywords != null and param.keywords != ''">
|
||||
AND (a.username LIKE CONCAT('%', #{param.keywords}, '%')
|
||||
OR u.nickname LIKE CONCAT('%', #{param.keywords}, '%')
|
||||
)
|
||||
OR a.nickname LIKE CONCAT('%', #{param.keywords}, '%'))
|
||||
</if>
|
||||
</where>
|
||||
</sql>
|
||||
|
||||
38
src/main/java/com/gxwebsoft/app/param/AppConfigParam.java
Normal file
38
src/main/java/com/gxwebsoft/app/param/AppConfigParam.java
Normal 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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
33
src/main/java/com/gxwebsoft/app/param/AppTicketParam.java
Normal file
33
src/main/java/com/gxwebsoft/app/param/AppTicketParam.java
Normal 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;
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -57,4 +57,12 @@ public interface AppUserService extends IService<AppUser> {
|
||||
*/
|
||||
boolean isMember(Long websiteId, Integer userId);
|
||||
|
||||
/**
|
||||
* 根据手机号查找系统用户(用于手机号邀请)
|
||||
*
|
||||
* @param phone 手机号
|
||||
* @return 系统用户,不存在返回 null
|
||||
*/
|
||||
com.gxwebsoft.common.system.entity.User findUserByPhone(String phone);
|
||||
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -10,9 +10,12 @@ 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;
|
||||
|
||||
@@ -26,6 +29,10 @@ import java.util.List;
|
||||
@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);
|
||||
@@ -56,6 +63,12 @@ public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, AppUser> impl
|
||||
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);
|
||||
@@ -64,9 +77,14 @@ public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, AppUser> impl
|
||||
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={}, role={}", websiteId, userId, role);
|
||||
log.info("邀请成员成功,websiteId={}, userId={}, username={}, role={}", websiteId, userId, sysUser.getUsername(), role);
|
||||
return appUser;
|
||||
}
|
||||
|
||||
@@ -86,4 +104,9 @@ public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, AppUser> impl
|
||||
return count > 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public User findUserByPhone(String phone) {
|
||||
return userService.getByPhone(phone);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
54
src/main/java/com/gxwebsoft/app/sql/app_resource.sql
Normal file
54
src/main/java/com/gxwebsoft/app/sql/app_resource.sql
Normal 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/EV(SSL用)',
|
||||
`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)';
|
||||
@@ -1,104 +0,0 @@
|
||||
package com.gxwebsoft.auto.controller;
|
||||
|
||||
import com.gxwebsoft.auto.dto.QrLoginConfirmRequest;
|
||||
import com.gxwebsoft.auto.dto.QrLoginGenerateResponse;
|
||||
import com.gxwebsoft.auto.dto.QrLoginStatusResponse;
|
||||
import com.gxwebsoft.auto.service.QrLoginService;
|
||||
import com.gxwebsoft.common.core.web.BaseController;
|
||||
import com.gxwebsoft.common.core.web.ApiResult;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.validation.Valid;
|
||||
|
||||
/**
|
||||
* 认证模块
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-03-06 22:50:25
|
||||
*/
|
||||
@Tag(name = "认证模块")
|
||||
@RestController
|
||||
@RequestMapping("/api/qr-login")
|
||||
public class QrLoginController extends BaseController {
|
||||
|
||||
@Autowired
|
||||
private QrLoginService qrLoginService;
|
||||
|
||||
/**
|
||||
* 生成扫码登录token
|
||||
*/
|
||||
@Operation(summary = "生成扫码登录token")
|
||||
@PostMapping("/generate")
|
||||
public ApiResult<?> generateQrLoginToken() {
|
||||
try {
|
||||
QrLoginGenerateResponse response = qrLoginService.generateQrLoginToken();
|
||||
return success("生成成功", response);
|
||||
} catch (Exception e) {
|
||||
return fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查扫码登录状态
|
||||
*/
|
||||
@Operation(summary = "检查扫码登录状态")
|
||||
@GetMapping("/status/{token}")
|
||||
public ApiResult<?> checkQrLoginStatus(
|
||||
@Parameter(description = "扫码登录token") @PathVariable String token) {
|
||||
try {
|
||||
QrLoginStatusResponse response = qrLoginService.checkQrLoginStatus(token);
|
||||
return success("查询成功", response);
|
||||
} catch (Exception e) {
|
||||
return fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 确认扫码登录
|
||||
*/
|
||||
@Operation(summary = "确认扫码登录")
|
||||
@PostMapping("/confirm")
|
||||
public ApiResult<?> confirmQrLogin(@Valid @RequestBody QrLoginConfirmRequest request) {
|
||||
try {
|
||||
QrLoginStatusResponse response = qrLoginService.confirmQrLogin(request);
|
||||
return success("确认成功", response);
|
||||
} catch (Exception e) {
|
||||
return fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 扫码操作(可选接口,用于移动端扫码后更新状态)
|
||||
*/
|
||||
@Operation(summary = "扫码操作")
|
||||
@PostMapping("/scan/{token}")
|
||||
public ApiResult<?> scanQrCode(@Parameter(description = "扫码登录token") @PathVariable String token) {
|
||||
try {
|
||||
boolean result = qrLoginService.scanQrCode(token);
|
||||
return success("操作成功", result);
|
||||
} catch (Exception e) {
|
||||
return fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 微信小程序扫码登录确认(便捷接口)
|
||||
*/
|
||||
@Operation(summary = "微信小程序扫码登录确认")
|
||||
@PostMapping("/wechat-confirm")
|
||||
public ApiResult<?> wechatMiniProgramConfirm(@Valid @RequestBody QrLoginConfirmRequest request) {
|
||||
try {
|
||||
// 设置平台为微信小程序
|
||||
request.setPlatform("miniprogram");
|
||||
QrLoginStatusResponse response = qrLoginService.confirmQrLogin(request);
|
||||
return success("微信小程序登录确认成功", response);
|
||||
} catch (Exception e) {
|
||||
return fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
package com.gxwebsoft.auto.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
|
||||
/**
|
||||
* 扫码登录确认请求
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-08-31
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "扫码登录确认请求")
|
||||
public class QrLoginConfirmRequest {
|
||||
|
||||
@Schema(description = "扫码登录token")
|
||||
@NotBlank(message = "token不能为空")
|
||||
private String token;
|
||||
|
||||
@Schema(description = "用户ID")
|
||||
private Integer userId;
|
||||
|
||||
@Schema(description = "登录平台: web-网页端, app-移动应用, miniprogram-微信小程序")
|
||||
private String platform;
|
||||
|
||||
@Schema(description = "微信小程序相关信息")
|
||||
private WechatMiniProgramInfo wechatInfo;
|
||||
|
||||
/**
|
||||
* 微信小程序信息
|
||||
*/
|
||||
@Data
|
||||
@Schema(description = "微信小程序信息")
|
||||
public static class WechatMiniProgramInfo {
|
||||
@Schema(description = "微信openid")
|
||||
private String openid;
|
||||
|
||||
@Schema(description = "微信unionid")
|
||||
private String unionid;
|
||||
|
||||
@Schema(description = "微信昵称")
|
||||
private String nickname;
|
||||
|
||||
@Schema(description = "微信头像")
|
||||
private String avatar;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
package com.gxwebsoft.auto.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 扫码登录数据模型
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-08-31
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class QrLoginData {
|
||||
|
||||
/**
|
||||
* 扫码登录token
|
||||
*/
|
||||
private String token;
|
||||
|
||||
/**
|
||||
* 状态: pending-等待扫码, scanned-已扫码, confirmed-已确认, expired-已过期
|
||||
*/
|
||||
private String status;
|
||||
|
||||
/**
|
||||
* 用户ID(扫码确认后设置)
|
||||
*/
|
||||
private Integer userId;
|
||||
|
||||
/**
|
||||
* 用户名(扫码确认后设置)
|
||||
*/
|
||||
private String username;
|
||||
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
private LocalDateTime createTime;
|
||||
|
||||
/**
|
||||
* 过期时间
|
||||
*/
|
||||
private LocalDateTime expireTime;
|
||||
|
||||
/**
|
||||
* JWT访问令牌(确认后生成)
|
||||
*/
|
||||
private String accessToken;
|
||||
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package com.gxwebsoft.auto.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* 扫码登录生成响应
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-08-31
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Schema(description = "扫码登录生成响应")
|
||||
public class QrLoginGenerateResponse {
|
||||
|
||||
@Schema(description = "扫码登录token")
|
||||
private String token;
|
||||
|
||||
@Schema(description = "二维码内容")
|
||||
private String qrCode;
|
||||
|
||||
@Schema(description = "过期时间(秒)")
|
||||
private Long expiresIn;
|
||||
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package com.gxwebsoft.auto.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* 扫码登录状态响应
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-08-31
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Schema(description = "扫码登录状态响应")
|
||||
public class QrLoginStatusResponse {
|
||||
|
||||
@Schema(description = "状态: pending-等待扫码, scanned-已扫码, confirmed-已确认, expired-已过期")
|
||||
private String status;
|
||||
|
||||
@Schema(description = "JWT访问令牌(仅在confirmed状态时返回)")
|
||||
private String accessToken;
|
||||
|
||||
@Schema(description = "用户信息(仅在confirmed状态时返回)")
|
||||
private Object userInfo;
|
||||
|
||||
@Schema(description = "剩余过期时间(秒)")
|
||||
private Long expiresIn;
|
||||
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
package com.gxwebsoft.auto.service;
|
||||
|
||||
import com.gxwebsoft.auto.dto.QrLoginConfirmRequest;
|
||||
import com.gxwebsoft.auto.dto.QrLoginGenerateResponse;
|
||||
import com.gxwebsoft.auto.dto.QrLoginStatusResponse;
|
||||
|
||||
/**
|
||||
* 扫码登录服务接口
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-08-31
|
||||
*/
|
||||
public interface QrLoginService {
|
||||
|
||||
/**
|
||||
* 生成扫码登录token
|
||||
*
|
||||
* @return QrLoginGenerateResponse
|
||||
*/
|
||||
QrLoginGenerateResponse generateQrLoginToken();
|
||||
|
||||
/**
|
||||
* 检查扫码登录状态
|
||||
*
|
||||
* @param token 扫码登录token
|
||||
* @return QrLoginStatusResponse
|
||||
*/
|
||||
QrLoginStatusResponse checkQrLoginStatus(String token);
|
||||
|
||||
/**
|
||||
* 确认扫码登录
|
||||
*
|
||||
* @param request 确认请求
|
||||
* @return QrLoginStatusResponse
|
||||
*/
|
||||
QrLoginStatusResponse confirmQrLogin(QrLoginConfirmRequest request);
|
||||
|
||||
/**
|
||||
* 扫码操作(更新状态为已扫码)
|
||||
*
|
||||
* @param token 扫码登录token
|
||||
* @return boolean
|
||||
*/
|
||||
boolean scanQrCode(String token);
|
||||
|
||||
}
|
||||
@@ -1,239 +0,0 @@
|
||||
package com.gxwebsoft.auto.service.impl;
|
||||
|
||||
import cn.hutool.core.lang.UUID;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.gxwebsoft.auto.dto.*;
|
||||
import com.gxwebsoft.auto.service.QrLoginService;
|
||||
import com.gxwebsoft.common.core.security.JwtSubject;
|
||||
import com.gxwebsoft.common.core.security.JwtUtil;
|
||||
import com.gxwebsoft.common.core.utils.JSONUtil;
|
||||
import com.gxwebsoft.common.core.utils.RedisUtil;
|
||||
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.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static com.gxwebsoft.common.core.constants.RedisConstants.*;
|
||||
|
||||
/**
|
||||
* 扫码登录服务实现
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-08-31
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class QrLoginServiceImpl implements QrLoginService {
|
||||
|
||||
@Autowired
|
||||
private RedisUtil redisUtil;
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
@Value("${config.jwt.secret:websoft-jwt-secret-key-2025}")
|
||||
private String jwtSecret;
|
||||
|
||||
@Value("${config.jwt.expire:86400}")
|
||||
private Long jwtExpire;
|
||||
|
||||
@Override
|
||||
public QrLoginGenerateResponse generateQrLoginToken() {
|
||||
// 生成唯一的扫码登录token
|
||||
String token = UUID.randomUUID().toString(true);
|
||||
|
||||
// 创建扫码登录数据
|
||||
QrLoginData qrLoginData = new QrLoginData();
|
||||
qrLoginData.setToken(token);
|
||||
qrLoginData.setStatus(QR_LOGIN_STATUS_PENDING);
|
||||
qrLoginData.setCreateTime(LocalDateTime.now());
|
||||
qrLoginData.setExpireTime(LocalDateTime.now().plusSeconds(QR_LOGIN_TOKEN_TTL));
|
||||
|
||||
// 存储到Redis,设置过期时间
|
||||
String redisKey = QR_LOGIN_TOKEN_KEY + token;
|
||||
redisUtil.set(redisKey, qrLoginData, QR_LOGIN_TOKEN_TTL, TimeUnit.SECONDS);
|
||||
|
||||
log.info("生成扫码登录token: {}", token);
|
||||
|
||||
// 构造二维码内容(这里可以是前端登录页面的URL + token参数)
|
||||
String qrCodeContent = "qr-login:" + token;
|
||||
|
||||
return new QrLoginGenerateResponse(token, qrCodeContent, QR_LOGIN_TOKEN_TTL);
|
||||
}
|
||||
|
||||
@Override
|
||||
public QrLoginStatusResponse checkQrLoginStatus(String token) {
|
||||
if (StrUtil.isBlank(token)) {
|
||||
return new QrLoginStatusResponse(QR_LOGIN_STATUS_EXPIRED, null, null, 0L);
|
||||
}
|
||||
|
||||
String redisKey = QR_LOGIN_TOKEN_KEY + token;
|
||||
QrLoginData qrLoginData = redisUtil.get(redisKey, QrLoginData.class);
|
||||
|
||||
if (qrLoginData == null) {
|
||||
return new QrLoginStatusResponse(QR_LOGIN_STATUS_EXPIRED, null, null, 0L);
|
||||
}
|
||||
|
||||
// 检查是否过期
|
||||
if (LocalDateTime.now().isAfter(qrLoginData.getExpireTime())) {
|
||||
// 删除过期的token
|
||||
redisUtil.delete(redisKey);
|
||||
return new QrLoginStatusResponse(QR_LOGIN_STATUS_EXPIRED, null, null, 0L);
|
||||
}
|
||||
|
||||
// 计算剩余过期时间
|
||||
long expiresIn = ChronoUnit.SECONDS.between(LocalDateTime.now(), qrLoginData.getExpireTime());
|
||||
|
||||
QrLoginStatusResponse response = new QrLoginStatusResponse();
|
||||
response.setStatus(qrLoginData.getStatus());
|
||||
response.setExpiresIn(expiresIn);
|
||||
|
||||
// 如果已确认,返回token和用户信息
|
||||
if (QR_LOGIN_STATUS_CONFIRMED.equals(qrLoginData.getStatus())) {
|
||||
response.setAccessToken(qrLoginData.getAccessToken());
|
||||
|
||||
// 获取用户信息
|
||||
if (qrLoginData.getUserId() != null) {
|
||||
User user = userService.getByIdRel(qrLoginData.getUserId());
|
||||
if (user != null) {
|
||||
// 清除敏感信息
|
||||
user.setPassword(null);
|
||||
response.setUserInfo(user);
|
||||
}
|
||||
}
|
||||
|
||||
// 确认后删除token,防止重复使用
|
||||
redisUtil.delete(redisKey);
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
@Override
|
||||
public QrLoginStatusResponse confirmQrLogin(QrLoginConfirmRequest request) {
|
||||
String token = request.getToken();
|
||||
Integer userId = request.getUserId();
|
||||
String platform = request.getPlatform();
|
||||
|
||||
if (StrUtil.isBlank(token) || userId == null) {
|
||||
throw new RuntimeException("参数不能为空");
|
||||
}
|
||||
|
||||
String redisKey = QR_LOGIN_TOKEN_KEY + token;
|
||||
QrLoginData qrLoginData = redisUtil.get(redisKey, QrLoginData.class);
|
||||
|
||||
if (qrLoginData == null) {
|
||||
throw new RuntimeException("扫码登录token不存在或已过期");
|
||||
}
|
||||
|
||||
// 检查是否过期
|
||||
if (LocalDateTime.now().isAfter(qrLoginData.getExpireTime())) {
|
||||
redisUtil.delete(redisKey);
|
||||
throw new RuntimeException("扫码登录token已过期");
|
||||
}
|
||||
|
||||
// 获取用户信息
|
||||
User user = userService.getByIdRel(userId);
|
||||
if (user == null) {
|
||||
throw new RuntimeException("用户不存在");
|
||||
}
|
||||
|
||||
// 检查用户状态
|
||||
if (user.getStatus() != null && user.getStatus() != 0) {
|
||||
throw new RuntimeException("用户已被冻结");
|
||||
}
|
||||
|
||||
// 如果是微信小程序登录,处理微信相关信息
|
||||
if ("miniprogram".equals(platform) && request.getWechatInfo() != null) {
|
||||
handleWechatMiniProgramLogin(user, request.getWechatInfo());
|
||||
}
|
||||
|
||||
// 生成JWT token
|
||||
JwtSubject jwtSubject = new JwtSubject(user.getUsername(), user.getTenantId());
|
||||
String accessToken = JwtUtil.buildToken(jwtSubject, jwtExpire, jwtSecret);
|
||||
|
||||
// 更新扫码登录数据
|
||||
qrLoginData.setStatus(QR_LOGIN_STATUS_CONFIRMED);
|
||||
qrLoginData.setUserId(userId);
|
||||
qrLoginData.setUsername(user.getUsername());
|
||||
qrLoginData.setAccessToken(accessToken);
|
||||
|
||||
// 更新Redis中的数据
|
||||
redisUtil.set(redisKey, qrLoginData, 60L, TimeUnit.SECONDS); // 给前端60秒时间获取token
|
||||
|
||||
log.info("用户 {} 通过 {} 平台确认扫码登录,token: {}", user.getUsername(),
|
||||
platform != null ? platform : "unknown", token);
|
||||
|
||||
// 清除敏感信息
|
||||
user.setPassword(null);
|
||||
|
||||
return new QrLoginStatusResponse(QR_LOGIN_STATUS_CONFIRMED, accessToken, user, 60L);
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理微信小程序登录相关逻辑
|
||||
*/
|
||||
private void handleWechatMiniProgramLogin(User user, QrLoginConfirmRequest.WechatMiniProgramInfo wechatInfo) {
|
||||
// 更新用户的微信信息
|
||||
if (StrUtil.isNotBlank(wechatInfo.getOpenid())) {
|
||||
user.setOpenid(wechatInfo.getOpenid());
|
||||
}
|
||||
if (StrUtil.isNotBlank(wechatInfo.getUnionid())) {
|
||||
user.setUnionid(wechatInfo.getUnionid());
|
||||
}
|
||||
if (StrUtil.isNotBlank(wechatInfo.getNickname()) && StrUtil.isBlank(user.getNickname())) {
|
||||
user.setNickname(wechatInfo.getNickname());
|
||||
}
|
||||
if (StrUtil.isNotBlank(wechatInfo.getAvatar()) && StrUtil.isBlank(user.getAvatar())) {
|
||||
user.setAvatar(wechatInfo.getAvatar());
|
||||
}
|
||||
|
||||
// 更新用户信息到数据库
|
||||
try {
|
||||
userService.updateById(user);
|
||||
log.info("更新用户 {} 的微信小程序信息成功", user.getUsername());
|
||||
} catch (Exception e) {
|
||||
log.warn("更新用户 {} 的微信小程序信息失败: {}", user.getUsername(), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean scanQrCode(String token) {
|
||||
if (StrUtil.isBlank(token)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String redisKey = QR_LOGIN_TOKEN_KEY + token;
|
||||
QrLoginData qrLoginData = redisUtil.get(redisKey, QrLoginData.class);
|
||||
|
||||
if (qrLoginData == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 检查是否过期
|
||||
if (LocalDateTime.now().isAfter(qrLoginData.getExpireTime())) {
|
||||
redisUtil.delete(redisKey);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 只有pending状态才能更新为scanned
|
||||
if (QR_LOGIN_STATUS_PENDING.equals(qrLoginData.getStatus())) {
|
||||
qrLoginData.setStatus(QR_LOGIN_STATUS_SCANNED);
|
||||
|
||||
// 计算剩余过期时间
|
||||
long remainingSeconds = ChronoUnit.SECONDS.between(LocalDateTime.now(), qrLoginData.getExpireTime());
|
||||
redisUtil.set(redisKey, qrLoginData, remainingSeconds, TimeUnit.SECONDS);
|
||||
|
||||
log.info("扫码登录token {} 状态更新为已扫码", token);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
package com.gxwebsoft.clinic.controller;
|
||||
|
||||
import com.gxwebsoft.common.core.web.BaseController;
|
||||
import com.gxwebsoft.clinic.service.ClinicAppointmentService;
|
||||
import com.gxwebsoft.clinic.entity.ClinicAppointment;
|
||||
import com.gxwebsoft.clinic.param.ClinicAppointmentParam;
|
||||
import com.gxwebsoft.common.core.web.ApiResult;
|
||||
import com.gxwebsoft.common.core.web.PageResult;
|
||||
import com.gxwebsoft.common.core.web.PageParam;
|
||||
import com.gxwebsoft.common.core.web.BatchParam;
|
||||
import com.gxwebsoft.common.core.annotation.OperationLog;
|
||||
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;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 挂号控制器
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-10-19 09:27:04
|
||||
*/
|
||||
@Tag(name = "挂号管理")
|
||||
@RestController
|
||||
@RequestMapping("/api/clinic/clinic-appointment")
|
||||
public class ClinicAppointmentController extends BaseController {
|
||||
@Resource
|
||||
private ClinicAppointmentService clinicAppointmentService;
|
||||
|
||||
@Operation(summary = "分页查询挂号")
|
||||
@GetMapping("/page")
|
||||
public ApiResult<PageResult<ClinicAppointment>> page(ClinicAppointmentParam param) {
|
||||
// 使用关联查询
|
||||
return success(clinicAppointmentService.pageRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicAppointment:list')")
|
||||
@Operation(summary = "查询全部挂号")
|
||||
@GetMapping()
|
||||
public ApiResult<List<ClinicAppointment>> list(ClinicAppointmentParam param) {
|
||||
// 使用关联查询
|
||||
return success(clinicAppointmentService.listRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicAppointment:list')")
|
||||
@Operation(summary = "根据id查询挂号")
|
||||
@GetMapping("/{id}")
|
||||
public ApiResult<ClinicAppointment> get(@PathVariable("id") Integer id) {
|
||||
// 使用关联查询
|
||||
return success(clinicAppointmentService.getByIdRel(id));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicAppointment:save')")
|
||||
@OperationLog
|
||||
@Operation(summary = "添加挂号")
|
||||
@PostMapping()
|
||||
public ApiResult<?> save(@RequestBody ClinicAppointment clinicAppointment) {
|
||||
if (clinicAppointmentService.save(clinicAppointment)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicAppointment:update')")
|
||||
@OperationLog
|
||||
@Operation(summary = "修改挂号")
|
||||
@PutMapping()
|
||||
public ApiResult<?> update(@RequestBody ClinicAppointment clinicAppointment) {
|
||||
if (clinicAppointmentService.updateById(clinicAppointment)) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicAppointment:remove')")
|
||||
@OperationLog
|
||||
@Operation(summary = "删除挂号")
|
||||
@DeleteMapping("/{id}")
|
||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||
if (clinicAppointmentService.removeById(id)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicAppointment:save')")
|
||||
@OperationLog
|
||||
@Operation(summary = "批量添加挂号")
|
||||
@PostMapping("/batch")
|
||||
public ApiResult<?> saveBatch(@RequestBody List<ClinicAppointment> list) {
|
||||
if (clinicAppointmentService.saveBatch(list)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicAppointment:update')")
|
||||
@OperationLog
|
||||
@Operation(summary = "批量修改挂号")
|
||||
@PutMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody BatchParam<ClinicAppointment> batchParam) {
|
||||
if (batchParam.update(clinicAppointmentService, "id")) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicAppointment:remove')")
|
||||
@OperationLog
|
||||
@Operation(summary = "批量删除挂号")
|
||||
@DeleteMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||
if (clinicAppointmentService.removeByIds(ids)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
package com.gxwebsoft.clinic.controller;
|
||||
|
||||
import com.gxwebsoft.common.core.web.BaseController;
|
||||
import com.gxwebsoft.clinic.service.ClinicDoctorApplyService;
|
||||
import com.gxwebsoft.clinic.entity.ClinicDoctorApply;
|
||||
import com.gxwebsoft.clinic.param.ClinicDoctorApplyParam;
|
||||
import com.gxwebsoft.common.core.web.ApiResult;
|
||||
import com.gxwebsoft.common.core.web.PageResult;
|
||||
import com.gxwebsoft.common.core.web.PageParam;
|
||||
import com.gxwebsoft.common.core.web.BatchParam;
|
||||
import com.gxwebsoft.common.core.annotation.OperationLog;
|
||||
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;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 医生入驻申请控制器
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-10-19 09:27:04
|
||||
*/
|
||||
@Tag(name = "医生入驻申请管理")
|
||||
@RestController
|
||||
@RequestMapping("/api/clinic/clinic-doctor-apply")
|
||||
public class ClinicDoctorApplyController extends BaseController {
|
||||
@Resource
|
||||
private ClinicDoctorApplyService clinicDoctorApplyService;
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicDoctorApply:list')")
|
||||
@Operation(summary = "分页查询医生入驻申请")
|
||||
@GetMapping("/page")
|
||||
public ApiResult<PageResult<ClinicDoctorApply>> page(ClinicDoctorApplyParam param) {
|
||||
// 使用关联查询
|
||||
return success(clinicDoctorApplyService.pageRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicDoctorApply:list')")
|
||||
@Operation(summary = "查询全部医生入驻申请")
|
||||
@GetMapping()
|
||||
public ApiResult<List<ClinicDoctorApply>> list(ClinicDoctorApplyParam param) {
|
||||
// 使用关联查询
|
||||
return success(clinicDoctorApplyService.listRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicDoctorApply:list')")
|
||||
@Operation(summary = "根据id查询医生入驻申请")
|
||||
@GetMapping("/{id}")
|
||||
public ApiResult<ClinicDoctorApply> get(@PathVariable("id") Integer id) {
|
||||
// 使用关联查询
|
||||
return success(clinicDoctorApplyService.getByIdRel(id));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicDoctorApply:save')")
|
||||
@OperationLog
|
||||
@Operation(summary = "添加医生入驻申请")
|
||||
@PostMapping()
|
||||
public ApiResult<?> save(@RequestBody ClinicDoctorApply clinicDoctorApply) {
|
||||
// 记录当前登录用户id
|
||||
// User loginUser = getLoginUser();
|
||||
// if (loginUser != null) {
|
||||
// clinicDoctorApply.setUserId(loginUser.getUserId());
|
||||
// }
|
||||
if (clinicDoctorApplyService.save(clinicDoctorApply)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicDoctorApply:update')")
|
||||
@OperationLog
|
||||
@Operation(summary = "修改医生入驻申请")
|
||||
@PutMapping()
|
||||
public ApiResult<?> update(@RequestBody ClinicDoctorApply clinicDoctorApply) {
|
||||
if (clinicDoctorApplyService.updateById(clinicDoctorApply)) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicDoctorApply:remove')")
|
||||
@OperationLog
|
||||
@Operation(summary = "删除医生入驻申请")
|
||||
@DeleteMapping("/{id}")
|
||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||
if (clinicDoctorApplyService.removeById(id)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicDoctorApply:save')")
|
||||
@OperationLog
|
||||
@Operation(summary = "批量添加医生入驻申请")
|
||||
@PostMapping("/batch")
|
||||
public ApiResult<?> saveBatch(@RequestBody List<ClinicDoctorApply> list) {
|
||||
if (clinicDoctorApplyService.saveBatch(list)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicDoctorApply:update')")
|
||||
@OperationLog
|
||||
@Operation(summary = "批量修改医生入驻申请")
|
||||
@PutMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody BatchParam<ClinicDoctorApply> batchParam) {
|
||||
if (batchParam.update(clinicDoctorApplyService, "apply_id")) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicDoctorApply:remove')")
|
||||
@OperationLog
|
||||
@Operation(summary = "批量删除医生入驻申请")
|
||||
@DeleteMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||
if (clinicDoctorApplyService.removeByIds(ids)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
package com.gxwebsoft.clinic.controller;
|
||||
|
||||
import com.gxwebsoft.clinic.entity.ClinicDoctorUser;
|
||||
import com.gxwebsoft.clinic.param.ClinicDoctorUserParam;
|
||||
import com.gxwebsoft.clinic.service.ClinicDoctorUserService;
|
||||
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.BatchParam;
|
||||
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 org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 分销商用户记录表控制器
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-10-23 15:58:21
|
||||
*/
|
||||
@Tag(name = "分销商用户记录表管理")
|
||||
@RestController
|
||||
@RequestMapping("/api/clinic/clinic-doctor-user")
|
||||
public class ClinicDoctorUserController extends BaseController {
|
||||
@Resource
|
||||
private ClinicDoctorUserService clinicDoctorUserService;
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicDoctorUser:list')")
|
||||
@Operation(summary = "分页查询分销商用户记录表")
|
||||
@GetMapping("/page")
|
||||
public ApiResult<PageResult<ClinicDoctorUser>> page(ClinicDoctorUserParam param) {
|
||||
// 使用关联查询
|
||||
return success(clinicDoctorUserService.pageRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicDoctorUser:list')")
|
||||
@Operation(summary = "查询全部分销商用户记录表")
|
||||
@GetMapping()
|
||||
public ApiResult<List<ClinicDoctorUser>> list(ClinicDoctorUserParam param) {
|
||||
// 使用关联查询
|
||||
return success(clinicDoctorUserService.listRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicDoctorUser:list')")
|
||||
@Operation(summary = "根据id查询分销商用户记录表")
|
||||
@GetMapping("/{id}")
|
||||
public ApiResult<ClinicDoctorUser> get(@PathVariable("id") Integer id) {
|
||||
// 使用关联查询
|
||||
return success(clinicDoctorUserService.getByIdRel(id));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicDoctorUser:save')")
|
||||
@OperationLog
|
||||
@Operation(summary = "添加分销商用户记录表")
|
||||
@PostMapping()
|
||||
public ApiResult<?> save(@RequestBody ClinicDoctorUser clinicDoctorUser) {
|
||||
// 记录当前登录用户id
|
||||
User loginUser = getLoginUser();
|
||||
if (loginUser != null) {
|
||||
clinicDoctorUser.setUserId(loginUser.getUserId());
|
||||
}
|
||||
if (clinicDoctorUserService.save(clinicDoctorUser)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicDoctorUser:update')")
|
||||
@OperationLog
|
||||
@Operation(summary = "修改分销商用户记录表")
|
||||
@PutMapping()
|
||||
public ApiResult<?> update(@RequestBody ClinicDoctorUser clinicDoctorUser) {
|
||||
if (clinicDoctorUserService.updateById(clinicDoctorUser)) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicDoctorUser:remove')")
|
||||
@OperationLog
|
||||
@Operation(summary = "删除分销商用户记录表")
|
||||
@DeleteMapping("/{id}")
|
||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||
if (clinicDoctorUserService.removeById(id)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicDoctorUser:save')")
|
||||
@OperationLog
|
||||
@Operation(summary = "批量添加分销商用户记录表")
|
||||
@PostMapping("/batch")
|
||||
public ApiResult<?> saveBatch(@RequestBody List<ClinicDoctorUser> list) {
|
||||
if (clinicDoctorUserService.saveBatch(list)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicDoctorUser:update')")
|
||||
@OperationLog
|
||||
@Operation(summary = "批量修改分销商用户记录表")
|
||||
@PutMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody BatchParam<ClinicDoctorUser> batchParam) {
|
||||
if (batchParam.update(clinicDoctorUserService, "id")) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicDoctorUser:remove')")
|
||||
@OperationLog
|
||||
@Operation(summary = "批量删除分销商用户记录表")
|
||||
@DeleteMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||
if (clinicDoctorUserService.removeByIds(ids)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
package com.gxwebsoft.clinic.controller;
|
||||
|
||||
import com.gxwebsoft.clinic.entity.ClinicMedicine;
|
||||
import com.gxwebsoft.clinic.param.ClinicMedicineParam;
|
||||
import com.gxwebsoft.clinic.service.ClinicMedicineService;
|
||||
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.BatchParam;
|
||||
import com.gxwebsoft.common.core.web.PageResult;
|
||||
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;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 药品库控制器
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-10-22 02:06:32
|
||||
*/
|
||||
@Tag(name = "药品库管理")
|
||||
@RestController
|
||||
@RequestMapping("/api/clinic/clinic-medicine")
|
||||
public class ClinicMedicineController extends BaseController {
|
||||
@Resource
|
||||
private ClinicMedicineService clinicMedicineService;
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicMedicine:list')")
|
||||
@Operation(summary = "分页查询药品库")
|
||||
@GetMapping("/page")
|
||||
public ApiResult<PageResult<ClinicMedicine>> page(ClinicMedicineParam param) {
|
||||
// 使用关联查询
|
||||
return success(clinicMedicineService.pageRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicMedicine:list')")
|
||||
@Operation(summary = "查询全部药品库")
|
||||
@GetMapping()
|
||||
public ApiResult<List<ClinicMedicine>> list(ClinicMedicineParam param) {
|
||||
// 使用关联查询
|
||||
return success(clinicMedicineService.listRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicMedicine:list')")
|
||||
@Operation(summary = "根据id查询药品库")
|
||||
@GetMapping("/{id}")
|
||||
public ApiResult<ClinicMedicine> get(@PathVariable("id") Integer id) {
|
||||
// 使用关联查询
|
||||
return success(clinicMedicineService.getByIdRel(id));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicMedicine:save')")
|
||||
@OperationLog
|
||||
@Operation(summary = "添加药品库")
|
||||
@PostMapping()
|
||||
public ApiResult<?> save(@RequestBody ClinicMedicine clinicMedicine) {
|
||||
// 记录当前登录用户id
|
||||
// User loginUser = getLoginUser();
|
||||
// if (loginUser != null) {
|
||||
// clinicMedicine.setUserId(loginUser.getUserId());
|
||||
// }
|
||||
if (clinicMedicineService.save(clinicMedicine)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicMedicine:update')")
|
||||
@OperationLog
|
||||
@Operation(summary = "修改药品库")
|
||||
@PutMapping()
|
||||
public ApiResult<?> update(@RequestBody ClinicMedicine clinicMedicine) {
|
||||
if (clinicMedicineService.updateById(clinicMedicine)) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicMedicine:remove')")
|
||||
@OperationLog
|
||||
@Operation(summary = "删除药品库")
|
||||
@DeleteMapping("/{id}")
|
||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||
if (clinicMedicineService.removeById(id)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicMedicine:save')")
|
||||
@OperationLog
|
||||
@Operation(summary = "批量添加药品库")
|
||||
@PostMapping("/batch")
|
||||
public ApiResult<?> saveBatch(@RequestBody List<ClinicMedicine> list) {
|
||||
if (clinicMedicineService.saveBatch(list)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicMedicine:update')")
|
||||
@OperationLog
|
||||
@Operation(summary = "批量修改药品库")
|
||||
@PutMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody BatchParam<ClinicMedicine> batchParam) {
|
||||
if (batchParam.update(clinicMedicineService, "id")) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicMedicine:remove')")
|
||||
@OperationLog
|
||||
@Operation(summary = "批量删除药品库")
|
||||
@DeleteMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||
if (clinicMedicineService.removeByIds(ids)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
package com.gxwebsoft.clinic.controller;
|
||||
|
||||
import com.gxwebsoft.clinic.entity.ClinicMedicineInout;
|
||||
import com.gxwebsoft.clinic.param.ClinicMedicineInoutParam;
|
||||
import com.gxwebsoft.clinic.service.ClinicMedicineInoutService;
|
||||
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.BatchParam;
|
||||
import com.gxwebsoft.common.core.web.PageResult;
|
||||
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;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 出入库控制器
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-10-22 02:06:32
|
||||
*/
|
||||
@Tag(name = "出入库管理")
|
||||
@RestController
|
||||
@RequestMapping("/api/clinic/clinic-medicine-inout")
|
||||
public class ClinicMedicineInoutController extends BaseController {
|
||||
@Resource
|
||||
private ClinicMedicineInoutService clinicMedicineInoutService;
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicMedicineInout:list')")
|
||||
@Operation(summary = "分页查询出入库")
|
||||
@GetMapping("/page")
|
||||
public ApiResult<PageResult<ClinicMedicineInout>> page(ClinicMedicineInoutParam param) {
|
||||
// 使用关联查询
|
||||
return success(clinicMedicineInoutService.pageRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicMedicineInout:list')")
|
||||
@Operation(summary = "查询全部出入库")
|
||||
@GetMapping()
|
||||
public ApiResult<List<ClinicMedicineInout>> list(ClinicMedicineInoutParam param) {
|
||||
// 使用关联查询
|
||||
return success(clinicMedicineInoutService.listRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicMedicineInout:list')")
|
||||
@Operation(summary = "根据id查询出入库")
|
||||
@GetMapping("/{id}")
|
||||
public ApiResult<ClinicMedicineInout> get(@PathVariable("id") Integer id) {
|
||||
// 使用关联查询
|
||||
return success(clinicMedicineInoutService.getByIdRel(id));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicMedicineInout:save')")
|
||||
@OperationLog
|
||||
@Operation(summary = "添加出入库")
|
||||
@PostMapping()
|
||||
public ApiResult<?> save(@RequestBody ClinicMedicineInout clinicMedicineInout) {
|
||||
// 记录当前登录用户id
|
||||
// User loginUser = getLoginUser();
|
||||
// if (loginUser != null) {
|
||||
// clinicMedicineInout.setUserId(loginUser.getUserId());
|
||||
// }
|
||||
if (clinicMedicineInoutService.save(clinicMedicineInout)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicMedicineInout:update')")
|
||||
@OperationLog
|
||||
@Operation(summary = "修改出入库")
|
||||
@PutMapping()
|
||||
public ApiResult<?> update(@RequestBody ClinicMedicineInout clinicMedicineInout) {
|
||||
if (clinicMedicineInoutService.updateById(clinicMedicineInout)) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicMedicineInout:remove')")
|
||||
@OperationLog
|
||||
@Operation(summary = "删除出入库")
|
||||
@DeleteMapping("/{id}")
|
||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||
if (clinicMedicineInoutService.removeById(id)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicMedicineInout:save')")
|
||||
@OperationLog
|
||||
@Operation(summary = "批量添加出入库")
|
||||
@PostMapping("/batch")
|
||||
public ApiResult<?> saveBatch(@RequestBody List<ClinicMedicineInout> list) {
|
||||
if (clinicMedicineInoutService.saveBatch(list)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicMedicineInout:update')")
|
||||
@OperationLog
|
||||
@Operation(summary = "批量修改出入库")
|
||||
@PutMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody BatchParam<ClinicMedicineInout> batchParam) {
|
||||
if (batchParam.update(clinicMedicineInoutService, "id")) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicMedicineInout:remove')")
|
||||
@OperationLog
|
||||
@Operation(summary = "批量删除出入库")
|
||||
@DeleteMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||
if (clinicMedicineInoutService.removeByIds(ids)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
package com.gxwebsoft.clinic.controller;
|
||||
|
||||
import com.gxwebsoft.clinic.entity.ClinicMedicineStock;
|
||||
import com.gxwebsoft.clinic.param.ClinicMedicineStockParam;
|
||||
import com.gxwebsoft.clinic.service.ClinicMedicineStockService;
|
||||
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.BatchParam;
|
||||
import com.gxwebsoft.common.core.web.PageResult;
|
||||
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;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 药品库存控制器
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-10-22 02:06:32
|
||||
*/
|
||||
@Tag(name = "药品库存管理")
|
||||
@RestController
|
||||
@RequestMapping("/api/clinic/clinic-medicine-stock")
|
||||
public class ClinicMedicineStockController extends BaseController {
|
||||
@Resource
|
||||
private ClinicMedicineStockService clinicMedicineStockService;
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicMedicineStock:list')")
|
||||
@Operation(summary = "分页查询药品库存")
|
||||
@GetMapping("/page")
|
||||
public ApiResult<PageResult<ClinicMedicineStock>> page(ClinicMedicineStockParam param) {
|
||||
// 使用关联查询
|
||||
return success(clinicMedicineStockService.pageRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicMedicineStock:list')")
|
||||
@Operation(summary = "查询全部药品库存")
|
||||
@GetMapping()
|
||||
public ApiResult<List<ClinicMedicineStock>> list(ClinicMedicineStockParam param) {
|
||||
// 使用关联查询
|
||||
return success(clinicMedicineStockService.listRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicMedicineStock:list')")
|
||||
@Operation(summary = "根据id查询药品库存")
|
||||
@GetMapping("/{id}")
|
||||
public ApiResult<ClinicMedicineStock> get(@PathVariable("id") Integer id) {
|
||||
// 使用关联查询
|
||||
return success(clinicMedicineStockService.getByIdRel(id));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicMedicineStock:save')")
|
||||
@OperationLog
|
||||
@Operation(summary = "添加药品库存")
|
||||
@PostMapping()
|
||||
public ApiResult<?> save(@RequestBody ClinicMedicineStock clinicMedicineStock) {
|
||||
// 记录当前登录用户id
|
||||
// User loginUser = getLoginUser();
|
||||
// if (loginUser != null) {
|
||||
// clinicMedicineStock.setUserId(loginUser.getUserId());
|
||||
// }
|
||||
if (clinicMedicineStockService.save(clinicMedicineStock)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicMedicineStock:update')")
|
||||
@OperationLog
|
||||
@Operation(summary = "修改药品库存")
|
||||
@PutMapping()
|
||||
public ApiResult<?> update(@RequestBody ClinicMedicineStock clinicMedicineStock) {
|
||||
if (clinicMedicineStockService.updateById(clinicMedicineStock)) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicMedicineStock:remove')")
|
||||
@OperationLog
|
||||
@Operation(summary = "删除药品库存")
|
||||
@DeleteMapping("/{id}")
|
||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||
if (clinicMedicineStockService.removeById(id)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicMedicineStock:save')")
|
||||
@OperationLog
|
||||
@Operation(summary = "批量添加药品库存")
|
||||
@PostMapping("/batch")
|
||||
public ApiResult<?> saveBatch(@RequestBody List<ClinicMedicineStock> list) {
|
||||
if (clinicMedicineStockService.saveBatch(list)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicMedicineStock:update')")
|
||||
@OperationLog
|
||||
@Operation(summary = "批量修改药品库存")
|
||||
@PutMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody BatchParam<ClinicMedicineStock> batchParam) {
|
||||
if (batchParam.update(clinicMedicineStockService, "id")) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicMedicineStock:remove')")
|
||||
@OperationLog
|
||||
@Operation(summary = "批量删除药品库存")
|
||||
@DeleteMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||
if (clinicMedicineStockService.removeByIds(ids)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
package com.gxwebsoft.clinic.controller;
|
||||
|
||||
import com.gxwebsoft.common.core.web.BaseController;
|
||||
import com.gxwebsoft.clinic.service.ClinicPatientUserService;
|
||||
import com.gxwebsoft.clinic.entity.ClinicPatientUser;
|
||||
import com.gxwebsoft.clinic.param.ClinicPatientUserParam;
|
||||
import com.gxwebsoft.common.core.web.ApiResult;
|
||||
import com.gxwebsoft.common.core.web.PageResult;
|
||||
import com.gxwebsoft.common.core.web.PageParam;
|
||||
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 org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 患者控制器
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-10-19 09:27:04
|
||||
*/
|
||||
@Tag(name = "患者管理")
|
||||
@RestController
|
||||
@RequestMapping("/api/clinic/clinic-patient-user")
|
||||
public class ClinicPatientUserController extends BaseController {
|
||||
@Resource
|
||||
private ClinicPatientUserService clinicPatientUserService;
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicPatientUser:list')")
|
||||
@Operation(summary = "分页查询患者")
|
||||
@GetMapping("/page")
|
||||
public ApiResult<PageResult<ClinicPatientUser>> page(ClinicPatientUserParam param) {
|
||||
// 使用关联查询
|
||||
return success(clinicPatientUserService.pageRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicPatientUser:list')")
|
||||
@Operation(summary = "查询全部患者")
|
||||
@GetMapping()
|
||||
public ApiResult<List<ClinicPatientUser>> list(ClinicPatientUserParam param) {
|
||||
// 使用关联查询
|
||||
return success(clinicPatientUserService.listRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicPatientUser:list')")
|
||||
@Operation(summary = "根据id查询患者")
|
||||
@GetMapping("/{id}")
|
||||
public ApiResult<ClinicPatientUser> get(@PathVariable("id") Integer id) {
|
||||
// 使用关联查询
|
||||
return success(clinicPatientUserService.getByIdRel(id));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicPatientUser:save')")
|
||||
@OperationLog
|
||||
@Operation(summary = "添加患者")
|
||||
@PostMapping()
|
||||
public ApiResult<?> save(@RequestBody ClinicPatientUser clinicPatientUser) {
|
||||
// 记录当前登录用户id
|
||||
User loginUser = getLoginUser();
|
||||
if (loginUser != null) {
|
||||
clinicPatientUser.setUserId(loginUser.getUserId());
|
||||
}
|
||||
if (clinicPatientUserService.save(clinicPatientUser)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicPatientUser:update')")
|
||||
@OperationLog
|
||||
@Operation(summary = "修改患者")
|
||||
@PutMapping()
|
||||
public ApiResult<?> update(@RequestBody ClinicPatientUser clinicPatientUser) {
|
||||
if (clinicPatientUserService.updateById(clinicPatientUser)) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicPatientUser:remove')")
|
||||
@OperationLog
|
||||
@Operation(summary = "删除患者")
|
||||
@DeleteMapping("/{id}")
|
||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||
if (clinicPatientUserService.removeById(id)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicPatientUser:save')")
|
||||
@OperationLog
|
||||
@Operation(summary = "批量添加患者")
|
||||
@PostMapping("/batch")
|
||||
public ApiResult<?> saveBatch(@RequestBody List<ClinicPatientUser> list) {
|
||||
if (clinicPatientUserService.saveBatch(list)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicPatientUser:update')")
|
||||
@OperationLog
|
||||
@Operation(summary = "批量修改患者")
|
||||
@PutMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody BatchParam<ClinicPatientUser> batchParam) {
|
||||
if (batchParam.update(clinicPatientUserService, "id")) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicPatientUser:remove')")
|
||||
@OperationLog
|
||||
@Operation(summary = "批量删除患者")
|
||||
@DeleteMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||
if (clinicPatientUserService.removeByIds(ids)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,191 +0,0 @@
|
||||
package com.gxwebsoft.clinic.controller;
|
||||
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import com.gxwebsoft.clinic.dto.PrescriptionOrderRequest;
|
||||
import com.gxwebsoft.clinic.entity.ClinicPrescription;
|
||||
import com.gxwebsoft.clinic.param.ClinicPrescriptionParam;
|
||||
import com.gxwebsoft.clinic.service.ClinicPrescriptionService;
|
||||
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.BatchParam;
|
||||
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.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 处方主表
|
||||
控制器
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-10-22 02:01:13
|
||||
*/
|
||||
@Tag(name = "处方主表管理")
|
||||
@RestController
|
||||
@RequestMapping("/api/clinic/clinic-prescription")
|
||||
public class ClinicPrescriptionController extends BaseController {
|
||||
@Resource
|
||||
private ClinicPrescriptionService clinicPrescriptionService;
|
||||
|
||||
@Operation(summary = "分页查询处方主表")
|
||||
@GetMapping("/page")
|
||||
public ApiResult<PageResult<ClinicPrescription>> page(ClinicPrescriptionParam param) {
|
||||
// 使用关联查询
|
||||
return success(clinicPrescriptionService.pageRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicPrescription:list')")
|
||||
@Operation(summary = "查询全部处方主表")
|
||||
@GetMapping()
|
||||
public ApiResult<List<ClinicPrescription>> list(ClinicPrescriptionParam param) {
|
||||
// 使用关联查询
|
||||
return success(clinicPrescriptionService.listRel(param));
|
||||
}
|
||||
|
||||
@Operation(summary = "根据id查询处方主表")
|
||||
@GetMapping("/{id}")
|
||||
public ApiResult<ClinicPrescription> get(@PathVariable("id") Integer id) {
|
||||
// 使用关联查询
|
||||
return success(clinicPrescriptionService.getByIdRel(id));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicPrescription:save')")
|
||||
@OperationLog
|
||||
@Operation(summary = "添加处方主表")
|
||||
@PostMapping()
|
||||
public ApiResult<?> save(@RequestBody ClinicPrescription clinicPrescription) {
|
||||
// 记录当前登录用户id
|
||||
User loginUser = getLoginUser();
|
||||
if (loginUser != null) {
|
||||
clinicPrescription.setDoctorId(loginUser.getUserId());
|
||||
// 生成订单号
|
||||
String orderNo = Long.toString(IdUtil.getSnowflakeNextId());
|
||||
clinicPrescription.setOrderNo(orderNo);
|
||||
}
|
||||
if (clinicPrescriptionService.save(clinicPrescription)) {
|
||||
// 返回处方数据,包含处方ID
|
||||
return success("添加成功",clinicPrescriptionService.getByLastId(clinicPrescription));
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicPrescription:update')")
|
||||
@OperationLog
|
||||
@Operation(summary = "修改处方主表")
|
||||
@PutMapping()
|
||||
public ApiResult<?> update(@RequestBody ClinicPrescription clinicPrescription) {
|
||||
if (clinicPrescriptionService.updateById(clinicPrescription)) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicPrescription:remove')")
|
||||
@OperationLog
|
||||
@Operation(summary = "删除处方主表")
|
||||
@DeleteMapping("/{id}")
|
||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||
if (clinicPrescriptionService.removeById(id)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicPrescription:save')")
|
||||
@OperationLog
|
||||
@Operation(summary = "批量添加处方主表")
|
||||
@PostMapping("/batch")
|
||||
public ApiResult<?> saveBatch(@RequestBody List<ClinicPrescription> list) {
|
||||
if (clinicPrescriptionService.saveBatch(list)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicPrescription:update')")
|
||||
@OperationLog
|
||||
@Operation(summary = "批量修改处方主表")
|
||||
@PutMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody BatchParam<ClinicPrescription> batchParam) {
|
||||
if (batchParam.update(clinicPrescriptionService, "id")) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicPrescription:remove')")
|
||||
@OperationLog
|
||||
@Operation(summary = "批量删除处方主表")
|
||||
@DeleteMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||
if (clinicPrescriptionService.removeByIds(ids)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@Operation(summary = "创建处方订单")
|
||||
@PostMapping("/order")
|
||||
public ApiResult<?> createOrder(@RequestBody PrescriptionOrderRequest request) {
|
||||
try {
|
||||
// 1. 参数校验
|
||||
if (request.getPrescriptionId() == null) {
|
||||
return fail("处方ID不能为空");
|
||||
}
|
||||
if (request.getPayType() == null) {
|
||||
return fail("支付方式不能为空");
|
||||
}
|
||||
|
||||
// 2. 查询处方信息
|
||||
ClinicPrescription prescription = clinicPrescriptionService.getById(request.getPrescriptionId());
|
||||
if (prescription == null) {
|
||||
return fail("处方不存在");
|
||||
}
|
||||
|
||||
// 3. 检查处方状态
|
||||
if (prescription.getStatus() != null && prescription.getStatus() == 2) {
|
||||
return fail("该处方已支付,无需重复支付");
|
||||
}
|
||||
if (prescription.getStatus() != null && prescription.getStatus() == 3) {
|
||||
return fail("该处方已取消,无法支付");
|
||||
}
|
||||
|
||||
// 4. 更新处方订单信息
|
||||
ClinicPrescription updatePrescription = new ClinicPrescription();
|
||||
updatePrescription.setId(request.getPrescriptionId());
|
||||
|
||||
// 根据支付类型更新状态
|
||||
if (request.getPayType() == 1) {
|
||||
// 微信支付,状态保持为正常,等待支付回调
|
||||
updatePrescription.setStatus(0);
|
||||
} else if (request.getPayType() == 4 || request.getPayType() == 5) {
|
||||
// 现金支付或POS机支付,直接标记为已支付
|
||||
updatePrescription.setStatus(2);
|
||||
updatePrescription.setIsSettled(1);
|
||||
updatePrescription.setSettleTime(LocalDateTime.now());
|
||||
} else if (request.getPayType() == 6) {
|
||||
// 免费,直接标记为已完成
|
||||
updatePrescription.setStatus(1);
|
||||
updatePrescription.setIsSettled(1);
|
||||
updatePrescription.setSettleTime(LocalDateTime.now());
|
||||
}
|
||||
|
||||
if (clinicPrescriptionService.updateById(updatePrescription)) {
|
||||
return success("订单创建成功", prescription);
|
||||
}
|
||||
return fail("订单创建失败");
|
||||
|
||||
} catch (Exception e) {
|
||||
return fail("订单创建失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
package com.gxwebsoft.clinic.controller;
|
||||
|
||||
import com.gxwebsoft.clinic.entity.ClinicPrescriptionItem;
|
||||
import com.gxwebsoft.clinic.param.ClinicPrescriptionItemParam;
|
||||
import com.gxwebsoft.clinic.service.ClinicPrescriptionItemService;
|
||||
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.BatchParam;
|
||||
import com.gxwebsoft.common.core.web.PageResult;
|
||||
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;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 处方明细表
|
||||
控制器
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-10-22 02:01:13
|
||||
*/
|
||||
@Tag(name = "处方明细表管理")
|
||||
@RestController
|
||||
@RequestMapping("/api/clinic/clinic-prescription-item")
|
||||
public class ClinicPrescriptionItemController extends BaseController {
|
||||
@Resource
|
||||
private ClinicPrescriptionItemService clinicPrescriptionItemService;
|
||||
|
||||
@Operation(summary = "分页查询处方明细表")
|
||||
@GetMapping("/page")
|
||||
public ApiResult<PageResult<ClinicPrescriptionItem>> page(ClinicPrescriptionItemParam param) {
|
||||
// 使用关联查询
|
||||
return success(clinicPrescriptionItemService.pageRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicPrescription:list')")
|
||||
@Operation(summary = "查询全部处方明细表")
|
||||
@GetMapping()
|
||||
public ApiResult<List<ClinicPrescriptionItem>> list(ClinicPrescriptionItemParam param) {
|
||||
// 使用关联查询
|
||||
return success(clinicPrescriptionItemService.listRel(param));
|
||||
}
|
||||
|
||||
@Operation(summary = "根据id查询处方明细表")
|
||||
@GetMapping("/{id}")
|
||||
public ApiResult<ClinicPrescriptionItem> get(@PathVariable("id") Integer id) {
|
||||
// 使用关联查询
|
||||
return success(clinicPrescriptionItemService.getByIdRel(id));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicPrescription:save')")
|
||||
@OperationLog
|
||||
@Operation(summary = "添加处方明细表")
|
||||
@PostMapping()
|
||||
public ApiResult<?> save(@RequestBody ClinicPrescriptionItem clinicPrescriptionItem) {
|
||||
if (clinicPrescriptionItemService.save(clinicPrescriptionItem)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicPrescription:update')")
|
||||
@OperationLog
|
||||
@Operation(summary = "修改处方明细表")
|
||||
@PutMapping()
|
||||
public ApiResult<?> update(@RequestBody ClinicPrescriptionItem clinicPrescriptionItem) {
|
||||
if (clinicPrescriptionItemService.updateById(clinicPrescriptionItem)) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicPrescription:remove')")
|
||||
@OperationLog
|
||||
@Operation(summary = "删除处方明细表")
|
||||
@DeleteMapping("/{id}")
|
||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||
if (clinicPrescriptionItemService.removeById(id)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicPrescription:save')")
|
||||
@OperationLog
|
||||
@Operation(summary = "批量添加处方明细表")
|
||||
@PostMapping("/batch")
|
||||
public ApiResult<?> saveBatch(@RequestBody List<ClinicPrescriptionItem> list) {
|
||||
if (clinicPrescriptionItemService.saveBatch(list)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicPrescription:update')")
|
||||
@OperationLog
|
||||
@Operation(summary = "批量修改处方明细表")
|
||||
@PutMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody BatchParam<ClinicPrescriptionItem> batchParam) {
|
||||
if (batchParam.update(clinicPrescriptionItemService, "id")) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('clinic:clinicPrescription:remove')")
|
||||
@OperationLog
|
||||
@Operation(summary = "批量删除处方明细表")
|
||||
@DeleteMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||
if (clinicPrescriptionItemService.removeByIds(ids)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
}
|
||||
Binary file not shown.
@@ -1,24 +0,0 @@
|
||||
package com.gxwebsoft.clinic.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* 处方订单请求参数
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-11-03
|
||||
*/
|
||||
@Data
|
||||
@Schema(name = "PrescriptionOrderRequest", description = "处方订单请求参数")
|
||||
public class PrescriptionOrderRequest implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Schema(description = "处方ID", required = true)
|
||||
private Integer prescriptionId;
|
||||
|
||||
@Schema(description = "支付方式:0余额支付,1微信支付,2支付宝支付,3银联支付,4现金支付,5POS机支付,6免费,7积分支付", required = true)
|
||||
private Integer payType;
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
package com.gxwebsoft.clinic.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import java.time.LocalDateTime;
|
||||
import java.io.Serializable;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
|
||||
/**
|
||||
* 挂号
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-10-19 09:27:03
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@Schema(name = "ClinicAppointment对象", description = "挂号")
|
||||
public class ClinicAppointment implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Schema(description = "主键ID")
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Integer id;
|
||||
|
||||
@Schema(description = "类型")
|
||||
private Integer type;
|
||||
|
||||
@Schema(description = "就诊原因")
|
||||
private String reason;
|
||||
|
||||
@Schema(description = "挂号时间")
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private LocalDateTime evaluateTime;
|
||||
|
||||
@Schema(description = "医生")
|
||||
private Integer doctorId;
|
||||
|
||||
@Schema(description = "医生名称")
|
||||
@TableField(exist = false)
|
||||
private String doctorName;
|
||||
|
||||
@Schema(description = "医生职位")
|
||||
@TableField(exist = false)
|
||||
private String doctorPosition;
|
||||
|
||||
@Schema(description = "患者")
|
||||
private Integer userId;
|
||||
|
||||
@Schema(description = "患者名称")
|
||||
@TableField(exist = false)
|
||||
private String nickname;
|
||||
|
||||
@Schema(description = "手机")
|
||||
@TableField(exist = false)
|
||||
private String phone;
|
||||
|
||||
@Schema(description = "备注")
|
||||
private String comments;
|
||||
|
||||
@Schema(description = "排序号")
|
||||
private Integer sortNumber;
|
||||
|
||||
@Schema(description = "是否删除")
|
||||
private Integer isDelete;
|
||||
|
||||
@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;
|
||||
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
package com.gxwebsoft.clinic.entity;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import java.time.LocalDate;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import java.time.LocalDateTime;
|
||||
import java.io.Serializable;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
|
||||
/**
|
||||
* 医生入驻申请
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-10-19 09:27:04
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@Schema(name = "ClinicDoctorApply对象", description = "医生入驻申请")
|
||||
public class ClinicDoctorApply implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Schema(description = "主键ID")
|
||||
@TableId(value = "apply_id", type = IdType.AUTO)
|
||||
private Integer applyId;
|
||||
|
||||
@Schema(description = "类型 0医生")
|
||||
private Integer type;
|
||||
|
||||
@Schema(description = "用户ID")
|
||||
private Integer userId;
|
||||
|
||||
@Schema(description = "姓名")
|
||||
private String realName;
|
||||
|
||||
@Schema(description = "性别 1男 2女")
|
||||
private Integer gender;
|
||||
|
||||
@Schema(description = "手机号")
|
||||
private String mobile;
|
||||
|
||||
@Schema(description = "客户名称")
|
||||
private String dealerName;
|
||||
|
||||
@Schema(description = "证件号码")
|
||||
private String idCard;
|
||||
|
||||
@Schema(description = "生日")
|
||||
@JsonFormat(pattern = "yyyy-MM-dd")
|
||||
private LocalDate birthDate;
|
||||
|
||||
@Schema(description = "区分职称等级(如主治医师、副主任医师)")
|
||||
private String professionalTitle;
|
||||
|
||||
@Schema(description = "工作单位")
|
||||
private String workUnit;
|
||||
|
||||
@Schema(description = "执业资格核心凭证")
|
||||
private String practiceLicense;
|
||||
|
||||
@Schema(description = "限定可执业科室或疾病类型")
|
||||
private String practiceScope;
|
||||
|
||||
@Schema(description = "开始工作时间")
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private LocalDateTime startWorkDate;
|
||||
|
||||
@Schema(description = "简历")
|
||||
private String resume;
|
||||
|
||||
@Schema(description = "使用 JSON 存储多个证件文件路径(如执业证、学历证)")
|
||||
private String certificationFiles;
|
||||
|
||||
@Schema(description = "详细地址")
|
||||
private String address;
|
||||
|
||||
@Schema(description = "签约价格")
|
||||
private BigDecimal money;
|
||||
|
||||
@Schema(description = "推荐人用户ID")
|
||||
private Integer refereeId;
|
||||
|
||||
@Schema(description = "申请方式(10需后台审核 20无需审核)")
|
||||
private Integer applyType;
|
||||
|
||||
@Schema(description = "审核状态 (10待审核 20审核通过 30驳回)")
|
||||
private Integer applyStatus;
|
||||
|
||||
@Schema(description = "申请时间")
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private LocalDateTime applyTime;
|
||||
|
||||
@Schema(description = "审核时间")
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private LocalDateTime auditTime;
|
||||
|
||||
@Schema(description = "合同时间")
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private LocalDateTime contractTime;
|
||||
|
||||
@Schema(description = "过期时间")
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private LocalDateTime expirationTime;
|
||||
|
||||
@Schema(description = "驳回原因")
|
||||
private String rejectReason;
|
||||
|
||||
@Schema(description = "备注")
|
||||
private String comments;
|
||||
|
||||
@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;
|
||||
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
package com.gxwebsoft.clinic.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
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.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 分销商用户记录表
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-10-23 15:58:20
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@Schema(name = "ClinicDoctorUser对象", description = "分销商用户记录表")
|
||||
public class ClinicDoctorUser implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Schema(description = "主键ID")
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Integer id;
|
||||
|
||||
@Schema(description = "类型 0经销商 1企业 2集团")
|
||||
private Integer type;
|
||||
|
||||
@Schema(description = "自增ID")
|
||||
private Integer userId;
|
||||
|
||||
@Schema(description = "昵称")
|
||||
@TableField(exist = false)
|
||||
private String nickname;
|
||||
|
||||
@Schema(description = "头像")
|
||||
@TableField(exist = false)
|
||||
private String avatar;
|
||||
|
||||
@Schema(description = "姓名")
|
||||
private String realName;
|
||||
|
||||
@Schema(description = "手机号")
|
||||
@TableField(exist = false)
|
||||
private String phone;
|
||||
|
||||
@Schema(description = "部门")
|
||||
private Integer departmentId;
|
||||
|
||||
@Schema(description = "专业领域")
|
||||
private String specialty;
|
||||
|
||||
@Schema(description = "职务级别")
|
||||
private String position;
|
||||
|
||||
@Schema(description = "执业资格")
|
||||
private String qualification;
|
||||
|
||||
@Schema(description = "医生简介")
|
||||
private String introduction;
|
||||
|
||||
@Schema(description = "挂号费")
|
||||
private BigDecimal consultationFee;
|
||||
|
||||
@Schema(description = "工作年限")
|
||||
private Integer workYears;
|
||||
|
||||
@Schema(description = "问诊人数")
|
||||
private Integer consultationCount;
|
||||
|
||||
@Schema(description = "专属二维码")
|
||||
private String qrcode;
|
||||
|
||||
@Schema(description = "备注")
|
||||
private String comments;
|
||||
|
||||
@Schema(description = "排序号")
|
||||
private Integer sortNumber;
|
||||
|
||||
@Schema(description = "是否删除")
|
||||
private Integer isDelete;
|
||||
|
||||
@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;
|
||||
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
package com.gxwebsoft.clinic.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
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.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 药品库
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-10-22 02:06:31
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@Schema(name = "ClinicMedicine对象", description = "药品库")
|
||||
public class ClinicMedicine implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Schema(description = "主键ID")
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Integer id;
|
||||
|
||||
@Schema(description = "药名")
|
||||
private String name;
|
||||
|
||||
@Schema(description = "拼音")
|
||||
private String pinyin;
|
||||
|
||||
@Schema(description = "分类(如“清热解毒”、“补气养血”)")
|
||||
private String category;
|
||||
|
||||
@Schema(description = "规格(如“饮片”、“颗粒”)")
|
||||
private String specification;
|
||||
|
||||
@Schema(description = "单位(如“克”、“袋”)")
|
||||
private String unit;
|
||||
|
||||
@Schema(description = "描述")
|
||||
private String content;
|
||||
|
||||
@Schema(description = "单价")
|
||||
private BigDecimal pricePerUnit;
|
||||
|
||||
@Schema(description = "是否活跃")
|
||||
private Integer isActive;
|
||||
|
||||
@Schema(description = "买家用户ID")
|
||||
private Integer userId;
|
||||
|
||||
@Schema(description = "备注")
|
||||
private String comments;
|
||||
|
||||
@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;
|
||||
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
package com.gxwebsoft.clinic.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
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.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 出入库
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-10-22 02:06:32
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@Schema(name = "ClinicMedicineInout对象", description = "出入库")
|
||||
public class ClinicMedicineInout implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Schema(description = "主键ID")
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Integer id;
|
||||
|
||||
@Schema(description = "买家用户ID")
|
||||
private Integer userId;
|
||||
|
||||
@Schema(description = "订单编号")
|
||||
private String orderNo;
|
||||
|
||||
@Schema(description = "分销商用户id(一级)")
|
||||
private Integer firstUserId;
|
||||
|
||||
@Schema(description = "分销商用户id(二级)")
|
||||
private Integer secondUserId;
|
||||
|
||||
@Schema(description = "分销商用户id(三级)")
|
||||
private Integer thirdUserId;
|
||||
|
||||
@Schema(description = "分销佣金(一级)")
|
||||
private BigDecimal firstMoney;
|
||||
|
||||
@Schema(description = "分销佣金(二级)")
|
||||
private BigDecimal secondMoney;
|
||||
|
||||
@Schema(description = "分销佣金(三级)")
|
||||
private BigDecimal thirdMoney;
|
||||
|
||||
@Schema(description = "单价")
|
||||
private BigDecimal price;
|
||||
|
||||
@Schema(description = "订单总金额")
|
||||
private BigDecimal orderPrice;
|
||||
|
||||
@Schema(description = "结算金额")
|
||||
private BigDecimal settledPrice;
|
||||
|
||||
@Schema(description = "换算成度")
|
||||
private BigDecimal degreePrice;
|
||||
|
||||
@Schema(description = "实发金额")
|
||||
private BigDecimal payPrice;
|
||||
|
||||
@Schema(description = "税率")
|
||||
private BigDecimal rate;
|
||||
|
||||
@Schema(description = "结算月份")
|
||||
private String month;
|
||||
|
||||
@Schema(description = "订单是否失效(0未失效 1已失效)")
|
||||
private Integer isInvalid;
|
||||
|
||||
@Schema(description = "佣金结算(0未结算 1已结算)")
|
||||
private Integer isSettled;
|
||||
|
||||
@Schema(description = "结算时间")
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private LocalDateTime settleTime;
|
||||
|
||||
@Schema(description = "备注")
|
||||
private String comments;
|
||||
|
||||
@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;
|
||||
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
package com.gxwebsoft.clinic.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
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 2025-10-22 02:06:32
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@Schema(name = "ClinicMedicineStock对象", description = "药品库存")
|
||||
public class ClinicMedicineStock implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Schema(description = "主键ID")
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Integer id;
|
||||
|
||||
@Schema(description = "药品")
|
||||
private Integer medicineId;
|
||||
|
||||
@Schema(description = "库存数量")
|
||||
private Integer stockQuantity;
|
||||
|
||||
@Schema(description = "最小库存预警")
|
||||
private Integer minStockLevel;
|
||||
|
||||
@Schema(description = "上次更新时间")
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private LocalDateTime lastUpdated;
|
||||
|
||||
@Schema(description = "买家用户ID")
|
||||
private Integer userId;
|
||||
|
||||
@Schema(description = "备注")
|
||||
private String comments;
|
||||
|
||||
@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;
|
||||
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
package com.gxwebsoft.clinic.entity;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import java.time.LocalDateTime;
|
||||
import java.io.Serializable;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
|
||||
/**
|
||||
* 患者
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-10-19 09:27:04
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@Schema(name = "ClinicPatientUser对象", description = "患者")
|
||||
public class ClinicPatientUser implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Schema(description = "主键ID")
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Integer id;
|
||||
|
||||
@Schema(description = "类型 0经销商 1企业 2集团")
|
||||
private Integer type;
|
||||
|
||||
@Schema(description = "自增ID")
|
||||
private Integer userId;
|
||||
|
||||
@Schema(description = "姓名")
|
||||
private String realName;
|
||||
|
||||
@Schema(description = "头像")
|
||||
@TableField(exist = false)
|
||||
private String avatar;
|
||||
|
||||
@Schema(description = "手机号")
|
||||
@TableField(exist = false)
|
||||
private String phone;
|
||||
|
||||
@Schema(description = "性别 0未知 1男 2女")
|
||||
private Integer sex;
|
||||
|
||||
@Schema(description = "年龄")
|
||||
private Integer age;
|
||||
|
||||
@Schema(description = "身高")
|
||||
private String height;
|
||||
|
||||
@Schema(description = "体重")
|
||||
private String weight;
|
||||
|
||||
@Schema(description = "过敏史")
|
||||
private String allergyHistory;
|
||||
|
||||
@Schema(description = "专属二维码")
|
||||
private String qrcode;
|
||||
|
||||
@Schema(description = "备注")
|
||||
private String comments;
|
||||
|
||||
@Schema(description = "排序号")
|
||||
private Integer sortNumber;
|
||||
|
||||
@Schema(description = "是否删除")
|
||||
private Integer isDelete;
|
||||
|
||||
@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;
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user