master
xiaoning 5 days ago
commit 948a3fced5

@ -0,0 +1 @@
custom: http://doc.ruoyi.vip/ruoyi-vue/other/donate.html

47
.gitignore vendored

@ -0,0 +1,47 @@
######################################################################
# Build Tools
.gradle
/build/
!gradle/wrapper/gradle-wrapper.jar
target/
!.mvn/wrapper/maven-wrapper.jar
######################################################################
# IDE
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### JRebel ###
rebel.xml
### NetBeans ###
nbproject/private/
build/*
nbbuild/
dist/
nbdist/
.nb-gradle/
######################################################################
# Others
*.log
*.xml.versionsBackup
*.swp
!*/build/*.java
!*/build/*.html
!*/build/*.xml

@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright (c) 2018 RuoYi
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

@ -0,0 +1,97 @@
<p align="center">
<img alt="logo" src="https://oscimg.oschina.net/oscnet/up-d3d0a9303e11d522a06cd263f3079027715.png">
</p>
<h1 align="center" style="margin: 30px 0 30px; font-weight: bold;">RuoYi v3.8.3</h1>
<h4 align="center">基于SpringBoot+Vue前后端分离的Java快速开发框架</h4>
<p align="center">
<a href="https://gitee.com/y_project/RuoYi-Vue/stargazers"><img src="https://gitee.com/y_project/RuoYi-Vue/badge/star.svg?theme=dark"></a>
<a href="https://gitee.com/y_project/RuoYi-Vue"><img src="https://img.shields.io/badge/RuoYi-v3.8.3-brightgreen.svg"></a>
<a href="https://gitee.com/y_project/RuoYi-Vue/blob/master/LICENSE"><img src="https://img.shields.io/github/license/mashape/apistatus.svg"></a>
</p>
## 平台简介
若依是一套全部开源的快速开发平台,毫无保留给个人及企业免费使用。
* 前端采用Vue、Element UI。
* 后端采用Spring Boot、Spring Security、Redis & Jwt。
* 权限认证使用Jwt支持多终端认证系统。
* 支持加载动态权限菜单,多方式轻松权限控制。
* 高效率开发,使用代码生成器可以一键生成前后端代码。
* 提供了技术栈([Vue3](https://v3.cn.vuejs.org) [Element Plus](https://element-plus.org/zh-CN) [Vite](https://cn.vitejs.dev))版本[RuoYi-Vue3](https://github.com/yangzongzhuan/RuoYi-Vue3),保持同步更新。
* 提供了单应用版本[RuoYi-Vue-fast](https://github.com/yangzongzhuan/RuoYi-Vue-fast)Oracle版本[RuoYi-Vue-Oracle](https://github.com/yangzongzhuan/RuoYi-Vue-Oracle),保持同步更新。
* 不分离版本,请移步[RuoYi](https://gitee.com/y_project/RuoYi),微服务版本,请移步[RuoYi-Cloud](https://gitee.com/y_project/RuoYi-Cloud)
* 特别鸣谢:[element](https://github.com/ElemeFE/element)[vue-element-admin](https://github.com/PanJiaChen/vue-element-admin)[eladmin-web](https://github.com/elunez/eladmin-web)。
* 阿里云折扣场:[点我进入](http://aly.ruoyi.vip),腾讯云秒杀场:[点我进入](http://txy.ruoyi.vip)&nbsp;&nbsp;
* 阿里云优惠券:[点我领取](https://www.aliyun.com/minisite/goods?userCode=brki8iof&share_source=copy_link),腾讯云优惠券:[点我领取](https://cloud.tencent.com/redirect.php?redirect=1025&cps_key=198c8df2ed259157187173bc7f4f32fd&from=console)&nbsp;&nbsp;
## 内置功能
1. 用户管理:用户是系统操作者,该功能主要完成系统用户配置。
2. 部门管理:配置系统组织机构(公司、部门、小组),树结构展现支持数据权限。
3. 岗位管理:配置系统用户所属担任职务。
4. 菜单管理:配置系统菜单,操作权限,按钮权限标识等。
5. 角色管理:角色菜单权限分配、设置角色按机构进行数据范围权限划分。
6. 字典管理:对系统中经常使用的一些较为固定的数据进行维护。
7. 参数管理:对系统动态配置常用参数。
8. 通知公告:系统通知公告信息发布维护。
9. 操作日志:系统正常操作日志记录和查询;系统异常信息日志记录和查询。
10. 登录日志:系统登录日志记录查询包含登录异常。
11. 在线用户:当前系统中活跃用户状态监控。
12. 定时任务:在线(添加、修改、删除)任务调度包含执行结果日志。
13. 代码生成前后端代码的生成java、html、xml、sql支持CRUD下载 。
14. 系统接口根据业务代码自动生成相关的api接口文档。
15. 服务监控监视当前系统CPU、内存、磁盘、堆栈等相关信息。
16. 缓存监控:对系统的缓存信息查询,命令统计等。
17. 在线构建器拖动表单元素生成相应的HTML代码。
18. 连接池监视监视当前系统数据库连接池状态可进行分析SQL找出系统性能瓶颈。
## 在线体验
- admin/admin123
- 陆陆续续收到一些打赏,为了更好的体验已用于演示服务器升级。谢谢各位小伙伴。
演示地址http://vue.ruoyi.vip
文档地址http://doc.ruoyi.vip
## 演示图
<table>
<tr>
<td><img src="https://oscimg.oschina.net/oscnet/cd1f90be5f2684f4560c9519c0f2a232ee8.jpg"/></td>
<td><img src="https://oscimg.oschina.net/oscnet/1cbcf0e6f257c7d3a063c0e3f2ff989e4b3.jpg"/></td>
</tr>
<tr>
<td><img src="https://oscimg.oschina.net/oscnet/up-8074972883b5ba0622e13246738ebba237a.png"/></td>
<td><img src="https://oscimg.oschina.net/oscnet/up-9f88719cdfca9af2e58b352a20e23d43b12.png"/></td>
</tr>
<tr>
<td><img src="https://oscimg.oschina.net/oscnet/up-39bf2584ec3a529b0d5a3b70d15c9b37646.png"/></td>
<td><img src="https://oscimg.oschina.net/oscnet/up-936ec82d1f4872e1bc980927654b6007307.png"/></td>
</tr>
<tr>
<td><img src="https://oscimg.oschina.net/oscnet/up-b2d62ceb95d2dd9b3fbe157bb70d26001e9.png"/></td>
<td><img src="https://oscimg.oschina.net/oscnet/up-d67451d308b7a79ad6819723396f7c3d77a.png"/></td>
</tr>
<tr>
<td><img src="https://oscimg.oschina.net/oscnet/5e8c387724954459291aafd5eb52b456f53.jpg"/></td>
<td><img src="https://oscimg.oschina.net/oscnet/644e78da53c2e92a95dfda4f76e6d117c4b.jpg"/></td>
</tr>
<tr>
<td><img src="https://oscimg.oschina.net/oscnet/up-8370a0d02977eebf6dbf854c8450293c937.png"/></td>
<td><img src="https://oscimg.oschina.net/oscnet/up-49003ed83f60f633e7153609a53a2b644f7.png"/></td>
</tr>
<tr>
<td><img src="https://oscimg.oschina.net/oscnet/up-d4fe726319ece268d4746602c39cffc0621.png"/></td>
<td><img src="https://oscimg.oschina.net/oscnet/up-c195234bbcd30be6927f037a6755e6ab69c.png"/></td>
</tr>
<tr>
<td><img src="https://oscimg.oschina.net/oscnet/b6115bc8c31de52951982e509930b20684a.jpg"/></td>
<td><img src="https://oscimg.oschina.net/oscnet/up-5e4daac0bb59612c5038448acbcef235e3a.png"/></td>
</tr>
</table>
## 若依前后端分离交流群
QQ群 [![加入QQ群](https://img.shields.io/badge/已满-937441-blue.svg)](https://jq.qq.com/?_wv=1027&k=5bVB1og) [![加入QQ群](https://img.shields.io/badge/已满-887144332-blue.svg)](https://jq.qq.com/?_wv=1027&k=5eiA4DH) [![加入QQ群](https://img.shields.io/badge/已满-180251782-blue.svg)](https://jq.qq.com/?_wv=1027&k=5AxMKlC) [![加入QQ群](https://img.shields.io/badge/已满-104180207-blue.svg)](https://jq.qq.com/?_wv=1027&k=51G72yr) [![加入QQ群](https://img.shields.io/badge/已满-186866453-blue.svg)](https://jq.qq.com/?_wv=1027&k=VvjN2nvu) [![加入QQ群](https://img.shields.io/badge/已满-201396349-blue.svg)](https://jq.qq.com/?_wv=1027&k=5vYAqA05) [![加入QQ群](https://img.shields.io/badge/已满-101456076-blue.svg)](https://jq.qq.com/?_wv=1027&k=kOIINEb5) [![加入QQ群](https://img.shields.io/badge/已满-101539465-blue.svg)](https://jq.qq.com/?_wv=1027&k=UKtX5jhs) [![加入QQ群](https://img.shields.io/badge/已满-264312783-blue.svg)](https://jq.qq.com/?_wv=1027&k=EI9an8lJ) [![加入QQ群](https://img.shields.io/badge/已满-167385320-blue.svg)](https://jq.qq.com/?_wv=1027&k=SWCtLnMz) [![加入QQ群](https://img.shields.io/badge/已满-104748341-blue.svg)](https://jq.qq.com/?_wv=1027&k=96Dkdq0k) [![加入QQ群](https://img.shields.io/badge/160110482-blue.svg)](https://jq.qq.com/?_wv=1027&k=0fsNiYZt) 点击按钮入群。

@ -0,0 +1,11 @@
{
"applinks": {
"apps": [],
"details": [
{
"appID": "uni.UNIE9791EE",
"paths": [ "*"]
}
]
}
}

@ -0,0 +1,12 @@
@echo off
echo.
echo [信息] 清理工程target生成路径。
echo.
%~d0
cd %~dp0
cd ..
call mvn clean
pause

@ -0,0 +1,12 @@
@echo off
echo.
echo [信息] 打包Web工程生成war/jar包文件。
echo.
%~d0
cd %~dp0
cd ..
call mvn clean package -Dmaven.test.skip=true
pause

@ -0,0 +1,14 @@
@echo off
echo.
echo [信息] 使用Jar命令运行Web工程。
echo.
cd %~dp0
cd ../ruoyi-admin/target
set JAVA_OPTS=-Xms256m -Xmx1024m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=512m
java -jar %JAVA_OPTS% ruoyi-admin.jar
cd bin
pause

Binary file not shown.

197
et

@ -0,0 +1,197 @@
commit 9ee12ce4095ce7feb96a425cfa107ba985e77618 (HEAD -> master)
Author: xiaoning <1097449274@qq.com>
Date: Sat Oct 8 14:47:35 2022 +0800
修改商户字段
commit cc068cbb4539314546a9dce897198a5212201bd6
Author: xiaoning <1097449274@qq.com>
Date: Fri Sep 30 16:54:34 2022 +0800
订单提交
commit 163c24de9529bcd67782ba3629d7ddc7cbc2a7f1
Author: gaojiayin <1164794711@qq.com>
Date: Fri Sep 30 16:47:46 2022 +0800
会籍管理后台
commit d71acb9a99ec3f8541a58f3b6caf5690ac561ab9
Author: gaojiayin <1164794711@qq.com>
Date: Fri Sep 30 15:29:59 2022 +0800
hj
commit 63f09d17f4998c73dae8f41978f3addf61cfa152
Author: xiaoning <1097449274@qq.com>
Date: Fri Sep 30 14:17:22 2022 +0800
订单详情加字段
commit 9674dbed62e4135aa1432c740cadca40d25bf11f
Author: xhj <xhjzrq@163.com>
Date: Fri Sep 30 14:01:38 2022 +0800
修正订单
commit bd3c94fd8d7cfd5089605d75e008f4001f7b86e0
Author: xhj <xhjzrq@163.com>
Date: Fri Sep 30 10:14:25 2022 +0800
修正订单
commit ca97aa5756887a3ad1be1845a8ee1c1dfbaeb870
Author: xiaoning <1097449274@qq.com>
Date: Fri Sep 30 09:14:17 2022 +0800
app登录修改
commit ed7b2eedacf0c599a2bf9da3cd9969a4d8fb9daa
Author: xhj <xhjzrq@163.com>
Date: Thu Sep 29 16:39:53 2022 +0800
修正
commit cdbfa5f89d174d82cbc60ca490525ba4d16bccb4
Author: xiaoning <1097449274@qq.com>
Date: Thu Sep 29 16:18:18 2022 +0800
app地址管理
commit 36104b331eaa00638a1dcdf3a2263d9ab35d4737
Author: gaojiayin <1164794711@qq.com>
Date: Thu Sep 29 11:56:56 2022 +0800
hj
commit 7acea60605faa9698b139b858c7a2b71970779df
Author: xiaoning <1097449274@qq.com>
Date: Wed Sep 28 16:56:29 2022 +0800
app登录
commit bfd77c4e6d3996edb67ad03d17a90c837ef9bb92
Author: xhj <xhjzrq@163.com>
Date: Wed Sep 28 16:48:04 2022 +0800
修正
commit d18652fcb95518d44cdb5d79d9f5be69bf2cd316
Author: xhj <xhjzrq@163.com>
Date: Wed Sep 28 16:08:30 2022 +0800
修正
commit 23f1deb15aa69b2dfa2883eb2121fd2e7b08c615
Author: xiaoning <1097449274@qq.com>
Date: Wed Sep 28 15:37:32 2022 +0800
RestResponse改位置
commit ff420ef156779fbeb166245af1d49dc69450b5ac
Author: xiaoning <1097449274@qq.com>
Date: Wed Sep 28 14:41:22 2022 +0800
+ RestResponse
commit 12f11892708e3544382fedd4ac510895201e04cd
Author: xiaoning <1097449274@qq.com>
Date: Wed Sep 28 14:24:05 2022 +0800
app模块pom打包配置
commit 2a0c39190c0c9915c8b22554808f87eebbed1343
Author: xiaoning <1097449274@qq.com>
Date: Wed Sep 28 13:58:55 2022 +0800
app模块
commit f5c6d1b339fb6737ba4d8b1d5e4f586b378b1203
Author: xhj <xhjzrq@163.com>
Date: Wed Sep 28 09:52:51 2022 +0800
课程
commit e8ee8779bfd117eef99527911a14493ba72e8c0a
Author: xhj <xhjzrq@163.com>
Date: Tue Sep 27 15:14:18 2022 +0800
课程
commit a1696453568dc33c914acf18c87ae1d55279e19f
Author: xiaoning <1097449274@qq.com>
Date: Mon Sep 26 17:08:56 2022 +0800
瑜伽传承..
commit 5eac960a00e222052115ea1538090bc0ad409493
Author: xiaoning <1097449274@qq.com>
Date: Sat Sep 24 16:32:47 2022 +0800
产品/订单/图片资源管理
commit 33a415dd9792701400d93e7f9a80853c0edadebb
Author: xiaoning <1097449274@qq.com>
Date: Sat Sep 24 13:55:06 2022 +0800
产品类型管理
commit 2c5c3521a8894d0079dc16df00068ced504943fe
Author: xhj <xhjzrq@163.com>
Date: Fri Sep 23 15:32:26 2022 +0800
课程基础zsgc
commit d9240b249ddd513bdb8e5bcf3539b654855728fd
Author: xhj <xhjzrq@163.com>
Date: Fri Sep 23 14:09:35 2022 +0800
11
commit c8eac97c4ca03f61acddad4506f7c68bf73dc62e
Author: xhj <xhjzrq@163.com>
Date: Fri Sep 23 11:56:06 2022 +0800
11
commit a892b1052a4e645fcef9fb28c79c9e9c7c5bd81c
Author: xhj <xhjzrq@163.com>
Date: Fri Sep 23 09:39:31 2022 +0800
课程
commit 5ad5e50cc991ecf7c5cab67f656ac13fb99e5235
Author: xiaoning <1097449274@qq.com>
Date: Thu Sep 22 16:58:09 2022 +0800
+返回类
commit f25c469b1885ff934afa0b2303e4c820ae79f685
Author: xiaoning <1097449274@qq.com>
Date: Thu Sep 22 16:51:57 2022 +0800
+lombok
commit 5bc001e3a0b316c0f792eecd4d4cab2d5690824f
Author: xiaoning <1097449274@qq.com>
Date: Thu Sep 22 15:48:29 2022 +0800
修改
commit 218eaf58a9d9f0c3862e2809641f9e88bfb5ff00
Author: xiaoning <1097449274@qq.com>
Date: Thu Sep 22 15:47:13 2022 +0800
修改
commit a9bec4de91e5cc122400b9c1733e9c47726220db
Author: xiaoning <1097449274@qq.com>
Date: Thu Sep 22 15:30:06 2022 +0800
加mybatisplus
commit 3a7716039f36f5a3aed502b047969f14c3550918
Author: xhj <xhjzrq@163.com>
Date: Thu Sep 22 10:11:39 2022 +0800
11

@ -0,0 +1,253 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi</artifactId>
<version>3.8.3</version>
<name>ruoyi</name>
<url>http://www.ruoyi.vip</url>
<description>若依管理系统</description>
<properties>
<ruoyi.version>3.8.3</ruoyi.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
<druid.version>1.2.11</druid.version>
<bitwalker.version>1.21</bitwalker.version>
<swagger.version>3.0.0</swagger.version>
<kaptcha.version>2.3.2</kaptcha.version>
<mybatis-spring-boot.version>2.2.2</mybatis-spring-boot.version>
<pagehelper.boot.version>1.4.3</pagehelper.boot.version>
<fastjson.version>2.0.12</fastjson.version>
<oshi.version>6.2.2</oshi.version>
<commons.io.version>2.11.0</commons.io.version>
<commons.fileupload.version>1.4</commons.fileupload.version>
<commons.collections.version>3.2.2</commons.collections.version>
<poi.version>4.1.2</poi.version>
<velocity.version>2.3</velocity.version>
<jwt.version>0.9.1</jwt.version>
</properties>
<!-- 依赖声明 -->
<dependencyManagement>
<dependencies>
<!-- SpringBoot的依赖配置-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.5.14</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- 阿里数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
</dependency>
<!-- 解析客户端操作系统、浏览器等 -->
<dependency>
<groupId>eu.bitwalker</groupId>
<artifactId>UserAgentUtils</artifactId>
<version>${bitwalker.version}</version>
</dependency>
<!-- SpringBoot集成mybatis框架 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis-spring-boot.version}</version>
</dependency>
<!-- pagehelper 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>${pagehelper.boot.version}</version>
</dependency>
<!-- 获取系统信息 -->
<dependency>
<groupId>com.github.oshi</groupId>
<artifactId>oshi-core</artifactId>
<version>${oshi.version}</version>
</dependency>
<!-- Swagger3依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>${swagger.version}</version>
<exclusions>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- io常用工具类 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons.io.version}</version>
</dependency>
<!-- 文件上传工具类 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons.fileupload.version}</version>
</dependency>
<!-- excel工具 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<!-- velocity代码生成使用模板 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>${velocity.version}</version>
</dependency>
<!-- collections工具类 -->
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>${commons.collections.version}</version>
</dependency>
<!-- 阿里JSON解析器 -->
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>${fastjson.version}</version>
</dependency>
<!-- Token生成与解析-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>${jwt.version}</version>
</dependency>
<!-- 验证码 -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>${kaptcha.version}</version>
</dependency>
<!-- 定时任务-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-quartz</artifactId>
<version>${ruoyi.version}</version>
</dependency>
<!-- 代码生成-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-generator</artifactId>
<version>${ruoyi.version}</version>
</dependency>
<!-- 核心模块-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-framework</artifactId>
<version>${ruoyi.version}</version>
</dependency>
<!-- 系统模块-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-system</artifactId>
<version>${ruoyi.version}</version>
</dependency>
<!-- 通用工具-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common</artifactId>
<version>${ruoyi.version}</version>
</dependency>
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-app-domain</artifactId>
<version>${ruoyi.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<modules>
<module>ruoyi-admin</module>
<module>ruoyi-framework</module>
<module>ruoyi-system</module>
<module>ruoyi-quartz</module>
<module>ruoyi-generator</module>
<module>ruoyi-common</module>
</modules>
<packaging>pom</packaging>
<dependencies>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>public</id>
<name>aliyun nexus</name>
<url>https://maven.aliyun.com/repository/public</url>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>public</id>
<name>aliyun nexus</name>
<url>https://maven.aliyun.com/repository/public</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>

@ -0,0 +1,113 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>ruoyi</artifactId>
<groupId>com.ruoyi</groupId>
<version>3.8.3</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>jar</packaging>
<artifactId>ruoyi-admin</artifactId>
<description>
web服务入口
</description>
<dependencies>
<!-- spring-boot-devtools -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional> <!-- 表示依赖不会传递 -->
</dependency>
<!-- Mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 核心模块-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-framework</artifactId>
</dependency>
<!-- 定时任务-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-quartz</artifactId>
</dependency>
<!-- 代码生成-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-generator</artifactId>
</dependency>
<!--极光推送-->
<!-- <dependency>-->
<!-- <groupId>cn.jpush.api</groupId>-->
<!-- <artifactId>jiguang-common</artifactId>-->
<!-- <version>1.1.7</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>cn.jpush.api</groupId>-->
<!-- <artifactId>jpush-client</artifactId>-->
<!-- <version>3.4.3</version>-->
<!-- </dependency>-->
<!-- //微信支付-->
<dependency>
<groupId>com.github.wechatpay-apiv3</groupId>
<artifactId>wechatpay-apache-httpclient</artifactId>
<version>0.4.8</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp-android-support</artifactId>
<version>3.13.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.1.1.RELEASE</version>
<configuration>
<fork>true</fork> <!-- 如果没有该配置devtools不会生效 -->
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<warName>${project.artifactId}</warName>
</configuration>
</plugin>
</plugins>
<finalName>${project.artifactId}</finalName>
</build>
</project>

@ -0,0 +1,30 @@
package com.ruoyi;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
/**
*
*
* @author ruoyi
*/
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
public class RuoYiApplication
{
public static void main(String[] args)
{
// System.setProperty("spring.devtools.restart.enabled", "false");
SpringApplication.run(RuoYiApplication.class, args);
System.out.println("(♥◠‿◠)ノ゙ 若依启动成功 ლ(´ڡ`ლ)゙ \n" +
" .-------. ____ __ \n" +
" | _ _ \\ \\ \\ / / \n" +
" | ( ' ) | \\ _. / ' \n" +
" |(_ o _) / _( )_ .' \n" +
" | (_,_).' __ ___(_ o _)' \n" +
" | |\\ \\ | || |(_,_)' \n" +
" | | \\ `' /| `-' / \n" +
" | | \\ / \\ / \n" +
" ''-' `'-' `-..-' ");
}
}

@ -0,0 +1,18 @@
package com.ruoyi;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
/**
* web
*
* @author ruoyi
*/
public class RuoYiServletInitializer extends SpringBootServletInitializer
{
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application)
{
return application.sources(RuoYiApplication.class);
}
}

@ -0,0 +1,125 @@
package com.ruoyi.web.controller.app_course;
import cn.hutool.core.date.DateUtil;
import com.ruoyi.RestResponse;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.course.domain.Appointment;
import com.ruoyi.course.domain.AppointmentVo;
import com.ruoyi.course.mapper.AppointmentMapper;
import com.ruoyi.course.service.AppointmentServiceImpl;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <p>
*
* </p>
*
* @author xhj
* @since 2022-09-22
*/
@Api(tags = "课程", description = "提供课程相关的API")
@RestController
@RequestMapping("/api/appointment")
public class AppointmentAppController extends BaseController {
@Autowired
AppointmentServiceImpl appointmentService;
@Autowired
AppointmentMapper mapper;
// @PostMapping("/getAppointmentList")
public RestResponse getAppointmentList(@RequestBody Map map) {
// List<Course> list = appointmentService.getList(map);
// return new RestResponse().setData(list);
return RestResponse.success().setData(appointmentService.findList(map));
}
// @PostMapping("/updateAppointment")
public RestResponse updateAppointment(@RequestBody Appointment appointment) {
String username = SecurityUtils.getUsername();
appointment.setUpdateUser(username);
// LocalDateTime now= ;
appointment.setUpdateTime(DateUtil.parseLocalDateTime(DateUtil.now(),"yyyy-MM-dd HH:mm:ss"));
appointmentService.updateById(appointment);
return RestResponse.success();
}
/**
*
* @param appointment
* @return
*/
// @PostMapping("/yy")
public RestResponse yy(@RequestBody Appointment appointment) {
appointment.setCreateTime(DateUtil.parseLocalDateTime(DateUtil.now(),"yyyy-MM-dd HH:mm:ss"));
appointmentService.save(appointment);
return RestResponse.success();
}
//我的预约
//预约成功
//预约失败
@PostMapping("/appointments")
public RestResponse appointments(HttpServletRequest request) {
Long userId= Long.parseLong(request.getAttribute("userId").toString());
Map map=new HashMap();
map.put("consumerId",userId);
List<AppointmentVo> list=appointmentService.findList(map);
List<AppointmentVo> list1=new ArrayList<>();//预约中
List<AppointmentVo> list2=new ArrayList<>();//预约成功
List<AppointmentVo> list3=new ArrayList<>();//预约失败
List<AppointmentVo> list4=new ArrayList<>();//取消预约
for (AppointmentVo a:list){
if (a.getFlag()==0){
list1.add(a);
continue;
}
if (a.getFlag()==1){
list2.add(a);
continue;
}
if (a.getFlag()==2){
list3.add(a);
continue;
}
if (a.getFlag()==3){
list4.add(a);
}
}
map.clear();
map.put("list1",list1);
map.put("list2",list2);
map.put("list3",list3);
map.put("list4",list4);
return RestResponse.success().setData(map);
}
//取消预约
@PostMapping("/cancel")
public RestResponse cancel(@RequestBody Appointment appointment) {
appointment.setUpdateTime(DateUtil.parseLocalDateTime(DateUtil.now(),"yyyy-MM-dd HH:mm:ss"));
int i= mapper.cancel(appointment);
return RestResponse.success().setMessage(i==0?"修改失败,当前状态无法取消预约!":"成功!");
}
}

@ -0,0 +1,62 @@
package com.ruoyi.web.controller.app_course;
import com.ruoyi.RestResponse;
import com.ruoyi.course.domain.CourseLog;
import com.ruoyi.course.mapper.ConsumerCourseMapper;
import com.ruoyi.course.service.ConsumerCourseServiceImpl;
import com.ruoyi.course.service.CourseServiceImpl;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <p>
*
* </p>
*
* @author xn
* @since 2022-12-29
*/
@RestController
@RequestMapping("/api/consumerCourse")
public class ConsumerCourseController {
@Resource
private CourseServiceImpl courseService;
@Resource
private ConsumerCourseServiceImpl consumerCourseService;
@Resource
private ConsumerCourseMapper mapper;
//我的课程 (视频)
@PostMapping("/myCourse")
public RestResponse myCourse(HttpServletRequest request){
Long userId= Long.parseLong(request.getAttribute("userId").toString());
List<CourseLog> list= mapper.myCourse(userId);
List<CourseLog> list1=new ArrayList<>();
List<CourseLog> list2=new ArrayList<>();
for (CourseLog l:list){
if (l.getCourseType().equals("2")){
list1.add(l);
}
if (l.getCourseType().equals("3")){
list2.add(l);
}
}
Map map=new HashMap();
map.put("list1",list1);//大咖课
map.put("list2",list2);//教练培训
return new RestResponse().setSuccess(true).setData(map);
}
}

@ -0,0 +1,42 @@
package com.ruoyi.web.controller.app_course;
import com.ruoyi.RestResponse;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.course.domain.Context;
import com.ruoyi.course.service.ContextServicelmpl;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@Api(tags = "教练", description = "获取教练信息")
@RestController
@RequestMapping("/api/context")
public class ContextAppController extends BaseController {
@Autowired
ContextServicelmpl contextService;
@Autowired
SysUserServiceImpl userService;
@ApiOperation("教练列表")
@PostMapping(value = "/getList")
public RestResponse findList1(@RequestBody Map<String, Object> params) {
params.put("releases",true);
List<Context> list =contextService.getList(params);
return new RestResponse().setSuccess(true).setMessage("成功").setData(list);
}
@ApiOperation("教练详细信息")
@PostMapping("/getOne")
public RestResponse update(@RequestBody Map<String, Object> params) {
Context c =contextService.getList(params).get(0);
return RestResponse.success().setData(c);
}
}

@ -0,0 +1,406 @@
package com.ruoyi.web.controller.app_course;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.RestResponse;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.JpushClientUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.course.domain.*;
import com.ruoyi.course.service.ConsumerCourseServiceImpl;
import com.ruoyi.course.service.CourseLogServiceImpl;
import com.ruoyi.course.service.CourseServiceImpl;
import com.ruoyi.course.service.HistoryMessageServiceImpl;
import com.ruoyi.search.domain.MemberUser;
import com.ruoyi.search.service.MemberUserServicelmpl;
import com.ruoyi.shop.domain.ShopOrder;
import com.ruoyi.shop.domain.ShopOrderItem;
import com.ruoyi.shop.service.impl.ShopOrderItemServiceImpl;
import com.ruoyi.shop.service.impl.ShopOrderServiceImpl;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.web.util.PayUtil;
import com.ruoyi.web.util.SnowFlake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <p>
*
* </p>
*
* @author xhj
* @since 2022-09-22
*/
@RestController
@RequestMapping("/api/course")
public class CourseAppController extends BaseController {
@Autowired
CourseServiceImpl courseService;
@Autowired
HistoryMessageServiceImpl historyMessageService;
@Autowired
CourseLogServiceImpl courseLogService;
@Autowired
ISysDictDataService iSysDictDataService;
@Autowired
MemberUserServicelmpl memberUserService;
@Resource
private ShopOrderServiceImpl orderService;
@Resource
private ShopOrderItemServiceImpl itemService;
@Resource
private ConsumerCourseServiceImpl consumerCourseService;
@Resource
private SysUserRoleMapper sysUserRoleMapper;
/**
*
* courseName
* courseType //1 传入1
* memberType[]
* @param map
* @return courseType1
*/
@PostMapping("/list")
public RestResponse list(@RequestBody Map map) {
map.put("releases",1);
List<Course> list = courseService.getList(map);
return new RestResponse().setData(list);
}
/**
*
* @param map
* @return
*/
@PostMapping("/listByCourseType1")
public RestResponse listByCourseType1(@RequestBody Map map) {
SysDictData sysDictData= new SysDictData();
sysDictData.setDictType("yj_source_pt_type");
sysDictData.setMerchantId(SecurityUtils.getMerchanId());
return RestResponse.success().setData(iSysDictDataService.selectDictDataList(sysDictData));
}
/**
*
* @param appointment
* @return
*/
// @PostMapping("/yyCourse")
public RestResponse yyCourse(@RequestBody Appointment appointment) {
courseService.yyCourse(appointment);
return RestResponse.success();
}
/**
* courseId id id
* @param map
* @return userName course_names memberType course_picture
* memberType 1 courseType1 = /11 courseType
*/
@PostMapping("/listLog")
public RestResponse listLog(@RequestBody Map map) {
//todo
List<CourseLogVo> list = courseService.getListLog(map);
return new RestResponse().setData(list);
}
/**
*
*
* @param map date courseId id
* @return
* 2022.11.30xn
*/
@PostMapping("/listLogDate")
public RestResponse listLogDate(@RequestBody Map map) {
// Map map1 = courseService.listLogDate(map);
map.put("userId",null);
Map map1 = courseService.listLogDate1(map);
return new RestResponse().setData(map1);
}
@PostMapping("/listLogDateForMember")
public RestResponse listLogDateForMember(@RequestBody Map map,HttpServletRequest request) {
Long userId= Long.parseLong(request.getAttribute("userId").toString());
// Map map1 = courseService.listLogDate(map);
map.put("userId",userId);
Map map1 = courseService.listLogDate1(map);
return new RestResponse().setData(map1);
}
@PostMapping("/getTeacherList")
public RestResponse getTeacherList(@RequestBody Map map) {
// sysUserService.selectUserList()
List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectALLByRole(map.get("merchantId").toString());
if(sysUserRoles.size()==0){
return RestResponse.failure("没有教练信息");
}
return RestResponse.success().setData(sysUserRoles);
}
/**
*
* app-/
* @param course
* @return
* @author xn
*/
// @PostMapping("/listForService")
public RestResponse listForService(@RequestBody Course course) {
course.setReleases(1);
List<Course> list = courseService.listForApp(course);
return new RestResponse().success().setData(list);
}
/**
*
* app-
* @param course
* @return
* @author xn
*/
// @PostMapping("/getOne")
public RestResponse getOne(@RequestBody Course course) {
Course c = courseService.listForApp(course).get(0);
return new RestResponse().success().setData(c);
}
/**
* ()
* @param courseLogVo
* @return
*/
@PostMapping("/getDetail")
public RestResponse getDetail(@RequestBody CourseLogVo courseLogVo) {
CourseLog courseLog =courseLogService.getById(courseLogVo.getId());
Course course =courseService.getById(courseLog.getCourseId());
courseLog.generateMemberNum();
Map map=new HashMap();
map.put("course",course);
courseLog.setVideoLong("1");
map.put("courseLog",courseLog);
return new RestResponse().success().setData(map);
}
/**
*
* @param courseLogVo
* @param request
* @return
*/
@PostMapping("/watchLongVideo")
public RestResponse watchLongVideo(@RequestBody CourseLogVo courseLogVo, HttpServletRequest request) {
Long userId= Long.parseLong(request.getAttribute("userId").toString());
CourseLog courseLog =courseLogService.getById(courseLogVo.getId());
Course course =courseService.getById(courseLog.getCourseId());
Map map=new HashMap();
map.put("course",course);
map.put("courseLog",courseLog);
//判断是否购买过
Long l= consumerCourseService.count(new QueryWrapper<ConsumerCourse>()
.eq("consumer_id",userId)
.eq("course_log_id",courseLogVo.getId()));
if (l<1l){
courseLog.setVideoLong("1"); //页面
return new RestResponse().success().setData(map);
}
return new RestResponse().success().setData(map);
}
/**
* 1
* @param appointment
* @return
*/
@PostMapping("/yyCourse1")
@Transactional(rollbackFor = RuntimeException.class)
public RestResponse yyCourse1(@RequestBody Appointment appointment, HttpServletRequest request) {
Long userId= Long.parseLong(request.getAttribute("userId").toString());
//查看校验课程是否符合预约条件
CourseLog log=courseLogService.getById(appointment.getCourseLogId());
if ( DateUtil.parse(log.getStartDate()+" "+log.getStartTime(),"yyyy-MM-dd HH:mm").before(DateUtil.date())){
return new RestResponse().setSuccess(false).setMessage("该课程已过期,请选择其他课程!");
}
if (log.getNumber()==log.getAppointmentNum()){
return new RestResponse().setSuccess(false).setMessage("该课程预约已满,请选择其他课程!");
}
log.generateMemberNum();
if (ObjectUtil.isNotEmpty(log.getMemberNum())){
//判断是否为会员
List<MemberUser> memberUsers=memberUserService.list(new QueryWrapper<MemberUser>().eq("consumer_id",userId));
if (ObjectUtil.isEmpty(memberUsers)){
return new RestResponse().setSuccess(false).setMessage("该课程为会员课,请加入相应会籍后预约!");
}
int flag=0;
for (Object memberId:log.getMemberNum()){
int id=Integer.parseInt(memberId.toString());
for (MemberUser user:memberUsers){
//判断会员会籍与课程会籍是否相符
if (user.getMemberId()==id){
//如果上课日期在会员有效期之内
if (DateUtil.parse(log.getStartDate(),"yyyy-MM-dd").before(
DateUtil.parse(user.getValidityTime(),"yyyy-MM-dd"))){
flag=1;
}
}
}
}
if (flag==0){
return new RestResponse().setSuccess(false).setMessage("该课程为会员课,您的会籍类型与课程不符,请加入相应会籍后预约!");
}
}
appointment.setPhone(request.getAttribute("phone").toString());
courseService.yyCourse1(appointment);
//给教练发送消息,提醒确认
Context context=courseService.getTeacherPhone(appointment.getCourseLogId());
String notification_title=context.getUserName()+"教练,您有一条课程预约";
String msg_content="学员:"+request.getAttribute("phone").toString()+"预约您的课程,请登录后台处理!";
try {
JpushClientUtil.sendMessage(context.getPhonenumber(),notification_title,msg_content);
} catch (Exception e) {
e.printStackTrace();
}
//消息记录
HistoryMessage message=new HistoryMessage();
message.setPhone(context.getPhonenumber());
message.setNotificationTitle(notification_title);
message.setMsgContent(msg_content);
message.setSendTime(DateUtil.now());
historyMessageService.save(message);
return RestResponse.success();
}
/**
*
* @param courseLogVo
* @param request
* @return
* @throws Exception
*/
@PostMapping("/createOrderForCourse")
@Transactional(rollbackFor = RuntimeException.class)
public RestResponse createOrderForCourse(@RequestBody CourseLogVo courseLogVo, HttpServletRequest request) throws Exception{
Long userId= Long.parseLong(request.getAttribute("userId").toString());
//判断是否购买过
long count= consumerCourseService.count(new QueryWrapper<ConsumerCourse>()
.eq("consumer_id",userId)
.eq("course_log_id",courseLogVo.getId()));
if (count>0l){
return new RestResponse().setSuccess(false).setMessage("课程已购买过,请到 我的->我的课程 中查看!");
}
//生成订单(支付中)
ShopOrder order=new ShopOrder();
order.setOrderSn(SnowFlake.getOrder()+"");//订单号
order.setBusinessId(courseLogVo.getStroreId());//商户
order.setIdUser(userId);//客户id
order.setMobile(request.getAttribute("phone").toString());//收件人电话(客户电话)
order.setCreateTime(DateUtil.parseLocalDateTime(DateUtil.now(),"yyyy-MM-dd HH:mm:ss"));
order.setOrderType(3);//订单类型1.商品 2.会籍 3.课程
order.setPayType("微信支付");
order.setTradeAmount(courseLogVo.getCoursePrice());//TradeAmount交易金额 MemberPrice价格
orderService.save(order);
//生成订单详情
ShopOrderItem item=new ShopOrderItem();
item.setIdOrder(order.getId());//订单id
item.setIdSouseLog(courseLogVo.getId());//开课记录id
item.setTotalPrice(courseLogVo.getCoursePrice());//总价
item.setThumbnail(courseLogVo.getCoursePicture());//缩略图
item.setType("3");//1 商品 2 会籍 3 课程
item.setCourseContext(courseLogVo.getCourseContext());//课程内容
item.setCourseType(courseLogVo.getCourseType());//2大咖课 3教练培训
item.setCourseNames(courseLogVo.getCourseNames());
itemService.save(item);
//单位: 元 转换成 分
BigDecimal total=courseLogVo.getCoursePrice().multiply(new BigDecimal(100));
Map map=new HashMap();
//0元
if (total.equals(BigDecimal.ZERO)){
//支付成功 给用户添加课程 TODO
map.put("timeStamp","1");
return new RestResponse().setSuccess(true).setMessage("成功").setData(map);
}
map= PayUtil.creatOrder(total.setScale(1, RoundingMode.HALF_UP).intValue(),order.getOrderSn());
return new RestResponse().setSuccess(true).setMessage("成功").setData(map);
}
//视频以流的方式播放
// @RequestMapping(value = "/longView", method = {RequestMethod.GET})
@GetMapping("/longView")
public void imageView1(HttpServletRequest request, HttpServletResponse httpServletResponse){
String fileName="/profile/upload/2022/11/10/WeChat_20221110133401_20221110133433A027.mp4";
byte[] bytes = file2byte("../ruoyi/uploadPath"+fileName.substring(8));
httpServletResponse.setContentType("application/octet-stream");
httpServletResponse.setContentLength(bytes.length);
try {
httpServletResponse.getOutputStream().write(bytes);
} catch (IOException e) {
System.out.println("IO异常----");
}
}
public byte[] file2byte(String filePath) {
byte[] buffer = null;
try {
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
}
}

@ -0,0 +1,54 @@
package com.ruoyi.web.controller.app_course;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.RestResponse;
import com.ruoyi.course.domain.HistoryMessage;
import com.ruoyi.course.service.HistoryMessageServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
*
*/
@Api(tags = "我的消息", description = "提供我的消息相关的API")
@RestController
@RequestMapping("/api/historyMessage")
public class HistoryMessageController {
@Autowired
HistoryMessageServiceImpl historyMessageService;
@ApiOperation("我的消息列表")
@PostMapping("/getMessages")
public RestResponse getMessages(HttpServletRequest request){
List<HistoryMessage> list= historyMessageService.list(new QueryWrapper<HistoryMessage>()
.eq("phone",request.getAttribute("phone").toString())
.eq("releases",true));
return new RestResponse().setSuccess(true).setData(list);
}
@ApiOperation("消息详情")
@PostMapping("/getOne")
public RestResponse getOne(@RequestBody HistoryMessage message){
HistoryMessage historyMessage= historyMessageService.getById(message.getId());
return new RestResponse().setSuccess(true).setData(historyMessage);
}
@ApiOperation("删除消息")
@PostMapping("/remove")
public RestResponse remove(@RequestBody HistoryMessage message){
message.setReleases(false);
historyMessageService.updateById(message);
return new RestResponse().setSuccess(true);
}
}

@ -0,0 +1,186 @@
package com.ruoyi.web.controller.app_course;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.RestResponse;
import com.ruoyi.course.domain.Member;
import com.ruoyi.course.service.ConsumerCourseServiceImpl;
import com.ruoyi.course.service.MemberServiceImpl;
import com.ruoyi.search.domain.MemberUser;
import com.ruoyi.search.service.MemberUserServicelmpl;
import com.ruoyi.shop.domain.ShopOrder;
import com.ruoyi.shop.domain.ShopOrderItem;
import com.ruoyi.shop.service.impl.ShopOrderItemServiceImpl;
import com.ruoyi.shop.service.impl.ShopOrderServiceImpl;
import com.ruoyi.web.util.PayUtil;
import com.ruoyi.web.util.SnowFlake;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <p>
*
* </p>
*
* @author xhj
* @since 2022-09-23
*/
@Api(tags = "会籍", description = "提供会籍相关的API")
@RestController
@RequestMapping("/api/member")
public class
MemberAppController {
@Autowired
private MemberServiceImpl memberService;
@Autowired
private MemberUserServicelmpl memberUserServicel;
@Resource
private ShopOrderServiceImpl orderService;
@Resource
private ShopOrderItemServiceImpl itemService;
@Resource
private ConsumerCourseServiceImpl consumerCourseService;
/**
* app-
* @param member
* @return
* @author xn
*/
// @ApiOperation("获取本店会籍列表")
@PostMapping("/getMembers")
public RestResponse getMembers(@RequestBody Member member) {
List<Member> list = memberService.list(new QueryWrapper<Member>()
.eq("strore_id",member.getStroreId())
.eq("releases",1)
);
return new RestResponse().setData(list);
}
/**
* app-
* @param member
* @return
* @author xn
*/
// @ApiOperation("会籍详情")
@PostMapping("/getOne")
public RestResponse getOne(@RequestBody Member member) {
Member m = memberService.getById(member.getMemberId());
return new RestResponse().setData(m);
}
/**
*
* @param member
* @return
*/
// @ApiOperation("会籍数据字典")
@PostMapping(value = "/getList")
public RestResponse findList1(@RequestBody Member member) {
List<Member> list =memberService.findList(member);
return new RestResponse().setSuccess(true).setMessage("成功").setData(list);
}
/**
*
* @param memberUser
* @param request
* @return
*/
// @ApiOperation("购买会籍")
@PostMapping("/createOrderForMember")
@Transactional(rollbackFor = RuntimeException.class)
public RestResponse createOrderForMember(@RequestBody MemberUser memberUser, HttpServletRequest request) throws Exception{
Long userId= Long.parseLong(request.getAttribute("userId").toString());
//判断是否已经在籍
LocalDateTime dateTime= DateUtil.parseLocalDateTime(DateUtil.format(DateUtil.tomorrow(),"yyyy-MM-dd 00:00:00"));
List<MemberUser> list=memberUserServicel.list(new QueryWrapper<MemberUser>()//DateUtil.now()
.eq("member_id",memberUser.getMemberId())
.eq("consumer_id",userId)
.last(" and (validity_time > now() or come_time ='"+dateTime+"')"));//截止日期为今天之后(未到期) 或 开始日期在明天(今天办的)
if (list.size()>0){
if (list.get(0).getComeTime().equals(dateTime)){
return new RestResponse().setSuccess(false).setMessage("您已成功办理会籍,生效时间为"+DateUtil.tomorrow().toString("yyyy-MM-dd 00:00:00")+"!请勿重复办理!");
}else {
return new RestResponse().setSuccess(false).setMessage("会籍存续中,请勿重复办理!");
}
}
//价格/月 * 有效期(月)
BigDecimal price= memberUser.getMemberPrice().multiply(new BigDecimal(memberUser.getValidity()));
//生成订单(支付中)
ShopOrder order=new ShopOrder();
order.setOrderSn(SnowFlake.getOrder()+"");//订单号
order.setBusinessId(memberUser.getStroreId());//商户
order.setIdUser(userId);//客户id
order.setMobile(request.getAttribute("phone").toString());//收件人电话(客户电话)
order.setCreateTime(DateUtil.parseLocalDateTime(DateUtil.now(),"yyyy-MM-dd HH:mm:ss"));
order.setOrderType(2);//订单类型1.商品 2.会籍 3.课程
order.setPayType("微信支付");
order.setTradeAmount(price);//TradeAmount交易金额
orderService.save(order);
//生成订单详情
ShopOrderItem item=new ShopOrderItem();
item.setIdOrder(order.getId());//订单id
item.setIdMember(memberUser.getMemberId());//会员id
item.setTotalPrice(price);//总价
item.setThumbnail(memberUser.getMemberPicture());//缩略图
item.setType("2");//1 商品 2 会籍 3 课程
item.setMemberType(memberUser.getMemberName());//会籍类型=会籍名称
item.setMemberValidity(memberUser.getValidity());//会籍有效期(月)
item.setBrief(memberUser.getMemberContext());//简介=会籍内容
item.setMemberRecommend(memberUser.getRecommend());//推荐人
itemService.save(item);
//单位: 元 转换成 分
BigDecimal total=price.multiply(new BigDecimal(100));
Map map=new HashMap();
//0元
if (total.equals(BigDecimal.ZERO)){
//支付成功 生成会籍
map.put("timeStamp","1");
return new RestResponse().setSuccess(true).setMessage("成功").setData(map);
}
map= PayUtil.creatOrder(total.setScale(1, RoundingMode.HALF_UP).intValue(),order.getOrderSn());
return new RestResponse().setSuccess(true).setMessage("成功").setData(map);
}
/**
*
*
* @return
*/
// @ApiOperation("我的会籍")
@PostMapping("/myMembers")
public RestResponse myMembers(HttpServletRequest request){
Long userId= Long.parseLong(request.getAttribute("userId").toString());
List<MemberUser> list=memberUserServicel.list(new QueryWrapper<MemberUser>()
.eq("consumer_id",userId)
.last("and validity_time > now()"));
return new RestResponse().setSuccess(true).setData(list);
}
//课程表与会籍相关联
}

@ -0,0 +1,57 @@
package com.ruoyi.web.controller.app_shop;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.RestResponse;
import com.ruoyi.shop.domain.YjAppreciate;
import com.ruoyi.shop.service.impl.YjAppreciateServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
/**
*
*/
@Api(tags = "瑜伽欣赏", description = "提供瑜伽欣赏相关的API")
@RestController
@RequestMapping("/api/appreciate")
public class AppreciateController {
@Resource
private YjAppreciateServiceImpl service;
/**
*
* @param appreciate
* @return
*/
@ApiOperation("获取瑜伽欣赏 列表")
@PostMapping("/getList")
public RestResponse getList(@RequestBody YjAppreciate appreciate){
List<YjAppreciate> list= service.list(new QueryWrapper<YjAppreciate>()
.eq("merchan_id",appreciate.getMerchanId())
.eq("status",true)
.orderByDesc("modify_time"));
return new RestResponse().setSuccess(true).setMessage("成功").setData(list);
}
/**
*
* @param appreciate
* @return
*/
@PostMapping("/getOne")
public RestResponse getOne(@RequestBody YjAppreciate appreciate){
service.update(new UpdateWrapper<YjAppreciate>()
.setSql("read_num=read_num+1")
.eq("id",appreciate.getId()));//阅读量
YjAppreciate i=service.getById(appreciate.getId());
return new RestResponse().setSuccess(true).setMessage("成功").setData(i);
}
}

@ -0,0 +1,72 @@
package com.ruoyi.web.controller.app_shop;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.RestResponse;
import com.ruoyi.course.domain.CourseLog;
import com.ruoyi.course.service.CourseLogServiceImpl;
import com.ruoyi.shop.domain.YjCourseLp;
import com.ruoyi.shop.service.impl.YjCourceLpMenuServiceImpl;
import com.ruoyi.shop.service.impl.YjCourceLpServiceImpl;
import com.ruoyi.shop.service.impl.YjMerchantServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
@Api(tags = "瑜伽流派", description = "提供瑜伽流派相关的API")
@RestController
@RequestMapping("/api/courseLp")
public class CourceLpController {
@Resource
private YjCourceLpServiceImpl service;
@Resource
private YjMerchantServiceImpl merchantService;
@Resource
private YjCourceLpMenuServiceImpl menuService;
@Resource
private CourseLogServiceImpl courseLogService;
/**
*
* @param lp
* @return
*/
@PostMapping("/list")
@ApiOperation("获取瑜伽流派 列表")
public RestResponse list(@RequestBody YjCourseLp lp){
List<YjCourseLp> list=service.list(new QueryWrapper<YjCourseLp>()
.eq("merchant_id", lp.getMerchantId())
.eq("enabled",true)
.orderByDesc("modify_time")
);
return new RestResponse().setSuccess(true).setMessage("成功").setData(list);
}
@ApiOperation("获取当前瑜伽流派下的课程")
@PostMapping("/courseList")
public RestResponse courseList(@RequestBody YjCourseLp lp){
// 课程分类courseType 是否显示releases
List<YjCourseLp> list=service.list(new QueryWrapper<YjCourseLp>()
.eq("merchant_id", lp.getMerchantId())
.eq("enabled",true)
.orderByDesc("modify_time")
);
list.forEach(l->{
l.setCourseType(lp.getCourseType());
l.setReleases(true);
List<CourseLog> courseList=courseLogService.list(new QueryWrapper<CourseLog>()
.select("id","course_id","course_names","course_price","course_picture","course_type")
.eq("course_type",lp.getCourseType())//课程类型 2大咖课 3教练培训
.eq("releases",true) //上架
.eq("lp_id",l.getId())//流派
);
l.setCourseList(courseList);
});
return new RestResponse().setSuccess(true).setMessage("成功").setData(list);
}
}

@ -0,0 +1,58 @@
package com.ruoyi.web.controller.app_shop;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.RestResponse;
import com.ruoyi.shop.domain.ShopGoods;
import com.ruoyi.shop.domain.ShopGoodsCategory;
import com.ruoyi.shop.mapper.ShopGoodsMapper;
import com.ruoyi.shop.service.impl.ShopGoodsCategoryServiceImpl;
import com.ruoyi.shop.service.impl.ShopGoodsServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
@Api(tags = "商品", description = "提供商品相关的API")
@RestController
@RequestMapping("/api/goods")
public class GoodsController {
@Resource
private ShopGoodsServiceImpl service;
@Resource
private ShopGoodsCategoryServiceImpl categoryService;
@Resource
private ShopGoodsMapper goodsMapper;
@ApiOperation("商品类别")
@PostMapping("/getGoodsCategory")
public RestResponse getGoodsCategory(@RequestBody ShopGoodsCategory category){
List<ShopGoodsCategory> categoryList=categoryService.list(new QueryWrapper<ShopGoodsCategory>()
.eq("business_id",category.getBusinessId())
.eq("pid","0")
.eq("display",true)
.eq("is_delete",false));
return new RestResponse().setSuccess(true).setMessage("成功").setData(categoryList);
}
@ApiOperation("商品列表")
@PostMapping("/getGoods")
public RestResponse getGoods(@RequestBody ShopGoodsCategory category){
List<ShopGoods> goods=goodsMapper.getByPid(category.getId());
return new RestResponse().setSuccess(true).setMessage("成功").setData(goods);
}
@ApiOperation("商品详情")
@PostMapping("/getOne")
public RestResponse getOne(@RequestBody ShopGoods goods){
return new RestResponse().setSuccess(true).setMessage("成功").setData(service.getById(goods.getId()));
}
}

@ -0,0 +1,57 @@
package com.ruoyi.web.controller.app_shop;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.RestResponse;
import com.ruoyi.shop.domain.YjHealthy;
import com.ruoyi.shop.service.impl.YjHealthyServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
/**
*
*/
@Api(tags = "健康饮食", description = "提供健康饮食相关的API")
@RestController
@RequestMapping("/api/healthy")
public class HealthyController {
@Resource
private YjHealthyServiceImpl service;
/**
*
* @param healthy
* @return
*/
@ApiOperation(value = "获取健康饮食列表")
@PostMapping("/getList")
public RestResponse getList(@RequestBody YjHealthy healthy){
List<YjHealthy> list= service.list(new QueryWrapper<YjHealthy>()
.eq("merchan_id",healthy.getMerchanId())
.eq("status",true)
.orderByDesc("modify_time"));
return new RestResponse().setSuccess(true).setMessage("成功").setData(list);
}
/**
*
* @param healthy
* @return
*/
@ApiOperation(value = "健康饮食详情")
@PostMapping("/getOne")
public RestResponse getOne(@RequestBody YjHealthy healthy){
service.update(new UpdateWrapper<YjHealthy>()
.setSql("read_num=read_num+1")
.eq("id",healthy.getId()));//阅读量
YjHealthy i=service.getById(healthy.getId());
return new RestResponse().setSuccess(true).setMessage("成功").setData(i);
}
}

@ -0,0 +1,56 @@
package com.ruoyi.web.controller.app_shop;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.RestResponse;
import com.ruoyi.shop.domain.YjIndex;
import com.ruoyi.shop.domain.YjMerchant;
import com.ruoyi.shop.service.impl.YjIndexServiceImpl;
import com.ruoyi.shop.service.impl.YjMerchantServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
@Api(tags = "首页", description = "提供首页信息相关的API")
@RestController
@RequestMapping("/api/index")
public class IndexController {
@Resource
private YjIndexServiceImpl indexService;
@Resource
private YjMerchantServiceImpl merchantService;
//商户list
@ApiOperation("门店列表")
@PostMapping("/getMerchant")
public RestResponse getMerchant(){
List<YjMerchant> list=merchantService.list(new QueryWrapper<YjMerchant>()
.select("address","enterprise_name","phone","banner","id")
.eq("status",2));
return new RestResponse().setSuccess(true).setData(list);
}
@ApiOperation("首页图标")
@ApiImplicitParam(name = "merchantId", value = "商户ID", required = true, dataType = "String", dataTypeClass = String.class)
@PostMapping("/getIndex")
public RestResponse getIndex(@RequestBody YjIndex yjIndex){
YjIndex y= indexService.getOne(new QueryWrapper<YjIndex>()
.eq("merchant_id",yjIndex.getMerchantId()));
if (ObjectUtil.isNotEmpty(y)){
return new RestResponse().setSuccess(true).setData(y);
}else {
return new RestResponse().setSuccess(false);
}
}
}

@ -0,0 +1,59 @@
package com.ruoyi.web.controller.app_shop;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.RestResponse;
import com.ruoyi.shop.domain.YjInherit;
import com.ruoyi.shop.service.impl.YjInheritServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
/**
*
*/
@Api(tags = "瑜伽传承", description = "提供瑜伽传承相关的API")
@RestController
@RequestMapping("/api/inherit")
public class InheritController {
@Resource
private YjInheritServiceImpl inheritService;
/**
*
* @param inherit
* @return
*/
@ApiOperation(value = "获取瑜伽传承列表")
@PostMapping("/getList")
public RestResponse getList(@RequestBody YjInherit inherit){
List<YjInherit> list= inheritService.list(new QueryWrapper<YjInherit>()
.eq("merchan_id",inherit.getMerchanId())
.eq("status",true)
.orderByDesc("modify_time"));
return new RestResponse().setSuccess(true).setMessage("成功").setData(list);
}
/**
*
* @param inherit
* @return
*/
@ApiOperation(value = "瑜伽传承详情")
@PostMapping("/getOne")
public RestResponse getOne(@RequestBody YjInherit inherit){
inheritService.update(new UpdateWrapper<YjInherit>()
.setSql("read_num=read_num+1")
.eq("id",inherit.getId()));//阅读量
YjInherit i=inheritService.getById(inherit.getId());
return new RestResponse().setSuccess(true).setMessage("成功").setData(i);
}
}

@ -0,0 +1,315 @@
package com.ruoyi.web.controller.app_shop;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.RestResponse;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.config.JwtUtil1;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.shop.domain.Consumer;
import com.ruoyi.shop.domain.YjMerchant;
import com.ruoyi.shop.service.ConsumerService;
import com.ruoyi.shop.service.impl.YjMerchantServiceImpl;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@Api(tags = "登录与验证")
@RestController
@RequestMapping("/api")
public class LoginController {
@Resource
private ConsumerService service;
@Autowired
private ISysUserService userService;
@Resource
JwtUtil1 jwtUtil1;
@Autowired
private TokenService tokenService;
@Resource
RedisTemplate<String,Object> redisTemplate;
@Autowired
private RedisCache redisCache;
@Autowired
private ISysConfigService configService;
@Resource
private AuthenticationManager authenticationManager;
@ApiOperation("登录")
@PostMapping("/login")
public AjaxResult login(@RequestBody LoginBody loginBody){
AjaxResult ajax = AjaxResult.success();
if (StrUtil.isEmpty(loginBody.getRegisterId())){
ajax.put(Constants.FAIL, "设备id异常");
return ajax;
}
boolean captchaEnabled = configService.selectCaptchaEnabled();
// 验证码开关
if (captchaEnabled)
{
validateCaptcha(loginBody.getAccount(),loginBody.getCode(),loginBody.getUuid());
}
//用户名是否存在
SysUser user = userService.selectUserByUserName(loginBody.getAccount());
//未注册
if(ObjectUtil.isEmpty(user) ){
//注册并登录
//用户账号 昵称 门店 密码 头像
// registerId 地址
// 必填 user_name nick_name merchant_id
user=new SysUser();
user.setUserName(loginBody.getAccount());
user.setNickName("用户"+loginBody.getAccount());
user.setPassword(SecurityUtils.encryptPassword(loginBody.getPassword()));
user.setRegisterId(loginBody.getRegisterId());
user.setVisitStore(getIndex(user).get("id"));
Long[] ros={107l};//用户角色
user.setRoleIds(ros);
userService.insertUser(user);
String token = validateUser(loginBody.getAccount(),loginBody.getPassword());
//设置推送别名
JpushClientUtil.bindAlias(loginBody.getRegisterId(),loginBody.getAccount());
ajax.put(Constants.TOKEN, token);
return ajax;
}
//已注册 直接登录
String token = validateUser(loginBody.getAccount(),loginBody.getPassword());
//设置推送别名
JpushClientUtil.bindAlias(loginBody.getRegisterId(),loginBody.getAccount());
if (!loginBody.getRegisterId().equals(user.getRegisterId())){
//判断登录设备是否更换 todo
// userService.updateUser();
}
//返回token
ajax.put(Constants.TOKEN, token);
return ajax;
}
/**
*
*
* @param code
* @param uuid
* @return
*/
public void validateCaptcha(String username, String code, String uuid)
{
String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
String captcha = redisCache.getCacheObject(verifyKey);
redisCache.deleteObject(verifyKey);
if (captcha == null)
{
//验证码为空
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
throw new CaptchaExpireException();
}
if (!code.equalsIgnoreCase(captcha))
{
//验证码不存在
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
throw new CaptchaException();
}
}
//用户验证
public String validateUser(String username,String password){
// 用户验证
Authentication authentication = null;
try
{
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
AuthenticationContextHolder.setContext(authenticationToken);
// 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
authentication = authenticationManager.authenticate(authenticationToken);
}
catch (Exception e)
{
if (e instanceof BadCredentialsException)
{
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
throw new UserPasswordNotMatchException();
}
else
{
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
throw new ServiceException(e.getMessage());
}
}
finally
{
AuthenticationContextHolder.clearContext();
}
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
LoginUser loginUser = (LoginUser) authentication.getPrincipal();
if (StrUtil.isEmpty(loginUser.getUser().getMerchantId())){
throw new RuntimeException("未建商户无法登录");
}
recordLoginInfo(loginUser.getUserId());
// 生成token
return tokenService.createToken(loginUser);
}
/**
*
*
* @return
*/
@GetMapping("/getInfo")
public AjaxResult getInfo()
{
SysUser user = SecurityUtils.getLoginUser().getUser();
// 角色集合
// Set<String> roles = permissionService.getRolePermission(user);
// 权限集合
// Set<String> permissions = permissionService.getMenuPermission(user);
AjaxResult ajax = AjaxResult.success();
ajax.put("user", user);
ajax.put("merchant",getIndex(user));
// ajax.put("roles", roles);
// ajax.put("permissions", permissions);
return ajax;
}
/**
*
*
* @param userId ID
*/
public void recordLoginInfo(Long userId)
{
SysUser sysUser = new SysUser();
sysUser.setUserId(userId);
sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
sysUser.setLoginDate(DateUtils.getNowDate());
userService.updateUserProfile(sysUser);
}
// -----------------------------------------------
@ApiOperation("获取验证码")
// @PostMapping ("/getCode")
public RestResponse getCode(@RequestBody Consumer consumer){
String captcha=(String) redisTemplate.opsForValue().get(consumer.getConsumerPhonenumber());
if (StrUtil.isNotEmpty(captcha)){
return new RestResponse().setSuccess(false).setMessage("请1分钟后重试");
}
captcha =gen()+"";
//发送成功 手机号存到redis 对应code 1分钟有效期
redisTemplate.opsForValue().set(consumer.getConsumerPhonenumber(),
captcha,
1,
TimeUnit.MINUTES);
return new RestResponse().setSuccess(true).setMessage("发送成功").setData(captcha);
}
public int gen() {
Random r = new Random( System.currentTimeMillis() );
return ((1 + r.nextInt(2)) * 100000 + r.nextInt(100000));
}
/**
*
* @param map
* @return
*/
public RestResponse login(@RequestBody Map<String,String> map){
System.out.println("---------------------registerId"+map.get("registerId"));
String captcha=(String)redisTemplate.opsForValue().get(map.get("consumerPhonenumber"));
if(map.get("captcha").equals(captcha)){
//登录成功
redisTemplate.delete(map.get("consumerPhonenumber"));
Map<String, Object> dataMap = new HashMap<>();
//查找数据库,判断是否为新用户:
//老用戶
Consumer consumer=service.getOne(new QueryWrapper<Consumer>()
.eq("consumer_phonenumber",map.get("consumerPhonenumber")));
if (ObjectUtil.isNotEmpty(consumer)){
//老客户
if (StrUtil.isNotEmpty(map.get("registerId"))){
consumer.setRegisterId(map.get("registerId"));
service.updateById(consumer);
//设置推送别名
JpushClientUtil.bindAlias(consumer.getRegisterId(),consumer.getConsumerPhonenumber());
}
String token = jwtUtil1.generateToken(consumer.getConsumerId().toString(),consumer.getConsumerPhonenumber());
dataMap.put("jwt",token);
dataMap.put("userInfo",consumer);
return new RestResponse().setSuccess(true).setMessage("成功").setData(dataMap);
}
//新用戶
consumer=new Consumer();
consumer.setConsumerPhonenumber(map.get("consumerPhonenumber"));
consumer.setConsumerName("用户"+map.get("consumerPhonenumber"));
consumer.setConsumerNickName("用户"+map.get("consumerPhonenumber"));
consumer.setRegisterId(map.get("registerId"));
consumer.setConsumerAvatar("/default.jpeg");
service.save(consumer);
//设置推送别名
JpushClientUtil.bindAlias(consumer.getRegisterId(),consumer.getConsumerPhonenumber());
String token = jwtUtil1.generateToken(consumer.getConsumerId().toString(),consumer.getConsumerPhonenumber());
dataMap.put("jwt",token);
dataMap.put("userInfo",consumer);
// dataMap.put("index",getIndex(consumer));
return new RestResponse().setSuccess(true).setMessage("成功").setData(dataMap);
}
return new RestResponse().setSuccess(false).setMessage("失败");
}
@Resource
private YjMerchantServiceImpl merchantService;
public Map<String,String> getIndex(SysUser c){
YjMerchant merchant;
Map m=new HashMap();
if (StrUtil.isNotEmpty(c.getVisitStore())){
merchant=merchantService.getById(c.getVisitStore());
}else {
merchant= merchantService.list().get(0);
}
m.put("address",merchant.getAddress());
m.put("enterpriseName",merchant.getEnterpriseName());
m.put("phone",merchant.getPhone());
m.put("banner",merchant.getBanner());
m.put("id",merchant.getId());
return m;
}
}

@ -0,0 +1,41 @@
package com.ruoyi.web.controller.app_shop;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.RestResponse;
import com.ruoyi.shop.domain.YjMerchant;
import com.ruoyi.shop.service.impl.YjMerchantServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
*
*/
@Api(tags = "门店", description = "提供门店相关的API")
@RestController
@RequestMapping("/api/merchan")
public class MerchantController {
@Resource
private YjMerchantServiceImpl merchantService;
/**
* +
* @param merchan
* @return
*/
@ApiOperation(value = "创始人+企业简介+门店列表")
@PostMapping("/getList")
public RestResponse getList(@RequestBody YjMerchant merchan){
YjMerchant m=merchantService.getOne(new QueryWrapper<YjMerchant>()
.select("id,enterprise_name,address,phone,founder,profile")
.eq("id",merchan.getId()));
return new RestResponse().setSuccess(true).setMessage("成功").setData(m);
}
}

@ -0,0 +1,323 @@
package com.ruoyi.web.controller.app_shop;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.RestResponse;
import com.ruoyi.shop.domain.ShopGoods;
import com.ruoyi.shop.domain.ShopOrder;
import com.ruoyi.shop.domain.ShopOrderItem;
import com.ruoyi.shop.service.impl.ShopCartServiceImpl;
import com.ruoyi.shop.service.impl.ShopGoodsServiceImpl;
import com.ruoyi.shop.service.impl.ShopOrderItemServiceImpl;
import com.ruoyi.shop.service.impl.ShopOrderServiceImpl;
import com.ruoyi.web.controller.app_shop.dto.ShopOrderDto;
import com.ruoyi.web.util.PayUtil;
import com.ruoyi.web.util.SnowFlake;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Api(tags = "订单信息", description = "提供订单信息相关的API")
@RestController
@RequestMapping("/api/order")
public class OrderController {
@Resource
private ShopGoodsServiceImpl goodsService;
@Resource
private ShopCartServiceImpl cartService;
@Resource
private ShopOrderServiceImpl orderService;
@Resource
private ShopOrderItemServiceImpl itemService;
/**
*
* @param orderDto
* @param request
* @return
*
*
*
*
*/
@ApiOperation("提交订单-生成预付单")
@PostMapping("/createOrder")
@Transactional(rollbackFor = RuntimeException.class)
public RestResponse createOrder(@RequestBody ShopOrderDto orderDto, HttpServletRequest request) throws Exception{
Long userId= Long.parseLong(request.getAttribute("userId").toString());
//商户:商品list
Map<String,List<ShopGoods>> goodsMap=orderDto.getList().stream().collect(Collectors.groupingBy(ShopGoods::getBusinessId));
String OrderSn=SnowFlake.getOrder()+"";
BigDecimal total=new BigDecimal(0);//微信支付金额
for (String key:goodsMap.keySet()){
//生成订单
ShopOrder order=new ShopOrder();
order.setBusinessId(key);//商户
order.setIdUser(userId);
order.setConsignee(orderDto.getName());//收件人
order.setConsigneeAddress(orderDto.getProvince()+" "+
orderDto.getCity()+" "+
orderDto.getAddress());//收件地址
order.setMobile(orderDto.getPhone());//收件人电话
order.setCreateTime(DateUtil.parseLocalDateTime(DateUtil.now(),"yyyy-MM-dd HH:mm:ss"));
order.setOrderSn(OrderSn);//订单号
order.setPayType("微信支付");
order.setOrderType(1);//订单类型1.商品 2.会籍 3.课程
orderService.save(order);
BigDecimal totalPrice=new BigDecimal(0);//总金额
BigDecimal tradeAmount=new BigDecimal(0);//交易金额
for (ShopGoods goods:goodsMap.get(key)){
ShopOrderItem item=new ShopOrderItem();
item.setGoodsName(goods.getName());//* 商品名称
item.setIdGoods(goods.getId());//* 商品名称
item.setThumbnail(goods.getThumbnail());//* 商品缩略图
item.setBrief(goods.getBrief());//* 商品简介
item.setAttribute(goods.getAttribute());//* 规格
item.setCount(goods.getCount());//数量
item.setPrice(goods.getPrice());//单价
item.setIdOrder(order.getId());//订单id
item.setType("1");//1 商品 2 会籍 3 课程
BigDecimal to=goods.getPrice().multiply(new BigDecimal(goods.getCount()));
item.setTotalPrice(to);//总金额
//商品库存更改
Boolean isEnough= goodsService.update(new UpdateWrapper<ShopGoods>()
.setSql("stock=stock-"+goods.getCount())
.eq("id",goods.getId())
.ge("stock",goods.getCount()));
if(!isEnough){
throw new RuntimeException("商品["+goods.getName()+"]库存不足!");
// return new RestResponse().setSuccess(false).setMessage("商品["+goods.getName()+"]库存不足!");
}
itemService.save(item);
if (StrUtil.isNotEmpty(goods.getCartId())){
cartService.removeById(goods.getCartId());
}
tradeAmount=tradeAmount.add(to);//实际需要支付的金额
totalPrice=totalPrice.add(goods.getMarketPrice().multiply(new BigDecimal(goods.getCount())));
}
order.setTotalPrice(totalPrice);
order.setTradeAmount( tradeAmount);//实际需要支付的金额
orderService.updateById(order);
//
total=total.add(order.getTradeAmount());
}
total=total.multiply(new BigDecimal(100));
Map map=new HashMap();
if (total.equals(BigDecimal.ZERO)){
//0元直接支付成功 无需调用微信支付
orderService.paySuccess(OrderSn,DateUtil.now(),"","0");
map.put("timeStamp","1");
return new RestResponse().setSuccess(true).setMessage("成功").setData(map);
}
//调用微信支付 生成预付单
map= PayUtil.creatOrder(total.setScale(1, RoundingMode.HALF_UP).intValue(),OrderSn);
return new RestResponse().setSuccess(true).setMessage("成功").setData(map);
}
// public RestResponse createOrder(@RequestBody ShopOrderDto orderDto, HttpServletRequest request){
// Long userId= Long.parseLong(request.getAttribute("userId").toString());
//
//// List<String> goodsIds = orderDto.getList().stream().map(ShopGoods::getId).collect(Collectors.toList());
//// List<ShopGoods> goodsList = goodsMapper.selectBatchIds(goodsIds);
// Map<String,List<ShopGoods>> goodsMap=orderDto.getList().stream().collect(Collectors.groupingBy(ShopGoods::getBusinessId));
//
// for (String key:goodsMap.keySet()){
// //生成订单
// ShopOrder order=new ShopOrder();
// order.setBusinessId(key);//商户
// order.setIdUser(userId);
// order.setConsignee(orderDto.getName());//收件人
// order.setConsigneeAddress(orderDto.getProvince()+" "+
// orderDto.getCity()+" "+
// orderDto.getAddress());//收件地址
// order.setMobile(orderDto.getPhone());//收件人电话
// order.setCreateTime(DateUtil.parseLocalDateTime(DateUtil.now(),"yyyy-MM-dd HH:mm:ss"));
// order.setOrderSn(SnowFlake.getOrder()+"");
// orderService.save(order);
// BigDecimal totalPrice=new BigDecimal(0);//总金额
// BigDecimal tradeAmount=new BigDecimal(0);//交易金额
//
// for (ShopGoods goods:goodsMap.get(key)){
// ShopOrderItem item=new ShopOrderItem();
// item.setGoodsName(goods.getName());//* 商品名称
// item.setIdGoods(goods.getId());//* 商品名称
// item.setThumbnail(goods.getThumbnail());//* 商品缩略图
// item.setBrief(goods.getBrief());//* 商品简介
// item.setAttribute(goods.getAttribute());//* 规格
// item.setCount(goods.getCount());//数量
// item.setPrice(goods.getPrice());//单价
// item.setIdOrder(order.getId());//订单id
// BigDecimal To=goods.getPrice().multiply(new BigDecimal(goods.getCount()));
// item.setTotalPrice(To);//总金额
// //商品库存更改
// Boolean isEnough= goodsService.update(new UpdateWrapper<ShopGoods>()
// .setSql("stock=stock-"+goods.getCount())
// .eq("id",goods.getId())
// .ge("stock",goods.getCount()));
// if(!isEnough){
// throw new RuntimeException("商品["+goods.getName()+"]库存不足!");
//// return new RestResponse().setSuccess(false).setMessage("商品["+goods.getName()+"]库存不足!");
// }
// itemService.save(item);
// if (StrUtil.isNotEmpty(goods.getCartId())){
// cartService.removeById(goods.getCartId());
// }
// totalPrice=totalPrice.add(To);
// tradeAmount=tradeAmount.add(goods.getMarketPrice().multiply(new BigDecimal(goods.getCount())));
// }
// order.setTotalPrice(tradeAmount);
// order.setTradeAmount(totalPrice);//
// orderService.updateById(order);
// }
// return new RestResponse().setSuccess(true).setMessage("成功");
// }
/**
* 1/
*
*
* @param order
* @return
*/
// @PostMapping("/cancelOrder")
@Transactional(rollbackFor = RuntimeException.class)
public RestResponse cancelOrder(@RequestBody ShopOrder order){
//更改订单状态
//查询对应订单详情
//根据订单详情数量 更改商品库存
Boolean isUpdate= orderService.update(new UpdateWrapper<ShopOrder>()
.set("status",2)
.eq("id",order.getId())
.eq("status",1));
if (isUpdate){
List<ShopOrderItem> itemList=itemService.list(new QueryWrapper<ShopOrderItem>()
.eq("id_order",order.getId()));
for (ShopOrderItem item:itemList){
goodsService.update(new UpdateWrapper<ShopGoods>()
.setSql("stock=stock+"+item.getCount())
.eq("id",item.getIdGoods()));
}
return new RestResponse().setSuccess(true).setMessage("订单取消成功");
}
return new RestResponse().setSuccess(false).setMessage("该订单无法取消");
}
/**
*
* @param order
* @return
*/
// @PostMapping("/pay")
public RestResponse pay(@RequestBody ShopOrder order){
if(orderService.getById(order.getId()).getPayStatus()==2){
return new RestResponse().setSuccess(true).setMessage("该订单已支付成功,请勿重复支付!");
}
ShopOrder o=orderService.getById(order);
order.setStatus(3);
order.setPayStatus(2);
order.setPayTime(DateUtil.now());
order.setRealPrice(o.getTradeAmount());
orderService.updateById(order);
return new RestResponse().setSuccess(true).setMessage("订单支付成功");
}
/**
*
* @param order
* @return
*/
@ApiOperation("确认收货")
@PostMapping("/received")
public RestResponse received(@RequestBody ShopOrder order){
order.setStatus(6);
orderService.updateById(order);
return new RestResponse().setSuccess(true).setMessage("成功");
}
/**
*
* @param request
* @return
*/
@ApiOperation(value = "获取订单列表", notes = "我的订单")
@PostMapping("/orderList")
public RestResponse orderList(HttpServletRequest request){
Long userId= Long.parseLong(request.getAttribute("userId").toString());
List<ShopOrder> list=orderService.list(new QueryWrapper<ShopOrder>()
.eq("id_user",userId));
List<ShopOrder> list1=new ArrayList<>();
List<ShopOrder> list2=new ArrayList<>();
List<ShopOrder> list3=new ArrayList<>();
List<ShopOrder> list4=new ArrayList<>();
List<ShopOrder> list6=new ArrayList<>();
for (ShopOrder order:list){
order.setItemList(getItemList(order.getId()));
if (order.getStatus()==1){
list1.add(order);
}
if (order.getStatus()==2){
list2.add(order);
}
if (order.getStatus()==3){
list3.add(order);
}
if (order.getStatus()==4){
list4.add(order);
}
if (order.getStatus()==6){
list6.add(order);
}
}
Map<String,List<ShopOrder>> map=new HashMap<>();
map.put("list",list);//全部订单
map.put("list1",list1);//未付款
map.put("list2",list2);//2已取消
map.put("list3",list3);//3已付款/待发货
map.put("list4",list4);//4已发货/待收货
map.put("list6",list6);//6已签收
return new RestResponse().setSuccess(true).setMessage("成功").setData(map);
}
/**
*
* @param order
* @return
*/
@ApiOperation("订单详情")
@PostMapping("/getOrder")
public RestResponse getOrder(@RequestBody ShopOrder order){
ShopOrder o= orderService.getById(order.getId());
o.setItemList(getItemList(order.getId()));
return new RestResponse().setSuccess(true).setMessage("成功").setData(o);
}
public List<ShopOrderItem> getItemList(String orderId){
return itemService.list(new QueryWrapper<ShopOrderItem>().eq("id_order",orderId));
}
}

@ -0,0 +1,220 @@
package com.ruoyi.web.controller.app_shop;
import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.shop.domain.ShopOrder;
import com.ruoyi.shop.service.impl.ShopOrderServiceImpl;
import com.ruoyi.web.util.PayConstants;
import com.ruoyi.web.util.PayUtil;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.Verifier;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.cert.CertificatesManager;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;
import java.text.SimpleDateFormat;
import java.util.*;
@RestController
@RequestMapping("/api")
public class PayController {
@Resource
private ShopOrderServiceImpl orderService;
/**
*
* @param amount
* @return
* @throws Exception
*/
// @PostMapping("/creat_order")
// private Map creatOrder(int amount) throws Exception{
// return PayUtil.creatOrder("三朵兰",amount,"123");
// }
/**
*
* @return
* https://www.test.com/callback
*/
@PostMapping("/callback")
public Map callback(HttpServletRequest request) {
System.out.println("Wechatpay-Timestamp:"+ request.getHeader("Wechatpay-Timestamp"));
System.out.println("Wechatpay-Nonce:"+ request.getHeader("Wechatpay-Nonce"));
System.out.println("Wechatpay-Signature:"+ request.getHeader("Wechatpay-Signature"));
System.out.println("Wechatpay-Serial:"+ request.getHeader("Wechatpay-Serial"));
Map result=new HashMap();
result.put("code","FAIL");
try {
StringBuilder signStr=new StringBuilder();
signStr.append( request.getHeader("Wechatpay-Timestamp")).append("\n");
signStr.append( request.getHeader("Wechatpay-Nonce")).append("\n");
BufferedReader br=request.getReader();
String str=null;
StringBuilder builder=new StringBuilder();
while ((str=br.readLine())!=null){
builder.append(str);
}
System.out.println(builder);
signStr.append( builder.toString()).append("\n");
//验证签名
if (!PayUtil.signVerify(request.getHeader("Wechatpay-Serial"),signStr.toString(),request.getHeader("Wechatpay-Signature"))){
result.put("message","sign error");
return result;
}
//解密密文
String ciphertext=PayUtil.decryptOrder(builder.toString());
System.out.println(ciphertext);
//验证订单
ObjectMapper objectMapper = new ObjectMapper();
JsonNode node=objectMapper.readTree(ciphertext);
JsonNode amount=node.get("amount");//订单金额信息
String payer_total=amount.get("payer_total").textValue();//用户支付金额,单位为分
String payer_currency=amount.get("payer_currency").textValue();//用户支付币种 示例值CNY
String trade_state=node.get("trade_state").textValue();//交易状态 SUCCESS
String out_trade_no=node.get("out_trade_no").textValue();//商户订单号
String success_time=node.get("success_time").textValue();//支付完成时间
String transaction_id=node.get("transaction_id").textValue();//支付完成时间
List<ShopOrder> list = orderService.list(new QueryWrapper<ShopOrder>().eq("orderSn",out_trade_no));
//判断交易状态 可能是多次 SUCCESS 也可能是 多次不同状态
// 现只处理支付成功与支付失败两种状态
//判断是否处理过
if (list.get(0).getPayStatus()==1){
System.out.println("处理订单:"+out_trade_no+" 交易状态:"+trade_state);
//支付失败
if (trade_state.equals("PAYERROR")){
System.out.println("取消订单+关单");
orderService.cancelOrder(out_trade_no);
try {
PayUtil.closeOrder(out_trade_no);//关单
} catch (Exception e) {
e.printStackTrace();
}
}
//支付成功
if (trade_state.equals("SUCCESS")){
System.out.println("支付成功");
orderService.paySuccess(out_trade_no
,getStringByRFC3339(success_time)
,transaction_id
,payer_total);
result.put("code","SUCCESS");
}
}
}catch (IOException e){
e.printStackTrace();
}
return result;
}
public void a(@RequestBody Map<String,String> map){
String out_trade_no=map.get("out_trade_no");
String trade_state=map.get("trade_state");
String success_time="2022-12-31T10:34:56+08:00";
String transaction_id="微信支付订单号";
String payer_total="0.1";
List<ShopOrder> list = orderService.list(new QueryWrapper<ShopOrder>().eq("order_sn",out_trade_no));
//判断交易状态 可能是多次 SUCCESS 也可能是 多次不同状态
// 现只处理支付成功与支付失败两种状态
//判断是否处理过
if (list.get(0).getPayStatus()==1){
//支付失败
if (trade_state.equals("PAYERROR")){
System.out.println("取消订单+关单");
orderService.cancelOrder(out_trade_no);
try {
PayUtil.closeOrder(out_trade_no);//关单
System.out.println("code,***");
} catch (Exception e) {
e.printStackTrace();
}
}
//支付成功
if (trade_state.equals("SUCCESS")){
System.out.println("支付成功");
orderService.paySuccess(out_trade_no
,getStringByRFC3339(success_time)
,transaction_id
,payer_total);
System.out.println("code,SUCCESS");
}
}
}
//查询订单
public void queryOrder() throws Exception{
PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(PayConstants.PRIVATE_KEY);
// 获取证书管理器实例
CertificatesManager certificatesManager = CertificatesManager.getInstance();
// 向证书管理器增加需要自动更新平台证书的商户信息
certificatesManager.putMerchant(PayConstants.MCH_ID, new WechatPay2Credentials(PayConstants.MCH_ID,
new PrivateKeySigner(PayConstants.MCH_SERIAL_NO, merchantPrivateKey)),
PayConstants.API_V3KEY.getBytes(StandardCharsets.UTF_8));
// 从证书管理器中获取verifier
Verifier verifier = certificatesManager.getVerifier(PayConstants.MCH_ID);
CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
.withMerchant(PayConstants.MCH_ID, PayConstants.MCH_SERIAL_NO, merchantPrivateKey)
.withValidator(new WechatPay2Validator(certificatesManager.getVerifier(PayConstants.MCH_ID)))
.build();
//***********************
URIBuilder uriBuilder = new URIBuilder("https://api.mch.weixin.qq.com/v3/pay/partner/transactions/id/"+"订单号"+"?mchid="+PayConstants.MCH_ID);
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.addHeader("Accept", "application/json");
CloseableHttpResponse response = httpClient.execute(httpGet);
String bodyAsString = EntityUtils.toString(response.getEntity());
System.out.println(bodyAsString);
}
/**
*
*
* rfc3339
* yyyy-MM-DDTHH:mm:ss+TIMEZONE
* 2018-06-08T10:34:56+08:00
* @param dateStr
* @return
*/
public static String getStringByRFC3339(String dateStr){
DateTime dateTime = new DateTime(dateStr);
long timeInMillis = dateTime.toCalendar(Locale.getDefault()).getTimeInMillis();
Date date = new Date(timeInMillis);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = format.format(date);
return time;
}
}

@ -0,0 +1,55 @@
package com.ruoyi.web.controller.app_shop;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.RestResponse;
import com.ruoyi.shop.domain.YjPracticeMoments;
import com.ruoyi.shop.service.impl.YjPracticeMomentsServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
/**
*
*/
@Api(tags = "练习瞬间", description = "提供练习瞬间相关的API")
@RestController
@RequestMapping("/api/moments")
public class PracticeMomentsController {
@Resource
private YjPracticeMomentsServiceImpl momentsService;
/**
*
* @param moments
* @return
*/
@ApiOperation(value = "获取练习瞬间列表")
@PostMapping("/getList")
public RestResponse getList(@RequestBody YjPracticeMoments moments){
List<YjPracticeMoments> list=momentsService.list(new QueryWrapper<YjPracticeMoments>()
.eq("merchan_id",moments.getMerchanId())
.eq("status",true)
.orderByDesc("modify_time"));
return new RestResponse().setSuccess(true).setMessage("成功").setData(list);
}
/**
*
* @param moments
* @return
*/
@ApiOperation(value = "获取练习瞬间详情")
@PostMapping("/getOne")
public RestResponse getOne(@RequestBody YjPracticeMoments moments){
YjPracticeMoments m=momentsService.getOne(new QueryWrapper<YjPracticeMoments>()
.eq("id",moments.getId()));
return new RestResponse().setSuccess(true).setMessage("成功").setData(m);
}
}

@ -0,0 +1,57 @@
package com.ruoyi.web.controller.app_shop;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.RestResponse;
import com.ruoyi.shop.domain.YjSense;
import com.ruoyi.shop.service.impl.YjSenseServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
/**
*
*/
@Api(tags = "瑜伽常识", description = "提供瑜伽常识相关的API")
@RestController
@RequestMapping("/api/sense")
public class SenseController {
@Resource
private YjSenseServiceImpl service;
/**
*
* @param sense
* @return
*/
@ApiOperation(value = "获取瑜伽常识列表")
@PostMapping("/getList")
public RestResponse getList(@RequestBody YjSense sense){
List<YjSense> list= service.list(new QueryWrapper<YjSense>()
.eq("merchan_id",sense.getMerchanId())
.eq("status",true)
.orderByDesc("modify_time"));
return new RestResponse().setSuccess(true).setMessage("成功").setData(list);
}
/**
*
* @param sense
* @return
*/
@ApiOperation(value = "瑜伽常识详情")
@PostMapping("/getOne")
public RestResponse getOne(@RequestBody YjSense sense){
service.update(new UpdateWrapper<YjSense>()
.setSql("read_num=read_num+1")
.eq("id",sense.getId()));//阅读量
YjSense i=service.getById(sense.getId());
return new RestResponse().setSuccess(true).setMessage("成功").setData(i);
}
}

@ -0,0 +1,87 @@
package com.ruoyi.web.controller.app_shop;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.RestResponse;
import com.ruoyi.shop.domain.ShopAddress;
import com.ruoyi.shop.mapper.ShopAddressMapper;
import com.ruoyi.shop.service.ShopAddressService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
/**
* <p>
*
* </p>
*
* @author xn
* @since 2022-09-29
*/
@Api(tags = "用户地址", description = "提供用户地址相关的API")
@RestController
@RequestMapping("/api/address")
public class ShopAddressController {
@Resource
private ShopAddressMapper mapper;
@Resource
private ShopAddressService service;
@ApiOperation("新增收货地址")
@PostMapping("/add")
public RestResponse add(@RequestBody ShopAddress address, HttpServletRequest request){
Long userId= Long.parseLong(request.getAttribute("userId").toString());
address.setUserId(userId);
if (address.getIsDefault()){
changeDefault(userId);
}
mapper.insert(address);
return new RestResponse().setSuccess(true).setMessage("成功");
}
@ApiOperation("收货地址列表")
@PostMapping("/list")
public RestResponse list(HttpServletRequest request){
Long userId= Long.parseLong(request.getAttribute("userId").toString());
List<String> columns=new ArrayList<>();
columns.add("add_time");
columns.add("is_default");
List<ShopAddress> list=mapper.selectList(new QueryWrapper<ShopAddress>()
.eq("user_id",userId)
.orderByDesc(columns));
return new RestResponse().setSuccess(true).setMessage("成功").setData(list);
}
@ApiOperation("修改收货地址")
@PostMapping("/edit")
public RestResponse edit(@RequestBody ShopAddress address, HttpServletRequest request){
Long userId= Long.parseLong(request.getAttribute("userId").toString());
if (address.getIsDefault()){
changeDefault(userId);
}
mapper.updateById(address);
return new RestResponse().setSuccess(true).setMessage("成功");
}
@ApiOperation("删除收货地址")
@PostMapping("/del")
public RestResponse del(@RequestBody ShopAddress address){
mapper.deleteById(address.getId());
return new RestResponse().setSuccess(true).setMessage("成功");
}
public void changeDefault(Long userId){
service.update(new UpdateWrapper<ShopAddress>().set("is_default",false).eq("user_id",userId));
}
}

@ -0,0 +1,68 @@
package com.ruoyi.web.controller.app_shop;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.RestResponse;
import com.ruoyi.shop.domain.ShopCart;
import com.ruoyi.shop.domain.ShopGoods;
import com.ruoyi.shop.mapper.ShopCartMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
@Api(tags = "购物车", description = "提供购物车相关的API")
@RestController
@RequestMapping("/api/shopCart")
public class ShopCartController {
@Resource
private ShopCartMapper shopCartMapper;
@ApiOperation("加入购物车")
@PostMapping("/addShopCart")
public RestResponse addShopCart(@RequestBody ShopCart shopCart, HttpServletRequest request){
Long userId= Long.parseLong(request.getAttribute("userId").toString());
ShopCart s=shopCartMapper.selectOne(new QueryWrapper<ShopCart>()
.eq("id_user",userId)
.eq("id_goods",shopCart.getIdGoods()));
if (ObjectUtil.isNotEmpty(s)){
s.setCount(s.getCount()+1);
shopCartMapper.updateById(s);
return new RestResponse().setSuccess(true).setMessage("成功");
}
shopCart.setIdUser(userId);
shopCartMapper.insert(shopCart);
return new RestResponse().setSuccess(true).setMessage("成功");
}
@ApiOperation("购物车删除商品")
@PostMapping("/removeShopCart")
public RestResponse removeShopCart(@RequestBody Map<String, List<String>> map){
List<String> ids=map.get("ids");
shopCartMapper.deleteBatchIds(ids);
return new RestResponse().setSuccess(true).setMessage("成功");
}
@ApiOperation("购物车商品列表")
@PostMapping("/shopCartList")
public RestResponse shopCartList(HttpServletRequest request){
Long userId= Long.parseLong(request.getAttribute("userId").toString());
List<ShopGoods> list=shopCartMapper.cartList(userId);
return new RestResponse().setSuccess(true).setMessage("成功").setData(list);
}
@ApiOperation("购物车修改商品数量")
@PostMapping("/changeCount")
public RestResponse changeCount(@RequestBody ShopCart shopCart){
shopCartMapper.updateById(shopCart);
return new RestResponse().setSuccess(true).setMessage("成功");
}
}

@ -0,0 +1,40 @@
package com.ruoyi.web.controller.app_shop.dto;
import com.ruoyi.shop.domain.ShopGoods;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.List;
@Data
public class ShopOrderDto {
/**
*
*/
@ApiModelProperty("省")
private String province;
/**
*
*/
private String city;
/**
*
*/
private String address;
/**
*
*/
private String phone;
/**
*
*/
private String name;
private String message;
private List<ShopGoods> list;
}

@ -0,0 +1,95 @@
package com.ruoyi.web.controller.common;
import com.google.code.kaptcha.Producer;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.sign.Base64;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
/**
*
*
* @author ruoyi
*/
@RestController
public class CaptchaController
{
@Resource(name = "captchaProducer")
private Producer captchaProducer;
@Resource(name = "captchaProducerMath")
private Producer captchaProducerMath;
@Autowired
private RedisCache redisCache;
@Autowired
private ISysConfigService configService;
/**
*
*/
@GetMapping("/captchaImage")
public AjaxResult getCode(HttpServletResponse response) throws IOException
{
AjaxResult ajax = AjaxResult.success();
boolean captchaEnabled = configService.selectCaptchaEnabled();
ajax.put("captchaEnabled", captchaEnabled);
if (!captchaEnabled)
{
return ajax;
}
// 保存验证码信息
String uuid = IdUtils.simpleUUID();
String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
String capStr = null, code = null;
BufferedImage image = null;
// 生成验证码
String captchaType = RuoYiConfig.getCaptchaType();
if ("math".equals(captchaType))
{
String capText = captchaProducerMath.createText();
capStr = capText.substring(0, capText.lastIndexOf("@"));
code = capText.substring(capText.lastIndexOf("@") + 1);
image = captchaProducerMath.createImage(capStr);
}
else if ("char".equals(captchaType))
{
capStr = code = captchaProducer.createText();
image = captchaProducer.createImage(capStr);
}
redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
// 转换流信息写出
FastByteArrayOutputStream os = new FastByteArrayOutputStream();
try
{
ImageIO.write(image, "jpg", os);
}
catch (IOException e)
{
return AjaxResult.error(e.getMessage());
}
ajax.put("uuid", uuid);
ajax.put("img", Base64.encode(os.toByteArray()));
return ajax;
}
}

@ -0,0 +1,223 @@
package com.ruoyi.web.controller.common;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.shop.service.impl.YjLinkServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
/**
*
*
* @author ruoyi
*/
@RestController
@RequestMapping("/common")
public class CommonController
{
private static final Logger log = LoggerFactory.getLogger(CommonController.class);
@Autowired
private ServerConfig serverConfig;
@Autowired
private YjLinkServiceImpl yjLinkService;
private static final String FILE_DELIMETER = ",";
/**
*
*
* @param fileName
* @param delete
*/
@GetMapping("/download")
public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
{
try
{
if (!FileUtils.checkAllowDownload(fileName))
{
throw new Exception(StringUtils.format("文件名称({})非法,不允许下载。 ", fileName));
}
String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
String filePath = RuoYiConfig.getDownloadPath() + fileName;
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
FileUtils.setAttachmentResponseHeader(response, realFileName);
FileUtils.writeBytes(filePath, response.getOutputStream());
if (delete)
{
FileUtils.deleteFile(filePath);
}
}
catch (Exception e)
{
log.error("下载文件失败", e);
}
}
/**
*
*/
@PostMapping("/upload")
public AjaxResult uploadFile(MultipartFile file) throws Exception
{
try
{
// 上传文件路径
String filePath = RuoYiConfig.getUploadPath();
// 上传并返回新文件名称
String fileName = FileUploadUtils.upload(filePath, file);
yjLinkService.add(fileName,"picture");
String url = serverConfig.getUrl() + fileName;
AjaxResult ajax = AjaxResult.success();
ajax.put("url", url);
ajax.put("fileName", fileName);
ajax.put("newFileName", FileUtils.getName(fileName));
ajax.put("originalFilename", file.getOriginalFilename());
return ajax;
}
catch (Exception e)
{
return AjaxResult.error(e.getMessage());
}
}
@PostMapping("/uploadVideo")
public AjaxResult uploadVideo(MultipartFile file) throws Exception
{
try
{
// 上传文件路径
String filePath = RuoYiConfig.getUploadPath();
// 上传并返回新文件名称
String fileName = FileUploadUtils.upload(filePath, file);
yjLinkService.add(fileName,"video");
String url = serverConfig.getUrl() + fileName;
AjaxResult ajax = AjaxResult.success();
ajax.put("url", url);
ajax.put("fileName", fileName);
ajax.put("newFileName", FileUtils.getName(fileName));
ajax.put("originalFilename", file.getOriginalFilename());
return ajax;
}
catch (Exception e)
{
return AjaxResult.error(e.getMessage());
}
}
@PostMapping("/uploadSp")
public AjaxResult uploadFileSp(MultipartFile file) throws Exception
{
try
{
// 上传文件路径
String filePath = RuoYiConfig.getUploadPath();
// 上传并返回新文件名称
String fileName = FileUploadUtils.upload(filePath, file);
yjLinkService.add(fileName,"video");
String url = serverConfig.getUrl() + fileName;
AjaxResult ajax = AjaxResult.success();
ajax.put("url", url);
ajax.put("fileName", fileName);
ajax.put("newFileName", FileUtils.getName(fileName));
ajax.put("originalFilename", file.getOriginalFilename());
return ajax;
}
catch (Exception e)
{
return AjaxResult.error(e.getMessage());
}
}
/**
*
*/
@PostMapping("/uploads")
public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception
{
try
{
// 上传文件路径
String filePath = RuoYiConfig.getUploadPath();
List<String> urls = new ArrayList<String>();
List<String> fileNames = new ArrayList<String>();
List<String> newFileNames = new ArrayList<String>();
List<String> originalFilenames = new ArrayList<String>();
for (MultipartFile file : files)
{
// 上传并返回新文件名称
String fileName = FileUploadUtils.upload(filePath, file);
yjLinkService.add(fileName,"picture");
String url = serverConfig.getUrl() + fileName;
urls.add(url);
fileNames.add(fileName);
newFileNames.add(FileUtils.getName(fileName));
originalFilenames.add(file.getOriginalFilename());
}
AjaxResult ajax = AjaxResult.success();
ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
return ajax;
}
catch (Exception e)
{
return AjaxResult.error(e.getMessage());
}
}
/**
*
*/
@GetMapping("/download/resource")
public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
throws Exception
{
try
{
if (!FileUtils.checkAllowDownload(resource))
{
throw new Exception(StringUtils.format("资源文件({})非法,不允许下载。 ", resource));
}
// 本地资源路径
String localPath = RuoYiConfig.getProfile();
// 数据库资源地址
String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
// 下载名称
String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
FileUtils.setAttachmentResponseHeader(response, downloadName);
FileUtils.writeBytes(downloadPath, response.getOutputStream());
}
catch (Exception e)
{
log.error("下载文件失败", e);
}
}
}

@ -0,0 +1,120 @@
package com.ruoyi.web.controller.monitor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysCache;
/**
*
*
* @author ruoyi
*/
@RestController
@RequestMapping("/monitor/cache")
public class CacheController
{
@Autowired
private RedisTemplate<String, String> redisTemplate;
private final static List<SysCache> caches = new ArrayList<SysCache>();
{
caches.add(new SysCache(CacheConstants.LOGIN_TOKEN_KEY, "用户信息"));
caches.add(new SysCache(CacheConstants.SYS_CONFIG_KEY, "配置信息"));
caches.add(new SysCache(CacheConstants.SYS_DICT_KEY, "数据字典"));
caches.add(new SysCache(CacheConstants.CAPTCHA_CODE_KEY, "验证码"));
caches.add(new SysCache(CacheConstants.REPEAT_SUBMIT_KEY, "防重提交"));
caches.add(new SysCache(CacheConstants.RATE_LIMIT_KEY, "限流处理"));
caches.add(new SysCache(CacheConstants.PWD_ERR_CNT_KEY, "密码错误次数"));
}
@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
@GetMapping()
public AjaxResult getInfo() throws Exception
{
Properties info = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info());
Properties commandStats = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info("commandstats"));
Object dbSize = redisTemplate.execute((RedisCallback<Object>) connection -> connection.dbSize());
Map<String, Object> result = new HashMap<>(3);
result.put("info", info);
result.put("dbSize", dbSize);
List<Map<String, String>> pieList = new ArrayList<>();
commandStats.stringPropertyNames().forEach(key -> {
Map<String, String> data = new HashMap<>(2);
String property = commandStats.getProperty(key);
data.put("name", StringUtils.removeStart(key, "cmdstat_"));
data.put("value", StringUtils.substringBetween(property, "calls=", ",usec"));
pieList.add(data);
});
result.put("commandStats", pieList);
return AjaxResult.success(result);
}
@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
@GetMapping("/getNames")
public AjaxResult cache()
{
return AjaxResult.success(caches);
}
@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
@GetMapping("/getKeys/{cacheName}")
public AjaxResult getCacheKeys(@PathVariable String cacheName)
{
Set<String> cacheKeys = redisTemplate.keys(cacheName + "*");
return AjaxResult.success(cacheKeys);
}
@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
@GetMapping("/getValue/{cacheName}/{cacheKey}")
public AjaxResult getCacheValue(@PathVariable String cacheName, @PathVariable String cacheKey)
{
String cacheValue = redisTemplate.opsForValue().get(cacheKey);
SysCache sysCache = new SysCache(cacheName, cacheKey, cacheValue);
return AjaxResult.success(sysCache);
}
@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
@DeleteMapping("/clearCacheName/{cacheName}")
public AjaxResult clearCacheName(@PathVariable String cacheName)
{
Collection<String> cacheKeys = redisTemplate.keys(cacheName + "*");
redisTemplate.delete(cacheKeys);
return AjaxResult.success();
}
@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
@DeleteMapping("/clearCacheKey/{cacheKey}")
public AjaxResult clearCacheKey(@PathVariable String cacheKey)
{
redisTemplate.delete(cacheKey);
return AjaxResult.success();
}
@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
@DeleteMapping("/clearCacheAll")
public AjaxResult clearCacheAll()
{
Collection<String> cacheKeys = redisTemplate.keys("*");
redisTemplate.delete(cacheKeys);
return AjaxResult.success();
}
}

@ -0,0 +1,27 @@
package com.ruoyi.web.controller.monitor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.framework.web.domain.Server;
/**
*
*
* @author ruoyi
*/
@RestController
@RequestMapping("/monitor/server")
public class ServerController
{
@PreAuthorize("@ss.hasPermi('monitor:server:list')")
@GetMapping()
public AjaxResult getInfo() throws Exception
{
Server server = new Server();
server.copyTo();
return AjaxResult.success(server);
}
}

@ -0,0 +1,82 @@
package com.ruoyi.web.controller.monitor;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.SysPasswordService;
import com.ruoyi.system.domain.SysLogininfor;
import com.ruoyi.system.service.ISysLogininforService;
/**
* 访
*
* @author ruoyi
*/
@RestController
@RequestMapping("/monitor/logininfor")
public class SysLogininforController extends BaseController
{
@Autowired
private ISysLogininforService logininforService;
@Autowired
private SysPasswordService passwordService;
@PreAuthorize("@ss.hasPermi('monitor:logininfor:list')")
@GetMapping("/list")
public TableDataInfo list(SysLogininfor logininfor)
{
startPage();
List<SysLogininfor> list = logininforService.selectLogininforList(logininfor);
return getDataTable(list);
}
@Log(title = "登录日志", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('monitor:logininfor:export')")
@PostMapping("/export")
public void export(HttpServletResponse response, SysLogininfor logininfor)
{
List<SysLogininfor> list = logininforService.selectLogininforList(logininfor);
ExcelUtil<SysLogininfor> util = new ExcelUtil<SysLogininfor>(SysLogininfor.class);
util.exportExcel(response, list, "登录日志");
}
@PreAuthorize("@ss.hasPermi('monitor:logininfor:remove')")
@Log(title = "登录日志", businessType = BusinessType.DELETE)
@DeleteMapping("/{infoIds}")
public AjaxResult remove(@PathVariable Long[] infoIds)
{
return toAjax(logininforService.deleteLogininforByIds(infoIds));
}
@PreAuthorize("@ss.hasPermi('monitor:logininfor:remove')")
@Log(title = "登录日志", businessType = BusinessType.CLEAN)
@DeleteMapping("/clean")
public AjaxResult clean()
{
logininforService.cleanLogininfor();
return success();
}
@PreAuthorize("@ss.hasPermi('monitor:logininfor:unlock')")
@Log(title = "账户解锁", businessType = BusinessType.OTHER)
@GetMapping("/unlock/{userName}")
public AjaxResult unlock(@PathVariable("userName") String userName)
{
passwordService.clearLoginRecordCache(userName);
return success();
}
}

@ -0,0 +1,69 @@
package com.ruoyi.web.controller.monitor;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysOperLog;
import com.ruoyi.system.service.ISysOperLogService;
/**
*
*
* @author ruoyi
*/
@RestController
@RequestMapping("/monitor/operlog")
public class SysOperlogController extends BaseController
{
@Autowired
private ISysOperLogService operLogService;
@PreAuthorize("@ss.hasPermi('monitor:operlog:list')")
@GetMapping("/list")
public TableDataInfo list(SysOperLog operLog)
{
startPage();
List<SysOperLog> list = operLogService.selectOperLogList(operLog);
return getDataTable(list);
}
@Log(title = "操作日志", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('monitor:operlog:export')")
@PostMapping("/export")
public void export(HttpServletResponse response, SysOperLog operLog)
{
List<SysOperLog> list = operLogService.selectOperLogList(operLog);
ExcelUtil<SysOperLog> util = new ExcelUtil<SysOperLog>(SysOperLog.class);
util.exportExcel(response, list, "操作日志");
}
@Log(title = "操作日志", businessType = BusinessType.DELETE)
@PreAuthorize("@ss.hasPermi('monitor:operlog:remove')")
@DeleteMapping("/{operIds}")
public AjaxResult remove(@PathVariable Long[] operIds)
{
return toAjax(operLogService.deleteOperLogByIds(operIds));
}
@Log(title = "操作日志", businessType = BusinessType.CLEAN)
@PreAuthorize("@ss.hasPermi('monitor:operlog:remove')")
@DeleteMapping("/clean")
public AjaxResult clean()
{
operLogService.cleanOperLog();
return AjaxResult.success();
}
}

@ -0,0 +1,92 @@
package com.ruoyi.web.controller.monitor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysUserOnline;
import com.ruoyi.system.service.ISysUserOnlineService;
/**
* 线
*
* @author ruoyi
*/
@RestController
@RequestMapping("/monitor/online")
public class SysUserOnlineController extends BaseController
{
@Autowired
private ISysUserOnlineService userOnlineService;
@Autowired
private RedisCache redisCache;
@PreAuthorize("@ss.hasPermi('monitor:online:list')")
@GetMapping("/list")
public TableDataInfo list(String ipaddr, String userName)
{
Collection<String> keys = redisCache.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
List<SysUserOnline> userOnlineList = new ArrayList<SysUserOnline>();
for (String key : keys)
{
LoginUser user = redisCache.getCacheObject(key);
if (StringUtils.isNotEmpty(ipaddr) && StringUtils.isNotEmpty(userName))
{
if (StringUtils.equals(ipaddr, user.getIpaddr()) && StringUtils.equals(userName, user.getUsername()))
{
userOnlineList.add(userOnlineService.selectOnlineByInfo(ipaddr, userName, user));
}
}
else if (StringUtils.isNotEmpty(ipaddr))
{
if (StringUtils.equals(ipaddr, user.getIpaddr()))
{
userOnlineList.add(userOnlineService.selectOnlineByIpaddr(ipaddr, user));
}
}
else if (StringUtils.isNotEmpty(userName) && StringUtils.isNotNull(user.getUser()))
{
if (StringUtils.equals(userName, user.getUsername()))
{
userOnlineList.add(userOnlineService.selectOnlineByUserName(userName, user));
}
}
else
{
userOnlineList.add(userOnlineService.loginUserToUserOnline(user));
}
}
Collections.reverse(userOnlineList);
userOnlineList.removeAll(Collections.singleton(null));
return getDataTable(userOnlineList);
}
/**
* 退
*/
@PreAuthorize("@ss.hasPermi('monitor:online:forceLogout')")
@Log(title = "在线用户", businessType = BusinessType.FORCE)
@DeleteMapping("/{tokenId}")
public AjaxResult forceLogout(@PathVariable String tokenId)
{
redisCache.deleteObject(CacheConstants.LOGIN_TOKEN_KEY + tokenId);
return AjaxResult.success();
}
}

@ -0,0 +1,38 @@
package com.ruoyi.web.controller.search;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.search.domain.MemberUserWo;
import com.ruoyi.search.service.MemberUserServicelmpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/member_user")
public class MemberUserController extends BaseController {
@Autowired
MemberUserServicelmpl memberuserService;
@GetMapping("/list")
public TableDataInfo list(@RequestParam Map map) {
startPage();
map.put("stroreId", SecurityUtils.getMerchanId());
List<MemberUserWo> list = memberuserService.getList(map);
return getDataTable(list);
}
// @PostMapping(value = "/getList")
// public RestResponse findList1(@RequestBody Map<String, Object> params) {
// List<MemberUser> list =memberuserService.findList((String) params.get("memberName"));
// return new RestResponse().setSuccess(true).setMessage("成功").setData(list);
//
// }
}

@ -0,0 +1,134 @@
package com.ruoyi.web.controller.system;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.service.ISysConfigService;
/**
*
*
* @author ruoyi
*/
@RestController
@RequestMapping("/system/config")
public class SysConfigController extends BaseController
{
@Autowired
private ISysConfigService configService;
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:config:list')")
@GetMapping("/list")
public TableDataInfo list(SysConfig config)
{
startPage();
List<SysConfig> list = configService.selectConfigList(config);
return getDataTable(list);
}
@Log(title = "参数管理", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('system:config:export')")
@PostMapping("/export")
public void export(HttpServletResponse response, SysConfig config)
{
List<SysConfig> list = configService.selectConfigList(config);
ExcelUtil<SysConfig> util = new ExcelUtil<SysConfig>(SysConfig.class);
util.exportExcel(response, list, "参数数据");
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:config:query')")
@GetMapping(value = "/{configId}")
public AjaxResult getInfo(@PathVariable Long configId)
{
return AjaxResult.success(configService.selectConfigById(configId));
}
/**
*
*/
@GetMapping(value = "/configKey/{configKey}")
public AjaxResult getConfigKey(@PathVariable String configKey)
{
return AjaxResult.success(configService.selectConfigByKey(configKey));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:config:add')")
@Log(title = "参数管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody SysConfig config)
{
if (UserConstants.NOT_UNIQUE.equals(configService.checkConfigKeyUnique(config)))
{
return AjaxResult.error("新增参数'" + config.getConfigName() + "'失败,参数键名已存在");
}
config.setCreateBy(getUsername());
return toAjax(configService.insertConfig(config));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:config:edit')")
@Log(title = "参数管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody SysConfig config)
{
if (UserConstants.NOT_UNIQUE.equals(configService.checkConfigKeyUnique(config)))
{
return AjaxResult.error("修改参数'" + config.getConfigName() + "'失败,参数键名已存在");
}
config.setUpdateBy(getUsername());
return toAjax(configService.updateConfig(config));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:config:remove')")
@Log(title = "参数管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{configIds}")
public AjaxResult remove(@PathVariable Long[] configIds)
{
configService.deleteConfigByIds(configIds);
return success();
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:config:remove')")
@Log(title = "参数管理", businessType = BusinessType.CLEAN)
@DeleteMapping("/refreshCache")
public AjaxResult refreshCache()
{
configService.resetConfigCache();
return AjaxResult.success();
}
}

@ -0,0 +1,147 @@
package com.ruoyi.web.controller.system;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysDeptService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;
/**
*
*
* @author ruoyi
*/
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController
{
@Autowired
private ISysDeptService deptService;
@Resource
private TokenService tokenService;
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:dept:list')")
@GetMapping("/list")
public AjaxResult list(SysDept dept, HttpServletRequest request){
SysUser loginUser=tokenService.getLoginUser(request).getUser();
dept.setMerchanId(loginUser.getMerchantId());
List<SysDept> depts = deptService.selectDeptList(dept);
if (!loginUser.isAdmin()){
depts=depts.stream().filter(d->d.getParentId() !=0l).collect(Collectors.toList());
}
return AjaxResult.success(depts);
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:dept:list')")
@GetMapping("/list/exclude/{deptId}")
public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId, HttpServletRequest request){
SysUser loginUser=tokenService.getLoginUser(request).getUser();
SysDept dept=new SysDept();
dept.setMerchanId(loginUser.getMerchantId());
List<SysDept> depts = deptService.selectDeptList(dept);
depts.removeIf(d -> d.getDeptId().intValue() == deptId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
return AjaxResult.success(depts);
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:dept:query')")
@GetMapping(value = "/{deptId}")
public AjaxResult getInfo(@PathVariable Long deptId)
{
deptService.checkDeptDataScope(deptId);
return AjaxResult.success(deptService.selectDeptById(deptId));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:dept:add')")
@Log(title = "部门管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody SysDept dept){
SysDept d=new SysDept();
d.setParentId(0l);
d.setMerchanId(SecurityUtils.getMerchanId());
dept.setParentId(deptService.selectDeptList(d).get(0).getDeptId());
dept.setMerchanId(SecurityUtils.getMerchanId());
if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
{
return AjaxResult.error("新增部门'" + dept.getDeptName() + "'失败,部门名称已存在");
}
dept.setCreateBy(getUsername());
return toAjax(deptService.insertDept(dept));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:dept:edit')")
@Log(title = "部门管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody SysDept dept)
{
Long deptId = dept.getDeptId();
deptService.checkDeptDataScope(deptId);
if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
{
return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败,部门名称已存在");
}
else if (dept.getParentId().equals(deptId))
{
return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败,上级部门不能是自己");
}
else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0)
{
return AjaxResult.error("该部门包含未停用的子部门!");
}
dept.setUpdateBy(getUsername());
return toAjax(deptService.updateDept(dept));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:dept:remove')")
@Log(title = "部门管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{deptId}")
public AjaxResult remove(@PathVariable Long deptId)
{
if (deptService.hasChildByDeptId(deptId))
{
return AjaxResult.error("存在下级部门,不允许删除");
}
if (deptService.checkDeptExistUser(deptId))
{
return AjaxResult.error("部门存在用户,不允许删除");
}
deptService.checkDeptDataScope(deptId);
return toAjax(deptService.deleteDeptById(deptId));
}
}

@ -0,0 +1,139 @@
package com.ruoyi.web.controller.system;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.shop.domain.YjMerchant;
import com.ruoyi.shop.service.impl.YjMerchantServiceImpl;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysDictTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
/**
*
*
* @author ruoyi
*/
@RestController
@RequestMapping("/system/dict/data")
public class SysDictDataController extends BaseController
{
@Autowired
private ISysDictDataService dictDataService;
@Autowired
private ISysDictTypeService dictTypeService;
@Resource
private YjMerchantServiceImpl merchantService;
@PreAuthorize("@ss.hasPermi('system:dict:list')")
@GetMapping("/list")
public TableDataInfo list(SysDictData dictData)
{
dictData.setMerchantId(SecurityUtils.getMerchanId());
startPage();
List<SysDictData> list = dictDataService.selectDictDataList(dictData);
return getDataTable(list);
}
@Log(title = "字典数据", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('system:dict:export')")
@PostMapping("/export")
public void export(HttpServletResponse response, SysDictData dictData)
{
dictData.setMerchantId(SecurityUtils.getMerchanId());
List<SysDictData> list = dictDataService.selectDictDataList(dictData);
ExcelUtil<SysDictData> util = new ExcelUtil<SysDictData>(SysDictData.class);
util.exportExcel(response, list, "字典数据");
}
/**
*
*/
// @PreAuthorize("@ss.hasPermi('system:dict:query')")
@PreAuthorize("@ss.hasPermi('system:dict:list')")
@GetMapping(value = "/{dictCode}")
public AjaxResult getInfo(@PathVariable Long dictCode)
{
return AjaxResult.success(dictDataService.selectDictDataById(dictCode));
}
/**
*
*/
@GetMapping(value = "/type/{dictType}")
public AjaxResult dictType(@PathVariable String dictType)
{
List<SysDictData> data = dictTypeService.selectDictDataByType(dictType);
if (StringUtils.isNull(data))
{
data = new ArrayList<SysDictData>();
}
return AjaxResult.success(data);
}
/**
*
*/
// @PreAuthorize("@ss.hasPermi('system:dict:add')")
// @Log(title = "字典数据", businessType = BusinessType.INSERT)
@PreAuthorize("@ss.hasPermi('system:dict:list')")
@PostMapping
public AjaxResult add(@Validated @RequestBody SysDictData dict)
{
dict.setCreateBy(getUsername());
List<YjMerchant> list= merchantService.list();
for (YjMerchant m:list){
dict.setMerchantId(m.getId());
dictDataService.insertDictData(dict);
}
return toAjax(1);
}
/**
*
*/
// @PreAuthorize("@ss.hasPermi('system:dict:edit')")
// @Log(title = "字典数据", businessType = BusinessType.UPDATE)
@PreAuthorize("@ss.hasPermi('system:dict:list')")
@PutMapping
public AjaxResult edit(@Validated @RequestBody SysDictData dict)
{
if (!SecurityUtils.getUserId().equals(1)) {
SysDictData d=new SysDictData();
d.setDictCode(dict.getDictCode());
d.setDictLabel(dict.getDictLabel());
return toAjax(dictDataService.updateDictData(d));
}
dict.setUpdateBy(getUsername());
return toAjax(dictDataService.updateDictData(dict));
}
/**
*
*/
// @PreAuthorize("@ss.hasPermi('system:dict:remove')")
// @Log(title = "字典类型", businessType = BusinessType.DELETE)
@PreAuthorize("@ss.hasPermi('system:dict:list')")
@DeleteMapping("/{dictCodes}")
public AjaxResult remove(@PathVariable Long[] dictCodes)
{
dictDataService.deleteDictDataByIds(dictCodes);
return success();
}
}

@ -0,0 +1,134 @@
package com.ruoyi.web.controller.system;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictType;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.mapper.SysDictTypeMapper;
import com.ruoyi.system.service.ISysDictTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
*
*
* @author ruoyi
*/
@RestController
@RequestMapping("/system/dict/type")
public class SysDictTypeController extends BaseController
{
@Autowired
private ISysDictTypeService dictTypeService;
@Resource
private SysDictTypeMapper dictTypeMapper;
@PreAuthorize("@ss.hasPermi('system:dict:list')")
@GetMapping("/list")
public TableDataInfo list(SysDictType dictType){
startPage();
List<SysDictType> list ;
if (SecurityUtils.getMerchanId().equals("1")){
list = dictTypeService.selectDictTypeList(dictType);
}else {
list = dictTypeMapper.selectDictTypeList1(dictType);
}
return getDataTable(list);
}
@Log(title = "字典类型", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('system:dict:export')")
@PostMapping("/export")
public void export(HttpServletResponse response, SysDictType dictType)
{
List<SysDictType> list = dictTypeService.selectDictTypeList(dictType);
ExcelUtil<SysDictType> util = new ExcelUtil<SysDictType>(SysDictType.class);
util.exportExcel(response, list, "字典类型");
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:dict:query')")
@GetMapping(value = "/{dictId}")
public AjaxResult getInfo(@PathVariable Long dictId)
{
return AjaxResult.success(dictTypeService.selectDictTypeById(dictId));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:dict:add')")
@Log(title = "字典类型", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody SysDictType dict){
if (UserConstants.NOT_UNIQUE.equals(dictTypeService.checkDictTypeUnique(dict)))
{
return AjaxResult.error("新增字典'" + dict.getDictName() + "'失败,字典类型已存在");
}
dict.setCreateBy(getUsername());
return toAjax(dictTypeService.insertDictType(dict));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:dict:edit')")
@Log(title = "字典类型", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody SysDictType dict)
{
if (UserConstants.NOT_UNIQUE.equals(dictTypeService.checkDictTypeUnique(dict)))
{
return AjaxResult.error("修改字典'" + dict.getDictName() + "'失败,字典类型已存在");
}
dict.setUpdateBy(getUsername());
return toAjax(dictTypeService.updateDictType(dict));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:dict:remove')")
@Log(title = "字典类型", businessType = BusinessType.DELETE)
@DeleteMapping("/{dictIds}")
public AjaxResult remove(@PathVariable Long[] dictIds)
{
dictTypeService.deleteDictTypeByIds(dictIds);
return success();
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:dict:remove')")
@Log(title = "字典类型", businessType = BusinessType.CLEAN)
@DeleteMapping("/refreshCache")
public AjaxResult refreshCache()
{
dictTypeService.resetDictCache();
return AjaxResult.success();
}
/**
*
*/
@GetMapping("/optionselect")
public AjaxResult optionselect()
{
List<SysDictType> dictTypes = dictTypeService.selectDictTypeAll();
return AjaxResult.success(dictTypes);
}
}

@ -0,0 +1,29 @@
package com.ruoyi.web.controller.system;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.StringUtils;
/**
*
*
* @author ruoyi
*/
@RestController
public class SysIndexController
{
/** 系统基础配置 */
@Autowired
private RuoYiConfig ruoyiConfig;
/**
* 访
*/
@RequestMapping("/")
public String index()
{
return StringUtils.format("欢迎使用{}后台管理框架当前版本v{},请通过前端地址访问。", ruoyiConfig.getName(), ruoyiConfig.getVersion());
}
}

@ -0,0 +1,86 @@
package com.ruoyi.web.controller.system;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysMenuService;
/**
*
*
* @author ruoyi
*/
@RestController
public class SysLoginController
{
@Autowired
private SysLoginService loginService;
@Autowired
private ISysMenuService menuService;
@Autowired
private SysPermissionService permissionService;
/**
*
*
* @param loginBody
* @return
*/
@PostMapping("/login")
public AjaxResult login(@RequestBody LoginBody loginBody)
{
AjaxResult ajax = AjaxResult.success();
// 生成令牌
String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
loginBody.getUuid());
ajax.put(Constants.TOKEN, token);
return ajax;
}
/**
*
*
* @return
*/
@GetMapping("getInfo")
public AjaxResult getInfo()
{
SysUser user = SecurityUtils.getLoginUser().getUser();
// 角色集合
Set<String> roles = permissionService.getRolePermission(user);
// 权限集合
Set<String> permissions = permissionService.getMenuPermission(user);
AjaxResult ajax = AjaxResult.success();
ajax.put("user", user);
ajax.put("roles", roles);
ajax.put("permissions", permissions);
return ajax;
}
/**
*
*
* @return
*/
@GetMapping("getRouters")
public AjaxResult getRouters()
{
Long userId = SecurityUtils.getUserId();
List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
return AjaxResult.success(menuService.buildMenus(menus));
}
}

@ -0,0 +1,142 @@
package com.ruoyi.web.controller.system;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysMenuService;
/**
*
*
* @author ruoyi
*/
@RestController
@RequestMapping("/system/menu")
public class SysMenuController extends BaseController
{
@Autowired
private ISysMenuService menuService;
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:menu:list')")
@GetMapping("/list")
public AjaxResult list(SysMenu menu)
{
List<SysMenu> menus = menuService.selectMenuList(menu, getUserId());
return AjaxResult.success(menus);
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:menu:query')")
@GetMapping(value = "/{menuId}")
public AjaxResult getInfo(@PathVariable Long menuId)
{
return AjaxResult.success(menuService.selectMenuById(menuId));
}
/**
*
*/
@GetMapping("/treeselect")
public AjaxResult treeselect(SysMenu menu)
{
List<SysMenu> menus = menuService.selectMenuList(menu, getUserId());
return AjaxResult.success(menuService.buildMenuTreeSelect(menus));
}
/**
*
*/
@GetMapping(value = "/roleMenuTreeselect/{roleId}")
public AjaxResult roleMenuTreeselect(@PathVariable("roleId") Long roleId)
{
List<SysMenu> menus = menuService.selectMenuList(getUserId());
AjaxResult ajax = AjaxResult.success();
ajax.put("checkedKeys", menuService.selectMenuListByRoleId(roleId));
ajax.put("menus", menuService.buildMenuTreeSelect(menus));
return ajax;
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:menu:add')")
@Log(title = "菜单管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody SysMenu menu)
{
if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu)))
{
return AjaxResult.error("新增菜单'" + menu.getMenuName() + "'失败,菜单名称已存在");
}
else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath()))
{
return AjaxResult.error("新增菜单'" + menu.getMenuName() + "'失败地址必须以http(s)://开头");
}
menu.setCreateBy(getUsername());
return toAjax(menuService.insertMenu(menu));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:menu:edit')")
@Log(title = "菜单管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody SysMenu menu)
{
if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu)))
{
return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败,菜单名称已存在");
}
else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath()))
{
return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败地址必须以http(s)://开头");
}
else if (menu.getMenuId().equals(menu.getParentId()))
{
return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败,上级菜单不能选择自己");
}
menu.setUpdateBy(getUsername());
return toAjax(menuService.updateMenu(menu));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:menu:remove')")
@Log(title = "菜单管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{menuId}")
public AjaxResult remove(@PathVariable("menuId") Long menuId)
{
if (menuService.hasChildByMenuId(menuId))
{
return AjaxResult.error("存在子菜单,不允许删除");
}
if (menuService.checkMenuExistRole(menuId))
{
return AjaxResult.error("菜单已分配,不允许删除");
}
return toAjax(menuService.deleteMenuById(menuId));
}
}

@ -0,0 +1,91 @@
package com.ruoyi.web.controller.system;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SysNotice;
import com.ruoyi.system.service.ISysNoticeService;
/**
*
*
* @author ruoyi
*/
@RestController
@RequestMapping("/system/notice")
public class SysNoticeController extends BaseController
{
@Autowired
private ISysNoticeService noticeService;
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:notice:list')")
@GetMapping("/list")
public TableDataInfo list(SysNotice notice)
{
startPage();
List<SysNotice> list = noticeService.selectNoticeList(notice);
return getDataTable(list);
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:notice:query')")
@GetMapping(value = "/{noticeId}")
public AjaxResult getInfo(@PathVariable Long noticeId)
{
return AjaxResult.success(noticeService.selectNoticeById(noticeId));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:notice:add')")
@Log(title = "通知公告", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody SysNotice notice)
{
notice.setCreateBy(getUsername());
return toAjax(noticeService.insertNotice(notice));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:notice:edit')")
@Log(title = "通知公告", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody SysNotice notice)
{
notice.setUpdateBy(getUsername());
return toAjax(noticeService.updateNotice(notice));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:notice:remove')")
@Log(title = "通知公告", businessType = BusinessType.DELETE)
@DeleteMapping("/{noticeIds}")
public AjaxResult remove(@PathVariable Long[] noticeIds)
{
return toAjax(noticeService.deleteNoticeByIds(noticeIds));
}
}

@ -0,0 +1,133 @@
package com.ruoyi.web.controller.system;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.service.ISysPostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
*
*
* @author ruoyi
*/
@RestController
@RequestMapping("/system/post")
public class SysPostController extends BaseController
{
@Autowired
private ISysPostService postService;
@Resource
private TokenService tokenService;
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:post:list')")
@GetMapping("/list")
public TableDataInfo list(SysPost post, HttpServletRequest request){
SysUser loginUser=tokenService.getLoginUser(request).getUser();
post.setMerchanId(loginUser.getMerchantId());
startPage();
List<SysPost> list = postService.selectPostList(post);
return getDataTable(list);
}
@Log(title = "岗位管理", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('system:post:export')")
@PostMapping("/export")
public void export(HttpServletResponse response, SysPost post)
{
List<SysPost> list = postService.selectPostList(post);
ExcelUtil<SysPost> util = new ExcelUtil<SysPost>(SysPost.class);
util.exportExcel(response, list, "岗位数据");
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:post:query')")
@GetMapping(value = "/{postId}")
public AjaxResult getInfo(@PathVariable Long postId)
{
return AjaxResult.success(postService.selectPostById(postId));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:post:add')")
@Log(title = "岗位管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody SysPost post, HttpServletRequest request){
SysUser loginUser=tokenService.getLoginUser(request).getUser();
post.setMerchanId(loginUser.getMerchantId());
if (UserConstants.NOT_UNIQUE.equals(postService.checkPostNameUnique(post)))
{
return AjaxResult.error("新增岗位'" + post.getPostName() + "'失败,岗位名称已存在");
}
else if (UserConstants.NOT_UNIQUE.equals(postService.checkPostCodeUnique(post)))
{
return AjaxResult.error("新增岗位'" + post.getPostName() + "'失败,岗位编码已存在");
}
post.setCreateBy(getUsername());
return toAjax(postService.insertPost(post));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:post:edit')")
@Log(title = "岗位管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody SysPost post)
{
if (UserConstants.NOT_UNIQUE.equals(postService.checkPostNameUnique(post)))
{
return AjaxResult.error("修改岗位'" + post.getPostName() + "'失败,岗位名称已存在");
}
else if (UserConstants.NOT_UNIQUE.equals(postService.checkPostCodeUnique(post)))
{
return AjaxResult.error("修改岗位'" + post.getPostName() + "'失败,岗位编码已存在");
}
post.setUpdateBy(getUsername());
return toAjax(postService.updatePost(post));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:post:remove')")
@Log(title = "岗位管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{postIds}")
public AjaxResult remove(@PathVariable Long[] postIds)
{
return toAjax(postService.deletePostByIds(postIds));
}
/**
*
*/
@GetMapping("/optionselect")
public AjaxResult optionselect(HttpServletRequest request){
SysUser loginUser=tokenService.getLoginUser(request).getUser();
List<SysPost> posts = postService.selectPostAll(loginUser.getMerchantId());
return AjaxResult.success(posts);
}
}

@ -0,0 +1,144 @@
package com.ruoyi.web.controller.system;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysUserService;
/**
*
*
* @author ruoyi
*/
@RestController
@RequestMapping("/system/user/profile")
public class SysProfileController extends BaseController
{
@Autowired
private ISysUserService userService;
@Autowired
private TokenService tokenService;
/**
*
*/
@GetMapping
public AjaxResult profile()
{
LoginUser loginUser = getLoginUser();
SysUser user = loginUser.getUser();
AjaxResult ajax = AjaxResult.success(user);
ajax.put("roleGroup", userService.selectUserRoleGroup(loginUser.getUsername()));
ajax.put("postGroup", userService.selectUserPostGroup(loginUser.getUsername()));
return ajax;
}
/**
*
*/
@Log(title = "个人信息", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult updateProfile(@RequestBody SysUser user)
{
LoginUser loginUser = getLoginUser();
SysUser sysUser = loginUser.getUser();
user.setUserName(sysUser.getUserName());
if (StringUtils.isNotEmpty(user.getPhonenumber())
&& UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
{
return AjaxResult.error("修改用户'" + user.getUserName() + "'失败,手机号码已存在");
}
if (StringUtils.isNotEmpty(user.getEmail())
&& UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
{
return AjaxResult.error("修改用户'" + user.getUserName() + "'失败,邮箱账号已存在");
}
user.setUserId(sysUser.getUserId());
user.setPassword(null);
user.setAvatar(null);
user.setDeptId(null);
if (userService.updateUserProfile(user) > 0)
{
// 更新缓存用户信息
sysUser.setNickName(user.getNickName());
sysUser.setPhonenumber(user.getPhonenumber());
sysUser.setEmail(user.getEmail());
sysUser.setSex(user.getSex());
tokenService.setLoginUser(loginUser);
return AjaxResult.success();
}
return AjaxResult.error("修改个人信息异常,请联系管理员");
}
/**
*
*/
@Log(title = "个人信息", businessType = BusinessType.UPDATE)
@PutMapping("/updatePwd")
public AjaxResult updatePwd(String oldPassword, String newPassword)
{
LoginUser loginUser = getLoginUser();
String userName = loginUser.getUsername();
String password = loginUser.getPassword();
if (!SecurityUtils.matchesPassword(oldPassword, password))
{
return AjaxResult.error("修改密码失败,旧密码错误");
}
if (SecurityUtils.matchesPassword(newPassword, password))
{
return AjaxResult.error("新密码不能与旧密码相同");
}
if (userService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0)
{
// 更新缓存用户密码
loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword));
tokenService.setLoginUser(loginUser);
return AjaxResult.success();
}
return AjaxResult.error("修改密码异常,请联系管理员");
}
/**
*
*/
@Log(title = "用户头像", businessType = BusinessType.UPDATE)
@PostMapping("/avatar")
public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws Exception
{
if (!file.isEmpty())
{
LoginUser loginUser = getLoginUser();
String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
if (userService.updateUserAvatar(loginUser.getUsername(), avatar))
{
AjaxResult ajax = AjaxResult.success();
ajax.put("imgUrl", avatar);
// 更新缓存用户头像
loginUser.getUser().setAvatar(avatar);
tokenService.setLoginUser(loginUser);
return ajax;
}
}
return AjaxResult.error("上传图片异常,请联系管理员");
}
}

@ -0,0 +1,38 @@
package com.ruoyi.web.controller.system;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysRegisterService;
import com.ruoyi.system.service.ISysConfigService;
/**
*
*
* @author ruoyi
*/
@RestController
public class SysRegisterController extends BaseController
{
@Autowired
private SysRegisterService registerService;
@Autowired
private ISysConfigService configService;
@PostMapping("/register")
public AjaxResult register(@RequestBody RegisterBody user)
{
if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser"))))
{
return error("当前系统没有开启注册功能!");
}
String msg = registerService.register(user);
return StringUtils.isEmpty(msg) ? success() : error(msg);
}
}

@ -0,0 +1,260 @@
package com.ruoyi.web.controller.system;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
*
*
* @author ruoyi
*/
@RestController
@RequestMapping("/system/role")
public class SysRoleController extends BaseController
{
@Autowired
private ISysRoleService roleService;
@Autowired
private TokenService tokenService;
@Autowired
private SysPermissionService permissionService;
@Autowired
private ISysUserService userService;
@Autowired
private ISysDeptService deptService;
@PreAuthorize("@ss.hasPermi('system:role:list')")
@GetMapping("/list")
public TableDataInfo list(SysRole role)
{
startPage();
List<SysRole> list = roleService.selectRoleList(role);
return getDataTable(list);
}
@Log(title = "角色管理", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('system:role:export')")
@PostMapping("/export")
public void export(HttpServletResponse response, SysRole role)
{
List<SysRole> list = roleService.selectRoleList(role);
ExcelUtil<SysRole> util = new ExcelUtil<SysRole>(SysRole.class);
util.exportExcel(response, list, "角色数据");
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:role:query')")
@GetMapping(value = "/{roleId}")
public AjaxResult getInfo(@PathVariable Long roleId)
{
roleService.checkRoleDataScope(roleId);
return AjaxResult.success(roleService.selectRoleById(roleId));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:role:add')")
@Log(title = "角色管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody SysRole role)
{
if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role)))
{
return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败,角色名称已存在");
}
else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role)))
{
return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败,角色权限已存在");
}
role.setCreateBy(getUsername());
return toAjax(roleService.insertRole(role));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:role:edit')")
@Log(title = "角色管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody SysRole role)
{
roleService.checkRoleAllowed(role);
roleService.checkRoleDataScope(role.getRoleId());
if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role)))
{
return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败,角色名称已存在");
}
else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role)))
{
return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败,角色权限已存在");
}
role.setUpdateBy(getUsername());
if (roleService.updateRole(role) > 0)
{
// 更新缓存用户权限
LoginUser loginUser = getLoginUser();
if (StringUtils.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin())
{
loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getUser()));
loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUserName()));
tokenService.setLoginUser(loginUser);
}
return AjaxResult.success();
}
return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败,请联系管理员");
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:role:edit')")
@Log(title = "角色管理", businessType = BusinessType.UPDATE)
@PutMapping("/dataScope")
public AjaxResult dataScope(@RequestBody SysRole role)
{
roleService.checkRoleAllowed(role);
roleService.checkRoleDataScope(role.getRoleId());
return toAjax(roleService.authDataScope(role));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:role:edit')")
@Log(title = "角色管理", businessType = BusinessType.UPDATE)
@PutMapping("/changeStatus")
public AjaxResult changeStatus(@RequestBody SysRole role)
{
roleService.checkRoleAllowed(role);
roleService.checkRoleDataScope(role.getRoleId());
role.setUpdateBy(getUsername());
return toAjax(roleService.updateRoleStatus(role));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:role:remove')")
@Log(title = "角色管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{roleIds}")
public AjaxResult remove(@PathVariable Long[] roleIds)
{
return toAjax(roleService.deleteRoleByIds(roleIds));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:role:query')")
@GetMapping("/optionselect")
public AjaxResult optionselect()
{
return AjaxResult.success(roleService.selectRoleAll());
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:role:list')")
@GetMapping("/authUser/allocatedList")
public TableDataInfo allocatedList(SysUser user)
{
startPage();
List<SysUser> list = userService.selectAllocatedList(user);
return getDataTable(list);
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:role:list')")
@GetMapping("/authUser/unallocatedList")
public TableDataInfo unallocatedList(SysUser user)
{
startPage();
List<SysUser> list = userService.selectUnallocatedList(user);
return getDataTable(list);
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:role:edit')")
@Log(title = "角色管理", businessType = BusinessType.GRANT)
@PutMapping("/authUser/cancel")
public AjaxResult cancelAuthUser(@RequestBody SysUserRole userRole)
{
return toAjax(roleService.deleteAuthUser(userRole));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:role:edit')")
@Log(title = "角色管理", businessType = BusinessType.GRANT)
@PutMapping("/authUser/cancelAll")
public AjaxResult cancelAuthUserAll(Long roleId, Long[] userIds)
{
return toAjax(roleService.deleteAuthUsers(roleId, userIds));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:role:edit')")
@Log(title = "角色管理", businessType = BusinessType.GRANT)
@PutMapping("/authUser/selectAll")
public AjaxResult selectAuthUserAll(Long roleId, Long[] userIds)
{
roleService.checkRoleDataScope(roleId);
return toAjax(roleService.insertAuthUsers(roleId, userIds));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:role:query')")
@GetMapping(value = "/deptTree/{roleId}")
public AjaxResult deptTree(@PathVariable("roleId") Long roleId, HttpServletRequest request){
SysUser loginUser=tokenService.getLoginUser(request).getUser();
SysDept dept=new SysDept();
dept.setMerchanId(loginUser.getMerchantId());
AjaxResult ajax = AjaxResult.success();
ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
ajax.put("depts", deptService.selectDeptTreeList(dept));
return ajax;
}
}

@ -0,0 +1,290 @@
package com.ruoyi.web.controller.system;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;
/**
*
*
* @author ruoyi
*/
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController
{
@Autowired
private ISysUserService userService;
@Autowired
private ISysRoleService roleService;
@Autowired
private SysRoleMapper roleMapper;
@Autowired
private ISysDeptService deptService;
@Autowired
private ISysPostService postService;
@Resource
private TokenService tokenService;
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:user:list')")
@GetMapping("/list")
public TableDataInfo list(SysUser user){
if (!SecurityUtils.getMerchanId().equals("1")){
user.setMerchantId(SecurityUtils.getMerchanId());
}
startPage();
List<SysUser> list = userService.selectUserList(user);
if (!SecurityUtils.getMerchanId().equals("1")){
list.forEach(u->{
for (SysRole role:u.getRoles()){
if(role.isMerchant()){
u.setResponsible(true);
break;
}
}
});
}else {
list.forEach(u->{
for (SysRole role:u.getRoles()){
if(role.getRoleId() != null && 1L ==role.getRoleId()){
u.setResponsible(true);
break;
}
}
});
}
return getDataTable(list);
}
@Log(title = "用户管理", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('system:user:export')")
@PostMapping("/export")
public void export(HttpServletResponse response, SysUser user)
{
List<SysUser> list = userService.selectUserList(user);
ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
util.exportExcel(response, list, "用户数据");
}
@Log(title = "用户管理", businessType = BusinessType.IMPORT)
@PreAuthorize("@ss.hasPermi('system:user:import')")
// @PostMapping("/importData")
public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
{
ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
List<SysUser> userList = util.importExcel(file.getInputStream());
String operName = getUsername();
String message = userService.importUser(userList, updateSupport, operName);
return AjaxResult.success(message);
}
@PostMapping("/importTemplate")
public void importTemplate(HttpServletResponse response)
{
ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
util.importTemplateExcel(response, "用户数据");
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:user:query')")
@GetMapping(value = { "/", "/{userId}" })
public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId,HttpServletRequest request){
SysUser loginUser=tokenService.getLoginUser(request).getUser();
userService.checkUserDataScope(userId);
AjaxResult ajax = AjaxResult.success();
//todo 角色
// List<SysRole> roles = roleService.selectRoleAll();
List<SysRole> roles = roleMapper.selectRoleAll();
// ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
ajax.put("roles", SysUser.isAdmin(SecurityUtils.getUserId())?
roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList())
:
roles.stream().filter(r -> !r.isMerchant()).collect(Collectors.toList()));
//todo
// 岗位
ajax.put("posts", postService.selectPostAll(loginUser.getMerchantId()));
if (StringUtils.isNotNull(userId))
{
SysUser sysUser = userService.selectUserById(userId);
ajax.put(AjaxResult.DATA_TAG, sysUser);
ajax.put("postIds", postService.selectPostListByUserId(userId));
ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
}
return ajax;
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:user:add')")
@Log(title = "用户管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody SysUser user, HttpServletRequest request){
SysUser loginUser=tokenService.getLoginUser(request).getUser();
user.setMerchantId(loginUser.getMerchantId());
if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName())))
{
return AjaxResult.error("新增用户'" + user.getUserName() + "'失败,登录账号已存在");
}
else if (StringUtils.isNotEmpty(user.getPhonenumber())
&& UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
{
return AjaxResult.error("新增用户'" + user.getUserName() + "'失败,手机号码已存在");
}
else if (StringUtils.isNotEmpty(user.getEmail())
&& UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
{
return AjaxResult.error("新增用户'" + user.getUserName() + "'失败,邮箱账号已存在");
}
user.setCreateBy(getUsername());
user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
return toAjax(userService.insertUser(user));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:user:edit')")
@Log(title = "用户管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody SysUser user)
{
userService.checkUserAllowed(user);
userService.checkUserDataScope(user.getUserId());
if (StringUtils.isNotEmpty(user.getPhonenumber())
&& UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
{
return AjaxResult.error("修改用户'" + user.getUserName() + "'失败,手机号码已存在");
}
else if (StringUtils.isNotEmpty(user.getEmail())
&& UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
{
return AjaxResult.error("修改用户'" + user.getUserName() + "'失败,邮箱账号已存在");
}
user.setUpdateBy(getUsername());
return toAjax(userService.updateUser(user));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:user:remove')")
@Log(title = "用户管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{userIds}")
public AjaxResult remove(@PathVariable Long[] userIds)
{
if (ArrayUtils.contains(userIds, getUserId()))
{
return error("当前用户不能删除");
}
return toAjax(userService.deleteUserByIds(userIds));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
@Log(title = "用户管理", businessType = BusinessType.UPDATE)
@PutMapping("/resetPwd")
public AjaxResult resetPwd(@RequestBody SysUser user)
{
userService.checkUserAllowed(user);
userService.checkUserDataScope(user.getUserId());
user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
user.setUpdateBy(getUsername());
return toAjax(userService.resetPwd(user));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:user:edit')")
@Log(title = "用户管理", businessType = BusinessType.UPDATE)
@PutMapping("/changeStatus")
public AjaxResult changeStatus(@RequestBody SysUser user)
{
userService.checkUserAllowed(user);
userService.checkUserDataScope(user.getUserId());
user.setUpdateBy(getUsername());
return toAjax(userService.updateUserStatus(user));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:user:query')")
@GetMapping("/authRole/{userId}")
public AjaxResult authRole(@PathVariable("userId") Long userId)
{
AjaxResult ajax = AjaxResult.success();
SysUser user = userService.selectUserById(userId);
List<SysRole> roles = roleService.selectRolesByUserId(userId);
ajax.put("user", user);
ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
return ajax;
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:user:edit')")
@Log(title = "用户管理", businessType = BusinessType.GRANT)
@PutMapping("/authRole")
public AjaxResult insertAuthRole(Long userId, Long[] roleIds)
{
userService.checkUserDataScope(userId);
userService.insertUserAuth(userId, roleIds);
return success();
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:user:list')")
@GetMapping("/deptTree")
public AjaxResult deptTree(SysDept dept){
if (!SecurityUtils.getMerchanId().equals("1")){
dept.setMerchanId(SecurityUtils.getMerchanId());
}
return AjaxResult.success(deptService.selectDeptTreeList(dept));
}
}

@ -0,0 +1,24 @@
package com.ruoyi.web.controller.tool;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.ruoyi.common.core.controller.BaseController;
/**
* swagger
*
* @author ruoyi
*/
@Controller
@RequestMapping("/tool/swagger")
public class SwaggerController extends BaseController
{
@PreAuthorize("@ss.hasPermi('tool:swagger:view')")
@GetMapping()
public String index()
{
return redirect("/swagger-ui.html");
}
}

@ -0,0 +1,183 @@
package com.ruoyi.web.controller.tool;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
/**
* swagger
*
* @author ruoyi
*/
@Api("用户信息管理")
@RestController
@RequestMapping("/test/user")
public class TestController extends BaseController
{
private final static Map<Integer, UserEntity> users = new LinkedHashMap<Integer, UserEntity>();
{
users.put(1, new UserEntity(1, "admin", "admin123", "15888888888"));
users.put(2, new UserEntity(2, "ry", "admin123", "15666666666"));
}
@ApiOperation("获取用户列表")
@GetMapping("/list")
public R<List<UserEntity>> userList()
{
List<UserEntity> userList = new ArrayList<UserEntity>(users.values());
return R.ok(userList);
}
@ApiOperation("获取用户详细")
@ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "path", dataTypeClass = Integer.class)
@GetMapping("/{userId}")
public R<UserEntity> getUser(@PathVariable Integer userId)
{
if (!users.isEmpty() && users.containsKey(userId))
{
return R.ok(users.get(userId));
}
else
{
return R.fail("用户不存在");
}
}
@ApiOperation("新增用户")
@ApiImplicitParams({
@ApiImplicitParam(name = "userId", value = "用户id", dataType = "Integer", dataTypeClass = Integer.class),
@ApiImplicitParam(name = "username", value = "用户名称", dataType = "String", dataTypeClass = String.class),
@ApiImplicitParam(name = "password", value = "用户密码", dataType = "String", dataTypeClass = String.class),
@ApiImplicitParam(name = "mobile", value = "用户手机", dataType = "String", dataTypeClass = String.class)
})
@PostMapping("/save")
public R<String> save(UserEntity user)
{
if (StringUtils.isNull(user) || StringUtils.isNull(user.getUserId()))
{
return R.fail("用户ID不能为空");
}
users.put(user.getUserId(), user);
return R.ok();
}
@ApiOperation("更新用户")
@PutMapping("/update")
public R<String> update(@RequestBody UserEntity user)
{
if (StringUtils.isNull(user) || StringUtils.isNull(user.getUserId()))
{
return R.fail("用户ID不能为空");
}
if (users.isEmpty() || !users.containsKey(user.getUserId()))
{
return R.fail("用户不存在");
}
users.remove(user.getUserId());
users.put(user.getUserId(), user);
return R.ok();
}
@ApiOperation("删除用户信息")
@ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "path", dataTypeClass = Integer.class)
@DeleteMapping("/{userId}")
public R<String> delete(@PathVariable Integer userId)
{
if (!users.isEmpty() && users.containsKey(userId))
{
users.remove(userId);
return R.ok();
}
else
{
return R.fail("用户不存在");
}
}
}
@ApiModel(value = "UserEntity", description = "用户实体")
class UserEntity
{
@ApiModelProperty("用户ID")
private Integer userId;
@ApiModelProperty("用户名称")
private String username;
@ApiModelProperty("用户密码")
private String password;
@ApiModelProperty("用户手机")
private String mobile;
public UserEntity()
{
}
public UserEntity(Integer userId, String username, String password, String mobile)
{
this.userId = userId;
this.username = username;
this.password = password;
this.mobile = mobile;
}
public Integer getUserId()
{
return userId;
}
public void setUserId(Integer userId)
{
this.userId = userId;
}
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public String getMobile()
{
return mobile;
}
public void setMobile(String mobile)
{
this.mobile = mobile;
}
}

@ -0,0 +1,125 @@
package com.ruoyi.web.core.config;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.ruoyi.common.config.RuoYiConfig;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.Contact;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.service.SecurityScheme;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
/**
* Swagger2
*
* @author ruoyi
*/
@Configuration
public class SwaggerConfig
{
/** 系统基础配置 */
@Autowired
private RuoYiConfig ruoyiConfig;
/** 是否开启swagger */
@Value("${swagger.enabled}")
private boolean enabled;
/** 设置请求的统一前缀 */
@Value("${swagger.pathMapping}")
private String pathMapping;
/**
* API
*/
@Bean
public Docket createRestApi()
{
return new Docket(DocumentationType.OAS_30)
// 是否启用Swagger
.enable(enabled)
// 用来创建该API的基本信息展示在文档的页面中自定义展示的信息
.apiInfo(apiInfo())
// 设置哪些接口暴露给Swagger展示
.select()
// 扫描所有有注解的api用这种方式更灵活
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
// 扫描指定包中的swagger注解
// .apis(RequestHandlerSelectors.basePackage("com.ruoyi.project.tool.swagger"))
// 扫描所有 .apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
/* 设置安全模式swagger可以设置访问token */
.securitySchemes(securitySchemes())
.securityContexts(securityContexts())
.pathMapping(pathMapping);
}
/**
* tokenAuthorization
*/
private List<SecurityScheme> securitySchemes()
{
List<SecurityScheme> apiKeyList = new ArrayList<SecurityScheme>();
apiKeyList.add(new ApiKey("Authorization", "Authorization", In.HEADER.toValue()));
return apiKeyList;
}
/**
*
*/
private List<SecurityContext> securityContexts()
{
List<SecurityContext> securityContexts = new ArrayList<>();
securityContexts.add(
SecurityContext.builder()
.securityReferences(defaultAuth())
.operationSelector(o -> o.requestMappingPattern().matches("/.*"))
.build());
return securityContexts;
}
/**
*
*/
private List<SecurityReference> defaultAuth()
{
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
List<SecurityReference> securityReferences = new ArrayList<>();
securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
return securityReferences;
}
/**
*
*/
private ApiInfo apiInfo()
{
// 用ApiInfoBuilder进行定制
return new ApiInfoBuilder()
// 设置标题
.title("标题若依管理系统_接口文档")
// 描述
.description("描述:用于管理集团旗下公司的人员信息,具体包括XXX,XXX模块...")
// 作者信息
.contact(new Contact(ruoyiConfig.getName(), null, null))
// 版本
.version("版本号:" + ruoyiConfig.getVersion())
.build();
}
}

@ -0,0 +1,151 @@
package com.ruoyi.web.util;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpStatus;
import java.util.HashMap;
/**
*
*
*/
public class AjaxResult extends HashMap<String, Object>
{
private static final long serialVersionUID = 1L;
/** 状态码 */
public static final String CODE_TAG = "code";
/** 返回内容 */
public static final String MSG_TAG = "msg";
/** 数据对象 */
public static final String DATA_TAG = "data";
/**
* AjaxResult 使
*/
public AjaxResult()
{
}
/**
* AjaxResult
*
* @param code
* @param msg
*/
public AjaxResult(int code, String msg)
{
super.put(CODE_TAG, code);
super.put(MSG_TAG, msg);
}
/**
* AjaxResult
*
* @param code
* @param msg
* @param data
*/
public AjaxResult(int code, String msg, Object data)
{
super.put(CODE_TAG, code);
super.put(MSG_TAG, msg);
if (ObjectUtil.isNotEmpty(data))
{
super.put(DATA_TAG, data);
}
}
/**
*
*
* @return
*/
public static AjaxResult success()
{
return AjaxResult.success("操作成功");
}
/**
*
*
* @return
*/
public static AjaxResult success(Object data)
{
return AjaxResult.success("操作成功", data);
}
/**
*
*
* @param msg
* @return
*/
public static AjaxResult success(String msg)
{
return AjaxResult.success(msg, null);
}
/**
*
*
* @param msg
* @param data
* @return
*/
public static AjaxResult success(String msg, Object data)
{
return new AjaxResult(HttpStatus.HTTP_OK, msg, data);
}
/**
*
*
* @return
*/
public static AjaxResult error()
{
return AjaxResult.error("操作失败");
}
/**
*
*
* @param msg
* @return
*/
public static AjaxResult error(String msg)
{
return AjaxResult.error(msg, null);
}
/**
*
*
* @param msg
* @param data
* @return
*/
public static AjaxResult error(String msg, Object data)
{
return new AjaxResult(HttpStatus.HTTP_BAD_REQUEST, msg, data);
}
/**
*
*
* @param code
* @param msg
* @return
*/
public static AjaxResult error(int code, String msg)
{
return new AjaxResult(code, msg, null);
}
}

@ -0,0 +1,291 @@
package com.ruoyi.web.util;
/**
* Base64
*
*/
public final class Base64
{
static private final int BASELENGTH = 128;
static private final int LOOKUPLENGTH = 64;
static private final int TWENTYFOURBITGROUP = 24;
static private final int EIGHTBIT = 8;
static private final int SIXTEENBIT = 16;
static private final int FOURBYTE = 4;
static private final int SIGN = -128;
static private final char PAD = '=';
static final private byte[] base64Alphabet = new byte[BASELENGTH];
static final private char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH];
static
{
for (int i = 0; i < BASELENGTH; ++i)
{
base64Alphabet[i] = -1;
}
for (int i = 'Z'; i >= 'A'; i--)
{
base64Alphabet[i] = (byte) (i - 'A');
}
for (int i = 'z'; i >= 'a'; i--)
{
base64Alphabet[i] = (byte) (i - 'a' + 26);
}
for (int i = '9'; i >= '0'; i--)
{
base64Alphabet[i] = (byte) (i - '0' + 52);
}
base64Alphabet['+'] = 62;
base64Alphabet['/'] = 63;
for (int i = 0; i <= 25; i++)
{
lookUpBase64Alphabet[i] = (char) ('A' + i);
}
for (int i = 26, j = 0; i <= 51; i++, j++)
{
lookUpBase64Alphabet[i] = (char) ('a' + j);
}
for (int i = 52, j = 0; i <= 61; i++, j++)
{
lookUpBase64Alphabet[i] = (char) ('0' + j);
}
lookUpBase64Alphabet[62] = (char) '+';
lookUpBase64Alphabet[63] = (char) '/';
}
private static boolean isWhiteSpace(char octect)
{
return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
}
private static boolean isPad(char octect)
{
return (octect == PAD);
}
private static boolean isData(char octect)
{
return (octect < BASELENGTH && base64Alphabet[octect] != -1);
}
/**
* Encodes hex octects into Base64
*
* @param binaryData Array containing binaryData
* @return Encoded Base64 array
*/
public static String encode(byte[] binaryData)
{
if (binaryData == null)
{
return null;
}
int lengthDataBits = binaryData.length * EIGHTBIT;
if (lengthDataBits == 0)
{
return "";
}
int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets;
char encodedData[] = null;
encodedData = new char[numberQuartet * 4];
byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
int encodedIndex = 0;
int dataIndex = 0;
for (int i = 0; i < numberTriplets; i++)
{
b1 = binaryData[dataIndex++];
b2 = binaryData[dataIndex++];
b3 = binaryData[dataIndex++];
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];
encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];
}
// form integral number of 6-bit groups
if (fewerThan24bits == EIGHTBIT)
{
b1 = binaryData[dataIndex];
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];
encodedData[encodedIndex++] = PAD;
encodedData[encodedIndex++] = PAD;
}
else if (fewerThan24bits == SIXTEENBIT)
{
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1];
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];
encodedData[encodedIndex++] = PAD;
}
return new String(encodedData);
}
/**
* Decodes Base64 data into octects
*
* @param encoded string containing Base64 data
* @return Array containind decoded data.
*/
public static byte[] decode(String encoded)
{
if (encoded == null)
{
return null;
}
char[] base64Data = encoded.toCharArray();
// remove white spaces
int len = removeWhiteSpace(base64Data);
if (len % FOURBYTE != 0)
{
return null;// should be divisible by four
}
int numberQuadruple = (len / FOURBYTE);
if (numberQuadruple == 0)
{
return new byte[0];
}
byte decodedData[] = null;
byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
char d1 = 0, d2 = 0, d3 = 0, d4 = 0;
int i = 0;
int encodedIndex = 0;
int dataIndex = 0;
decodedData = new byte[(numberQuadruple) * 3];
for (; i < numberQuadruple - 1; i++)
{
if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))
|| !isData((d3 = base64Data[dataIndex++])) || !isData((d4 = base64Data[dataIndex++])))
{
return null;
} // if found "no data" just return null
b1 = base64Alphabet[d1];
b2 = base64Alphabet[d2];
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
}
if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++])))
{
return null;// if found "no data" just return null
}
b1 = base64Alphabet[d1];
b2 = base64Alphabet[d2];
d3 = base64Data[dataIndex++];
d4 = base64Data[dataIndex++];
if (!isData((d3)) || !isData((d4)))
{// Check if they are PAD characters
if (isPad(d3) && isPad(d4))
{
if ((b2 & 0xf) != 0)// last 4 bits should be zero
{
return null;
}
byte[] tmp = new byte[i * 3 + 1];
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
return tmp;
}
else if (!isPad(d3) && isPad(d4))
{
b3 = base64Alphabet[d3];
if ((b3 & 0x3) != 0)// last 2 bits should be zero
{
return null;
}
byte[] tmp = new byte[i * 3 + 2];
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
return tmp;
}
else
{
return null;
}
}
else
{ // No PAD e.g 3cQl
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
}
return decodedData;
}
/**
* remove WhiteSpace from MIME containing encoded Base64 data.
*
* @param data the byte array of base64 data (with WS)
* @return the new length
*/
private static int removeWhiteSpace(char[] data)
{
if (data == null)
{
return 0;
}
// count characters that's not whitespace
int newSize = 0;
int len = data.length;
for (int i = 0; i < len; i++)
{
if (!isWhiteSpace(data[i]))
{
data[newSize++] = data[i];
}
}
return newSize;
}
}

@ -0,0 +1,44 @@
package com.ruoyi.web.util;
import java.security.MessageDigest;
public class MD5Util {
private static String byteArrayToHexString(byte b[]) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++)
resultSb.append(byteToHexString(b[i]));
return resultSb.toString();
}
private static String byteToHexString(byte b) {
int n = b;
if (n < 0)
n += 256;
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
public static String MD5Encode(String origin, String charsetname) {
String resultString = null;
try {
resultString = new String(origin);
MessageDigest md = MessageDigest.getInstance("MD5");
if (charsetname == null || "".equals(charsetname))
resultString = byteArrayToHexString(md.digest(resultString
.getBytes()));
else
resultString = byteArrayToHexString(md.digest(resultString
.getBytes(charsetname)));
} catch (Exception exception) {
}
return resultString;
}
private static final String hexDigits[] = {"0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};
}

@ -0,0 +1,42 @@
package com.ruoyi.web.util;
public interface PayConstants {
//支付成功的回调地址
String NOTIFY_URL = "https://www.sanduolantoyoga.com/yoja/api/callback";//支付成功回调地址
String MCH_ID = "1636033352"; // 商户号
String APP_ID = "wx4f58086f54744e4a"; // appid
String MCH_SERIAL_NO = "3C9964908256A4D1D035B1F0E52BC69D0A27FB0A"; // 商户证书序列号
String API_V3KEY = "f99afc35b3af45998dea239a21644c5f"; // API V3密钥 (API key)
String PACKAGE = "Sign=WXPay"; // 签名固定字符串(微信要求的) 06838cc840093b9d4689fc419ba1a3f3
// 你的商户私钥
String PRIVATE_KEY = "-----BEGIN PRIVATE KEY-----" +
"MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCgLVT3XOIoENW5" +
"FM3DVvSYYWYXfns/6u6ZHPZ8UAJE7xYRtT/lwTv7Duh2pahdHbA2fGCZhYc9d55N" +
"+Zyqd3OgTHgNNge7EzA+HgKw7pnPLSufRXk7eNAq1Xy1M3u9Ph4xMazVX3mIhjX+" +
"IgTklPS+hCcxWkXLakmcR7Ps0ovTj//dEq4mZy/An1tRifYMIz/h/1bm6APhqJ8j" +
"AoKQBTBEJTIDoH0MUyH6SzSm1Xyfbp5qZKnsg7qXrbO0iC+9jtt4jQRI7STt2Jwf" +
"R0nYOsDxCLz+O7F7xzbTI0g77huf3taTin8bsK5t3ALlHwmByS0Oz/apMyMLuKgf" +
"Bkl7MkLtAgMBAAECggEAZZNZxmQIpw/F+NDQi4ehJODfNRboYehB1qcfSEYUqlJT" +
"1Hb0Rmb7+oHBuTvkQOiKzoKhX7nlwX0RzrD0QMXvdUAJAZe531CTz1CItFsa/t7O" +
"QvpznttGZ2Nq6h3z4lZ6Hwg5ajZZg9JYewhnwe0UJ5z2nb15dT254Hk4CH6cXVR7" +
"Ik5RyYZ7ejdbhWbksiuq2yMR8rahnr+PAM1jUAyrKl6OgyM54hUGfFXcRHpDUaG2" +
"IzIw2f2o/obEvijLlkL/1mCROlH/oqNVGHq2qXAkSN8O75eNSKVQHzPiemzBPE2L" +
"U8I3mA/I8wzk0soxZKOS5tFcahPtn77nsVnP+R93AQKBgQDQxNDqF9WBmb31Nes/" +
"N8cFU1Lkq8xW56cRUfPVT7n4aK/2i5eutwspTXNXyYb3T2FUSqZxpqgvLRJNkFLq" +
"jcy1T811ZFGCi78TQMT5XPIdS/ZFtccUNsA5YN1Xh7UG6h7E38PnWNJCmHO61eVo" +
"9voIQqJJ0dp5H2ZKfAwDVcAY5QKBgQDEaj8tnJZIF69x2yY3VyRqN3bM3fgFWTRG" +
"aQ2qdUSYWYzUw0V8WdJKqmbdPoqkL6UqjkWcepgpuKpCx1V8xzLowAea8se56Nty" +
"IONMkCLCJEmonmfreQyNwRf0ELkIoVtML/jJXsnqUCwptMGoiFCNDi9UqVGFMDL6" +
"op+YE+gJaQKBgHVXaqVpKBRkOaTt3X/29eJEZz8oYP4nznupuIeY/EpnbSACbgtB" +
"zwA0DDS3jSjMcURTgSI4Lif2CWeXS0OS2BDA/haRgE8EBS3pJc2TNHLLE20zMuZl" +
"r72QeFiOam2sggbeTtplziioT8QgHYXV68tgyJ79WPLjdzc+afIl7IcRAoGAPmH8" +
"ZPE57fXP3FqdXbBIuY+aJOFPF+vIJaDSHVSXj8fJaf4HQMKKfvp2J0jo4dLcI5MC" +
"Wvu4/m9PbFxBM5tU+QWcpML9Wnex0yLM7pFM6Np7ppmBKhHNQeyVPghdrHcLNzx5" +
"SQPZH5mNHUXyyCNbaiGaOMp6QNIZLu+dvsB7zxkCgYEAp5tw57hgD2QgwSqrR86s" +
"AQesiQ6PP2vqe7KIaBtWjJUnC+sZguHR5V373qAOco7n/Av3kZmCQkWUP8TU4g6A" +
"i3CgTEJrm9m/Tdg5Qv9AQa/xQUYf9GrsqlMzTPB8y5cGvfiXitYPxVeGTHYx8TY8" +
"PScGvZKnjQrglrlhxZPii+Y=" +
"-----END PRIVATE KEY-----";
}

@ -0,0 +1,360 @@
package com.ruoyi.web.util;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.*;
import com.wechat.pay.contrib.apache.httpclient.cert.CertificatesManager;
import com.wechat.pay.contrib.apache.httpclient.exception.HttpCodeException;
import com.wechat.pay.contrib.apache.httpclient.exception.NotFoundException;
import com.wechat.pay.contrib.apache.httpclient.util.AesUtil;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.Base64;
import java.util.*;
public class PayUtil {
// String schema = "WECHATPAY2-SHA256-RSA2048";
// HttpUrl httpurl = HttpUrl.parse(url);
/**
*
* @param amount
* @param orderSn
* @return
* @throws Exception
*/
public static Map creatOrder(int amount,String orderSn) throws Exception{
PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(
new ByteArrayInputStream(PayConstants.PRIVATE_KEY.getBytes(StandardCharsets.UTF_8)));
//使用自动更新的签名验证器,不需要传入证书
Verifier verifier = new AutoUpdateCertificatesVerifier(
new WechatPay2Credentials(PayConstants.MCH_ID,
new PrivateKeySigner(PayConstants.MCH_SERIAL_NO, merchantPrivateKey)),
PayConstants.API_V3KEY.getBytes(StandardCharsets.UTF_8));
CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
.withMerchant(PayConstants.MCH_ID, PayConstants.MCH_SERIAL_NO, merchantPrivateKey)
.withValidator(new WechatPay2Validator(verifier))
.build();
String url="https://api.mch.weixin.qq.com/v3/pay/transactions/app";
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Content-type","application/json; charset=utf-8");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode rootNode = objectMapper.createObjectNode();
rootNode.put("mchid", PayConstants.MCH_ID)
.put("appid", PayConstants.APP_ID)
.put("notify_url", PayConstants.NOTIFY_URL)
.put("description", "三朵兰瑜伽")
.put("out_trade_no",orderSn);//订单号 目前是时间戳System.currentTimeMillis()
rootNode.putObject("amount")
.put("total", amount)//订单金额 int类型单位为分
.put("currency", "CNY");//CNY人民币境内商户号仅支持人民币。
objectMapper.writeValue(bos, rootNode);
httpPost.setEntity(new StringEntity(bos.toString("UTF-8"), "UTF-8"));
CloseableHttpResponse response = httpClient.execute(httpPost);
//-----------------------------------------------------------------------------------------
String bodyAsString = EntityUtils.toString(response.getEntity());
System.out.println(bodyAsString);
Map<String,String> json=(Map)JSONUtil.parse(bodyAsString);
Long timestamp= System.currentTimeMillis();//时间戳
String nonce= RandomUtil.randomString(32);//随机字符串
StringBuilder builder=new StringBuilder();
//应用id
builder.append(PayConstants.APP_ID).append("\n");
//时间戳
builder.append(timestamp).append("\n");
//随机字符串
builder.append(nonce).append("\n");
//预支付交易会话ID
builder.append(json.get("prepay_id")).append("\n");
//生成签名 RSA
String ciphertext = sign(builder.toString().getBytes(StandardCharsets.UTF_8));
System.out.println(ciphertext);
//---------------------------------------------------------------------------------------------
//生成签名 MD5
// SortedMap<String,String> sort=new TreeMap();
// sort.put("appid",PayConstants.APP_ID);
// sort.put("timestamp",timestamp.toString());
// sort.put("noncestr",nonce);
// sort.put("prepayid",node.get("prepay_id").toString());
// String ciphertext = createSign(sort).toUpperCase();
// String stringA=
// "appid="+PayConstants.APP_ID
// +"&noncestr="+nonce
//// +"&package="+PayConstants.PACKAGE
// +"&partnerid="+PayConstants.MCH_ID
// +"&prepayid="+json.get("prepay_id").toString()
// +"&timestamp="+timestamp;
//
// System.out.println(stringA);
// String stringSignTemp = stringA+"&key="+PayConstants.API_V3KEY;
// String ciphertext = MD5Util.MD5Encode(stringSignTemp,"UTF-8").toUpperCase();
System.out.println(ciphertext);
Map map=new HashMap();
map.put("appid",PayConstants.APP_ID);
map.put("partnerid",PayConstants.MCH_ID);
map.put("prepayid",json.get("prepay_id").toString());//有效期为2小时超过2小时商户需要使用原下单参数重新请求下单接口获取新的prepay_id
map.put("package",PayConstants.PACKAGE);
map.put("noncestr",nonce);
map.put("timestamp",timestamp);
map.put("sign",ciphertext);
return map;
}
/**
* RSA
* @param message
* @return
*/
/*message为appId、timeStamp、nonceStr、package拼接成的字符串 计算得出paySign*/
static String sign(byte[] message) {
try {
PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(PayConstants.PRIVATE_KEY);
Signature sign = Signature.getInstance("SHA256withRSA");
sign.initSign(merchantPrivateKey);
sign.update(message);
return Base64.getEncoder().encodeToString(sign.sign());
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (SignatureException e) {
e.printStackTrace();
}
return null;
}
/**
* MD5
* @param parameters
* @return
*/
public static String createSign(SortedMap parameters){
StringBuffer sb = new StringBuffer();
Set es = parameters.entrySet();//全部参与传参的参数按照accsii排序(升序)
Iterator it = es.iterator();
while(it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
String k = (String)entry.getKey();
Object v = entry.getValue();
if(null != v && !"".equals(v)
&& !"sign".equals(k) && !"key".equals(k)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + PayConstants.API_V3KEY);//这里是商户那里设置的key
System.out.println("签名字符串:"+sb.toString());
String sign =MD5Util.MD5Encode(sb.toString(),"UTF-8");
return sign;
}
/**
*
* @param serialNumber
* @param message
* @param signature
* @return
*/
public static boolean signVerify(String serialNumber,String message,String signature){
try {
PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(PayConstants.PRIVATE_KEY);
// 获取证书管理器实例
CertificatesManager certificatesManager = CertificatesManager.getInstance();
// 向证书管理器增加需要自动更新平台证书的商户信息
certificatesManager.putMerchant(PayConstants.MCH_ID, new WechatPay2Credentials(PayConstants.MCH_ID,
new PrivateKeySigner(PayConstants.MCH_SERIAL_NO, merchantPrivateKey)),
PayConstants.API_V3KEY.getBytes(StandardCharsets.UTF_8));
// 从证书管理器中获取verifier
Verifier verifier = certificatesManager.getVerifier(PayConstants.MCH_ID);
return verifier.verify(serialNumber, message.getBytes(StandardCharsets.UTF_8), signature);
} catch (IOException e) {
e.printStackTrace();
} catch (GeneralSecurityException e) {
e.printStackTrace();
} catch (HttpCodeException e) {
e.printStackTrace();
} catch (NotFoundException e) {
e.printStackTrace();
}
return false;
}
/**
* 使
* @param body
* @return
*/
public static String decryptOrder(String body){
try {
AesUtil util=new AesUtil(PayConstants.API_V3KEY.getBytes(StandardCharsets.UTF_8));
ObjectMapper objectMapper = new ObjectMapper();
JsonNode node=objectMapper.readTree(body);
JsonNode resource=node.get("resource");
String ciphertext=resource.get("ciphertext").textValue();
String associatedData=resource.get("associated_data").textValue();
String nonce=resource.get("nonce").textValue();
return util.decryptToString(associatedData.getBytes(StandardCharsets.UTF_8)
,nonce.getBytes(StandardCharsets.UTF_8)
,ciphertext);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//关单
public static void closeOrder(String outTradeNo) throws Exception{
PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(
new ByteArrayInputStream(PayConstants.PRIVATE_KEY.getBytes(StandardCharsets.UTF_8)));
//使用自动更新的签名验证器,不需要传入证书
Verifier verifier = new AutoUpdateCertificatesVerifier(
new WechatPay2Credentials(PayConstants.MCH_ID,
new PrivateKeySigner(PayConstants.MCH_SERIAL_NO, merchantPrivateKey)),
PayConstants.API_V3KEY.getBytes(StandardCharsets.UTF_8));
CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
.withMerchant(PayConstants.MCH_ID, PayConstants.MCH_SERIAL_NO, merchantPrivateKey)
.withValidator(new WechatPay2Validator(verifier))
.build();
//************************************************
HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/pay/transactions/out-trade-no/"+outTradeNo+"/close");
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Content-type","application/json; charset=utf-8");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode rootNode = objectMapper.createObjectNode();
rootNode.put("mchid",PayConstants.MCH_ID);
objectMapper.writeValue(bos, rootNode);
httpPost.setEntity(new StringEntity(bos.toString("UTF-8"), "UTF-8"));
CloseableHttpResponse response = httpClient.execute(httpPost);
//204关单成功
System.out.println(response.getStatusLine().getStatusCode()+"----204关单成功");
// String bodyAsString = EntityUtils.toString(response.getEntity());
// System.out.println(bodyAsString);
}
/**
*
* @param amount
* @param orderSn
* @return
* @throws Exception
*/
public static Map creatMergeOrder(int amount,String orderSn) throws Exception{
PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(
new ByteArrayInputStream(PayConstants.PRIVATE_KEY.getBytes(StandardCharsets.UTF_8)));
//使用自动更新的签名验证器,不需要传入证书
Verifier verifier = new AutoUpdateCertificatesVerifier(
new WechatPay2Credentials(PayConstants.MCH_ID,
new PrivateKeySigner(PayConstants.MCH_SERIAL_NO, merchantPrivateKey)),
PayConstants.API_V3KEY.getBytes(StandardCharsets.UTF_8));
CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
.withMerchant(PayConstants.MCH_ID, PayConstants.MCH_SERIAL_NO, merchantPrivateKey)
.withValidator(new WechatPay2Validator(verifier))
.build();
HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/combine-transactions/app");
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Content-type","application/json; charset=utf-8");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode rootNode = objectMapper.createObjectNode();
rootNode.put("combine_mchid", PayConstants.MCH_ID)
.put("combine_appid", PayConstants.APP_ID)
.put("notify_url", PayConstants.NOTIFY_URL)
.put("combine_out_trade_no",orderSn);//订单号// 目前是时间戳System.currentTimeMillis()
rootNode.putArray("sub_orders")
.addObject()
.put("total", amount)//订单金额 int类型单位为分
.put("currency", "CNY");//CNY人民币境内商户号仅支持人民币。
objectMapper.writeValue(bos, rootNode);
httpPost.setEntity(new StringEntity(bos.toString("UTF-8"), "UTF-8"));
CloseableHttpResponse response = httpClient.execute(httpPost);
String bodyAsString = EntityUtils.toString(response.getEntity());
System.out.println(bodyAsString);
String timestamp=System.currentTimeMillis()+"";//时间戳
String nonce= RandomUtil.randomString(32);//随机字符串
StringBuilder builder=new StringBuilder();
//应用id
builder.append(PayConstants.APP_ID).append("\n");
//时间戳
builder.append(timestamp).append("\n");
//随机字符串
builder.append(nonce).append("\n");
JsonNode node=objectMapper.readTree(bodyAsString);
//预支付交易会话ID
builder.append(node.get("prepay_id")).append("\n");
// String cirphertext= RsaCryptoUtil.encryptOAEP(builder.toString(),verifier.getValidCertificate());
String ciphertext = sign(builder.toString().getBytes(StandardCharsets.UTF_8));
System.out.println(ciphertext);
Map map=new HashMap();
map.put("noncestr",nonce);
map.put("package",PayConstants.PACKAGE);
map.put("timeStamp",timestamp);
map.put("signType","RSA");
map.put("paySign",ciphertext);
return map;
}
}

@ -0,0 +1,188 @@
package com.ruoyi.web.util;
public class SnowFlake {
// ==============================Fields===========================================
/**
* (2018-07-03)
*/
private final Long twepoch = 1530607760000L;
/**
* id
*/
private final Long workerIdBits = 5L;
/**
* id
*/
private final Long datacenterIdBits = 5L;
/**
* id31 ()
*/
private final Long maxWorkerId = -1L ^ (-1L << workerIdBits);
/**
* id31
*/
private final Long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
/**
* id
*/
private final Long sequenceBits = 12L;
/**
* ID12
*/
private final Long workerIdShift = sequenceBits;
/**
* id17(12+5)
*/
private final Long datacenterIdShift = sequenceBits + workerIdBits;
/**
* 22(5+5+12)
*/
private final Long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
/**
* 4095 (0b111111111111=0xfff=4095)
*/
private final Long sequenceMask = -1L ^ (-1L << sequenceBits);
/**
* ID(0~31)
*/
private Long workerId;
/**
* ID(0~31)
*/
private Long datacenterId;
/**
* (0~4095)
*/
private Long sequence = 0L;
/**
* ID
*/
private Long lastTimestamp = -1L;
//==============================Constructors=====================================
/**
*
*
* @param workerId ID (0~31)
* @param datacenterId ID (0~31)
*/
public SnowFlake(Long workerId, Long datacenterId) {
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
}
if (datacenterId > maxDatacenterId || datacenterId < 0) {
throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
}
this.workerId = workerId;
this.datacenterId = datacenterId;
}
// ==============================Methods==========================================
/**
* ID (线)
*
* @return SnowflakeId
*/
public synchronized Long nextId() {
Long timestamp = timeGen();
//如果当前时间小于上一次ID生成的时间戳说明系统时钟回退过这个时候应当抛出异常
if (timestamp < lastTimestamp) {
throw new RuntimeException(
String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
//如果是同一时间生成的,则进行毫秒内序列
if (lastTimestamp == timestamp) {
sequence = (sequence + 1) & sequenceMask;
//毫秒内序列溢出
if (sequence == 0) {
//阻塞到下一个毫秒,获得新的时间戳
timestamp = tilNextMillis(lastTimestamp);
}
}
//时间戳改变,毫秒内序列重置
else {
sequence = 0L;
}
//上次生成ID的时间截
lastTimestamp = timestamp;
//移位并通过或运算拼到一起组成64位的ID
return (((timestamp - twepoch) << timestampLeftShift)
| (datacenterId << datacenterIdShift)
| (workerId << workerIdShift)
| sequence);
}
/**
*
*
* @param lastTimestamp ID
* @return
*/
protected Long tilNextMillis(Long lastTimestamp) {
Long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
/**
*
*
* @return ()
*/
protected Long timeGen() {
return System.currentTimeMillis();
}
//==============================Test=============================================
/**
*
*/
// public static void main(String[] args) {
// SnowFlake idWorker = new SnowFlake(0l, 0l);
// Long id = idWorker.nextId();
// System.out.println(id);
// }
public static Long getOrder() {
SnowFlake idWorker = new SnowFlake(0l, 0l);
Long id = idWorker.nextId();
return id;
}
// public String getOrder() {
// Long startTime = System.currentTimeMillis();
// SnowFlake idWorker = new SnowFlake(0, 0);
// Long id = idWorker.nextId();
// Set set = new HashSet();
// for (int i = 0; i < 10000000; i++) {
// Long id = idWorker.nextId();
// set.add(id);
// System.out.println("id----"+i+":"+id);
// }
// Long endTime = System.currentTimeMillis();
// System.out.println("set.size():" + set.size());
// System.out.println("endTime-startTime:" + (endTime - startTime));
// }
}

@ -0,0 +1,486 @@
package com.ruoyi.web.util;
import cn.hutool.core.exceptions.UtilException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
/**
* universally unique identifierUUID
*
*/
public final class UUID implements java.io.Serializable, Comparable<UUID>
{
private static final long serialVersionUID = -1185015143654744140L;
/**
* SecureRandom
*
*/
private static class Holder
{
static final SecureRandom numberGenerator = getSecureRandom();
}
/** 此UUID的最高64有效位 */
private final long mostSigBits;
/** 此UUID的最低64有效位 */
private final long leastSigBits;
/**
*
*
* @param data
*/
private UUID(byte[] data)
{
long msb = 0;
long lsb = 0;
assert data.length == 16 : "data must be 16 bytes in length";
for (int i = 0; i < 8; i++)
{
msb = (msb << 8) | (data[i] & 0xff);
}
for (int i = 8; i < 16; i++)
{
lsb = (lsb << 8) | (data[i] & 0xff);
}
this.mostSigBits = msb;
this.leastSigBits = lsb;
}
/**
* 使 UUID
*
* @param mostSigBits {@code UUID} 64
* @param leastSigBits {@code UUID} 64
*/
public UUID(long mostSigBits, long leastSigBits)
{
this.mostSigBits = mostSigBits;
this.leastSigBits = leastSigBits;
}
/**
* 4UUID 使线 UUID
*
* @return {@code UUID}
*/
public static UUID fastUUID()
{
return randomUUID(false);
}
/**
* 4UUID 使 UUID
*
* @return {@code UUID}
*/
public static UUID randomUUID()
{
return randomUUID(true);
}
/**
* 4UUID 使 UUID
*
* @param isSecure 使{@link SecureRandom}
* @return {@code UUID}
*/
public static UUID randomUUID(boolean isSecure)
{
final Random ng = isSecure ? Holder.numberGenerator : getSecureRandom();
byte[] randomBytes = new byte[16];
ng.nextBytes(randomBytes);
randomBytes[6] &= 0x0f; /* clear version */
randomBytes[6] |= 0x40; /* set to version 4 */
randomBytes[8] &= 0x3f; /* clear variant */
randomBytes[8] |= 0x80; /* set to IETF variant */
return new UUID(randomBytes);
}
/**
* 3UUID
*
* @param name UUID
*
* @return {@code UUID}
*/
public static UUID nameUUIDFromBytes(byte[] name)
{
MessageDigest md;
try
{
md = MessageDigest.getInstance("MD5");
}
catch (NoSuchAlgorithmException nsae)
{
throw new InternalError("MD5 not supported");
}
byte[] md5Bytes = md.digest(name);
md5Bytes[6] &= 0x0f; /* clear version */
md5Bytes[6] |= 0x30; /* set to version 3 */
md5Bytes[8] &= 0x3f; /* clear variant */
md5Bytes[8] |= 0x80; /* set to IETF variant */
return new UUID(md5Bytes);
}
/**
* {@link #toString()} {@code UUID}
*
* @param name {@code UUID}
* @return {@code UUID}
* @throws IllegalArgumentException name {@link #toString}
*
*/
public static UUID fromString(String name)
{
String[] components = name.split("-");
if (components.length != 5)
{
throw new IllegalArgumentException("Invalid UUID string: " + name);
}
for (int i = 0; i < 5; i++)
{
components[i] = "0x" + components[i];
}
long mostSigBits = Long.decode(components[0]).longValue();
mostSigBits <<= 16;
mostSigBits |= Long.decode(components[1]).longValue();
mostSigBits <<= 16;
mostSigBits |= Long.decode(components[2]).longValue();
long leastSigBits = Long.decode(components[3]).longValue();
leastSigBits <<= 48;
leastSigBits |= Long.decode(components[4]).longValue();
return new UUID(mostSigBits, leastSigBits);
}
/**
* UUID 128 64
*
* @return UUID 128 64
*/
public long getLeastSignificantBits()
{
return leastSigBits;
}
/**
* UUID 128 64
*
* @return UUID 128 64
*/
public long getMostSignificantBits()
{
return mostSigBits;
}
/**
* {@code UUID} . {@code UUID}
* <p>
* :
* <ul>
* <li>1 UUID
* <li>2 DCE UUID
* <li>3 UUID
* <li>4 UUID
* </ul>
*
* @return {@code UUID}
*/
public int version()
{
// Version is bits masked by 0x000000000000F000 in MS long
return (int) ((mostSigBits >> 12) & 0x0f);
}
/**
* {@code UUID} {@code UUID}
* <p>
*
* <ul>
* <li>0 NCS
* <li>2 <a href="http://www.ietf.org/rfc/rfc4122.txt">IETF&nbsp;RFC&nbsp;4122</a>(Leach-Salz),
* <li>6
* <li>7 使
* </ul>
*
* @return {@code UUID}
*/
public int variant()
{
// This field is composed of a varying number of bits.
// 0 - - Reserved for NCS backward compatibility
// 1 0 - The IETF aka Leach-Salz variant (used by this class)
// 1 1 0 Reserved, Microsoft backward compatibility
// 1 1 1 Reserved for future definition.
return (int) ((leastSigBits >>> (64 - (leastSigBits >>> 62))) & (leastSigBits >> 63));
}
/**
* UUID
*
* <p>
* 60 {@code UUID} time_lowtime_mid time_hi <br>
* 100 UTC 1582 10 15
*
* <p>
* UUID version 1<br>
* {@code UUID} UUID UnsupportedOperationException
*
* @throws UnsupportedOperationException {@code UUID} version 1 UUID
*/
public long timestamp() throws UnsupportedOperationException
{
checkTimeBase();
return (mostSigBits & 0x0FFFL) << 48//
| ((mostSigBits >> 16) & 0x0FFFFL) << 32//
| mostSigBits >>> 32;
}
/**
* UUID
*
* <p>
* 14 UUID clock_seq clock_seq UUID
* <p>
* {@code clockSequence} UUID version 1 UUID UUID
* UnsupportedOperationException
*
* @return {@code UUID}
*
* @throws UnsupportedOperationException UUID version 1
*/
public int clockSequence() throws UnsupportedOperationException
{
checkTimeBase();
return (int) ((leastSigBits & 0x3FFF000000000000L) >>> 48);
}
/**
* UUID
*
* <p>
* 48 UUID node IEEE 802 UUID
* <p>
* UUID version 1<br>
* UUID UUID UnsupportedOperationException
*
* @return {@code UUID}
*
* @throws UnsupportedOperationException UUID version 1
*/
public long node() throws UnsupportedOperationException
{
checkTimeBase();
return leastSigBits & 0x0000FFFFFFFFFFFFL;
}
/**
* {@code UUID}
*
* <p>
* UUID BNF
*
* <pre>
* {@code
* UUID = <time_low>-<time_mid>-<time_high_and_version>-<variant_and_sequence>-<node>
* time_low = 4*<hexOctet>
* time_mid = 2*<hexOctet>
* time_high_and_version = 2*<hexOctet>
* variant_and_sequence = 2*<hexOctet>
* node = 6*<hexOctet>
* hexOctet = <hexDigit><hexDigit>
* hexDigit = [0-9a-fA-F]
* }
* </pre>
*
* </blockquote>
*
* @return {@code UUID}
* @see #toString(boolean)
*/
@Override
public String toString()
{
return toString(false);
}
/**
* {@code UUID}
*
* <p>
* UUID BNF
*
* <pre>
* {@code
* UUID = <time_low>-<time_mid>-<time_high_and_version>-<variant_and_sequence>-<node>
* time_low = 4*<hexOctet>
* time_mid = 2*<hexOctet>
* time_high_and_version = 2*<hexOctet>
* variant_and_sequence = 2*<hexOctet>
* node = 6*<hexOctet>
* hexOctet = <hexDigit><hexDigit>
* hexDigit = [0-9a-fA-F]
* }
* </pre>
*
* </blockquote>
*
* @param isSimple '-'UUID
* @return {@code UUID}
*/
public String toString(boolean isSimple)
{
final StringBuilder builder = new StringBuilder(isSimple ? 32 : 36);
// time_low
builder.append(digits(mostSigBits >> 32, 8));
if (false == isSimple)
{
builder.append('-');
}
// time_mid
builder.append(digits(mostSigBits >> 16, 4));
if (false == isSimple)
{
builder.append('-');
}
// time_high_and_version
builder.append(digits(mostSigBits, 4));
if (false == isSimple)
{
builder.append('-');
}
// variant_and_sequence
builder.append(digits(leastSigBits >> 48, 4));
if (false == isSimple)
{
builder.append('-');
}
// node
builder.append(digits(leastSigBits, 12));
return builder.toString();
}
/**
* UUID
*
* @return UUID
*/
@Override
public int hashCode()
{
long hilo = mostSigBits ^ leastSigBits;
return ((int) (hilo >> 32)) ^ (int) hilo;
}
/**
*
* <p>
* {@code null} UUID UUID varriant {@code true}
*
* @param obj
*
* @return {@code true} {@code false}
*/
@Override
public boolean equals(Object obj)
{
if ((null == obj) || (obj.getClass() != UUID.class))
{
return false;
}
UUID id = (UUID) obj;
return (mostSigBits == id.mostSigBits && leastSigBits == id.leastSigBits);
}
// Comparison Operations
/**
* UUID UUID
*
* <p>
* UUID UUID UUID UUID UUID
*
* @param val UUID UUID
*
* @return UUID val -10 1
*
*/
@Override
public int compareTo(UUID val)
{
// The ordering is intentionally set up so that the UUIDs
// can simply be numerically compared as two numbers
return (this.mostSigBits < val.mostSigBits ? -1 : //
(this.mostSigBits > val.mostSigBits ? 1 : //
(this.leastSigBits < val.leastSigBits ? -1 : //
(this.leastSigBits > val.leastSigBits ? 1 : //
0))));
}
// -------------------------------------------------------------------------------------------------------------------
// Private method start
/**
* hex
*
* @param val
* @param digits
* @return
*/
private static String digits(long val, int digits)
{
long hi = 1L << (digits * 4);
return Long.toHexString(hi | (val & (hi - 1))).substring(1);
}
/**
* time-basedUUID
*/
private void checkTimeBase()
{
if (version() != 1)
{
throw new UnsupportedOperationException("Not a time-based UUID");
}
}
/**
* {@link SecureRandom} (RNG)
*
* @return {@link SecureRandom}
*/
public static SecureRandom getSecureRandom()
{
try
{
return SecureRandom.getInstance("SHA1PRNG");
}
catch (NoSuchAlgorithmException e)
{
throw new UtilException(e);
}
}
/**
* <br>
* ThreadLocalRandomJDK 7线
*
* @return {@link ThreadLocalRandom}
*/
public static ThreadLocalRandom getRandom()
{
return ThreadLocalRandom.current();
}
}

@ -0,0 +1,225 @@
package com.ruoyi.web.util;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Random;
/**
*
*
*/
public class VerifyCodeUtils
{
// 使用到Algerian字体系统里没有的话需要安装字体字体只显示大写去掉了1,0,i,o几个容易混淆的字符
public static final String VERIFY_CODES = "123456789ABCDEFGHJKLMNPQRSTUVWXYZ";
private static Random random = new SecureRandom();
/**
* 使
*
* @param verifySize
* @return
*/
public static String generateVerifyCode(int verifySize)
{
return generateVerifyCode(verifySize, VERIFY_CODES);
}
/**
* 使
*
* @param verifySize
* @param sources
* @return
*/
public static String generateVerifyCode(int verifySize, String sources)
{
if (sources == null || sources.length() == 0)
{
sources = VERIFY_CODES;
}
int codesLen = sources.length();
Random rand = new Random(System.currentTimeMillis());
StringBuilder verifyCode = new StringBuilder(verifySize);
for (int i = 0; i < verifySize; i++)
{
verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
}
return verifyCode.toString();
}
/**
*
*
* @param w
* @param h
* @param os
* @param code
* @throws IOException
*/
public static void outputImage(int w, int h, OutputStream os, String code) throws IOException
{
int verifySize = code.length();
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Random rand = new Random();
Graphics2D g2 = image.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Color[] colors = new Color[5];
Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN, Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA,
Color.ORANGE, Color.PINK, Color.YELLOW };
float[] fractions = new float[colors.length];
for (int i = 0; i < colors.length; i++)
{
colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
fractions[i] = rand.nextFloat();
}
Arrays.sort(fractions);
g2.setColor(Color.GRAY);// 设置边框色
g2.fillRect(0, 0, w, h);
Color c = getRandColor(200, 250);
g2.setColor(c);// 设置背景色
g2.fillRect(0, 2, w, h - 4);
// 绘制干扰线
Random random = new Random();
g2.setColor(getRandColor(160, 200));// 设置线条的颜色
for (int i = 0; i < 20; i++)
{
int x = random.nextInt(w - 1);
int y = random.nextInt(h - 1);
int xl = random.nextInt(6) + 1;
int yl = random.nextInt(12) + 1;
g2.drawLine(x, y, x + xl + 40, y + yl + 20);
}
// 添加噪点
float yawpRate = 0.05f;// 噪声率
int area = (int) (yawpRate * w * h);
for (int i = 0; i < area; i++)
{
int x = random.nextInt(w);
int y = random.nextInt(h);
int rgb = getRandomIntColor();
image.setRGB(x, y, rgb);
}
shear(g2, w, h, c);// 使图片扭曲
g2.setColor(getRandColor(100, 160));
int fontSize = h - 4;
Font font = new Font("Algerian", Font.ITALIC, fontSize);
g2.setFont(font);
char[] chars = code.toCharArray();
for (int i = 0; i < verifySize; i++)
{
AffineTransform affine = new AffineTransform();
affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1),
(w / verifySize) * i + fontSize / 2, h / 2);
g2.setTransform(affine);
g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);
}
g2.dispose();
ImageIO.write(image, "jpg", os);
}
private static Color getRandColor(int fc, int bc)
{
if (fc > 255) {
fc = 255;
}
if (bc > 255) {
bc = 255;
}
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
private static int getRandomIntColor()
{
int[] rgb = getRandomRgb();
int color = 0;
for (int c : rgb)
{
color = color << 8;
color = color | c;
}
return color;
}
private static int[] getRandomRgb()
{
int[] rgb = new int[3];
for (int i = 0; i < 3; i++)
{
rgb[i] = random.nextInt(255);
}
return rgb;
}
private static void shear(Graphics g, int w1, int h1, Color color)
{
shearX(g, w1, h1, color);
shearY(g, w1, h1, color);
}
private static void shearX(Graphics g, int w1, int h1, Color color)
{
int period = random.nextInt(2);
boolean borderGap = true;
int frames = 1;
int phase = random.nextInt(2);
for (int i = 0; i < h1; i++)
{
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
g.copyArea(0, i, w1, 1, (int) d, 0);
if (borderGap)
{
g.setColor(color);
g.drawLine((int) d, i, 0, i);
g.drawLine((int) d + w1, i, w1, i);
}
}
}
private static void shearY(Graphics g, int w1, int h1, Color color)
{
int period = random.nextInt(40) + 10; // 50;
boolean borderGap = true;
int frames = 20;
int phase = 7;
for (int i = 0; i < w1; i++)
{
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
g.copyArea(i, 0, 1, h1, 0, (int) d);
if (borderGap)
{
g.setColor(color);
g.drawLine(i, (int) d, i, 0);
g.drawLine(i, (int) d + h1, i, h1);
}
}
}
}

@ -0,0 +1,7 @@
package com.ruoyi.web.util;
public class clientServiceImpl {
}

@ -0,0 +1 @@
restart.include.json=/com.alibaba.fastjson.*.jar

@ -0,0 +1,59 @@
# 数据源配置
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.cj.jdbc.Driver
druid:
# 主库数据源
master:
url: jdbc:mysql://101.43.111.159:3306/yoga?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
# url: jdbc:mysql://localhost:3306/yj?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: '!Runpeng888'
# password: 123456
# 从库数据源
slave:
# 从数据源开关/默认关闭
enabled: false
url:
username:
password:
# 初始连接数
initialSize: 5
# 最小连接池数量
minIdle: 10
# 最大连接池数量
maxActive: 20
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 300000
# 配置一个连接在池中最大生存的时间,单位是毫秒
maxEvictableIdleTimeMillis: 900000
# 配置检测连接是否有效
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
webStatFilter:
enabled: true
statViewServlet:
enabled: true
# 设置白名单,不填则允许所有访问
allow:
url-pattern: /druid/*
# 控制台管理用户名和密码
login-username: ruoyi
login-password: 123456
filter:
stat:
enabled: true
# 慢SQL记录
log-slow-sql: true
slow-sql-millis: 1000
merge-sql: true
wall:
config:
multi-statement-allow: true

@ -0,0 +1,141 @@
# 项目相关配置
ruoyi:
# 名称
name: RuoYi
# 版本
version: 3.8.3
# 版权年份
copyrightYear: 2022
# 实例演示开关
demoEnabled: true
# 文件路径 示例( Windows配置D:/ruoyi/uploadPathLinux配置 /home/ruoyi/uploadPath
# profile: D:/ruoyi/uploadPath
profile: ../ruoyi/uploadPath
# 获取ip地址开关
addressEnabled: false
# 验证码类型 math 数组计算 char 字符验证
captchaType: math
# 开发环境配置
server:
# 服务器的HTTP端口默认为8080
port: 8083
# port: 8083
servlet:
# 应用的访问路径
context-path: /
tomcat:
# tomcat的URI编码
uri-encoding: UTF-8
# 连接数满后的排队数默认为100
accept-count: 1000
threads:
# tomcat最大线程数默认为200
max: 800
# Tomcat启动初始化的线程数默认值10
min-spare: 100
# 日志配置
logging:
level:
com.ruoyi: debug
org.springframework: warn
# 用户配置
user:
password:
# 密码最大错误次数
maxRetryCount: 5
# 密码锁定时间默认10分钟
lockTime: 10
# Spring配置
spring:
# 资源信息
messages:
# 国际化资源文件路径
basename: i18n/messages
profiles:
active: druid
# 文件上传
servlet:
multipart:
# 单个文件大小
max-file-size: 10MB
# 设置总上传的文件大小
max-request-size: 20MB
# 服务模块
devtools:
restart:
# 热部署开关
enabled: false
# redis 配置
redis:
# 地址
host: localhost
# 端口默认为6379
port: 6379
# 数据库索引
database: 0
# 密码
password:
# 连接超时时间
timeout: 10s
lettuce:
pool:
# 连接池中的最小空闲连接
min-idle: 0
# 连接池中的最大空闲连接
max-idle: 8
# 连接池的最大数据库连接数
max-active: 8
# #连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1ms
# token配置
token:
# 令牌自定义标识
header: Authorization
# 令牌密钥
secret: abcdefghijklmnopqrstuvwxyz
# 令牌有效期( 3000分钟
expireTime: 3000
# MyBatis配置
mybatis:
# 搜索指定包别名
typeAliasesPackage: com.ruoyi.**.domain
# 配置mapper的扫描找到所有的mapper.xml映射文件
mapperLocations: classpath*:mapper/**/*Mapper.xml
# 加载全局的配置文件
configLocation: classpath:mybatis/mybatis-config.xml
# PageHelper分页插件
pagehelper:
helperDialect: mysql
supportMethodsArguments: true
params: count=countSql
# Swagger配置
swagger:
# 是否开启swagger
enabled: true
# 请求前缀
pathMapping: /dev-api
# 防止XSS攻击
xss:
# 过滤开关
enabled: true
# 排除链接(多个用逗号分隔)
excludes: /system/notice
# 匹配链接
urlPatterns: /system/*,/monitor/*,/tool/*
mybatis-plus:
# 搜索指定包别名
typeAliasesPackage: com.ruoyi.**.domain
# 配置mapper的扫描找到所有的mapper.xml映射文件
mapperLocations: classpath*:mapper/**/*Mapper.xml
# 加载全局的配置文件
configLocation: classpath:mybatis/mybatis-config.xml

@ -0,0 +1,24 @@
Application Version: ${ruoyi.version}
Spring Boot Version: ${spring-boot.version}
////////////////////////////////////////////////////////////////////
// _ooOoo_ //
// o8888888o //
// 88" . "88 //
// (| ^_^ |) //
// O\ = /O //
// ____/`---'\____ //
// .' \\| |// `. //
// / \\||| : |||// \ //
// / _||||| -:- |||||- \ //
// | | \\\ - /// | | //
// | \_| ''\---/'' | | //
// \ .-\__ `-` ___/-. / //
// ___`. .' /--.--\ `. . ___ //
// ."" '< `.___\_<|>_/___.' >'"". //
// | | : `- \`.;`\ _ /`;.`/ - ` : | | //
// \ \ `-. \_ __\ /__ _/ .-` / / //
// ========`-.____`-.___\_____/___.-`____.-'======== //
// `=---=' //
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ //
// 佛祖保佑 永不宕机 永无BUG //
////////////////////////////////////////////////////////////////////

@ -0,0 +1,37 @@
#错误消息
not.null=* 必须填写
user.jcaptcha.error=验证码错误
user.jcaptcha.expire=验证码已失效
user.not.exists=用户不存在/密码错误
user.password.not.match=用户不存在/密码错误
user.password.retry.limit.count=密码输入错误{0}次
user.password.retry.limit.exceed=密码输入错误{0}次,帐户锁定{1}分钟
user.password.delete=对不起,您的账号已被删除
user.blocked=用户已封禁,请联系管理员
role.blocked=角色已封禁,请联系管理员
user.logout.success=退出成功
length.not.valid=长度必须在{min}到{max}个字符之间
user.username.not.valid=* 2到20个汉字、字母、数字或下划线组成且必须以非数字开头
user.password.not.valid=* 5-50个字符
user.email.not.valid=邮箱格式错误
user.mobile.phone.number.not.valid=手机号格式错误
user.login.success=登录成功
user.register.success=注册成功
user.notfound=请重新登录
user.forcelogout=管理员强制退出,请重新登录
user.unknown.error=未知错误,请重新登录
##文件上传消息
upload.exceed.maxSize=上传的文件大小超出限制的文件大小!<br/>允许的文件最大大小是:{0}MB
upload.filename.exceed.length=上传的文件名最长{0}个字符
##权限
no.permission=您没有数据的权限,请联系管理员添加权限 [{0}]
no.create.permission=您没有创建数据的权限,请联系管理员添加权限 [{0}]
no.update.permission=您没有修改数据的权限,请联系管理员添加权限 [{0}]
no.delete.permission=您没有删除数据的权限,请联系管理员添加权限 [{0}]
no.export.permission=您没有导出数据的权限,请联系管理员添加权限 [{0}]
no.view.permission=您没有查看数据的权限,请联系管理员添加权限 [{0}]

@ -0,0 +1,93 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- 日志存放路径 -->
<property name="log.path" value="/home/ruoyi/logs" />
<!-- 日志输出格式 -->
<property name="log.pattern" value="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{20} - [%method,%line] - %msg%n" />
<!-- 控制台输出 -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
</appender>
<!-- 系统日志输出 -->
<appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/sys-info.log</file>
<!-- 循环政策:基于时间创建日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志文件名格式 -->
<fileNamePattern>${log.path}/sys-info.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 过滤的级别 -->
<level>INFO</level>
<!-- 匹配时的操作:接收(记录) -->
<onMatch>ACCEPT</onMatch>
<!-- 不匹配时的操作:拒绝(不记录) -->
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/sys-error.log</file>
<!-- 循环政策:基于时间创建日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志文件名格式 -->
<fileNamePattern>${log.path}/sys-error.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 过滤的级别 -->
<level>ERROR</level>
<!-- 匹配时的操作:接收(记录) -->
<onMatch>ACCEPT</onMatch>
<!-- 不匹配时的操作:拒绝(不记录) -->
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 用户访问日志输出 -->
<appender name="sys-user" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/sys-user.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 按天回滚 daily -->
<fileNamePattern>${log.path}/sys-user.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
</appender>
<!-- 系统模块日志级别控制 -->
<logger name="com.ruoyi" level="info" />
<!-- Spring日志级别控制 -->
<logger name="org.springframework" level="warn" />
<root level="info">
<appender-ref ref="console" />
</root>
<!--系统操作日志-->
<root level="info">
<appender-ref ref="file_info" />
<appender-ref ref="file_error" />
</root>
<!--系统用户操作日志-->
<logger name="sys-user" level="info">
<appender-ref ref="sys-user"/>
</logger>
</configuration>

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 全局参数 -->
<settings>
<!-- 使全局的映射器启用或禁用缓存 -->
<setting name="cacheEnabled" value="true" />
<!-- 允许JDBC 支持自动生成主键 -->
<setting name="useGeneratedKeys" value="true" />
<!-- 配置默认的执行器.SIMPLE就是普通执行器;REUSE执行器会重用预处理语句(prepared statements);BATCH执行器将重用语句并执行批量更新 -->
<setting name="defaultExecutorType" value="SIMPLE" />
<!-- 指定 MyBatis 所用日志的具体实现 -->
<setting name="logImpl" value="SLF4J" />
<!-- 使用驼峰命名法转换字段 -->
<!-- <setting name="mapUnderscoreToCamelCase" value="true"/> -->
</settings>
</configuration>

@ -0,0 +1,175 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>ruoyi</artifactId>
<groupId>com.ruoyi</groupId>
<version>3.8.3</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>ruoyi-common</artifactId>
<description>
common通用工具
</description>
<dependencies>
<!-- Spring框架基本的核心工具 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<!-- SpringWeb模块 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<!-- spring security 安全认证 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- pagehelper 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
</dependency>
<!-- 自定义验证注解 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!--常用工具类 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<!-- JSON工具类 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<!-- 阿里JSON解析器 -->
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
</dependency>
<!-- io常用工具类 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<!-- 文件上传工具类 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
</dependency>
<!-- excel工具 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
</dependency>
<!-- yml解析器 -->
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
</dependency>
<!-- Token生成与解析-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
</dependency>
<!-- Jaxb -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
</dependency>
<!-- redis 缓存操作 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- pool 对象池 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<!-- 解析客户端操作系统、浏览器等 -->
<dependency>
<groupId>eu.bitwalker</groupId>
<artifactId>UserAgentUtils</artifactId>
</dependency>
<!-- servlet包 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<!-- mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.4</version>
</dependency>
<!-- hutool-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.1</version>
</dependency>
<!-- lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<!--极光推送-->
<dependency>
<groupId>cn.jpush.api</groupId>
<artifactId>jiguang-common</artifactId>
<version>1.1.7</version>
</dependency>
<dependency>
<groupId>cn.jpush.api</groupId>
<artifactId>jpush-client</artifactId>
<version>3.4.3</version>
</dependency>
<!-- swagger3-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
</dependency>
<!-- 防止进入swagger页面报类型转换错误排除3.0.0中的引用手动增加1.6.2版本 -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.6.2</version>
</dependency>
</dependencies>
</project>

@ -0,0 +1,19 @@
package com.ruoyi.common.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 访
*
* @author ruoyi
*/
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Anonymous
{
}

@ -0,0 +1,33 @@
package com.ruoyi.common.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
*
* @author ruoyi
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataScope
{
/**
*
*/
public String deptAlias() default "";
/**
*
*/
public String userAlias() default "";
/**
* @ss
*/
public String permission() default "";
}

@ -0,0 +1,28 @@
package com.ruoyi.common.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.ruoyi.common.enums.DataSourceType;
/**
*
*
*
*
* @author ruoyi
*/
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface DataSource
{
/**
*
*/
public DataSourceType value() default DataSourceType.MASTER;
}

@ -0,0 +1,187 @@
package com.ruoyi.common.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.math.BigDecimal;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import com.ruoyi.common.utils.poi.ExcelHandlerAdapter;
/**
* Excel
*
* @author ruoyi
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Excel
{
/**
* excel
*/
public int sort() default Integer.MAX_VALUE;
/**
* Excel.
*/
public String name() default "";
/**
* , : yyyy-MM-dd
*/
public String dateFormat() default "";
/**
* type (: sys_user_sex)
*/
public String dictType() default "";
/**
* (: 0=,1=,2=)
*/
public String readConverterExp() default "";
/**
*
*/
public String separator() default ",";
/**
* BigDecimal :-1(BigDecimal)
*/
public int scale() default -1;
/**
* BigDecimal :BigDecimal.ROUND_HALF_EVEN
*/
public int roundingMode() default BigDecimal.ROUND_HALF_EVEN;
/**
* excel
*/
public double height() default 14;
/**
* excel
*/
public double width() default 16;
/**
* ,% 90 90%
*/
public String suffix() default "";
/**
* ,
*/
public String defaultValue() default "";
/**
*
*/
public String prompt() default "";
/**
* .
*/
public String[] combo() default {};
/**
* ,:list)
*/
public boolean needMerge() default false;
/**
* ,:,.
*/
public boolean isExport() default true;
/**
* ,,
*/
public String targetAttr() default "";
/**
* ,
*/
public boolean isStatistics() default false;
/**
* 0 1 2
*/
public ColumnType cellType() default ColumnType.STRING;
/**
*
*/
public IndexedColors headerBackgroundColor() default IndexedColors.GREY_50_PERCENT;
/**
*
*/
public IndexedColors headerColor() default IndexedColors.WHITE;
/**
*
*/
public IndexedColors backgroundColor() default IndexedColors.WHITE;
/**
*
*/
public IndexedColors color() default IndexedColors.BLACK;
/**
*
*/
public HorizontalAlignment align() default HorizontalAlignment.CENTER;
/**
*
*/
public Class<?> handler() default ExcelHandlerAdapter.class;
/**
*
*/
public String[] args() default {};
/**
* 012
*/
Type type() default Type.ALL;
public enum Type
{
ALL(0), EXPORT(1), IMPORT(2);
private final int value;
Type(int value)
{
this.value = value;
}
public int value()
{
return this.value;
}
}
public enum ColumnType
{
NUMERIC(0), STRING(1), IMAGE(2);
private final int value;
ColumnType(int value)
{
this.value = value;
}
public int value()
{
return this.value;
}
}
}

@ -0,0 +1,18 @@
package com.ruoyi.common.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Excel
*
* @author ruoyi
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Excels
{
public Excel[] value();
}

@ -0,0 +1,46 @@
package com.ruoyi.common.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.OperatorType;
/**
*
*
* @author ruoyi
*
*/
@Target({ ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log
{
/**
*
*/
public String title() default "";
/**
*
*/
public BusinessType businessType() default BusinessType.OTHER;
/**
*
*/
public OperatorType operatorType() default OperatorType.MANAGE;
/**
*
*/
public boolean isSaveRequestData() default true;
/**
*
*/
public boolean isSaveResponseData() default true;
}

@ -0,0 +1,40 @@
package com.ruoyi.common.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.enums.LimitType;
/**
*
*
* @author ruoyi
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RateLimiter
{
/**
* key
*/
public String key() default CacheConstants.RATE_LIMIT_KEY;
/**
* ,
*/
public int time() default 60;
/**
*
*/
public int count() default 100;
/**
*
*/
public LimitType limitType() default LimitType.DEFAULT;
}

@ -0,0 +1,31 @@
package com.ruoyi.common.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
*
* @author ruoyi
*
*/
@Inherited
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RepeatSubmit
{
/**
* (ms)
*/
public int interval() default 5000;
/**
*
*/
public String message() default "不允许重复提交,请稍候再试";
}

@ -0,0 +1,135 @@
package com.ruoyi.common.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
*
*
* @author ruoyi
*/
@Component
@ConfigurationProperties(prefix = "ruoyi")
public class RuoYiConfig
{
/** 项目名称 */
private String name;
/** 版本 */
private String version;
/** 版权年份 */
private String copyrightYear;
/** 实例演示开关 */
private boolean demoEnabled;
/** 上传路径 */
private static String profile;
/** 获取地址开关 */
private static boolean addressEnabled;
/** 验证码类型 */
private static String captchaType;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getVersion()
{
return version;
}
public void setVersion(String version)
{
this.version = version;
}
public String getCopyrightYear()
{
return copyrightYear;
}
public void setCopyrightYear(String copyrightYear)
{
this.copyrightYear = copyrightYear;
}
public boolean isDemoEnabled()
{
return demoEnabled;
}
public void setDemoEnabled(boolean demoEnabled)
{
this.demoEnabled = demoEnabled;
}
public static String getProfile()
{
return profile;
}
public void setProfile(String profile)
{
RuoYiConfig.profile = profile;
}
public static boolean isAddressEnabled()
{
return addressEnabled;
}
public void setAddressEnabled(boolean addressEnabled)
{
RuoYiConfig.addressEnabled = addressEnabled;
}
public static String getCaptchaType() {
return captchaType;
}
public void setCaptchaType(String captchaType) {
RuoYiConfig.captchaType = captchaType;
}
/**
*
*/
public static String getImportPath()
{
return getProfile() + "/import";
}
/**
*
*/
public static String getAvatarPath()
{
return getProfile() + "/avatar";
}
/**
*
*/
public static String getDownloadPath()
{
return getProfile() + "/download/";
}
/**
*
*/
public static String getUploadPath()
{
return getProfile() + "/upload";
}
}

@ -0,0 +1,44 @@
package com.ruoyi.common.constant;
/**
* key
*
* @author ruoyi
*/
public class CacheConstants
{
/**
* redis key
*/
public static final String LOGIN_TOKEN_KEY = "login_tokens:";
/**
* redis key
*/
public static final String CAPTCHA_CODE_KEY = "captcha_codes:";
/**
* cache key
*/
public static final String SYS_CONFIG_KEY = "sys_config:";
/**
* cache key
*/
public static final String SYS_DICT_KEY = "sys_dict:";
/**
* redis key
*/
public static final String REPEAT_SUBMIT_KEY = "repeat_submit:";
/**
* redis key
*/
public static final String RATE_LIMIT_KEY = "rate_limit:";
/**
* redis key
*/
public static final String PWD_ERR_CNT_KEY = "pwd_err_cnt:";
}

@ -0,0 +1,142 @@
package com.ruoyi.common.constant;
import io.jsonwebtoken.Claims;
/**
*
*
* @author ruoyi
*/
public class Constants
{
/**
* UTF-8
*/
public static final String UTF8 = "UTF-8";
/**
* GBK
*/
public static final String GBK = "GBK";
/**
* www
*/
public static final String WWW = "www.";
/**
* http
*/
public static final String HTTP = "http://";
/**
* https
*/
public static final String HTTPS = "https://";
/**
*
*/
public static final String SUCCESS = "0";
/**
*
*/
public static final String FAIL = "1";
/**
*
*/
public static final String LOGIN_SUCCESS = "Success";
/**
*
*/
public static final String LOGOUT = "Logout";
/**
*
*/
public static final String REGISTER = "Register";
/**
*
*/
public static final String LOGIN_FAIL = "Error";
/**
*
*/
public static final Integer CAPTCHA_EXPIRATION = 2;
/**
*
*/
public static final String TOKEN = "token";
/**
*
*/
public static final String TOKEN_PREFIX = "Bearer ";
/**
*
*/
public static final String LOGIN_USER_KEY = "login_user_key";
/**
* ID
*/
public static final String JWT_USERID = "userid";
/**
*
*/
public static final String JWT_USERNAME = Claims.SUBJECT;
/**
*
*/
public static final String JWT_AVATAR = "avatar";
/**
*
*/
public static final String JWT_CREATED = "created";
/**
*
*/
public static final String JWT_AUTHORITIES = "authorities";
/**
*
*/
public static final String RESOURCE_PREFIX = "/profile";
/**
* RMI
*/
public static final String LOOKUP_RMI = "rmi:";
/**
* LDAP
*/
public static final String LOOKUP_LDAP = "ldap:";
/**
* LDAPS
*/
public static final String LOOKUP_LDAPS = "ldaps:";
/**
* 访
*/
public static final String[] JOB_WHITELIST_STR = { "com.ruoyi" };
/**
*
*/
public static final String[] JOB_ERROR_STR = { "java.net.URL", "javax.naming.InitialContext", "org.yaml.snakeyaml",
"org.springframework", "org.apache", "com.ruoyi.common.utils.file" };
}

@ -0,0 +1,117 @@
package com.ruoyi.common.constant;
/**
*
*
* @author ruoyi
*/
public class GenConstants
{
/** 单表(增删改查) */
public static final String TPL_CRUD = "crud";
/** 树表(增删改查) */
public static final String TPL_TREE = "tree";
/** 主子表(增删改查) */
public static final String TPL_SUB = "sub";
/** 树编码字段 */
public static final String TREE_CODE = "treeCode";
/** 树父编码字段 */
public static final String TREE_PARENT_CODE = "treeParentCode";
/** 树名称字段 */
public static final String TREE_NAME = "treeName";
/** 上级菜单ID字段 */
public static final String PARENT_MENU_ID = "parentMenuId";
/** 上级菜单名称字段 */
public static final String PARENT_MENU_NAME = "parentMenuName";
/** 数据库字符串类型 */
public static final String[] COLUMNTYPE_STR = { "char", "varchar", "nvarchar", "varchar2" };
/** 数据库文本类型 */
public static final String[] COLUMNTYPE_TEXT = { "tinytext", "text", "mediumtext", "longtext" };
/** 数据库时间类型 */
public static final String[] COLUMNTYPE_TIME = { "datetime", "time", "date", "timestamp" };
/** 数据库数字类型 */
public static final String[] COLUMNTYPE_NUMBER = { "tinyint", "smallint", "mediumint", "int", "number", "integer",
"bit", "bigint", "float", "double", "decimal" };
/** 页面不需要编辑字段 */
public static final String[] COLUMNNAME_NOT_EDIT = { "id", "create_by", "create_time", "del_flag" };
/** 页面不需要显示的列表字段 */
public static final String[] COLUMNNAME_NOT_LIST = { "id", "create_by", "create_time", "del_flag", "update_by",
"update_time" };
/** 页面不需要查询字段 */
public static final String[] COLUMNNAME_NOT_QUERY = { "id", "create_by", "create_time", "del_flag", "update_by",
"update_time", "remark" };
/** Entity基类字段 */
public static final String[] BASE_ENTITY = { "createBy", "createTime", "updateBy", "updateTime", "remark" };
/** Tree基类字段 */
public static final String[] TREE_ENTITY = { "parentName", "parentId", "orderNum", "ancestors", "children" };
/** 文本框 */
public static final String HTML_INPUT = "input";
/** 文本域 */
public static final String HTML_TEXTAREA = "textarea";
/** 下拉框 */
public static final String HTML_SELECT = "select";
/** 单选框 */
public static final String HTML_RADIO = "radio";
/** 复选框 */
public static final String HTML_CHECKBOX = "checkbox";
/** 日期控件 */
public static final String HTML_DATETIME = "datetime";
/** 图片上传控件 */
public static final String HTML_IMAGE_UPLOAD = "imageUpload";
/** 文件上传控件 */
public static final String HTML_FILE_UPLOAD = "fileUpload";
/** 富文本控件 */
public static final String HTML_EDITOR = "editor";
/** 字符串类型 */
public static final String TYPE_STRING = "String";
/** 整型 */
public static final String TYPE_INTEGER = "Integer";
/** 长整型 */
public static final String TYPE_LONG = "Long";
/** 浮点型 */
public static final String TYPE_DOUBLE = "Double";
/** 高精度计算类型 */
public static final String TYPE_BIGDECIMAL = "BigDecimal";
/** 时间类型 */
public static final String TYPE_DATE = "Date";
/** 模糊查询 */
public static final String QUERY_LIKE = "LIKE";
/** 相等查询 */
public static final String QUERY_EQ = "EQ";
/** 需要 */
public static final String REQUIRE = "1";
}

@ -0,0 +1,89 @@
package com.ruoyi.common.constant;
/**
*
*
* @author ruoyi
*/
public class HttpStatus
{
/**
*
*/
public static final int SUCCESS = 200;
/**
*
*/
public static final int CREATED = 201;
/**
*
*/
public static final int ACCEPTED = 202;
/**
*
*/
public static final int NO_CONTENT = 204;
/**
*
*/
public static final int MOVED_PERM = 301;
/**
*
*/
public static final int SEE_OTHER = 303;
/**
*
*/
public static final int NOT_MODIFIED = 304;
/**
*
*/
public static final int BAD_REQUEST = 400;
/**
*
*/
public static final int UNAUTHORIZED = 401;
/**
* 访
*/
public static final int FORBIDDEN = 403;
/**
*
*/
public static final int NOT_FOUND = 404;
/**
* http
*/
public static final int BAD_METHOD = 405;
/**
*
*/
public static final int CONFLICT = 409;
/**
*
*/
public static final int UNSUPPORTED_TYPE = 415;
/**
*
*/
public static final int ERROR = 500;
/**
*
*/
public static final int NOT_IMPLEMENTED = 501;
}

@ -0,0 +1,50 @@
package com.ruoyi.common.constant;
/**
*
*
* @author ruoyi
*/
public class ScheduleConstants
{
public static final String TASK_CLASS_NAME = "TASK_CLASS_NAME";
/** 执行目标key */
public static final String TASK_PROPERTIES = "TASK_PROPERTIES";
/** 默认 */
public static final String MISFIRE_DEFAULT = "0";
/** 立即触发执行 */
public static final String MISFIRE_IGNORE_MISFIRES = "1";
/** 触发一次执行 */
public static final String MISFIRE_FIRE_AND_PROCEED = "2";
/** 不触发立即执行 */
public static final String MISFIRE_DO_NOTHING = "3";
public enum Status
{
/**
*
*/
NORMAL("0"),
/**
*
*/
PAUSE("1");
private String value;
private Status(String value)
{
this.value = value;
}
public String getValue()
{
return value;
}
}
}

@ -0,0 +1,78 @@
package com.ruoyi.common.constant;
/**
*
*
* @author ruoyi
*/
public class UserConstants
{
/**
*
*/
public static final String SYS_USER = "SYS_USER";
/** 正常状态 */
public static final String NORMAL = "0";
/** 异常状态 */
public static final String EXCEPTION = "1";
/** 用户封禁状态 */
public static final String USER_DISABLE = "1";
/** 角色封禁状态 */
public static final String ROLE_DISABLE = "1";
/** 部门正常状态 */
public static final String DEPT_NORMAL = "0";
/** 部门停用状态 */
public static final String DEPT_DISABLE = "1";
/** 字典正常状态 */
public static final String DICT_NORMAL = "0";
/** 是否为系统默认(是) */
public static final String YES = "Y";
/** 是否菜单外链(是) */
public static final String YES_FRAME = "0";
/** 是否菜单外链(否) */
public static final String NO_FRAME = "1";
/** 菜单类型(目录) */
public static final String TYPE_DIR = "M";
/** 菜单类型(菜单) */
public static final String TYPE_MENU = "C";
/** 菜单类型(按钮) */
public static final String TYPE_BUTTON = "F";
/** Layout组件标识 */
public final static String LAYOUT = "Layout";
/** ParentView组件标识 */
public final static String PARENT_VIEW = "ParentView";
/** InnerLink组件标识 */
public final static String INNER_LINK = "InnerLink";
/** 校验返回结果码 */
public final static String UNIQUE = "0";
public final static String NOT_UNIQUE = "1";
/**
*
*/
public static final int USERNAME_MIN_LENGTH = 2;
public static final int USERNAME_MAX_LENGTH = 20;
/**
*
*/
public static final int PASSWORD_MIN_LENGTH = 5;
public static final int PASSWORD_MAX_LENGTH = 20;
}

@ -0,0 +1,186 @@
package com.ruoyi.common.core.controller;
import java.beans.PropertyEditorSupport;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sql.SqlUtil;
/**
* web
*
* @author ruoyi
*/
public class BaseController
{
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* Date
*/
@InitBinder
public void initBinder(WebDataBinder binder)
{
// Date 类型转换
binder.registerCustomEditor(Date.class, new PropertyEditorSupport()
{
@Override
public void setAsText(String text)
{
setValue(DateUtils.parseDate(text));
}
});
}
/**
*
*/
protected void startPage()
{
PageUtils.startPage();
}
/**
*
*/
protected void startOrderBy()
{
PageDomain pageDomain = TableSupport.buildPageRequest();
if (StringUtils.isNotEmpty(pageDomain.getOrderBy()))
{
String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
PageHelper.orderBy(orderBy);
}
}
/**
* 线
*/
protected void clearPage()
{
PageUtils.clearPage();
}
/**
*
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
protected TableDataInfo getDataTable(List<?> list)
{
TableDataInfo rspData = new TableDataInfo();
rspData.setCode(HttpStatus.SUCCESS);
rspData.setMsg("查询成功");
rspData.setRows(list);
rspData.setTotal(new PageInfo(list).getTotal());
return rspData;
}
/**
*
*/
public AjaxResult success()
{
return AjaxResult.success();
}
/**
*
*/
public AjaxResult error()
{
return AjaxResult.error();
}
/**
*
*/
public AjaxResult success(String message)
{
return AjaxResult.success(message);
}
/**
*
*/
public AjaxResult error(String message)
{
return AjaxResult.error(message);
}
/**
*
*
* @param rows
* @return
*/
protected AjaxResult toAjax(int rows)
{
return rows > 0 ? AjaxResult.success() : AjaxResult.error();
}
/**
*
*
* @param result
* @return
*/
protected AjaxResult toAjax(boolean result)
{
return result ? success() : error();
}
/**
*
*/
public String redirect(String url)
{
return StringUtils.format("redirect:{}", url);
}
/**
*
*/
public LoginUser getLoginUser()
{
return SecurityUtils.getLoginUser();
}
/**
* id
*/
public Long getUserId()
{
return getLoginUser().getUserId();
}
/**
* id
*/
public Long getDeptId()
{
return getLoginUser().getDeptId();
}
/**
*
*/
public String getUsername()
{
return getLoginUser().getUsername();
}
}

@ -0,0 +1,162 @@
package com.ruoyi.common.core.domain;
import java.util.HashMap;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.utils.StringUtils;
/**
*
*
* @author ruoyi
*/
public class AjaxResult extends HashMap<String, Object>
{
private static final long serialVersionUID = 1L;
/** 状态码 */
public static final String CODE_TAG = "code";
/** 返回内容 */
public static final String MSG_TAG = "msg";
/** 数据对象 */
public static final String DATA_TAG = "data";
/**
* AjaxResult 使
*/
public AjaxResult()
{
}
/**
* AjaxResult
*
* @param code
* @param msg
*/
public AjaxResult(int code, String msg)
{
super.put(CODE_TAG, code);
super.put(MSG_TAG, msg);
}
/**
* AjaxResult
*
* @param code
* @param msg
* @param data
*/
public AjaxResult(int code, String msg, Object data)
{
super.put(CODE_TAG, code);
super.put(MSG_TAG, msg);
if (StringUtils.isNotNull(data))
{
super.put(DATA_TAG, data);
}
}
/**
*
*
* @return
*/
public static AjaxResult success()
{
return AjaxResult.success("操作成功");
}
/**
*
*
* @return
*/
public static AjaxResult success(Object data)
{
return AjaxResult.success("操作成功", data);
}
/**
*
*
* @param msg
* @return
*/
public static AjaxResult success(String msg)
{
return AjaxResult.success(msg, null);
}
/**
*
*
* @param msg
* @param data
* @return
*/
public static AjaxResult success(String msg, Object data)
{
return new AjaxResult(HttpStatus.SUCCESS, msg, data);
}
/**
*
*
* @return
*/
public static AjaxResult error()
{
return AjaxResult.error("操作失败");
}
/**
*
*
* @param msg
* @return
*/
public static AjaxResult error(String msg)
{
return AjaxResult.error(msg, null);
}
/**
*
*
* @param msg
* @param data
* @return
*/
public static AjaxResult error(String msg, Object data)
{
return new AjaxResult(HttpStatus.ERROR, msg, data);
}
/**
*
*
* @param code
* @param msg
* @return
*/
public static AjaxResult error(int code, String msg)
{
return new AjaxResult(code, msg, null);
}
/**
* 便
*
* @param key
* @param value
* @return
*/
@Override
public AjaxResult put(String key, Object value)
{
super.put(key, value);
return this;
}
}

@ -0,0 +1,114 @@
package com.ruoyi.common.core.domain;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonFormat;
/**
* Entity
*
* @author ruoyi
*/
public class BaseEntity implements Serializable
{
private static final long serialVersionUID = 1L;
/** 搜索值 */
private String searchValue;
/** 创建者 */
private String createBy;
/** 创建时间 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
/** 更新者 */
private String updateBy;
/** 更新时间 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime;
/** 备注 */
private String remark;
/** 请求参数 */
private Map<String, Object> params;
public String getSearchValue()
{
return searchValue;
}
public void setSearchValue(String searchValue)
{
this.searchValue = searchValue;
}
public String getCreateBy()
{
return createBy;
}
public void setCreateBy(String createBy)
{
this.createBy = createBy;
}
public Date getCreateTime()
{
return createTime;
}
public void setCreateTime(Date createTime)
{
this.createTime = createTime;
}
public String getUpdateBy()
{
return updateBy;
}
public void setUpdateBy(String updateBy)
{
this.updateBy = updateBy;
}
public Date getUpdateTime()
{
return updateTime;
}
public void setUpdateTime(Date updateTime)
{
this.updateTime = updateTime;
}
public String getRemark()
{
return remark;
}
public void setRemark(String remark)
{
this.remark = remark;
}
public Map<String, Object> getParams()
{
if (params == null)
{
params = new HashMap<>();
}
return params;
}
public void setParams(Map<String, Object> params)
{
this.params = params;
}
}

@ -0,0 +1,105 @@
package com.ruoyi.common.core.domain;
import java.io.Serializable;
import com.ruoyi.common.constant.HttpStatus;
/**
*
*
* @author ruoyi
*/
public class R<T> implements Serializable
{
private static final long serialVersionUID = 1L;
/** 成功 */
public static final int SUCCESS = HttpStatus.SUCCESS;
/** 失败 */
public static final int FAIL = HttpStatus.ERROR;
private int code;
private String msg;
private T data;
public static <T> R<T> ok()
{
return restResult(null, SUCCESS, "操作成功");
}
public static <T> R<T> ok(T data)
{
return restResult(data, SUCCESS, "操作成功");
}
public static <T> R<T> ok(T data, String msg)
{
return restResult(data, SUCCESS, msg);
}
public static <T> R<T> fail()
{
return restResult(null, FAIL, "操作失败");
}
public static <T> R<T> fail(String msg)
{
return restResult(null, FAIL, msg);
}
public static <T> R<T> fail(T data)
{
return restResult(data, FAIL, "操作失败");
}
public static <T> R<T> fail(T data, String msg)
{
return restResult(data, FAIL, msg);
}
public static <T> R<T> fail(int code, String msg)
{
return restResult(null, code, msg);
}
private static <T> R<T> restResult(T data, int code, String msg)
{
R<T> apiResult = new R<>();
apiResult.setCode(code);
apiResult.setData(data);
apiResult.setMsg(msg);
return apiResult;
}
public int getCode()
{
return code;
}
public void setCode(int code)
{
this.code = code;
}
public String getMsg()
{
return msg;
}
public void setMsg(String msg)
{
this.msg = msg;
}
public T getData()
{
return data;
}
public void setData(T data)
{
this.data = data;
}
}

@ -0,0 +1,79 @@
package com.ruoyi.common.core.domain;
import java.util.ArrayList;
import java.util.List;
/**
* Tree
*
* @author ruoyi
*/
public class TreeEntity extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** 父菜单名称 */
private String parentName;
/** 父菜单ID */
private Long parentId;
/** 显示顺序 */
private Integer orderNum;
/** 祖级列表 */
private String ancestors;
/** 子部门 */
private List<?> children = new ArrayList<>();
public String getParentName()
{
return parentName;
}
public void setParentName(String parentName)
{
this.parentName = parentName;
}
public Long getParentId()
{
return parentId;
}
public void setParentId(Long parentId)
{
this.parentId = parentId;
}
public Integer getOrderNum()
{
return orderNum;
}
public void setOrderNum(Integer orderNum)
{
this.orderNum = orderNum;
}
public String getAncestors()
{
return ancestors;
}
public void setAncestors(String ancestors)
{
this.ancestors = ancestors;
}
public List<?> getChildren()
{
return children;
}
public void setChildren(List<?> children)
{
this.children = children;
}
}

@ -0,0 +1,77 @@
package com.ruoyi.common.core.domain;
import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysMenu;
/**
* Treeselect
*
* @author ruoyi
*/
public class TreeSelect implements Serializable
{
private static final long serialVersionUID = 1L;
/** 节点ID */
private Long id;
/** 节点名称 */
private String label;
/** 子节点 */
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private List<TreeSelect> children;
public TreeSelect()
{
}
public TreeSelect(SysDept dept)
{
this.id = dept.getDeptId();
this.label = dept.getDeptName();
this.children = dept.getChildren().stream().map(TreeSelect::new).collect(Collectors.toList());
}
public TreeSelect(SysMenu menu)
{
this.id = menu.getMenuId();
this.label = menu.getMenuName();
this.children = menu.getChildren().stream().map(TreeSelect::new).collect(Collectors.toList());
}
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
public String getLabel()
{
return label;
}
public void setLabel(String label)
{
this.label = label;
}
public List<TreeSelect> getChildren()
{
return children;
}
public void setChildren(List<TreeSelect> children)
{
this.children = children;
}
}

@ -0,0 +1,296 @@
package com.ruoyi.common.core.domain.entity;
import com.ruoyi.common.core.domain.BaseEntity;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.ArrayList;
import java.util.List;
/**
* sys_dept
*
* @author ruoyi
*/
public class SysDept extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** 部门ID */
private Long deptId;
/** 父部门ID */
private Long parentId;
/** 祖级列表 */
private String ancestors;
/** 部门名称 */
private String deptName;
/** 显示顺序 */
private Integer orderNum;
/** 负责人 */
private String leader;
/** 联系电话 */
private String phone;
/** 邮箱 */
private String email;
/** 部门状态:0正常,1停用 */
private String status;
/** 删除标志0代表存在 2代表删除 */
private String delFlag;
/** 父部门名称 */
private String parentName;
/**商户id*/
private String merchanId;
/**
*
*/
private String address;
/**
*
*/
private String detail;
/**
*
*/
private String brief;
/**
*
*/
private String picture;
/**
* */
private Boolean display;
private String dimension;//纬度
private String longitude;//经度
public String getDimension() {
return dimension;
}
public void setDimension(String dimension) {
this.dimension = dimension;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public Boolean getDisplay() {
return display;
}
public void setDisplay(Boolean display) {
this.display = display;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public String getBrief() {
return brief;
}
public void setBrief(String brief) {
this.brief = brief;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public String getMerchanId() {
return merchanId;
}
public void setMerchanId(String merchanId) {
this.merchanId = merchanId;
}
/** 子部门 */
private List<SysDept> children = new ArrayList<SysDept>();
public Long getDeptId()
{
return deptId;
}
public void setDeptId(Long deptId)
{
this.deptId = deptId;
}
public Long getParentId()
{
return parentId;
}
public void setParentId(Long parentId)
{
this.parentId = parentId;
}
public String getAncestors()
{
return ancestors;
}
public void setAncestors(String ancestors)
{
this.ancestors = ancestors;
}
@NotBlank(message = "部门名称不能为空")
@Size(min = 0, max = 30, message = "部门名称长度不能超过30个字符")
public String getDeptName()
{
return deptName;
}
public void setDeptName(String deptName)
{
this.deptName = deptName;
}
@NotNull(message = "显示顺序不能为空")
public Integer getOrderNum()
{
return orderNum;
}
public void setOrderNum(Integer orderNum)
{
this.orderNum = orderNum;
}
public String getLeader()
{
return leader;
}
public void setLeader(String leader)
{
this.leader = leader;
}
@Size(min = 0, max = 11, message = "联系电话长度不能超过11个字符")
public String getPhone()
{
return phone;
}
public void setPhone(String phone)
{
this.phone = phone;
}
@Email(message = "邮箱格式不正确")
@Size(min = 0, max = 50, message = "邮箱长度不能超过50个字符")
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public String getStatus()
{
return status;
}
public void setStatus(String status)
{
this.status = status;
}
public String getDelFlag()
{
return delFlag;
}
public void setDelFlag(String delFlag)
{
this.delFlag = delFlag;
}
public String getParentName()
{
return parentName;
}
public void setParentName(String parentName)
{
this.parentName = parentName;
}
public List<SysDept> getChildren()
{
return children;
}
public void setChildren(List<SysDept> children)
{
this.children = children;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("deptId", getDeptId())
.append("parentId", getParentId())
.append("ancestors", getAncestors())
.append("deptName", getDeptName())
.append("orderNum", getOrderNum())
.append("leader", getLeader())
.append("phone", getPhone())
.append("email", getEmail())
.append("status", getStatus())
.append("delFlag", getDelFlag())
.append("createBy", getCreateBy())
.append("createTime", getCreateTime())
.append("updateBy", getUpdateBy())
.append("updateTime", getUpdateTime())
.toString();
}
}

@ -0,0 +1,187 @@
package com.ruoyi.common.core.domain.entity;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.annotation.Excel.ColumnType;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.BaseEntity;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
/**
* sys_dict_data
*
* @author ruoyi
*/
public class SysDictData extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** 字典编码 */
@Excel(name = "字典编码", cellType = ColumnType.NUMERIC)
private Long dictCode;
/** 字典排序 */
@Excel(name = "字典排序", cellType = ColumnType.NUMERIC)
private Long dictSort;
/** 字典标签 */
@Excel(name = "字典标签")
private String dictLabel;
/** 字典键值 */
@Excel(name = "字典键值")
private String dictValue;
/** 字典类型 */
@Excel(name = "字典类型")
private String dictType;
/** 样式属性(其他样式扩展) */
private String cssClass;
/** 表格字典样式 */
private String listClass;
/** 是否默认Y是 N否 */
@Excel(name = "是否默认", readConverterExp = "Y=是,N=否")
private String isDefault;
/** 状态0正常 1停用 */
@Excel(name = "状态", readConverterExp = "0=正常,1=停用")
private String status;
/**商户id*/
private String merchantId;
public String getMerchantId() {
return merchantId;
}
public void setMerchantId(String merchantId) {
this.merchantId = merchantId;
}
public Long getDictCode()
{
return dictCode;
}
public void setDictCode(Long dictCode)
{
this.dictCode = dictCode;
}
public Long getDictSort()
{
return dictSort;
}
public void setDictSort(Long dictSort)
{
this.dictSort = dictSort;
}
@NotBlank(message = "字典标签不能为空")
@Size(min = 0, max = 100, message = "字典标签长度不能超过100个字符")
public String getDictLabel()
{
return dictLabel;
}
public void setDictLabel(String dictLabel)
{
this.dictLabel = dictLabel;
}
@NotBlank(message = "字典键值不能为空")
@Size(min = 0, max = 100, message = "字典键值长度不能超过100个字符")
public String getDictValue()
{
return dictValue;
}
public void setDictValue(String dictValue)
{
this.dictValue = dictValue;
}
@NotBlank(message = "字典类型不能为空")
@Size(min = 0, max = 100, message = "字典类型长度不能超过100个字符")
public String getDictType()
{
return dictType;
}
public void setDictType(String dictType)
{
this.dictType = dictType;
}
@Size(min = 0, max = 100, message = "样式属性长度不能超过100个字符")
public String getCssClass()
{
return cssClass;
}
public void setCssClass(String cssClass)
{
this.cssClass = cssClass;
}
public String getListClass()
{
return listClass;
}
public void setListClass(String listClass)
{
this.listClass = listClass;
}
public boolean getDefault()
{
return UserConstants.YES.equals(this.isDefault);
}
public String getIsDefault()
{
return isDefault;
}
public void setIsDefault(String isDefault)
{
this.isDefault = isDefault;
}
public String getStatus()
{
return status;
}
public void setStatus(String status)
{
this.status = status;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("dictCode", getDictCode())
.append("dictSort", getDictSort())
.append("dictLabel", getDictLabel())
.append("dictValue", getDictValue())
.append("dictType", getDictType())
.append("cssClass", getCssClass())
.append("listClass", getListClass())
.append("isDefault", getIsDefault())
.append("status", getStatus())
.append("createBy", getCreateBy())
.append("createTime", getCreateTime())
.append("updateBy", getUpdateBy())
.append("updateTime", getUpdateTime())
.append("remark", getRemark())
.toString();
}
}

@ -0,0 +1,97 @@
package com.ruoyi.common.core.domain.entity;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.annotation.Excel.ColumnType;
import com.ruoyi.common.core.domain.BaseEntity;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
/**
* sys_dict_type
*
* @author ruoyi
*/
public class SysDictType extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** 字典主键 */
@Excel(name = "字典主键", cellType = ColumnType.NUMERIC)
private Long dictId;
/** 字典名称 */
@Excel(name = "字典名称")
private String dictName;
/** 字典类型 */
@Excel(name = "字典类型")
private String dictType;
/** 状态0正常 1停用 */
@Excel(name = "状态", readConverterExp = "0=正常,1=停用")
private String status;
public Long getDictId()
{
return dictId;
}
public void setDictId(Long dictId)
{
this.dictId = dictId;
}
@NotBlank(message = "字典名称不能为空")
@Size(min = 0, max = 100, message = "字典类型名称长度不能超过100个字符")
public String getDictName()
{
return dictName;
}
public void setDictName(String dictName)
{
this.dictName = dictName;
}
@NotBlank(message = "字典类型不能为空")
@Size(min = 0, max = 100, message = "字典类型类型长度不能超过100个字符")
@Pattern(regexp = "^[a-z][a-z0-9_]*$", message = "字典类型必须以字母开头,且只能为(小写字母,数字,下滑线)")
public String getDictType()
{
return dictType;
}
public void setDictType(String dictType)
{
this.dictType = dictType;
}
public String getStatus()
{
return status;
}
public void setStatus(String status)
{
this.status = status;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("dictId", getDictId())
.append("dictName", getDictName())
.append("dictType", getDictType())
.append("status", getStatus())
.append("createBy", getCreateBy())
.append("createTime", getCreateTime())
.append("updateBy", getUpdateBy())
.append("updateTime", getUpdateTime())
.append("remark", getRemark())
.toString();
}
}

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

Loading…
Cancel
Save