init
This commit is contained in:
53
ruoyi-modules/pom.xml
Normal file
53
ruoyi-modules/pom.xml
Normal file
@ -0,0 +1,53 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>xny-cloud</artifactId>
|
||||
<version>${revision}</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<modules>
|
||||
<module>ruoyi-system</module>
|
||||
<module>ruoyi-gen</module>
|
||||
<module>ruoyi-job</module>
|
||||
<module>ruoyi-resource</module>
|
||||
<module>ruoyi-workflow</module>
|
||||
</modules>
|
||||
|
||||
<artifactId>ruoyi-modules</artifactId>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<description>
|
||||
ruoyi-modules业务模块
|
||||
</description>
|
||||
|
||||
<dependencies>
|
||||
<!-- 自定义负载均衡(多团队开发使用) -->
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>org.dromara</groupId>-->
|
||||
<!-- <artifactId>ruoyi-common-loadbalancer</artifactId>-->
|
||||
<!-- </dependency>-->
|
||||
|
||||
<!-- ELK 日志收集 -->
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>org.dromara</groupId>-->
|
||||
<!-- <artifactId>ruoyi-common-logstash</artifactId>-->
|
||||
<!-- </dependency>-->
|
||||
|
||||
<!-- skywalking 日志收集 -->
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>org.dromara</groupId>-->
|
||||
<!-- <artifactId>ruoyi-common-skylog</artifactId>-->
|
||||
<!-- </dependency>-->
|
||||
|
||||
<!-- prometheus 监控 -->
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>org.dromara</groupId>-->
|
||||
<!-- <artifactId>ruoyi-common-prometheus</artifactId>-->
|
||||
<!-- </dependency>-->
|
||||
|
||||
</dependencies>
|
||||
|
||||
</project>
|
20
ruoyi-modules/ruoyi-gen/Dockerfile
Normal file
20
ruoyi-modules/ruoyi-gen/Dockerfile
Normal file
@ -0,0 +1,20 @@
|
||||
# 贝尔实验室 Spring 官方推荐镜像 JDK下载地址 https://bell-sw.com/pages/downloads/
|
||||
FROM bellsoft/liberica-openjdk-rocky:17.0.15-cds
|
||||
#FROM bellsoft/liberica-openjdk-rocky:21.0.7-cds
|
||||
#FROM findepi/graalvm:java17-native
|
||||
|
||||
LABEL maintainer="Lion Li"
|
||||
|
||||
RUN mkdir -p /ruoyi/gen/logs
|
||||
|
||||
WORKDIR /ruoyi/gen
|
||||
|
||||
ENV SERVER_PORT=9202 LANG=C.UTF-8 LC_ALL=C.UTF-8 JAVA_OPTS=""
|
||||
|
||||
EXPOSE ${SERVER_PORT}
|
||||
|
||||
ADD ./target/ruoyi-gen.jar ./app.jar
|
||||
|
||||
SHELL ["/bin/bash", "-c"]
|
||||
|
||||
ENTRYPOINT java -Djava.security.egd=file:/dev/./urandom -Dserver.port=${SERVER_PORT} ${JAVA_OPTS} -jar app.jar
|
118
ruoyi-modules/ruoyi-gen/pom.xml
Normal file
118
ruoyi-modules/ruoyi-gen/pom.xml
Normal file
@ -0,0 +1,118 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-modules</artifactId>
|
||||
<version>${revision}</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>ruoyi-gen</artifactId>
|
||||
|
||||
<description>
|
||||
ruoyi-gen代码生成
|
||||
</description>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-nacos</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Apache Velocity -->
|
||||
<dependency>
|
||||
<groupId>org.apache.velocity</groupId>
|
||||
<artifactId>velocity-engine-core</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- RuoYi Common Log -->
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-log</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-doc</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-web</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-mybatis</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-dubbo</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-tenant</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-security</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.anyline</groupId>
|
||||
<artifactId>anyline-environment-spring-data-jdbc</artifactId>
|
||||
<version>${anyline.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.anyline</groupId>
|
||||
<artifactId>anyline-data-jdbc-mysql</artifactId>
|
||||
<version>${anyline.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- anyline支持100+种类型数据库 添加对应的jdbc依赖与anyline对应数据库依赖包即可 -->
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>org.anyline</groupId>-->
|
||||
<!-- <artifactId>anyline-data-jdbc-oracle</artifactId>-->
|
||||
<!-- <version>${anyline.version}</version>-->
|
||||
<!-- </dependency>-->
|
||||
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>org.anyline</groupId>-->
|
||||
<!-- <artifactId>anyline-data-jdbc-postgresql</artifactId>-->
|
||||
<!-- <version>${anyline.version}</version>-->
|
||||
<!-- </dependency>-->
|
||||
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>org.anyline</groupId>-->
|
||||
<!-- <artifactId>anyline-data-jdbc-mssql</artifactId>-->
|
||||
<!-- <version>${anyline.version}</version>-->
|
||||
<!-- </dependency>-->
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>${project.artifactId}</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>repackage</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
@ -0,0 +1,22 @@
|
||||
package org.dromara.gen;
|
||||
|
||||
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.context.metrics.buffering.BufferingApplicationStartup;
|
||||
|
||||
/**
|
||||
* 代码生成
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@EnableDubbo
|
||||
@SpringBootApplication
|
||||
public class RuoYiGenApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication application = new SpringApplication(RuoYiGenApplication.class);
|
||||
application.setApplicationStartup(new BufferingApplicationStartup(2048));
|
||||
application.run(args);
|
||||
System.out.println("(♥◠‿◠)ノ゙ 代码生成模块启动成功 ლ(´ڡ`ლ)゙ ");
|
||||
}
|
||||
}
|
@ -0,0 +1,66 @@
|
||||
package org.dromara.gen.config;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 代码生成相关配置
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "gen")
|
||||
public class GenConfig {
|
||||
|
||||
/**
|
||||
* 作者
|
||||
*/
|
||||
public static String author;
|
||||
|
||||
/**
|
||||
* 生成包路径
|
||||
*/
|
||||
public static String packageName;
|
||||
|
||||
/**
|
||||
* 自动去除表前缀,默认是false
|
||||
*/
|
||||
public static boolean autoRemovePre;
|
||||
|
||||
/**
|
||||
* 表前缀(类名不会包含表前缀)
|
||||
*/
|
||||
public static String tablePrefix;
|
||||
|
||||
public static String getAuthor() {
|
||||
return author;
|
||||
}
|
||||
|
||||
public void setAuthor(String author) {
|
||||
GenConfig.author = author;
|
||||
}
|
||||
|
||||
public static String getPackageName() {
|
||||
return packageName;
|
||||
}
|
||||
|
||||
public void setPackageName(String packageName) {
|
||||
GenConfig.packageName = packageName;
|
||||
}
|
||||
|
||||
public static boolean getAutoRemovePre() {
|
||||
return autoRemovePre;
|
||||
}
|
||||
|
||||
public void setAutoRemovePre(boolean autoRemovePre) {
|
||||
GenConfig.autoRemovePre = autoRemovePre;
|
||||
}
|
||||
|
||||
public static String getTablePrefix() {
|
||||
return tablePrefix;
|
||||
}
|
||||
|
||||
public void setTablePrefix(String tablePrefix) {
|
||||
GenConfig.tablePrefix = tablePrefix;
|
||||
}
|
||||
}
|
@ -0,0 +1,105 @@
|
||||
package org.dromara.gen.config;
|
||||
|
||||
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
|
||||
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.anyline.data.datasource.DataSourceMonitor;
|
||||
import org.anyline.data.runtime.DataRuntime;
|
||||
import org.anyline.util.ConfigTable;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.DataSourceUtils;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DatabaseMetaData;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* anyline 适配 动态数据源改造
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class MyBatisDataSourceMonitor implements DataSourceMonitor {
|
||||
|
||||
public MyBatisDataSourceMonitor() {
|
||||
// 调整执行模式为自定义
|
||||
ConfigTable.KEEP_ADAPTER = 2;
|
||||
// 禁用缓存
|
||||
ConfigTable.METADATA_CACHE_SCOPE = 0;
|
||||
}
|
||||
|
||||
private final Map<String, String> features = new HashMap<>();
|
||||
|
||||
/**
|
||||
* 数据源特征 用来定准 adapter 包含数据库或JDBC协议关键字<br/>
|
||||
* 一般会通过 产品名_url 合成 如果返回null 上层方法会通过driver_产品名_url合成
|
||||
*
|
||||
* @param datasource 数据源
|
||||
* @return String 返回null由上层自动提取
|
||||
*/
|
||||
@Override
|
||||
public String feature(DataRuntime runtime, Object datasource) {
|
||||
String feature = null;
|
||||
if (datasource instanceof JdbcTemplate jdbc) {
|
||||
DataSource ds = jdbc.getDataSource();
|
||||
if (ds instanceof DynamicRoutingDataSource) {
|
||||
String key = DynamicDataSourceContextHolder.peek();
|
||||
feature = features.get(key);
|
||||
if (null == feature) {
|
||||
Connection con = null;
|
||||
try {
|
||||
con = DataSourceUtils.getConnection(ds);
|
||||
DatabaseMetaData meta = con.getMetaData();
|
||||
String url = meta.getURL();
|
||||
feature = meta.getDatabaseProductName().toLowerCase().replace(" ", "") + "_" + url;
|
||||
features.put(key, feature);
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
} finally {
|
||||
if (null != con && !DataSourceUtils.isConnectionTransactional(con, ds)) {
|
||||
DataSourceUtils.releaseConnection(con, ds);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return feature;
|
||||
}
|
||||
|
||||
/**
|
||||
* 数据源唯一标识 如果不实现则默认feature
|
||||
* @param datasource 数据源
|
||||
* @return String 返回null由上层自动提取
|
||||
*/
|
||||
@Override
|
||||
public String key(DataRuntime runtime, Object datasource) {
|
||||
if(datasource instanceof JdbcTemplate jdbc){
|
||||
DataSource ds = jdbc.getDataSource();
|
||||
if(ds instanceof DynamicRoutingDataSource){
|
||||
return DynamicDataSourceContextHolder.peek();
|
||||
}
|
||||
}
|
||||
return runtime.getKey();
|
||||
}
|
||||
|
||||
/**
|
||||
* ConfigTable.KEEP_ADAPTER=2 : 根据当前接口判断是否保持同一个数据源绑定同一个adapter<br/>
|
||||
* DynamicRoutingDataSource类型的返回false,因为同一个DynamicRoutingDataSource可能对应多类数据库, 如果项目中只有一种数据库 应该直接返回true
|
||||
*
|
||||
* @param datasource 数据源
|
||||
* @return boolean
|
||||
*/
|
||||
@Override
|
||||
public boolean keepAdapter(DataRuntime runtime, Object datasource) {
|
||||
if (datasource instanceof JdbcTemplate jdbc) {
|
||||
DataSource ds = jdbc.getDataSource();
|
||||
return !(ds instanceof DynamicRoutingDataSource);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,186 @@
|
||||
package org.dromara.gen.constant;
|
||||
|
||||
/**
|
||||
* 代码生成通用常量
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
public interface GenConstants {
|
||||
/**
|
||||
* 单表(增删改查)
|
||||
*/
|
||||
String TPL_CRUD = "crud";
|
||||
|
||||
/**
|
||||
* 树表(增删改查)
|
||||
*/
|
||||
String TPL_TREE = "tree";
|
||||
|
||||
/**
|
||||
* 树编码字段
|
||||
*/
|
||||
String TREE_CODE = "treeCode";
|
||||
|
||||
/**
|
||||
* 树父编码字段
|
||||
*/
|
||||
String TREE_PARENT_CODE = "treeParentCode";
|
||||
|
||||
/**
|
||||
* 树名称字段
|
||||
*/
|
||||
String TREE_NAME = "treeName";
|
||||
|
||||
/**
|
||||
* 上级菜单ID字段
|
||||
*/
|
||||
String PARENT_MENU_ID = "parentMenuId";
|
||||
|
||||
/**
|
||||
* 上级菜单名称字段
|
||||
*/
|
||||
String PARENT_MENU_NAME = "parentMenuName";
|
||||
|
||||
/**
|
||||
* 数据库字符串类型
|
||||
*/
|
||||
String[] COLUMNTYPE_STR = {"char", "varchar", "enum", "set", "nchar", "nvarchar", "varchar2", "nvarchar2"};
|
||||
|
||||
/**
|
||||
* 数据库文本类型
|
||||
*/
|
||||
String[] COLUMNTYPE_TEXT = {"tinytext", "text", "mediumtext", "longtext", "binary", "varbinary", "blob",
|
||||
"ntext", "image", "bytea"};
|
||||
|
||||
/**
|
||||
* 数据库时间类型
|
||||
*/
|
||||
String[] COLUMNTYPE_TIME = {"datetime", "time", "date", "timestamp", "year", "interval",
|
||||
"smalldatetime", "datetime2", "datetimeoffset", "timestamptz"};
|
||||
|
||||
/**
|
||||
* 数据库数字类型
|
||||
*/
|
||||
String[] COLUMNTYPE_NUMBER = {"tinyint", "smallint", "mediumint", "int", "int2", "int4", "int8", "number", "integer",
|
||||
"bit", "bigint", "float", "float4", "float8", "double", "decimal", "numeric", "real", "double precision",
|
||||
"smallserial", "serial", "bigserial", "money", "smallmoney"};
|
||||
|
||||
/**
|
||||
* BO对象 不需要添加字段
|
||||
*/
|
||||
String[] COLUMNNAME_NOT_ADD = {"create_dept", "create_by", "create_time", "del_flag", "update_by",
|
||||
"update_time", "version", "tenant_id"};
|
||||
|
||||
/**
|
||||
* BO对象 不需要编辑字段
|
||||
*/
|
||||
String[] COLUMNNAME_NOT_EDIT = {"create_dept", "create_by", "create_time", "del_flag", "update_by",
|
||||
"update_time", "version", "tenant_id"};
|
||||
|
||||
/**
|
||||
* VO对象 不需要返回字段
|
||||
*/
|
||||
String[] COLUMNNAME_NOT_LIST = {"create_dept", "create_by", "create_time", "del_flag", "update_by",
|
||||
"update_time", "version", "tenant_id"};
|
||||
|
||||
/**
|
||||
* BO对象 不需要查询字段
|
||||
*/
|
||||
String[] COLUMNNAME_NOT_QUERY = {"id", "create_dept", "create_by", "create_time", "del_flag", "update_by",
|
||||
"update_time", "remark", "version", "tenant_id"};
|
||||
|
||||
/**
|
||||
* Entity基类字段
|
||||
*/
|
||||
String[] BASE_ENTITY = {"createDept", "createBy", "createTime", "updateBy", "updateTime", "tenantId"};
|
||||
|
||||
/**
|
||||
* 文本框
|
||||
*/
|
||||
String HTML_INPUT = "input";
|
||||
|
||||
/**
|
||||
* 文本域
|
||||
*/
|
||||
String HTML_TEXTAREA = "textarea";
|
||||
|
||||
/**
|
||||
* 下拉框
|
||||
*/
|
||||
String HTML_SELECT = "select";
|
||||
|
||||
/**
|
||||
* 单选框
|
||||
*/
|
||||
String HTML_RADIO = "radio";
|
||||
|
||||
/**
|
||||
* 复选框
|
||||
*/
|
||||
String HTML_CHECKBOX = "checkbox";
|
||||
|
||||
/**
|
||||
* 日期控件
|
||||
*/
|
||||
String HTML_DATETIME = "datetime";
|
||||
|
||||
/**
|
||||
* 图片上传控件
|
||||
*/
|
||||
String HTML_IMAGE_UPLOAD = "imageUpload";
|
||||
|
||||
/**
|
||||
* 文件上传控件
|
||||
*/
|
||||
String HTML_FILE_UPLOAD = "fileUpload";
|
||||
|
||||
/**
|
||||
* 富文本控件
|
||||
*/
|
||||
String HTML_EDITOR = "editor";
|
||||
|
||||
/**
|
||||
* 字符串类型
|
||||
*/
|
||||
String TYPE_STRING = "String";
|
||||
|
||||
/**
|
||||
* 整型
|
||||
*/
|
||||
String TYPE_INTEGER = "Integer";
|
||||
|
||||
/**
|
||||
* 长整型
|
||||
*/
|
||||
String TYPE_LONG = "Long";
|
||||
|
||||
/**
|
||||
* 浮点型
|
||||
*/
|
||||
String TYPE_DOUBLE = "Double";
|
||||
|
||||
/**
|
||||
* 高精度计算类型
|
||||
*/
|
||||
String TYPE_BIGDECIMAL = "BigDecimal";
|
||||
|
||||
/**
|
||||
* 时间类型
|
||||
*/
|
||||
String TYPE_DATE = "Date";
|
||||
|
||||
/**
|
||||
* 模糊查询
|
||||
*/
|
||||
String QUERY_LIKE = "LIKE";
|
||||
|
||||
/**
|
||||
* 相等查询
|
||||
*/
|
||||
String QUERY_EQ = "EQ";
|
||||
|
||||
/**
|
||||
* 需要
|
||||
*/
|
||||
String REQUIRE = "1";
|
||||
}
|
@ -0,0 +1,214 @@
|
||||
package org.dromara.gen.controller;
|
||||
|
||||
import cn.dev33.satoken.annotation.SaCheckPermission;
|
||||
import cn.hutool.core.convert.Convert;
|
||||
import cn.hutool.core.io.IoUtil;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.dromara.common.core.domain.R;
|
||||
import org.dromara.common.log.annotation.Log;
|
||||
import org.dromara.common.log.enums.BusinessType;
|
||||
import org.dromara.common.mybatis.core.page.PageQuery;
|
||||
import org.dromara.common.mybatis.core.page.TableDataInfo;
|
||||
import org.dromara.common.mybatis.helper.DataBaseHelper;
|
||||
import org.dromara.common.web.core.BaseController;
|
||||
import org.dromara.gen.domain.GenTable;
|
||||
import org.dromara.gen.domain.GenTableColumn;
|
||||
import org.dromara.gen.service.IGenTableService;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 代码生成 操作处理
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Validated
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/gen")
|
||||
public class GenController extends BaseController {
|
||||
|
||||
private final IGenTableService genTableService;
|
||||
|
||||
/**
|
||||
* 查询代码生成列表
|
||||
*/
|
||||
@SaCheckPermission("tool:gen:list")
|
||||
@GetMapping("/list")
|
||||
public TableDataInfo<GenTable> genList(GenTable genTable, PageQuery pageQuery) {
|
||||
return genTableService.selectPageGenTableList(genTable, pageQuery);
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改代码生成业务
|
||||
*
|
||||
* @param tableId 表ID
|
||||
*/
|
||||
@SaCheckPermission("tool:gen:query")
|
||||
@GetMapping(value = "/{tableId}")
|
||||
public R<Map<String, Object>> getInfo(@PathVariable Long tableId) {
|
||||
GenTable table = genTableService.selectGenTableById(tableId);
|
||||
List<GenTable> tables = genTableService.selectGenTableAll();
|
||||
List<GenTableColumn> list = genTableService.selectGenTableColumnListByTableId(tableId);
|
||||
Map<String, Object> map = new HashMap<>(3);
|
||||
map.put("info", table);
|
||||
map.put("rows", list);
|
||||
map.put("tables", tables);
|
||||
return R.ok(map);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询数据库列表
|
||||
*/
|
||||
@SaCheckPermission("tool:gen:list")
|
||||
@GetMapping("/db/list")
|
||||
public TableDataInfo<GenTable> dataList(GenTable genTable, PageQuery pageQuery) {
|
||||
return genTableService.selectPageDbTableList(genTable, pageQuery);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询数据表字段列表
|
||||
*
|
||||
* @param tableId 表ID
|
||||
*/
|
||||
@SaCheckPermission("tool:gen:list")
|
||||
@GetMapping(value = "/column/{tableId}")
|
||||
public TableDataInfo<GenTableColumn> columnList(@PathVariable("tableId") Long tableId) {
|
||||
List<GenTableColumn> list = genTableService.selectGenTableColumnListByTableId(tableId);
|
||||
return TableDataInfo.build(list);
|
||||
}
|
||||
|
||||
/**
|
||||
* 导入表结构(保存)
|
||||
*
|
||||
* @param tables 表名串
|
||||
*/
|
||||
@SaCheckPermission("tool:gen:import")
|
||||
@Log(title = "代码生成", businessType = BusinessType.IMPORT)
|
||||
@PostMapping("/importTable")
|
||||
public R<Void> importTableSave(String tables, String dataName) {
|
||||
String[] tableNames = Convert.toStrArray(tables);
|
||||
// 查询表信息
|
||||
List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames, dataName);
|
||||
genTableService.importGenTable(tableList, dataName);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改保存代码生成业务
|
||||
*/
|
||||
@SaCheckPermission("tool:gen:edit")
|
||||
@Log(title = "代码生成", businessType = BusinessType.UPDATE)
|
||||
@PutMapping
|
||||
public R<Void> editSave(@Validated @RequestBody GenTable genTable) {
|
||||
genTableService.validateEdit(genTable);
|
||||
genTableService.updateGenTable(genTable);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除代码生成
|
||||
*
|
||||
* @param tableIds 表ID串
|
||||
*/
|
||||
@SaCheckPermission("tool:gen:remove")
|
||||
@Log(title = "代码生成", businessType = BusinessType.DELETE)
|
||||
@DeleteMapping("/{tableIds}")
|
||||
public R<Void> remove(@PathVariable Long[] tableIds) {
|
||||
genTableService.deleteGenTableByIds(tableIds);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
/**
|
||||
* 预览代码
|
||||
*
|
||||
* @param tableId 表ID
|
||||
*/
|
||||
@SaCheckPermission("tool:gen:preview")
|
||||
@GetMapping("/preview/{tableId}")
|
||||
public R<Map<String, String>> preview(@PathVariable("tableId") Long tableId) throws IOException {
|
||||
Map<String, String> dataMap = genTableService.previewCode(tableId);
|
||||
return R.ok(dataMap);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成代码(下载方式)
|
||||
*
|
||||
* @param tableId 表ID
|
||||
*/
|
||||
@SaCheckPermission("tool:gen:code")
|
||||
@Log(title = "代码生成", businessType = BusinessType.GENCODE)
|
||||
@GetMapping("/download/{tableId}")
|
||||
public void download(HttpServletResponse response, @PathVariable("tableId") Long tableId) throws IOException {
|
||||
byte[] data = genTableService.downloadCode(tableId);
|
||||
genCode(response, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成代码(自定义路径)
|
||||
*
|
||||
* @param tableId 表ID
|
||||
*/
|
||||
@SaCheckPermission("tool:gen:code")
|
||||
@Log(title = "代码生成", businessType = BusinessType.GENCODE)
|
||||
@GetMapping("/genCode/{tableId}")
|
||||
public R<Void> genCode(@PathVariable("tableId") Long tableId) {
|
||||
genTableService.generatorCode(tableId);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步数据库
|
||||
*
|
||||
* @param tableId 表ID
|
||||
*/
|
||||
@SaCheckPermission("tool:gen:edit")
|
||||
@Log(title = "代码生成", businessType = BusinessType.UPDATE)
|
||||
@GetMapping("/synchDb/{tableId}")
|
||||
public R<Void> synchDb(@PathVariable("tableId") Long tableId) {
|
||||
genTableService.synchDb(tableId);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量生成代码
|
||||
*
|
||||
* @param tableIdStr 表ID串
|
||||
*/
|
||||
@SaCheckPermission("tool:gen:code")
|
||||
@Log(title = "代码生成", businessType = BusinessType.GENCODE)
|
||||
@GetMapping("/batchGenCode")
|
||||
public void batchGenCode(HttpServletResponse response, String tableIdStr) throws IOException {
|
||||
String[] tableIds = Convert.toStrArray(tableIdStr);
|
||||
byte[] data = genTableService.downloadCode(tableIds);
|
||||
genCode(response, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成zip文件
|
||||
*/
|
||||
private void genCode(HttpServletResponse response, byte[] data) throws IOException {
|
||||
response.reset();
|
||||
response.addHeader("Access-Control-Allow-Origin", "*");
|
||||
response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
|
||||
response.setHeader("Content-Disposition", "attachment; filename=\"ruoyi.zip\"");
|
||||
response.addHeader("Content-Length", "" + data.length);
|
||||
response.setContentType("application/octet-stream; charset=UTF-8");
|
||||
IoUtil.write(response.getOutputStream(), false, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询数据源名称列表
|
||||
*/
|
||||
@SaCheckPermission("tool:gen:list")
|
||||
@GetMapping(value = "/getDataNames")
|
||||
public R<Object> getCurrentDataSourceNameList(){
|
||||
return R.ok(DataBaseHelper.getDataSourceNameList());
|
||||
}
|
||||
}
|
@ -0,0 +1,196 @@
|
||||
package org.dromara.gen.domain;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldStrategy;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import org.dromara.common.core.utils.StringUtils;
|
||||
import org.dromara.common.mybatis.core.domain.BaseEntity;
|
||||
import org.dromara.gen.constant.GenConstants;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 业务表 gen_table
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@TableName("gen_table")
|
||||
public class GenTable extends BaseEntity {
|
||||
|
||||
/**
|
||||
* 编号
|
||||
*/
|
||||
@TableId(value = "table_id")
|
||||
private Long tableId;
|
||||
|
||||
/**
|
||||
* 数据源名称
|
||||
*/
|
||||
@NotBlank(message = "数据源名称不能为空")
|
||||
private String dataName;
|
||||
|
||||
/**
|
||||
* 表名称
|
||||
*/
|
||||
@NotBlank(message = "表名称不能为空")
|
||||
private String tableName;
|
||||
|
||||
/**
|
||||
* 表描述
|
||||
*/
|
||||
@NotBlank(message = "表描述不能为空")
|
||||
private String tableComment;
|
||||
|
||||
/**
|
||||
* 关联父表的表名
|
||||
*/
|
||||
private String subTableName;
|
||||
|
||||
/**
|
||||
* 本表关联父表的外键名
|
||||
*/
|
||||
private String subTableFkName;
|
||||
|
||||
/**
|
||||
* 实体类名称(首字母大写)
|
||||
*/
|
||||
@NotBlank(message = "实体类名称不能为空")
|
||||
private String className;
|
||||
|
||||
/**
|
||||
* 使用的模板(crud单表操作 tree树表操作 sub主子表操作)
|
||||
*/
|
||||
private String tplCategory;
|
||||
|
||||
/**
|
||||
* 生成包路径
|
||||
*/
|
||||
@NotBlank(message = "生成包路径不能为空")
|
||||
private String packageName;
|
||||
|
||||
/**
|
||||
* 生成模块名
|
||||
*/
|
||||
@NotBlank(message = "生成模块名不能为空")
|
||||
private String moduleName;
|
||||
|
||||
/**
|
||||
* 生成业务名
|
||||
*/
|
||||
@NotBlank(message = "生成业务名不能为空")
|
||||
private String businessName;
|
||||
|
||||
/**
|
||||
* 生成功能名
|
||||
*/
|
||||
@NotBlank(message = "生成功能名不能为空")
|
||||
private String functionName;
|
||||
|
||||
/**
|
||||
* 生成作者
|
||||
*/
|
||||
@NotBlank(message = "作者不能为空")
|
||||
private String functionAuthor;
|
||||
|
||||
/**
|
||||
* 生成代码方式(0zip压缩包 1自定义路径)
|
||||
*/
|
||||
private String genType;
|
||||
|
||||
/**
|
||||
* 生成路径(不填默认项目路径)
|
||||
*/
|
||||
@TableField(updateStrategy = FieldStrategy.NOT_EMPTY)
|
||||
private String genPath;
|
||||
|
||||
/**
|
||||
* 主键信息
|
||||
*/
|
||||
@TableField(exist = false)
|
||||
private GenTableColumn pkColumn;
|
||||
|
||||
/**
|
||||
* 表列信息
|
||||
*/
|
||||
@Valid
|
||||
@TableField(exist = false)
|
||||
private List<GenTableColumn> columns;
|
||||
|
||||
/**
|
||||
* 其它生成选项
|
||||
*/
|
||||
private String options;
|
||||
|
||||
/**
|
||||
* 备注
|
||||
*/
|
||||
private String remark;
|
||||
|
||||
/**
|
||||
* 树编码字段
|
||||
*/
|
||||
@TableField(exist = false)
|
||||
private String treeCode;
|
||||
|
||||
/**
|
||||
* 树父编码字段
|
||||
*/
|
||||
@TableField(exist = false)
|
||||
private String treeParentCode;
|
||||
|
||||
/**
|
||||
* 树名称字段
|
||||
*/
|
||||
@TableField(exist = false)
|
||||
private String treeName;
|
||||
|
||||
/*
|
||||
* 菜单id列表
|
||||
*/
|
||||
@TableField(exist = false)
|
||||
private List<Long> menuIds;
|
||||
|
||||
/**
|
||||
* 上级菜单ID字段
|
||||
*/
|
||||
@TableField(exist = false)
|
||||
private Long parentMenuId;
|
||||
|
||||
/**
|
||||
* 上级菜单名称字段
|
||||
*/
|
||||
@TableField(exist = false)
|
||||
private String parentMenuName;
|
||||
|
||||
public boolean isTree() {
|
||||
return isTree(this.tplCategory);
|
||||
}
|
||||
|
||||
public static boolean isTree(String tplCategory) {
|
||||
return tplCategory != null && StringUtils.equals(GenConstants.TPL_TREE, tplCategory);
|
||||
}
|
||||
|
||||
public boolean isCrud() {
|
||||
return isCrud(this.tplCategory);
|
||||
}
|
||||
|
||||
public static boolean isCrud(String tplCategory) {
|
||||
return tplCategory != null && StringUtils.equals(GenConstants.TPL_CRUD, tplCategory);
|
||||
}
|
||||
|
||||
public boolean isSuperColumn(String javaField) {
|
||||
return isSuperColumn(this.tplCategory, javaField);
|
||||
}
|
||||
|
||||
public static boolean isSuperColumn(String tplCategory, String javaField) {
|
||||
return StringUtils.equalsAnyIgnoreCase(javaField, GenConstants.BASE_ENTITY);
|
||||
}
|
||||
}
|
@ -0,0 +1,221 @@
|
||||
package org.dromara.gen.domain;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldStrategy;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import org.apache.ibatis.type.JdbcType;
|
||||
import org.dromara.common.core.utils.StringUtils;
|
||||
import org.dromara.common.mybatis.core.domain.BaseEntity;
|
||||
|
||||
/**
|
||||
* 代码生成业务字段表 gen_table_column
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@TableName("gen_table_column")
|
||||
public class GenTableColumn extends BaseEntity {
|
||||
|
||||
/**
|
||||
* 编号
|
||||
*/
|
||||
@TableId(value = "column_id")
|
||||
private Long columnId;
|
||||
|
||||
/**
|
||||
* 归属表编号
|
||||
*/
|
||||
private Long tableId;
|
||||
|
||||
/**
|
||||
* 列名称
|
||||
*/
|
||||
private String columnName;
|
||||
|
||||
/**
|
||||
* 列描述
|
||||
*/
|
||||
@TableField(updateStrategy = FieldStrategy.ALWAYS, jdbcType = JdbcType.VARCHAR)
|
||||
private String columnComment;
|
||||
|
||||
/**
|
||||
* 列类型
|
||||
*/
|
||||
private String columnType;
|
||||
|
||||
/**
|
||||
* JAVA类型
|
||||
*/
|
||||
private String javaType;
|
||||
|
||||
/**
|
||||
* JAVA字段名
|
||||
*/
|
||||
@NotBlank(message = "Java属性不能为空")
|
||||
private String javaField;
|
||||
|
||||
/**
|
||||
* 是否主键(1是)
|
||||
*/
|
||||
@TableField(updateStrategy = FieldStrategy.ALWAYS, jdbcType = JdbcType.VARCHAR)
|
||||
private String isPk;
|
||||
|
||||
/**
|
||||
* 是否自增(1是)
|
||||
*/
|
||||
@TableField(updateStrategy = FieldStrategy.ALWAYS, jdbcType = JdbcType.VARCHAR)
|
||||
private String isIncrement;
|
||||
|
||||
/**
|
||||
* 是否必填(1是)
|
||||
*/
|
||||
@TableField(updateStrategy = FieldStrategy.ALWAYS, jdbcType = JdbcType.VARCHAR)
|
||||
private String isRequired;
|
||||
|
||||
/**
|
||||
* 是否为插入字段(1是)
|
||||
*/
|
||||
@TableField(updateStrategy = FieldStrategy.ALWAYS, jdbcType = JdbcType.VARCHAR)
|
||||
private String isInsert;
|
||||
|
||||
/**
|
||||
* 是否编辑字段(1是)
|
||||
*/
|
||||
@TableField(updateStrategy = FieldStrategy.ALWAYS, jdbcType = JdbcType.VARCHAR)
|
||||
private String isEdit;
|
||||
|
||||
/**
|
||||
* 是否列表字段(1是)
|
||||
*/
|
||||
@TableField(updateStrategy = FieldStrategy.ALWAYS, jdbcType = JdbcType.VARCHAR)
|
||||
private String isList;
|
||||
|
||||
/**
|
||||
* 是否查询字段(1是)
|
||||
*/
|
||||
@TableField(updateStrategy = FieldStrategy.ALWAYS, jdbcType = JdbcType.VARCHAR)
|
||||
private String isQuery;
|
||||
|
||||
/**
|
||||
* 查询方式(EQ等于、NE不等于、GT大于、LT小于、LIKE模糊、BETWEEN范围)
|
||||
*/
|
||||
private String queryType;
|
||||
|
||||
/**
|
||||
* 显示类型(input文本框、textarea文本域、select下拉框、checkbox复选框、radio单选框、datetime日期控件、image图片上传控件、upload文件上传控件、editor富文本控件)
|
||||
*/
|
||||
private String htmlType;
|
||||
|
||||
/**
|
||||
* 字典类型
|
||||
*/
|
||||
private String dictType;
|
||||
|
||||
/**
|
||||
* 排序
|
||||
*/
|
||||
private Integer sort;
|
||||
|
||||
public String getCapJavaField() {
|
||||
return StringUtils.capitalize(javaField);
|
||||
}
|
||||
|
||||
public boolean isPk() {
|
||||
return isPk(this.isPk);
|
||||
}
|
||||
|
||||
public boolean isPk(String isPk) {
|
||||
return isPk != null && StringUtils.equals("1", isPk);
|
||||
}
|
||||
|
||||
public boolean isIncrement() {
|
||||
return isIncrement(this.isIncrement);
|
||||
}
|
||||
|
||||
public boolean isIncrement(String isIncrement) {
|
||||
return isIncrement != null && StringUtils.equals("1", isIncrement);
|
||||
}
|
||||
|
||||
public boolean isRequired() {
|
||||
return isRequired(this.isRequired);
|
||||
}
|
||||
|
||||
public boolean isRequired(String isRequired) {
|
||||
return isRequired != null && StringUtils.equals("1", isRequired);
|
||||
}
|
||||
|
||||
public boolean isInsert() {
|
||||
return isInsert(this.isInsert);
|
||||
}
|
||||
|
||||
public boolean isInsert(String isInsert) {
|
||||
return isInsert != null && StringUtils.equals("1", isInsert);
|
||||
}
|
||||
|
||||
public boolean isEdit() {
|
||||
return isEdit(this.isEdit);
|
||||
}
|
||||
|
||||
public boolean isEdit(String isEdit) {
|
||||
return isEdit != null && StringUtils.equals("1", isEdit);
|
||||
}
|
||||
|
||||
public boolean isList() {
|
||||
return isList(this.isList);
|
||||
}
|
||||
|
||||
public boolean isList(String isList) {
|
||||
return isList != null && StringUtils.equals("1", isList);
|
||||
}
|
||||
|
||||
public boolean isQuery() {
|
||||
return isQuery(this.isQuery);
|
||||
}
|
||||
|
||||
public boolean isQuery(String isQuery) {
|
||||
return isQuery != null && StringUtils.equals("1", isQuery);
|
||||
}
|
||||
|
||||
public boolean isSuperColumn() {
|
||||
return isSuperColumn(this.javaField);
|
||||
}
|
||||
|
||||
public static boolean isSuperColumn(String javaField) {
|
||||
return StringUtils.equalsAnyIgnoreCase(javaField,
|
||||
// BaseEntity
|
||||
"createBy", "createTime", "updateBy", "updateTime",
|
||||
// TreeEntity
|
||||
"parentName", "parentId");
|
||||
}
|
||||
|
||||
public boolean isUsableColumn() {
|
||||
return isUsableColumn(javaField);
|
||||
}
|
||||
|
||||
public static boolean isUsableColumn(String javaField) {
|
||||
// isSuperColumn()中的名单用于避免生成多余Domain属性,若某些属性在生成页面时需要用到不能忽略,则放在此处白名单
|
||||
return StringUtils.equalsAnyIgnoreCase(javaField, "parentId", "orderNum", "remark");
|
||||
}
|
||||
|
||||
public String readConverterExp() {
|
||||
String remarks = StringUtils.substringBetween(this.columnComment, "(", ")");
|
||||
StringBuffer sb = new StringBuffer();
|
||||
if (StringUtils.isNotEmpty(remarks)) {
|
||||
for (String value : remarks.split(" ")) {
|
||||
if (StringUtils.isNotEmpty(value)) {
|
||||
Object startStr = value.subSequence(0, 1);
|
||||
String endStr = value.substring(1);
|
||||
sb.append(StringUtils.EMPTY).append(startStr).append("=").append(endStr).append(StringUtils.SEPARATOR);
|
||||
}
|
||||
}
|
||||
return sb.deleteCharAt(sb.length() - 1).toString();
|
||||
} else {
|
||||
return this.columnComment;
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package org.dromara.gen.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
|
||||
import org.dromara.common.mybatis.core.mapper.BaseMapperPlus;
|
||||
import org.dromara.gen.domain.GenTableColumn;
|
||||
|
||||
/**
|
||||
* 业务字段 数据层
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@InterceptorIgnore(dataPermission = "true", tenantLine = "true")
|
||||
public interface GenTableColumnMapper extends BaseMapperPlus<GenTableColumn, GenTableColumn> {
|
||||
|
||||
}
|
@ -0,0 +1,51 @@
|
||||
package org.dromara.gen.mapper;
|
||||
|
||||
import com.baomidou.dynamic.datasource.annotation.DS;
|
||||
import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
|
||||
import org.dromara.common.mybatis.core.mapper.BaseMapperPlus;
|
||||
import org.dromara.gen.domain.GenTable;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 业务 数据层
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@InterceptorIgnore(dataPermission = "true", tenantLine = "true")
|
||||
public interface GenTableMapper extends BaseMapperPlus<GenTable, GenTable> {
|
||||
|
||||
/**
|
||||
* 查询所有表信息
|
||||
*
|
||||
* @return 表信息集合
|
||||
*/
|
||||
List<GenTable> selectGenTableAll();
|
||||
|
||||
/**
|
||||
* 查询表ID业务信息
|
||||
*
|
||||
* @param id 业务ID
|
||||
* @return 业务信息
|
||||
*/
|
||||
GenTable selectGenTableById(Long id);
|
||||
|
||||
/**
|
||||
* 查询表名称业务信息
|
||||
*
|
||||
* @param tableName 表名称
|
||||
* @return 业务信息
|
||||
*/
|
||||
GenTable selectGenTableByName(String tableName);
|
||||
|
||||
/**
|
||||
* 查询指定数据源下的所有表名列表
|
||||
*
|
||||
* @param dataName 数据源名称,用于选择不同的数据源
|
||||
* @return 当前数据库中的表名列表
|
||||
*
|
||||
* @DS("") 使用默认数据源执行查询操作
|
||||
*/
|
||||
@DS("")
|
||||
List<String> selectTableNameList(String dataName);
|
||||
}
|
@ -0,0 +1,576 @@
|
||||
package org.dromara.gen.service;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.io.IoUtil;
|
||||
import cn.hutool.core.lang.Dict;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.baomidou.dynamic.datasource.annotation.DS;
|
||||
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.anyline.metadata.Column;
|
||||
import org.anyline.metadata.Table;
|
||||
import org.anyline.proxy.ServiceProxy;
|
||||
import org.apache.velocity.Template;
|
||||
import org.apache.velocity.VelocityContext;
|
||||
import org.apache.velocity.app.Velocity;
|
||||
import org.dromara.common.core.constant.Constants;
|
||||
import org.dromara.common.core.exception.ServiceException;
|
||||
import org.dromara.common.core.utils.SpringUtils;
|
||||
import org.dromara.common.core.utils.StreamUtils;
|
||||
import org.dromara.common.core.utils.StringUtils;
|
||||
import org.dromara.common.core.utils.file.FileUtils;
|
||||
import org.dromara.common.json.utils.JsonUtils;
|
||||
import org.dromara.common.mybatis.core.page.PageQuery;
|
||||
import org.dromara.common.mybatis.core.page.TableDataInfo;
|
||||
import org.dromara.gen.constant.GenConstants;
|
||||
import org.dromara.gen.domain.GenTable;
|
||||
import org.dromara.gen.domain.GenTableColumn;
|
||||
import org.dromara.gen.mapper.GenTableColumnMapper;
|
||||
import org.dromara.gen.mapper.GenTableMapper;
|
||||
import org.dromara.gen.util.GenUtils;
|
||||
import org.dromara.gen.util.VelocityInitializer;
|
||||
import org.dromara.gen.util.VelocityUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.StringWriter;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
/**
|
||||
* 业务 服务层实现
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
public class GenTableServiceImpl implements IGenTableService {
|
||||
|
||||
private final GenTableMapper baseMapper;
|
||||
private final GenTableColumnMapper genTableColumnMapper;
|
||||
private final IdentifierGenerator identifierGenerator;
|
||||
|
||||
private static final String[] TABLE_IGNORE = new String[]{"sj_", "act_", "flw_", "gen_"};
|
||||
|
||||
/**
|
||||
* 查询业务字段列表
|
||||
*
|
||||
* @param tableId 业务字段编号
|
||||
* @return 业务字段集合
|
||||
*/
|
||||
@Override
|
||||
public List<GenTableColumn> selectGenTableColumnListByTableId(Long tableId) {
|
||||
return genTableColumnMapper.selectList(new LambdaQueryWrapper<GenTableColumn>()
|
||||
.eq(GenTableColumn::getTableId, tableId)
|
||||
.orderByAsc(GenTableColumn::getSort));
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询业务信息
|
||||
*
|
||||
* @param id 业务ID
|
||||
* @return 业务信息
|
||||
*/
|
||||
@Override
|
||||
public GenTable selectGenTableById(Long id) {
|
||||
GenTable genTable = baseMapper.selectGenTableById(id);
|
||||
setTableFromOptions(genTable);
|
||||
return genTable;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableDataInfo<GenTable> selectPageGenTableList(GenTable genTable, PageQuery pageQuery) {
|
||||
Page<GenTable> page = baseMapper.selectPage(pageQuery.build(), this.buildGenTableQueryWrapper(genTable));
|
||||
return TableDataInfo.build(page);
|
||||
}
|
||||
|
||||
private QueryWrapper<GenTable> buildGenTableQueryWrapper(GenTable genTable) {
|
||||
Map<String, Object> params = genTable.getParams();
|
||||
QueryWrapper<GenTable> wrapper = Wrappers.query();
|
||||
wrapper
|
||||
.eq(StringUtils.isNotEmpty(genTable.getDataName()), "data_name", genTable.getDataName())
|
||||
.like(StringUtils.isNotBlank(genTable.getTableName()), "lower(table_name)", StringUtils.lowerCase(genTable.getTableName()))
|
||||
.like(StringUtils.isNotBlank(genTable.getTableComment()), "lower(table_comment)", StringUtils.lowerCase(genTable.getTableComment()))
|
||||
.between(params.get("beginTime") != null && params.get("endTime") != null,
|
||||
"create_time", params.get("beginTime"), params.get("endTime"))
|
||||
.orderByDesc("update_time");
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询数据库列表
|
||||
*
|
||||
* @param genTable 包含查询条件的GenTable对象
|
||||
* @param pageQuery 包含分页信息的PageQuery对象
|
||||
* @return 包含分页结果的TableDataInfo对象
|
||||
*/
|
||||
@DS("#genTable.dataName")
|
||||
@Override
|
||||
public TableDataInfo<GenTable> selectPageDbTableList(GenTable genTable, PageQuery pageQuery) {
|
||||
// 获取查询条件
|
||||
String tableName = genTable.getTableName();
|
||||
String tableComment = genTable.getTableComment();
|
||||
|
||||
LinkedHashMap<String, Table<?>> tablesMap = ServiceProxy.metadata().tables();
|
||||
if (CollUtil.isEmpty(tablesMap)) {
|
||||
return TableDataInfo.build();
|
||||
}
|
||||
List<String> tableNames = baseMapper.selectTableNameList(genTable.getDataName());
|
||||
String[] tableArrays;
|
||||
if (CollUtil.isNotEmpty(tableNames)) {
|
||||
tableArrays = tableNames.toArray(new String[0]);
|
||||
} else {
|
||||
tableArrays = new String[0];
|
||||
}
|
||||
// 过滤并转换表格数据
|
||||
List<GenTable> tables = tablesMap.values().stream()
|
||||
.filter(x -> !StringUtils.startWithAnyIgnoreCase(x.getName(), TABLE_IGNORE))
|
||||
.filter(x -> {
|
||||
if (CollUtil.isEmpty(tableNames)) {
|
||||
return true;
|
||||
}
|
||||
return !StringUtils.equalsAnyIgnoreCase(x.getName(), tableArrays);
|
||||
})
|
||||
.filter(x -> {
|
||||
boolean nameMatches = true;
|
||||
boolean commentMatches = true;
|
||||
// 进行表名称的模糊查询
|
||||
if (StringUtils.isNotBlank(tableName)) {
|
||||
nameMatches = StringUtils.containsIgnoreCase(x.getName(), tableName);
|
||||
}
|
||||
// 进行表描述的模糊查询
|
||||
if (StringUtils.isNotBlank(tableComment)) {
|
||||
commentMatches = StringUtils.containsIgnoreCase(x.getComment(), tableComment);
|
||||
}
|
||||
// 同时匹配名称和描述
|
||||
return nameMatches && commentMatches;
|
||||
})
|
||||
.map(x -> {
|
||||
GenTable gen = new GenTable();
|
||||
gen.setTableName(x.getName());
|
||||
gen.setTableComment(x.getComment());
|
||||
// postgresql的表元数据没有创建时间这个东西(好奇葩) 只能new Date代替
|
||||
gen.setCreateTime(ObjectUtil.defaultIfNull(x.getCreateTime(), new Date()));
|
||||
gen.setUpdateTime(x.getUpdateTime());
|
||||
return gen;
|
||||
}).sorted(Comparator.comparing(GenTable::getCreateTime).reversed())
|
||||
.toList();
|
||||
return TableDataInfo.build(tables, pageQuery.build());
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询据库列表
|
||||
*
|
||||
* @param tableNames 表名称组
|
||||
* @param dataName 数据源名称
|
||||
* @return 数据库表集合
|
||||
*/
|
||||
@DS("#dataName")
|
||||
@Override
|
||||
public List<GenTable> selectDbTableListByNames(String[] tableNames, String dataName) {
|
||||
Set<String> tableNameSet = new HashSet<>(List.of(tableNames));
|
||||
LinkedHashMap<String, Table<?>> tablesMap = ServiceProxy.metadata().tables();
|
||||
|
||||
if (CollUtil.isEmpty(tablesMap)) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
List<Table<?>> tableList = tablesMap.values().stream()
|
||||
.filter(x -> !StringUtils.startWithAnyIgnoreCase(x.getName(), TABLE_IGNORE))
|
||||
.filter(x -> tableNameSet.contains(x.getName())).toList();
|
||||
|
||||
if (CollUtil.isEmpty(tableList)) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
return tableList.stream().map(x -> {
|
||||
GenTable gen = new GenTable();
|
||||
gen.setDataName(dataName);
|
||||
gen.setTableName(x.getName());
|
||||
gen.setTableComment(x.getComment());
|
||||
gen.setCreateTime(x.getCreateTime());
|
||||
gen.setUpdateTime(x.getUpdateTime());
|
||||
return gen;
|
||||
}).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询所有表信息
|
||||
*
|
||||
* @return 表信息集合
|
||||
*/
|
||||
@Override
|
||||
public List<GenTable> selectGenTableAll() {
|
||||
return baseMapper.selectGenTableAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改业务
|
||||
*
|
||||
* @param genTable 业务信息
|
||||
*/
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
@Override
|
||||
public void updateGenTable(GenTable genTable) {
|
||||
String options = JsonUtils.toJsonString(genTable.getParams());
|
||||
genTable.setOptions(options);
|
||||
int row = baseMapper.updateById(genTable);
|
||||
if (row > 0) {
|
||||
for (GenTableColumn cenTableColumn : genTable.getColumns()) {
|
||||
genTableColumnMapper.updateById(cenTableColumn);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除业务对象
|
||||
*
|
||||
* @param tableIds 需要删除的数据ID
|
||||
*/
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
@Override
|
||||
public void deleteGenTableByIds(Long[] tableIds) {
|
||||
List<Long> ids = Arrays.asList(tableIds);
|
||||
baseMapper.deleteByIds(ids);
|
||||
genTableColumnMapper.delete(new LambdaQueryWrapper<GenTableColumn>().in(GenTableColumn::getTableId, ids));
|
||||
}
|
||||
|
||||
/**
|
||||
* 导入表结构
|
||||
*
|
||||
* @param tableList 导入表列表
|
||||
* @param dataName 数据源名称
|
||||
*/
|
||||
@DSTransactional
|
||||
@Override
|
||||
public void importGenTable(List<GenTable> tableList, String dataName) {
|
||||
try {
|
||||
for (GenTable table : tableList) {
|
||||
String tableName = table.getTableName();
|
||||
GenUtils.initTable(table);
|
||||
table.setDataName(dataName);
|
||||
int row = baseMapper.insert(table);
|
||||
if (row > 0) {
|
||||
// 保存列信息
|
||||
List<GenTableColumn> genTableColumns = SpringUtils.getAopProxy(this).selectDbTableColumnsByName(tableName, dataName);
|
||||
List<GenTableColumn> saveColumns = new ArrayList<>();
|
||||
for (GenTableColumn column : genTableColumns) {
|
||||
GenUtils.initColumnField(column, table);
|
||||
saveColumns.add(column);
|
||||
}
|
||||
if (CollUtil.isNotEmpty(saveColumns)) {
|
||||
genTableColumnMapper.insertBatch(saveColumns);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new ServiceException("导入失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据表名称查询列信息
|
||||
*
|
||||
* @param tableName 表名称
|
||||
* @param dataName 数据源名称
|
||||
* @return 列信息
|
||||
*/
|
||||
@DS("#dataName")
|
||||
@Override
|
||||
public List<GenTableColumn> selectDbTableColumnsByName(String tableName, String dataName) {
|
||||
Table<?> table = ServiceProxy.metadata().table(tableName);
|
||||
if (ObjectUtil.isNull(table)) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
LinkedHashMap<String, Column> columns = table.getColumns();
|
||||
List<GenTableColumn> tableColumns = new ArrayList<>();
|
||||
columns.forEach((columnName, column) -> {
|
||||
GenTableColumn tableColumn = new GenTableColumn();
|
||||
tableColumn.setIsPk(column.isPrimaryKey() ? "1" : "0");
|
||||
tableColumn.setColumnName(column.getName());
|
||||
tableColumn.setColumnComment(column.getComment());
|
||||
tableColumn.setColumnType(column.getOriginType().toLowerCase());
|
||||
tableColumn.setSort(column.getPosition());
|
||||
tableColumn.setIsRequired(column.isNullable() ? "1" : "0");
|
||||
tableColumn.setIsIncrement(column.isAutoIncrement() ? "1" : "0");
|
||||
tableColumns.add(tableColumn);
|
||||
});
|
||||
return tableColumns;
|
||||
}
|
||||
|
||||
/**
|
||||
* 预览代码
|
||||
*
|
||||
* @param tableId 表编号
|
||||
* @return 预览数据列表
|
||||
*/
|
||||
@Override
|
||||
public Map<String, String> previewCode(Long tableId) {
|
||||
Map<String, String> dataMap = new LinkedHashMap<>();
|
||||
// 查询表信息
|
||||
GenTable table = baseMapper.selectGenTableById(tableId);
|
||||
List<Long> menuIds = new ArrayList<>();
|
||||
for (int i = 0; i < 6; i++) {
|
||||
menuIds.add(identifierGenerator.nextId(null).longValue());
|
||||
}
|
||||
table.setMenuIds(menuIds);
|
||||
// 设置主键列信息
|
||||
setPkColumn(table);
|
||||
VelocityInitializer.initVelocity();
|
||||
|
||||
VelocityContext context = VelocityUtils.prepareContext(table);
|
||||
|
||||
// 获取模板列表
|
||||
List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
|
||||
for (String template : templates) {
|
||||
// 渲染模板
|
||||
StringWriter sw = new StringWriter();
|
||||
Template tpl = Velocity.getTemplate(template, Constants.UTF8);
|
||||
tpl.merge(context, sw);
|
||||
dataMap.put(template, sw.toString());
|
||||
}
|
||||
return dataMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成代码(下载方式)
|
||||
*
|
||||
* @param tableId 表名称
|
||||
* @return 数据
|
||||
*/
|
||||
@Override
|
||||
public byte[] downloadCode(Long tableId) {
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
ZipOutputStream zip = new ZipOutputStream(outputStream);
|
||||
generatorCode(tableId, zip);
|
||||
IoUtil.close(zip);
|
||||
return outputStream.toByteArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成代码(自定义路径)
|
||||
*
|
||||
* @param tableId 表名称
|
||||
*/
|
||||
@Override
|
||||
public void generatorCode(Long tableId) {
|
||||
// 查询表信息
|
||||
GenTable table = baseMapper.selectGenTableById(tableId);
|
||||
// 设置主键列信息
|
||||
setPkColumn(table);
|
||||
|
||||
VelocityInitializer.initVelocity();
|
||||
|
||||
VelocityContext context = VelocityUtils.prepareContext(table);
|
||||
|
||||
// 获取模板列表
|
||||
List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
|
||||
for (String template : templates) {
|
||||
if (!StringUtils.containsAny(template, "sql.vm", "api.ts.vm", "types.ts.vm", "index.vue.vm", "index-tree.vue.vm")) {
|
||||
// 渲染模板
|
||||
StringWriter sw = new StringWriter();
|
||||
Template tpl = Velocity.getTemplate(template, Constants.UTF8);
|
||||
tpl.merge(context, sw);
|
||||
try {
|
||||
String path = getGenPath(table, template);
|
||||
FileUtils.writeUtf8String(sw.toString(), path);
|
||||
} catch (Exception e) {
|
||||
throw new ServiceException("渲染模板失败,表名:" + table.getTableName());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步数据库
|
||||
*
|
||||
* @param tableId 表名称
|
||||
*/
|
||||
@DSTransactional
|
||||
@Override
|
||||
public void synchDb(Long tableId) {
|
||||
GenTable table = baseMapper.selectGenTableById(tableId);
|
||||
List<GenTableColumn> tableColumns = table.getColumns();
|
||||
Map<String, GenTableColumn> tableColumnMap = StreamUtils.toIdentityMap(tableColumns, GenTableColumn::getColumnName);
|
||||
|
||||
List<GenTableColumn> dbTableColumns = SpringUtils.getAopProxy(this).selectDbTableColumnsByName(table.getTableName(), table.getDataName());
|
||||
if (CollUtil.isEmpty(dbTableColumns)) {
|
||||
throw new ServiceException("同步数据失败,原表结构不存在");
|
||||
}
|
||||
List<String> dbTableColumnNames = StreamUtils.toList(dbTableColumns, GenTableColumn::getColumnName);
|
||||
|
||||
List<GenTableColumn> saveColumns = new ArrayList<>();
|
||||
dbTableColumns.forEach(column -> {
|
||||
GenUtils.initColumnField(column, table);
|
||||
if (tableColumnMap.containsKey(column.getColumnName())) {
|
||||
GenTableColumn prevColumn = tableColumnMap.get(column.getColumnName());
|
||||
column.setColumnId(prevColumn.getColumnId());
|
||||
if (column.isList()) {
|
||||
// 如果是列表,继续保留查询方式/字典类型选项
|
||||
column.setDictType(prevColumn.getDictType());
|
||||
column.setQueryType(prevColumn.getQueryType());
|
||||
}
|
||||
if (StringUtils.isNotEmpty(prevColumn.getIsRequired()) && !column.isPk()
|
||||
&& (column.isInsert() || column.isEdit())
|
||||
&& ((column.isUsableColumn()) || (!column.isSuperColumn()))) {
|
||||
// 如果是(新增/修改&非主键/非忽略及父属性),继续保留必填/显示类型选项
|
||||
column.setIsRequired(prevColumn.getIsRequired());
|
||||
column.setHtmlType(prevColumn.getHtmlType());
|
||||
}
|
||||
}
|
||||
saveColumns.add(column);
|
||||
});
|
||||
if (CollUtil.isNotEmpty(saveColumns)) {
|
||||
genTableColumnMapper.insertOrUpdateBatch(saveColumns);
|
||||
}
|
||||
List<GenTableColumn> delColumns = StreamUtils.filter(tableColumns, column -> !dbTableColumnNames.contains(column.getColumnName()));
|
||||
if (CollUtil.isNotEmpty(delColumns)) {
|
||||
List<Long> ids = StreamUtils.toList(delColumns, GenTableColumn::getColumnId);
|
||||
if (CollUtil.isNotEmpty(ids)) {
|
||||
genTableColumnMapper.deleteByIds(ids);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量生成代码(下载方式)
|
||||
*
|
||||
* @param tableIds 表ID数组
|
||||
* @return 数据
|
||||
*/
|
||||
@Override
|
||||
public byte[] downloadCode(String[] tableIds) {
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
ZipOutputStream zip = new ZipOutputStream(outputStream);
|
||||
for (String tableId : tableIds) {
|
||||
generatorCode(Long.parseLong(tableId), zip);
|
||||
}
|
||||
IoUtil.close(zip);
|
||||
return outputStream.toByteArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询表信息并生成代码
|
||||
*/
|
||||
private void generatorCode(Long tableId, ZipOutputStream zip) {
|
||||
// 查询表信息
|
||||
GenTable table = baseMapper.selectGenTableById(tableId);
|
||||
List<Long> menuIds = new ArrayList<>();
|
||||
for (int i = 0; i < 6; i++) {
|
||||
menuIds.add(identifierGenerator.nextId(null).longValue());
|
||||
}
|
||||
table.setMenuIds(menuIds);
|
||||
// 设置主键列信息
|
||||
setPkColumn(table);
|
||||
|
||||
VelocityInitializer.initVelocity();
|
||||
|
||||
VelocityContext context = VelocityUtils.prepareContext(table);
|
||||
|
||||
// 获取模板列表
|
||||
List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
|
||||
for (String template : templates) {
|
||||
// 渲染模板
|
||||
StringWriter sw = new StringWriter();
|
||||
Template tpl = Velocity.getTemplate(template, Constants.UTF8);
|
||||
tpl.merge(context, sw);
|
||||
try {
|
||||
// 添加到zip
|
||||
zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template, table)));
|
||||
IoUtil.write(zip, StandardCharsets.UTF_8, false, sw.toString());
|
||||
IoUtil.close(sw);
|
||||
zip.flush();
|
||||
zip.closeEntry();
|
||||
} catch (IOException e) {
|
||||
log.error("渲染模板失败,表名:" + table.getTableName(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改保存参数校验
|
||||
*
|
||||
* @param genTable 业务信息
|
||||
*/
|
||||
@Override
|
||||
public void validateEdit(GenTable genTable) {
|
||||
if (GenConstants.TPL_TREE.equals(genTable.getTplCategory())) {
|
||||
String options = JsonUtils.toJsonString(genTable.getParams());
|
||||
Dict paramsObj = JsonUtils.parseMap(options);
|
||||
if (StringUtils.isEmpty(paramsObj.getStr(GenConstants.TREE_CODE))) {
|
||||
throw new ServiceException("树编码字段不能为空");
|
||||
} else if (StringUtils.isEmpty(paramsObj.getStr(GenConstants.TREE_PARENT_CODE))) {
|
||||
throw new ServiceException("树父编码字段不能为空");
|
||||
} else if (StringUtils.isEmpty(paramsObj.getStr(GenConstants.TREE_NAME))) {
|
||||
throw new ServiceException("树名称字段不能为空");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置主键列信息
|
||||
*
|
||||
* @param table 业务表信息
|
||||
*/
|
||||
public void setPkColumn(GenTable table) {
|
||||
for (GenTableColumn column : table.getColumns()) {
|
||||
if (column.isPk()) {
|
||||
table.setPkColumn(column);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (ObjectUtil.isNull(table.getPkColumn())) {
|
||||
table.setPkColumn(table.getColumns().get(0));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置代码生成其他选项值
|
||||
*
|
||||
* @param genTable 设置后的生成对象
|
||||
*/
|
||||
public void setTableFromOptions(GenTable genTable) {
|
||||
Dict paramsObj = JsonUtils.parseMap(genTable.getOptions());
|
||||
if (ObjectUtil.isNotNull(paramsObj)) {
|
||||
String treeCode = paramsObj.getStr(GenConstants.TREE_CODE);
|
||||
String treeParentCode = paramsObj.getStr(GenConstants.TREE_PARENT_CODE);
|
||||
String treeName = paramsObj.getStr(GenConstants.TREE_NAME);
|
||||
Long parentMenuId = paramsObj.getLong(GenConstants.PARENT_MENU_ID);
|
||||
String parentMenuName = paramsObj.getStr(GenConstants.PARENT_MENU_NAME);
|
||||
|
||||
genTable.setTreeCode(treeCode);
|
||||
genTable.setTreeParentCode(treeParentCode);
|
||||
genTable.setTreeName(treeName);
|
||||
genTable.setParentMenuId(parentMenuId);
|
||||
genTable.setParentMenuName(parentMenuName);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取代码生成地址
|
||||
*
|
||||
* @param table 业务表信息
|
||||
* @param template 模板文件路径
|
||||
* @return 生成地址
|
||||
*/
|
||||
public static String getGenPath(GenTable table, String template) {
|
||||
String genPath = table.getGenPath();
|
||||
if (StringUtils.equals(genPath, "/")) {
|
||||
return System.getProperty("user.dir") + File.separator + "src" + File.separator + VelocityUtils.getFileName(template, table);
|
||||
}
|
||||
return genPath + File.separator + VelocityUtils.getFileName(template, table);
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,141 @@
|
||||
package org.dromara.gen.service;
|
||||
|
||||
import org.dromara.common.mybatis.core.page.PageQuery;
|
||||
import org.dromara.common.mybatis.core.page.TableDataInfo;
|
||||
import org.dromara.gen.domain.GenTable;
|
||||
import org.dromara.gen.domain.GenTableColumn;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 业务 服务层
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
public interface IGenTableService {
|
||||
|
||||
/**
|
||||
* 查询业务字段列表
|
||||
*
|
||||
* @param tableId 业务字段编号
|
||||
* @return 业务字段集合
|
||||
*/
|
||||
List<GenTableColumn> selectGenTableColumnListByTableId(Long tableId);
|
||||
|
||||
/**
|
||||
* 查询业务列表
|
||||
*
|
||||
* @param genTable 业务信息
|
||||
* @return 业务集合
|
||||
*/
|
||||
TableDataInfo<GenTable> selectPageGenTableList(GenTable genTable, PageQuery pageQuery);
|
||||
|
||||
/**
|
||||
* 查询据库列表
|
||||
*
|
||||
* @param genTable 业务信息
|
||||
* @return 数据库表集合
|
||||
*/
|
||||
TableDataInfo<GenTable> selectPageDbTableList(GenTable genTable, PageQuery pageQuery);
|
||||
|
||||
/**
|
||||
* 查询据库列表
|
||||
*
|
||||
* @param tableNames 表名称组
|
||||
* @param dataName 数据源名称
|
||||
* @return 数据库表集合
|
||||
*/
|
||||
List<GenTable> selectDbTableListByNames(String[] tableNames, String dataName);
|
||||
|
||||
/**
|
||||
* 查询所有表信息
|
||||
*
|
||||
* @return 表信息集合
|
||||
*/
|
||||
List<GenTable> selectGenTableAll();
|
||||
|
||||
/**
|
||||
* 查询业务信息
|
||||
*
|
||||
* @param id 业务ID
|
||||
* @return 业务信息
|
||||
*/
|
||||
GenTable selectGenTableById(Long id);
|
||||
|
||||
/**
|
||||
* 修改业务
|
||||
*
|
||||
* @param genTable 业务信息
|
||||
*/
|
||||
void updateGenTable(GenTable genTable);
|
||||
|
||||
/**
|
||||
* 删除业务信息
|
||||
*
|
||||
* @param tableIds 需要删除的表数据ID
|
||||
*/
|
||||
void deleteGenTableByIds(Long[] tableIds);
|
||||
|
||||
/**
|
||||
* 导入表结构
|
||||
*
|
||||
* @param tableList 导入表列表
|
||||
* @param dataName 数据源名称
|
||||
*/
|
||||
void importGenTable(List<GenTable> tableList, String dataName);
|
||||
|
||||
/**
|
||||
* 根据表名称查询列信息
|
||||
*
|
||||
* @param tableName 表名称
|
||||
* @param dataName 数据源名称
|
||||
* @return 列信息
|
||||
*/
|
||||
List<GenTableColumn> selectDbTableColumnsByName(String tableName, String dataName);
|
||||
|
||||
/**
|
||||
* 预览代码
|
||||
*
|
||||
* @param tableId 表编号
|
||||
* @return 预览数据列表
|
||||
*/
|
||||
Map<String, String> previewCode(Long tableId);
|
||||
|
||||
/**
|
||||
* 生成代码(下载方式)
|
||||
*
|
||||
* @param tableId 表名称
|
||||
* @return 数据
|
||||
*/
|
||||
byte[] downloadCode(Long tableId);
|
||||
|
||||
/**
|
||||
* 生成代码(自定义路径)
|
||||
*
|
||||
* @param tableId 表名称
|
||||
*/
|
||||
void generatorCode(Long tableId);
|
||||
|
||||
/**
|
||||
* 同步数据库
|
||||
*
|
||||
* @param tableId 表名称
|
||||
*/
|
||||
void synchDb(Long tableId);
|
||||
|
||||
/**
|
||||
* 批量生成代码(下载方式)
|
||||
*
|
||||
* @param tableIds 表ID数组
|
||||
* @return 数据
|
||||
*/
|
||||
byte[] downloadCode(String[] tableIds);
|
||||
|
||||
/**
|
||||
* 修改保存参数校验
|
||||
*
|
||||
* @param genTable 业务信息
|
||||
*/
|
||||
void validateEdit(GenTable genTable);
|
||||
}
|
@ -0,0 +1,219 @@
|
||||
package org.dromara.gen.util;
|
||||
|
||||
import lombok.AccessLevel;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.apache.commons.lang3.RegExUtils;
|
||||
import org.dromara.common.core.utils.StringUtils;
|
||||
import org.dromara.gen.config.GenConfig;
|
||||
import org.dromara.gen.constant.GenConstants;
|
||||
import org.dromara.gen.domain.GenTable;
|
||||
import org.dromara.gen.domain.GenTableColumn;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* 代码生成器 工具类
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@NoArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
public class GenUtils {
|
||||
|
||||
/**
|
||||
* 初始化表信息
|
||||
*/
|
||||
public static void initTable(GenTable genTable) {
|
||||
genTable.setClassName(convertClassName(genTable.getTableName()));
|
||||
genTable.setPackageName(GenConfig.getPackageName());
|
||||
genTable.setModuleName(getModuleName(GenConfig.getPackageName()));
|
||||
genTable.setBusinessName(getBusinessName(genTable.getTableName()));
|
||||
genTable.setFunctionName(replaceText(genTable.getTableComment()));
|
||||
genTable.setFunctionAuthor(GenConfig.getAuthor());
|
||||
genTable.setCreateTime(null);
|
||||
genTable.setUpdateTime(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化列属性字段
|
||||
*/
|
||||
public static void initColumnField(GenTableColumn column, GenTable table) {
|
||||
String dataType = getDbType(column.getColumnType());
|
||||
// 统一转小写 避免有些数据库默认大写问题 如果需要特别书写方式 请在实体类增加注解标注别名
|
||||
String columnName = column.getColumnName().toLowerCase();
|
||||
column.setTableId(table.getTableId());
|
||||
column.setCreateTime(null);
|
||||
column.setUpdateTime(null);
|
||||
// 设置java字段名
|
||||
column.setJavaField(StringUtils.toCamelCase(columnName));
|
||||
// 设置默认类型
|
||||
column.setJavaType(GenConstants.TYPE_STRING);
|
||||
column.setQueryType(GenConstants.QUERY_EQ);
|
||||
|
||||
if (arraysContains(GenConstants.COLUMNTYPE_STR, dataType) || arraysContains(GenConstants.COLUMNTYPE_TEXT, dataType)) {
|
||||
// 字符串长度超过500设置为文本域
|
||||
Integer columnLength = getColumnLength(column.getColumnType());
|
||||
String htmlType = columnLength >= 500 || arraysContains(GenConstants.COLUMNTYPE_TEXT, dataType) ? GenConstants.HTML_TEXTAREA : GenConstants.HTML_INPUT;
|
||||
column.setHtmlType(htmlType);
|
||||
} else if (arraysContains(GenConstants.COLUMNTYPE_TIME, dataType)) {
|
||||
column.setJavaType(GenConstants.TYPE_DATE);
|
||||
column.setHtmlType(GenConstants.HTML_DATETIME);
|
||||
} else if (arraysContains(GenConstants.COLUMNTYPE_NUMBER, dataType)) {
|
||||
column.setHtmlType(GenConstants.HTML_INPUT);
|
||||
// 数据库的数字字段与java不匹配 且很多数据库的数字字段很模糊 例如oracle只有number没有细分
|
||||
// 所以默认数字类型全为Long可在界面上自行编辑想要的类型 有什么特殊需求也可以在这里特殊处理
|
||||
column.setJavaType(GenConstants.TYPE_LONG);
|
||||
}
|
||||
|
||||
// BO对象 默认插入勾选
|
||||
if (!arraysContains(GenConstants.COLUMNNAME_NOT_ADD, columnName) && !column.isPk()) {
|
||||
column.setIsInsert(GenConstants.REQUIRE);
|
||||
}
|
||||
// BO对象 默认编辑勾选
|
||||
if (!arraysContains(GenConstants.COLUMNNAME_NOT_EDIT, columnName)) {
|
||||
column.setIsEdit(GenConstants.REQUIRE);
|
||||
}
|
||||
// VO对象 默认返回勾选
|
||||
if (!arraysContains(GenConstants.COLUMNNAME_NOT_LIST, columnName)) {
|
||||
column.setIsList(GenConstants.REQUIRE);
|
||||
}
|
||||
// BO对象 默认查询勾选
|
||||
if (!arraysContains(GenConstants.COLUMNNAME_NOT_QUERY, columnName) && !column.isPk()) {
|
||||
column.setIsQuery(GenConstants.REQUIRE);
|
||||
}
|
||||
|
||||
// 查询字段类型
|
||||
if (StringUtils.endsWithIgnoreCase(columnName, "name")) {
|
||||
column.setQueryType(GenConstants.QUERY_LIKE);
|
||||
}
|
||||
// 状态字段设置单选框
|
||||
if (StringUtils.endsWithIgnoreCase(columnName, "status")) {
|
||||
column.setHtmlType(GenConstants.HTML_RADIO);
|
||||
}
|
||||
// 类型&性别字段设置下拉框
|
||||
else if (StringUtils.endsWithIgnoreCase(columnName, "type")
|
||||
|| StringUtils.endsWithIgnoreCase(columnName, "sex")) {
|
||||
column.setHtmlType(GenConstants.HTML_SELECT);
|
||||
}
|
||||
// 图片字段设置图片上传控件
|
||||
else if (StringUtils.endsWithIgnoreCase(columnName, "image")) {
|
||||
column.setHtmlType(GenConstants.HTML_IMAGE_UPLOAD);
|
||||
}
|
||||
// 文件字段设置文件上传控件
|
||||
else if (StringUtils.endsWithIgnoreCase(columnName, "file")) {
|
||||
column.setHtmlType(GenConstants.HTML_FILE_UPLOAD);
|
||||
}
|
||||
// 内容字段设置富文本控件
|
||||
else if (StringUtils.endsWithIgnoreCase(columnName, "content")) {
|
||||
column.setHtmlType(GenConstants.HTML_EDITOR);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验数组是否包含指定值
|
||||
*
|
||||
* @param arr 数组
|
||||
* @param targetValue 值
|
||||
* @return 是否包含
|
||||
*/
|
||||
public static boolean arraysContains(String[] arr, String targetValue) {
|
||||
return Arrays.asList(arr).contains(targetValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取模块名
|
||||
*
|
||||
* @param packageName 包名
|
||||
* @return 模块名
|
||||
*/
|
||||
public static String getModuleName(String packageName) {
|
||||
int lastIndex = packageName.lastIndexOf(".");
|
||||
int nameLength = packageName.length();
|
||||
return StringUtils.substring(packageName, lastIndex + 1, nameLength);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取业务名
|
||||
*
|
||||
* @param tableName 表名
|
||||
* @return 业务名
|
||||
*/
|
||||
public static String getBusinessName(String tableName) {
|
||||
int firstIndex = tableName.indexOf("_");
|
||||
int nameLength = tableName.length();
|
||||
String businessName = StringUtils.substring(tableName, firstIndex + 1, nameLength);
|
||||
businessName = StringUtils.toCamelCase(businessName);
|
||||
return businessName;
|
||||
}
|
||||
|
||||
/**
|
||||
* 表名转换成Java类名
|
||||
*
|
||||
* @param tableName 表名称
|
||||
* @return 类名
|
||||
*/
|
||||
public static String convertClassName(String tableName) {
|
||||
boolean autoRemovePre = GenConfig.getAutoRemovePre();
|
||||
String tablePrefix = GenConfig.getTablePrefix();
|
||||
if (autoRemovePre && StringUtils.isNotEmpty(tablePrefix)) {
|
||||
String[] searchList = StringUtils.split(tablePrefix, StringUtils.SEPARATOR);
|
||||
tableName = replaceFirst(tableName, searchList);
|
||||
}
|
||||
return StringUtils.convertToCamelCase(tableName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量替换前缀
|
||||
*
|
||||
* @param replacementm 替换值
|
||||
* @param searchList 替换列表
|
||||
*/
|
||||
public static String replaceFirst(String replacementm, String[] searchList) {
|
||||
String text = replacementm;
|
||||
for (String searchString : searchList) {
|
||||
if (replacementm.startsWith(searchString)) {
|
||||
text = replacementm.replaceFirst(searchString, StringUtils.EMPTY);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
/**
|
||||
* 关键字替换
|
||||
*
|
||||
* @param text 需要被替换的名字
|
||||
* @return 替换后的名字
|
||||
*/
|
||||
public static String replaceText(String text) {
|
||||
return RegExUtils.replaceAll(text, "(?:表|若依)", "");
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取数据库类型字段
|
||||
*
|
||||
* @param columnType 列类型
|
||||
* @return 截取后的列类型
|
||||
*/
|
||||
public static String getDbType(String columnType) {
|
||||
if (StringUtils.indexOf(columnType, "(") > 0) {
|
||||
return StringUtils.substringBefore(columnType, "(");
|
||||
} else {
|
||||
return columnType;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取字段长度
|
||||
*
|
||||
* @param columnType 列类型
|
||||
* @return 截取后的列类型
|
||||
*/
|
||||
public static Integer getColumnLength(String columnType) {
|
||||
if (StringUtils.indexOf(columnType, "(") > 0) {
|
||||
String length = StringUtils.substringBetween(columnType, "(", ")");
|
||||
return Integer.valueOf(length);
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,35 @@
|
||||
package org.dromara.gen.util;
|
||||
|
||||
import lombok.AccessLevel;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.apache.velocity.app.Velocity;
|
||||
import org.dromara.common.core.constant.Constants;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
* VelocityEngine工厂
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@NoArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
public class VelocityInitializer {
|
||||
|
||||
/**
|
||||
* 初始化vm方法
|
||||
*/
|
||||
public static void initVelocity() {
|
||||
Properties p = new Properties();
|
||||
try {
|
||||
// 加载classpath目录下的vm文件
|
||||
p.setProperty("resource.loader.file.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
|
||||
// 定义字符集
|
||||
p.setProperty(Velocity.INPUT_ENCODING, Constants.UTF8);
|
||||
// 初始化Velocity引擎,指定配置Properties
|
||||
Velocity.init(p);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,339 @@
|
||||
package org.dromara.gen.util;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.convert.Convert;
|
||||
import cn.hutool.core.lang.Dict;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.apache.velocity.VelocityContext;
|
||||
import org.dromara.common.core.utils.DateUtils;
|
||||
import org.dromara.common.core.utils.StringUtils;
|
||||
import org.dromara.common.json.utils.JsonUtils;
|
||||
import org.dromara.common.mybatis.helper.DataBaseHelper;
|
||||
import org.dromara.gen.constant.GenConstants;
|
||||
import org.dromara.gen.domain.GenTable;
|
||||
import org.dromara.gen.domain.GenTableColumn;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 模板处理工具类
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@NoArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
public class VelocityUtils {
|
||||
|
||||
/**
|
||||
* 项目空间路径
|
||||
*/
|
||||
private static final String PROJECT_PATH = "main/java";
|
||||
|
||||
/**
|
||||
* mybatis空间路径
|
||||
*/
|
||||
private static final String MYBATIS_PATH = "main/resources/mapper";
|
||||
|
||||
/**
|
||||
* 默认上级菜单,系统工具
|
||||
*/
|
||||
private static final String DEFAULT_PARENT_MENU_ID = "3";
|
||||
|
||||
/**
|
||||
* 设置模板变量信息
|
||||
*
|
||||
* @return 模板列表
|
||||
*/
|
||||
public static VelocityContext prepareContext(GenTable genTable) {
|
||||
String moduleName = genTable.getModuleName();
|
||||
String businessName = genTable.getBusinessName();
|
||||
String packageName = genTable.getPackageName();
|
||||
String tplCategory = genTable.getTplCategory();
|
||||
String functionName = genTable.getFunctionName();
|
||||
|
||||
VelocityContext velocityContext = new VelocityContext();
|
||||
velocityContext.put("tplCategory", genTable.getTplCategory());
|
||||
velocityContext.put("tableName", genTable.getTableName());
|
||||
velocityContext.put("functionName", StringUtils.isNotEmpty(functionName) ? functionName : "【请填写功能名称】");
|
||||
velocityContext.put("ClassName", genTable.getClassName());
|
||||
velocityContext.put("className", StringUtils.uncapitalize(genTable.getClassName()));
|
||||
velocityContext.put("moduleName", genTable.getModuleName());
|
||||
velocityContext.put("BusinessName", StringUtils.capitalize(genTable.getBusinessName()));
|
||||
velocityContext.put("businessName", genTable.getBusinessName());
|
||||
velocityContext.put("basePackage", getPackagePrefix(packageName));
|
||||
velocityContext.put("packageName", packageName);
|
||||
velocityContext.put("author", genTable.getFunctionAuthor());
|
||||
velocityContext.put("datetime", DateUtils.getDate());
|
||||
velocityContext.put("pkColumn", genTable.getPkColumn());
|
||||
velocityContext.put("importList", getImportList(genTable));
|
||||
velocityContext.put("permissionPrefix", getPermissionPrefix(moduleName, businessName));
|
||||
velocityContext.put("columns", genTable.getColumns());
|
||||
velocityContext.put("table", genTable);
|
||||
velocityContext.put("dicts", getDicts(genTable));
|
||||
setMenuVelocityContext(velocityContext, genTable);
|
||||
if (GenConstants.TPL_TREE.equals(tplCategory)) {
|
||||
setTreeVelocityContext(velocityContext, genTable);
|
||||
}
|
||||
return velocityContext;
|
||||
}
|
||||
|
||||
public static void setMenuVelocityContext(VelocityContext context, GenTable genTable) {
|
||||
String options = genTable.getOptions();
|
||||
Dict paramsObj = JsonUtils.parseMap(options);
|
||||
String parentMenuId = getParentMenuId(paramsObj);
|
||||
context.put("parentMenuId", parentMenuId);
|
||||
}
|
||||
|
||||
public static void setTreeVelocityContext(VelocityContext context, GenTable genTable) {
|
||||
String options = genTable.getOptions();
|
||||
Dict paramsObj = JsonUtils.parseMap(options);
|
||||
String treeCode = getTreecode(paramsObj);
|
||||
String treeParentCode = getTreeParentCode(paramsObj);
|
||||
String treeName = getTreeName(paramsObj);
|
||||
|
||||
context.put("treeCode", treeCode);
|
||||
context.put("treeParentCode", treeParentCode);
|
||||
context.put("treeName", treeName);
|
||||
context.put("expandColumn", getExpandColumn(genTable));
|
||||
if (paramsObj.containsKey(GenConstants.TREE_PARENT_CODE)) {
|
||||
context.put("tree_parent_code", paramsObj.get(GenConstants.TREE_PARENT_CODE));
|
||||
}
|
||||
if (paramsObj.containsKey(GenConstants.TREE_NAME)) {
|
||||
context.put("tree_name", paramsObj.get(GenConstants.TREE_NAME));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取模板信息
|
||||
*
|
||||
* @return 模板列表
|
||||
*/
|
||||
public static List<String> getTemplateList(String tplCategory) {
|
||||
List<String> templates = new ArrayList<>();
|
||||
templates.add("vm/java/domain.java.vm");
|
||||
templates.add("vm/java/vo.java.vm");
|
||||
templates.add("vm/java/bo.java.vm");
|
||||
templates.add("vm/java/mapper.java.vm");
|
||||
templates.add("vm/java/service.java.vm");
|
||||
templates.add("vm/java/serviceImpl.java.vm");
|
||||
templates.add("vm/java/controller.java.vm");
|
||||
templates.add("vm/xml/mapper.xml.vm");
|
||||
if (DataBaseHelper.isOracle()) {
|
||||
templates.add("vm/sql/oracle/sql.vm");
|
||||
} else if (DataBaseHelper.isPostgerSql()) {
|
||||
templates.add("vm/sql/postgres/sql.vm");
|
||||
} else {
|
||||
templates.add("vm/sql/sql.vm");
|
||||
}
|
||||
templates.add("vm/ts/api.ts.vm");
|
||||
templates.add("vm/ts/types.ts.vm");
|
||||
if (GenConstants.TPL_CRUD.equals(tplCategory)) {
|
||||
templates.add("vm/vue/index.vue.vm");
|
||||
} else if (GenConstants.TPL_TREE.equals(tplCategory)) {
|
||||
templates.add("vm/vue/index-tree.vue.vm");
|
||||
}
|
||||
return templates;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件名
|
||||
*/
|
||||
public static String getFileName(String template, GenTable genTable) {
|
||||
// 文件名称
|
||||
String fileName = "";
|
||||
// 包路径
|
||||
String packageName = genTable.getPackageName();
|
||||
// 模块名
|
||||
String moduleName = genTable.getModuleName();
|
||||
// 大写类名
|
||||
String className = genTable.getClassName();
|
||||
// 业务名称
|
||||
String businessName = genTable.getBusinessName();
|
||||
|
||||
String javaPath = PROJECT_PATH + "/" + StringUtils.replace(packageName, ".", "/");
|
||||
String mybatisPath = MYBATIS_PATH + "/" + moduleName;
|
||||
String vuePath = "vue";
|
||||
|
||||
if (template.contains("domain.java.vm")) {
|
||||
fileName = StringUtils.format("{}/domain/{}.java", javaPath, className);
|
||||
}
|
||||
if (template.contains("vo.java.vm")) {
|
||||
fileName = StringUtils.format("{}/domain/vo/{}Vo.java", javaPath, className);
|
||||
}
|
||||
if (template.contains("bo.java.vm")) {
|
||||
fileName = StringUtils.format("{}/domain/bo/{}Bo.java", javaPath, className);
|
||||
}
|
||||
if (template.contains("mapper.java.vm")) {
|
||||
fileName = StringUtils.format("{}/mapper/{}Mapper.java", javaPath, className);
|
||||
} else if (template.contains("service.java.vm")) {
|
||||
fileName = StringUtils.format("{}/service/I{}Service.java", javaPath, className);
|
||||
} else if (template.contains("serviceImpl.java.vm")) {
|
||||
fileName = StringUtils.format("{}/service/impl/{}ServiceImpl.java", javaPath, className);
|
||||
} else if (template.contains("controller.java.vm")) {
|
||||
fileName = StringUtils.format("{}/controller/{}Controller.java", javaPath, className);
|
||||
} else if (template.contains("mapper.xml.vm")) {
|
||||
fileName = StringUtils.format("{}/{}Mapper.xml", mybatisPath, className);
|
||||
} else if (template.contains("sql.vm")) {
|
||||
fileName = businessName + "Menu.sql";
|
||||
} else if (template.contains("api.ts.vm")) {
|
||||
fileName = StringUtils.format("{}/api/{}/{}/index.ts", vuePath, moduleName, businessName);
|
||||
} else if (template.contains("types.ts.vm")) {
|
||||
fileName = StringUtils.format("{}/api/{}/{}/types.ts", vuePath, moduleName, businessName);
|
||||
} else if (template.contains("index.vue.vm")) {
|
||||
fileName = StringUtils.format("{}/views/{}/{}/index.vue", vuePath, moduleName, businessName);
|
||||
} else if (template.contains("index-tree.vue.vm")) {
|
||||
fileName = StringUtils.format("{}/views/{}/{}/index.vue", vuePath, moduleName, businessName);
|
||||
}
|
||||
return fileName;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取包前缀
|
||||
*
|
||||
* @param packageName 包名称
|
||||
* @return 包前缀名称
|
||||
*/
|
||||
public static String getPackagePrefix(String packageName) {
|
||||
int lastIndex = packageName.lastIndexOf(".");
|
||||
return StringUtils.substring(packageName, 0, lastIndex);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据列类型获取导入包
|
||||
*
|
||||
* @param genTable 业务表对象
|
||||
* @return 返回需要导入的包列表
|
||||
*/
|
||||
public static HashSet<String> getImportList(GenTable genTable) {
|
||||
List<GenTableColumn> columns = genTable.getColumns();
|
||||
HashSet<String> importList = new HashSet<>();
|
||||
for (GenTableColumn column : columns) {
|
||||
if (!column.isSuperColumn() && GenConstants.TYPE_DATE.equals(column.getJavaType())) {
|
||||
importList.add("java.util.Date");
|
||||
importList.add("com.fasterxml.jackson.annotation.JsonFormat");
|
||||
} else if (!column.isSuperColumn() && GenConstants.TYPE_BIGDECIMAL.equals(column.getJavaType())) {
|
||||
importList.add("java.math.BigDecimal");
|
||||
} else if (!column.isSuperColumn() && "imageUpload".equals(column.getHtmlType())) {
|
||||
importList.add("org.dromara.common.translation.annotation.Translation");
|
||||
importList.add("org.dromara.common.translation.constant.TransConstant");
|
||||
}
|
||||
}
|
||||
return importList;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据列类型获取字典组
|
||||
*
|
||||
* @param genTable 业务表对象
|
||||
* @return 返回字典组
|
||||
*/
|
||||
public static String getDicts(GenTable genTable) {
|
||||
List<GenTableColumn> columns = genTable.getColumns();
|
||||
Set<String> dicts = new HashSet<>();
|
||||
addDicts(dicts, columns);
|
||||
return StringUtils.join(dicts, ", ");
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加字典列表
|
||||
*
|
||||
* @param dicts 字典列表
|
||||
* @param columns 列集合
|
||||
*/
|
||||
public static void addDicts(Set<String> dicts, List<GenTableColumn> columns) {
|
||||
for (GenTableColumn column : columns) {
|
||||
if (!column.isSuperColumn() && StringUtils.isNotEmpty(column.getDictType()) && StringUtils.equalsAny(
|
||||
column.getHtmlType(),
|
||||
new String[] { GenConstants.HTML_SELECT, GenConstants.HTML_RADIO, GenConstants.HTML_CHECKBOX })) {
|
||||
dicts.add("'" + column.getDictType() + "'");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取权限前缀
|
||||
*
|
||||
* @param moduleName 模块名称
|
||||
* @param businessName 业务名称
|
||||
* @return 返回权限前缀
|
||||
*/
|
||||
public static String getPermissionPrefix(String moduleName, String businessName) {
|
||||
return StringUtils.format("{}:{}", moduleName, businessName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取上级菜单ID字段
|
||||
*
|
||||
* @param paramsObj 生成其他选项
|
||||
* @return 上级菜单ID字段
|
||||
*/
|
||||
public static String getParentMenuId(Dict paramsObj) {
|
||||
if (CollUtil.isNotEmpty(paramsObj) && paramsObj.containsKey(GenConstants.PARENT_MENU_ID)
|
||||
&& StringUtils.isNotEmpty(paramsObj.getStr(GenConstants.PARENT_MENU_ID))) {
|
||||
return paramsObj.getStr(GenConstants.PARENT_MENU_ID);
|
||||
}
|
||||
return DEFAULT_PARENT_MENU_ID;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取树编码
|
||||
*
|
||||
* @param paramsObj 生成其他选项
|
||||
* @return 树编码
|
||||
*/
|
||||
public static String getTreecode(Map<String, Object> paramsObj) {
|
||||
if (CollUtil.isNotEmpty(paramsObj) && paramsObj.containsKey(GenConstants.TREE_CODE)) {
|
||||
return StringUtils.toCamelCase(Convert.toStr(paramsObj.get(GenConstants.TREE_CODE)));
|
||||
}
|
||||
return StringUtils.EMPTY;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取树父编码
|
||||
*
|
||||
* @param paramsObj 生成其他选项
|
||||
* @return 树父编码
|
||||
*/
|
||||
public static String getTreeParentCode(Dict paramsObj) {
|
||||
if (CollUtil.isNotEmpty(paramsObj) && paramsObj.containsKey(GenConstants.TREE_PARENT_CODE)) {
|
||||
return StringUtils.toCamelCase(paramsObj.getStr(GenConstants.TREE_PARENT_CODE));
|
||||
}
|
||||
return StringUtils.EMPTY;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取树名称
|
||||
*
|
||||
* @param paramsObj 生成其他选项
|
||||
* @return 树名称
|
||||
*/
|
||||
public static String getTreeName(Dict paramsObj) {
|
||||
if (CollUtil.isNotEmpty(paramsObj) && paramsObj.containsKey(GenConstants.TREE_NAME)) {
|
||||
return StringUtils.toCamelCase(paramsObj.getStr(GenConstants.TREE_NAME));
|
||||
}
|
||||
return StringUtils.EMPTY;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取需要在哪一列上面显示展开按钮
|
||||
*
|
||||
* @param genTable 业务表对象
|
||||
* @return 展开按钮列序号
|
||||
*/
|
||||
public static int getExpandColumn(GenTable genTable) {
|
||||
String options = genTable.getOptions();
|
||||
Dict paramsObj = JsonUtils.parseMap(options);
|
||||
String treeName = paramsObj.getStr(GenConstants.TREE_NAME);
|
||||
int num = 0;
|
||||
for (GenTableColumn column : genTable.getColumns()) {
|
||||
if (column.isList()) {
|
||||
num++;
|
||||
String columnName = column.getColumnName();
|
||||
if (columnName.equals(treeName)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return num;
|
||||
}
|
||||
}
|
34
ruoyi-modules/ruoyi-gen/src/main/resources/application.yml
Normal file
34
ruoyi-modules/ruoyi-gen/src/main/resources/application.yml
Normal file
@ -0,0 +1,34 @@
|
||||
# Tomcat
|
||||
server:
|
||||
port: 9202
|
||||
|
||||
# Spring
|
||||
spring:
|
||||
application:
|
||||
# 应用名称
|
||||
name: ruoyi-gen
|
||||
profiles:
|
||||
# 环境配置
|
||||
active: @profiles.active@
|
||||
|
||||
--- # nacos 配置
|
||||
spring:
|
||||
cloud:
|
||||
nacos:
|
||||
# nacos 服务地址
|
||||
server-addr: @nacos.server@
|
||||
username: @nacos.username@
|
||||
password: @nacos.password@
|
||||
discovery:
|
||||
# 注册组
|
||||
group: @nacos.discovery.group@
|
||||
namespace: ${spring.profiles.active}
|
||||
config:
|
||||
# 配置组
|
||||
group: @nacos.config.group@
|
||||
namespace: ${spring.profiles.active}
|
||||
config:
|
||||
import:
|
||||
- optional:nacos:application-common.yml
|
||||
- optional:nacos:datasource.yml
|
||||
- optional:nacos:${spring.application.name}.yml
|
10
ruoyi-modules/ruoyi-gen/src/main/resources/banner.txt
Normal file
10
ruoyi-modules/ruoyi-gen/src/main/resources/banner.txt
Normal file
@ -0,0 +1,10 @@
|
||||
Spring Boot Version: ${spring-boot.version}
|
||||
Spring Application Name: ${spring.application.name}
|
||||
_
|
||||
(_)
|
||||
_ __ _ _ ___ _ _ _ ______ __ _ ___ _ __
|
||||
| '__|| | | | / _ \ | | | || ||______| / _` | / _ \| '_ \
|
||||
| | | |_| || (_) || |_| || | | (_| || __/| | | |
|
||||
|_| \__,_| \___/ \__, ||_| \__, | \___||_| |_|
|
||||
__/ | __/ |
|
||||
|___/ |___/
|
25
ruoyi-modules/ruoyi-gen/src/main/resources/logback-plus.xml
Normal file
25
ruoyi-modules/ruoyi-gen/src/main/resources/logback-plus.xml
Normal file
@ -0,0 +1,25 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration scan="true" scanPeriod="60 seconds" debug="false">
|
||||
<!-- 日志存放路径 -->
|
||||
<property name="log.path" value="logs/${project.artifactId}"/>
|
||||
<!-- 日志输出格式 -->
|
||||
<property name="console.log.pattern"
|
||||
value="%cyan(%d{yyyy-MM-dd HH:mm:ss}) %green([%thread]) %highlight(%-5level) %boldMagenta(%logger{36}%n) - %msg%n"/>
|
||||
|
||||
<!-- 控制台输出 -->
|
||||
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>${console.log.pattern}</pattern>
|
||||
<charset>utf-8</charset>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<include resource="logback-common.xml" />
|
||||
|
||||
<include resource="logback-logstash.xml" />
|
||||
|
||||
<!--系统操作日志-->
|
||||
<root level="info">
|
||||
<appender-ref ref="console"/>
|
||||
</root>
|
||||
</configuration>
|
@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<!DOCTYPE mapper
|
||||
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="org.dromara.gen.mapper.GenTableColumnMapper">
|
||||
|
||||
<resultMap type="org.dromara.gen.domain.GenTableColumn" id="GenTableColumnResult">
|
||||
</resultMap>
|
||||
|
||||
</mapper>
|
@ -0,0 +1,42 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<!DOCTYPE mapper
|
||||
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="org.dromara.gen.mapper.GenTableMapper">
|
||||
|
||||
<!-- 多结构嵌套自动映射需带上每个实体的主键id 否则映射会失败 -->
|
||||
<resultMap type="org.dromara.gen.domain.GenTable" id="GenTableResult">
|
||||
<id property="tableId" column="table_id" />
|
||||
<collection property="columns" javaType="java.util.List" resultMap="GenTableColumnResult" />
|
||||
</resultMap>
|
||||
|
||||
<resultMap type="org.dromara.gen.domain.GenTableColumn" id="GenTableColumnResult">
|
||||
<id property="columnId" column="column_id"/>
|
||||
</resultMap>
|
||||
|
||||
<sql id="genSelect">
|
||||
SELECT t.table_id, t.data_name, t.table_name, t.table_comment, t.sub_table_name, t.sub_table_fk_name, t.class_name, t.tpl_category, t.package_name, t.module_name, t.business_name, t.function_name, t.function_author, t.gen_type, t.gen_path, t.options, t.remark,
|
||||
c.column_id, c.column_name, c.column_comment, c.column_type, c.java_type, c.java_field, c.is_pk, c.is_increment, c.is_required, c.is_insert, c.is_edit, c.is_list, c.is_query, c.query_type, c.html_type, c.dict_type, c.sort
|
||||
FROM gen_table t
|
||||
LEFT JOIN gen_table_column c ON t.table_id = c.table_id
|
||||
</sql>
|
||||
|
||||
<select id="selectGenTableById" parameterType="Long" resultMap="GenTableResult">
|
||||
<include refid="genSelect"/>
|
||||
where t.table_id = #{tableId} order by c.sort
|
||||
</select>
|
||||
|
||||
<select id="selectGenTableByName" parameterType="String" resultMap="GenTableResult">
|
||||
<include refid="genSelect"/>
|
||||
where t.table_name = #{tableName} order by c.sort
|
||||
</select>
|
||||
|
||||
<select id="selectGenTableAll" parameterType="String" resultMap="GenTableResult">
|
||||
<include refid="genSelect"/>
|
||||
order by c.sort
|
||||
</select>
|
||||
|
||||
<select id="selectTableNameList" resultType="java.lang.String">
|
||||
select table_name from gen_table where data_name = #{dataName,jdbcType=VARCHAR}
|
||||
</select>
|
||||
</mapper>
|
@ -0,0 +1,3 @@
|
||||
java包使用 `.` 分割 resource 目录使用 `/` 分割
|
||||
<br>
|
||||
此文件目的 防止文件夹粘连找不到 `xml` 文件
|
@ -0,0 +1,50 @@
|
||||
package ${packageName}.domain.bo;
|
||||
|
||||
import ${packageName}.domain.${ClassName};
|
||||
import org.dromara.common.mybatis.core.domain.BaseEntity;
|
||||
import org.dromara.common.core.validate.AddGroup;
|
||||
import org.dromara.common.core.validate.EditGroup;
|
||||
import io.github.linpeilie.annotations.AutoMapper;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import jakarta.validation.constraints.*;
|
||||
#foreach ($import in $importList)
|
||||
import ${import};
|
||||
#end
|
||||
|
||||
/**
|
||||
* ${functionName}业务对象 ${tableName}
|
||||
*
|
||||
* @author ${author}
|
||||
* @date ${datetime}
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@AutoMapper(target = ${ClassName}.class, reverseConvertGenerate = false)
|
||||
public class ${ClassName}Bo extends BaseEntity {
|
||||
|
||||
#foreach ($column in $columns)
|
||||
#if(!$table.isSuperColumn($column.javaField) && ($column.query || $column.insert || $column.edit))
|
||||
/**
|
||||
* $column.columnComment
|
||||
*/
|
||||
#if($column.insert && $column.edit)
|
||||
#set($Group="AddGroup.class, EditGroup.class")
|
||||
#elseif($column.insert)
|
||||
#set($Group="AddGroup.class")
|
||||
#elseif($column.edit)
|
||||
#set($Group="EditGroup.class")
|
||||
#end
|
||||
#if($column.required)
|
||||
#if($column.javaType == 'String')
|
||||
@NotBlank(message = "$column.columnComment不能为空", groups = { $Group })
|
||||
#else
|
||||
@NotNull(message = "$column.columnComment不能为空", groups = { $Group })
|
||||
#end
|
||||
#end
|
||||
private $column.javaType $column.javaField;
|
||||
|
||||
#end
|
||||
#end
|
||||
|
||||
}
|
@ -0,0 +1,116 @@
|
||||
package ${packageName}.controller;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import jakarta.validation.constraints.*;
|
||||
import cn.dev33.satoken.annotation.SaCheckPermission;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.dromara.common.idempotent.annotation.RepeatSubmit;
|
||||
import org.dromara.common.log.annotation.Log;
|
||||
import org.dromara.common.web.core.BaseController;
|
||||
import org.dromara.common.mybatis.core.page.PageQuery;
|
||||
import org.dromara.common.core.domain.R;
|
||||
import org.dromara.common.core.validate.AddGroup;
|
||||
import org.dromara.common.core.validate.EditGroup;
|
||||
import org.dromara.common.log.enums.BusinessType;
|
||||
import org.dromara.common.excel.utils.ExcelUtil;
|
||||
import ${packageName}.domain.vo.${ClassName}Vo;
|
||||
import ${packageName}.domain.bo.${ClassName}Bo;
|
||||
import ${packageName}.service.I${ClassName}Service;
|
||||
#if($table.crud)
|
||||
import org.dromara.common.mybatis.core.page.TableDataInfo;
|
||||
#elseif($table.tree)
|
||||
#end
|
||||
|
||||
/**
|
||||
* ${functionName}
|
||||
* 前端访问路由地址为:/${moduleName}/${businessName}
|
||||
*
|
||||
* @author ${author}
|
||||
* @date ${datetime}
|
||||
*/
|
||||
@Validated
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/${businessName}")
|
||||
public class ${ClassName}Controller extends BaseController {
|
||||
|
||||
private final I${ClassName}Service ${className}Service;
|
||||
|
||||
/**
|
||||
* 查询${functionName}列表
|
||||
*/
|
||||
@SaCheckPermission("${permissionPrefix}:list")
|
||||
@GetMapping("/list")
|
||||
#if($table.crud)
|
||||
public TableDataInfo<${ClassName}Vo> list(${ClassName}Bo bo, PageQuery pageQuery) {
|
||||
return ${className}Service.queryPageList(bo, pageQuery);
|
||||
}
|
||||
#elseif($table.tree)
|
||||
public R<List<${ClassName}Vo>> list(${ClassName}Bo bo) {
|
||||
List<${ClassName}Vo> list = ${className}Service.queryList(bo);
|
||||
return R.ok(list);
|
||||
}
|
||||
#end
|
||||
|
||||
/**
|
||||
* 导出${functionName}列表
|
||||
*/
|
||||
@SaCheckPermission("${permissionPrefix}:export")
|
||||
@Log(title = "${functionName}", businessType = BusinessType.EXPORT)
|
||||
@PostMapping("/export")
|
||||
public void export(${ClassName}Bo bo, HttpServletResponse response) {
|
||||
List<${ClassName}Vo> list = ${className}Service.queryList(bo);
|
||||
ExcelUtil.exportExcel(list, "${functionName}", ${ClassName}Vo.class, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取${functionName}详细信息
|
||||
*
|
||||
* @param ${pkColumn.javaField} 主键
|
||||
*/
|
||||
@SaCheckPermission("${permissionPrefix}:query")
|
||||
@GetMapping("/{${pkColumn.javaField}}")
|
||||
public R<${ClassName}Vo> getInfo(@NotNull(message = "主键不能为空")
|
||||
@PathVariable("${pkColumn.javaField}") ${pkColumn.javaType} ${pkColumn.javaField}) {
|
||||
return R.ok(${className}Service.queryById(${pkColumn.javaField}));
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增${functionName}
|
||||
*/
|
||||
@SaCheckPermission("${permissionPrefix}:add")
|
||||
@Log(title = "${functionName}", businessType = BusinessType.INSERT)
|
||||
@RepeatSubmit()
|
||||
@PostMapping()
|
||||
public R<Void> add(@Validated(AddGroup.class) @RequestBody ${ClassName}Bo bo) {
|
||||
return toAjax(${className}Service.insertByBo(bo));
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改${functionName}
|
||||
*/
|
||||
@SaCheckPermission("${permissionPrefix}:edit")
|
||||
@Log(title = "${functionName}", businessType = BusinessType.UPDATE)
|
||||
@RepeatSubmit()
|
||||
@PutMapping()
|
||||
public R<Void> edit(@Validated(EditGroup.class) @RequestBody ${ClassName}Bo bo) {
|
||||
return toAjax(${className}Service.updateByBo(bo));
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除${functionName}
|
||||
*
|
||||
* @param ${pkColumn.javaField}s 主键串
|
||||
*/
|
||||
@SaCheckPermission("${permissionPrefix}:remove")
|
||||
@Log(title = "${functionName}", businessType = BusinessType.DELETE)
|
||||
@DeleteMapping("/{${pkColumn.javaField}s}")
|
||||
public R<Void> remove(@NotEmpty(message = "主键不能为空")
|
||||
@PathVariable("${pkColumn.javaField}s") ${pkColumn.javaType}[] ${pkColumn.javaField}s) {
|
||||
return toAjax(${className}Service.deleteWithValidByIds(List.of(${pkColumn.javaField}s), true));
|
||||
}
|
||||
}
|
@ -0,0 +1,60 @@
|
||||
package ${packageName}.domain;
|
||||
|
||||
#foreach ($column in $columns)
|
||||
#if($column.javaField=='tenantId')
|
||||
#set($IsTenant=1)
|
||||
#end
|
||||
#end
|
||||
#if($IsTenant==1)
|
||||
import org.dromara.common.tenant.core.TenantEntity;
|
||||
#else
|
||||
import org.dromara.common.mybatis.core.domain.BaseEntity;
|
||||
#end
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
#foreach ($import in $importList)
|
||||
import ${import};
|
||||
#end
|
||||
|
||||
import java.io.Serial;
|
||||
|
||||
/**
|
||||
* ${functionName}对象 ${tableName}
|
||||
*
|
||||
* @author ${author}
|
||||
* @date ${datetime}
|
||||
*/
|
||||
#if($IsTenant==1)
|
||||
#set($Entity="TenantEntity")
|
||||
#else
|
||||
#set($Entity="BaseEntity")
|
||||
#end
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@TableName("${tableName}")
|
||||
public class ${ClassName} extends ${Entity} {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
#foreach ($column in $columns)
|
||||
#if(!$table.isSuperColumn($column.javaField))
|
||||
/**
|
||||
* $column.columnComment
|
||||
*/
|
||||
#if($column.javaField=='delFlag')
|
||||
@TableLogic
|
||||
#end
|
||||
#if($column.javaField=='version')
|
||||
@Version
|
||||
#end
|
||||
#if($column.isPk==1)
|
||||
@TableId(value = "$column.columnName")
|
||||
#end
|
||||
private $column.javaType $column.javaField;
|
||||
|
||||
#end
|
||||
#end
|
||||
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package ${packageName}.mapper;
|
||||
|
||||
import ${packageName}.domain.${ClassName};
|
||||
import ${packageName}.domain.vo.${ClassName}Vo;
|
||||
import org.dromara.common.mybatis.core.mapper.BaseMapperPlus;
|
||||
|
||||
/**
|
||||
* ${functionName}Mapper接口
|
||||
*
|
||||
* @author ${author}
|
||||
* @date ${datetime}
|
||||
*/
|
||||
public interface ${ClassName}Mapper extends BaseMapperPlus<${ClassName}, ${ClassName}Vo> {
|
||||
|
||||
}
|
@ -0,0 +1,73 @@
|
||||
package ${packageName}.service;
|
||||
|
||||
import ${packageName}.domain.${ClassName};
|
||||
import ${packageName}.domain.vo.${ClassName}Vo;
|
||||
import ${packageName}.domain.bo.${ClassName}Bo;
|
||||
#if($table.crud)
|
||||
import org.dromara.common.mybatis.core.page.TableDataInfo;
|
||||
import org.dromara.common.mybatis.core.page.PageQuery;
|
||||
#end
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* ${functionName}Service接口
|
||||
*
|
||||
* @author ${author}
|
||||
* @date ${datetime}
|
||||
*/
|
||||
public interface I${ClassName}Service {
|
||||
|
||||
/**
|
||||
* 查询${functionName}
|
||||
*
|
||||
* @param ${pkColumn.javaField} 主键
|
||||
* @return ${functionName}
|
||||
*/
|
||||
${ClassName}Vo queryById(${pkColumn.javaType} ${pkColumn.javaField});
|
||||
|
||||
#if($table.crud)
|
||||
/**
|
||||
* 分页查询${functionName}列表
|
||||
*
|
||||
* @param bo 查询条件
|
||||
* @param pageQuery 分页参数
|
||||
* @return ${functionName}分页列表
|
||||
*/
|
||||
TableDataInfo<${ClassName}Vo> queryPageList(${ClassName}Bo bo, PageQuery pageQuery);
|
||||
#end
|
||||
|
||||
/**
|
||||
* 查询符合条件的${functionName}列表
|
||||
*
|
||||
* @param bo 查询条件
|
||||
* @return ${functionName}列表
|
||||
*/
|
||||
List<${ClassName}Vo> queryList(${ClassName}Bo bo);
|
||||
|
||||
/**
|
||||
* 新增${functionName}
|
||||
*
|
||||
* @param bo ${functionName}
|
||||
* @return 是否新增成功
|
||||
*/
|
||||
Boolean insertByBo(${ClassName}Bo bo);
|
||||
|
||||
/**
|
||||
* 修改${functionName}
|
||||
*
|
||||
* @param bo ${functionName}
|
||||
* @return 是否修改成功
|
||||
*/
|
||||
Boolean updateByBo(${ClassName}Bo bo);
|
||||
|
||||
/**
|
||||
* 校验并批量删除${functionName}信息
|
||||
*
|
||||
* @param ids 待删除的主键集合
|
||||
* @param isValid 是否进行有效性校验
|
||||
* @return 是否删除成功
|
||||
*/
|
||||
Boolean deleteWithValidByIds(Collection<${pkColumn.javaType}> ids, Boolean isValid);
|
||||
}
|
@ -0,0 +1,160 @@
|
||||
package ${packageName}.service.impl;
|
||||
|
||||
import org.dromara.common.core.utils.MapstructUtils;
|
||||
import org.dromara.common.core.utils.StringUtils;
|
||||
#if($table.crud)
|
||||
import org.dromara.common.mybatis.core.page.TableDataInfo;
|
||||
import org.dromara.common.mybatis.core.page.PageQuery;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
#end
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import ${packageName}.domain.bo.${ClassName}Bo;
|
||||
import ${packageName}.domain.vo.${ClassName}Vo;
|
||||
import ${packageName}.domain.${ClassName};
|
||||
import ${packageName}.mapper.${ClassName}Mapper;
|
||||
import ${packageName}.service.I${ClassName}Service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Collection;
|
||||
|
||||
/**
|
||||
* ${functionName}Service业务层处理
|
||||
*
|
||||
* @author ${author}
|
||||
* @date ${datetime}
|
||||
*/
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
public class ${ClassName}ServiceImpl implements I${ClassName}Service {
|
||||
|
||||
private final ${ClassName}Mapper baseMapper;
|
||||
|
||||
/**
|
||||
* 查询${functionName}
|
||||
*
|
||||
* @param ${pkColumn.javaField} 主键
|
||||
* @return ${functionName}
|
||||
*/
|
||||
@Override
|
||||
public ${ClassName}Vo queryById(${pkColumn.javaType} ${pkColumn.javaField}){
|
||||
return baseMapper.selectVoById(${pkColumn.javaField});
|
||||
}
|
||||
|
||||
#if($table.crud)
|
||||
/**
|
||||
* 分页查询${functionName}列表
|
||||
*
|
||||
* @param bo 查询条件
|
||||
* @param pageQuery 分页参数
|
||||
* @return ${functionName}分页列表
|
||||
*/
|
||||
@Override
|
||||
public TableDataInfo<${ClassName}Vo> queryPageList(${ClassName}Bo bo, PageQuery pageQuery) {
|
||||
LambdaQueryWrapper<${ClassName}> lqw = buildQueryWrapper(bo);
|
||||
Page<${ClassName}Vo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
|
||||
return TableDataInfo.build(result);
|
||||
}
|
||||
#end
|
||||
|
||||
/**
|
||||
* 查询符合条件的${functionName}列表
|
||||
*
|
||||
* @param bo 查询条件
|
||||
* @return ${functionName}列表
|
||||
*/
|
||||
@Override
|
||||
public List<${ClassName}Vo> queryList(${ClassName}Bo bo) {
|
||||
LambdaQueryWrapper<${ClassName}> lqw = buildQueryWrapper(bo);
|
||||
return baseMapper.selectVoList(lqw);
|
||||
}
|
||||
|
||||
private LambdaQueryWrapper<${ClassName}> buildQueryWrapper(${ClassName}Bo bo) {
|
||||
Map<String, Object> params = bo.getParams();
|
||||
LambdaQueryWrapper<${ClassName}> lqw = Wrappers.lambdaQuery();
|
||||
#foreach($column in $columns)
|
||||
#if($column.query)
|
||||
#set($queryType=$column.queryType)
|
||||
#set($javaField=$column.javaField)
|
||||
#set($javaType=$column.javaType)
|
||||
#set($columnName=$column.columnName)
|
||||
#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)})
|
||||
#set($mpMethod=$column.queryType.toLowerCase())
|
||||
#if($queryType != 'BETWEEN')
|
||||
#if($javaType == 'String')
|
||||
#set($condition='StringUtils.isNotBlank(bo.get'+$AttrName+'())')
|
||||
#else
|
||||
#set($condition='bo.get'+$AttrName+'() != null')
|
||||
#end
|
||||
lqw.$mpMethod($condition, ${ClassName}::get$AttrName, bo.get$AttrName());
|
||||
#else
|
||||
lqw.between(params.get("begin$AttrName") != null && params.get("end$AttrName") != null,
|
||||
${ClassName}::get$AttrName ,params.get("begin$AttrName"), params.get("end$AttrName"));
|
||||
#end
|
||||
#end
|
||||
#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)})
|
||||
#if($column.isPk==1)
|
||||
lqw.orderByAsc(${ClassName}::get$AttrName);
|
||||
#end
|
||||
#end
|
||||
return lqw;
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增${functionName}
|
||||
*
|
||||
* @param bo ${functionName}
|
||||
* @return 是否新增成功
|
||||
*/
|
||||
@Override
|
||||
public Boolean insertByBo(${ClassName}Bo bo) {
|
||||
${ClassName} add = MapstructUtils.convert(bo, ${ClassName}.class);
|
||||
validEntityBeforeSave(add);
|
||||
boolean flag = baseMapper.insert(add) > 0;
|
||||
#set($pk=$pkColumn.javaField.substring(0,1).toUpperCase() + ${pkColumn.javaField.substring(1)})
|
||||
if (flag) {
|
||||
bo.set$pk(add.get$pk());
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改${functionName}
|
||||
*
|
||||
* @param bo ${functionName}
|
||||
* @return 是否修改成功
|
||||
*/
|
||||
@Override
|
||||
public Boolean updateByBo(${ClassName}Bo bo) {
|
||||
${ClassName} update = MapstructUtils.convert(bo, ${ClassName}.class);
|
||||
validEntityBeforeSave(update);
|
||||
return baseMapper.updateById(update) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存前的数据校验
|
||||
*/
|
||||
private void validEntityBeforeSave(${ClassName} entity){
|
||||
//TODO 做一些数据校验,如唯一约束
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验并批量删除${functionName}信息
|
||||
*
|
||||
* @param ids 待删除的主键集合
|
||||
* @param isValid 是否进行有效性校验
|
||||
* @return 是否删除成功
|
||||
*/
|
||||
@Override
|
||||
public Boolean deleteWithValidByIds(Collection<${pkColumn.javaType}> ids, Boolean isValid) {
|
||||
if(isValid){
|
||||
//TODO 做一些业务上的校验,判断是否需要校验
|
||||
}
|
||||
return baseMapper.deleteByIds(ids) > 0;
|
||||
}
|
||||
}
|
@ -0,0 +1,66 @@
|
||||
package ${packageName}.domain.vo;
|
||||
|
||||
#foreach ($import in $importList)
|
||||
import ${import};
|
||||
#end
|
||||
import ${packageName}.domain.${ClassName};
|
||||
import cn.idev.excel.annotation.ExcelIgnoreUnannotated;
|
||||
import cn.idev.excel.annotation.ExcelProperty;
|
||||
import org.dromara.common.excel.annotation.ExcelDictFormat;
|
||||
import org.dromara.common.excel.convert.ExcelDictConvert;
|
||||
import io.github.linpeilie.annotations.AutoMapper;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* ${functionName}视图对象 ${tableName}
|
||||
*
|
||||
* @author ${author}
|
||||
* @date ${datetime}
|
||||
*/
|
||||
@Data
|
||||
@ExcelIgnoreUnannotated
|
||||
@AutoMapper(target = ${ClassName}.class)
|
||||
public class ${ClassName}Vo implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
#foreach ($column in $columns)
|
||||
#if($column.list)
|
||||
/**
|
||||
* $column.columnComment
|
||||
*/
|
||||
#set($parentheseIndex=$column.columnComment.indexOf("("))
|
||||
#if($parentheseIndex != -1)
|
||||
#set($comment=$column.columnComment.substring(0, $parentheseIndex))
|
||||
#else
|
||||
#set($comment=$column.columnComment)
|
||||
#end
|
||||
#if(${column.dictType} && ${column.dictType} != '')
|
||||
@ExcelProperty(value = "${comment}", converter = ExcelDictConvert.class)
|
||||
@ExcelDictFormat(dictType = "${column.dictType}")
|
||||
#elseif($parentheseIndex != -1)
|
||||
@ExcelProperty(value = "${comment}", converter = ExcelDictConvert.class)
|
||||
@ExcelDictFormat(readConverterExp = "$column.readConverterExp()")
|
||||
#else
|
||||
@ExcelProperty(value = "${comment}")
|
||||
#end
|
||||
private $column.javaType $column.javaField;
|
||||
|
||||
#if($column.htmlType == "imageUpload")
|
||||
/**
|
||||
* ${column.columnComment}Url
|
||||
*/
|
||||
@Translation(type = TransConstant.OSS_ID_TO_URL, mapper = "${column.javaField}")
|
||||
private String ${column.javaField}Url;
|
||||
#end
|
||||
#end
|
||||
#end
|
||||
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
-- 菜单 SQL
|
||||
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
|
||||
values(${table.menuIds[0]}, '${functionName}', '${parentMenuId}', '1', '${businessName}', '${moduleName}/${businessName}/index', 1, 0, 'C', '0', '0', '${permissionPrefix}:list', '#', 103, 1, sysdate, null, null, '${functionName}菜单');
|
||||
|
||||
-- 按钮 SQL
|
||||
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
|
||||
values(${table.menuIds[1]}, '${functionName}查询', ${table.menuIds[0]}, '1', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:query', '#', 103, 1, sysdate, null, null, '');
|
||||
|
||||
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
|
||||
values(${table.menuIds[2]}, '${functionName}新增', ${table.menuIds[0]}, '2', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:add', '#', 103, 1, sysdate, null, null, '');
|
||||
|
||||
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
|
||||
values(${table.menuIds[3]}, '${functionName}修改', ${table.menuIds[0]}, '3', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:edit', '#', 103, 1, sysdate, null, null, '');
|
||||
|
||||
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
|
||||
values(${table.menuIds[4]}, '${functionName}删除', ${table.menuIds[0]}, '4', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:remove', '#', 103, 1, sysdate, null, null, '');
|
||||
|
||||
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
|
||||
values(${table.menuIds[5]}, '${functionName}导出', ${table.menuIds[0]}, '5', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:export', '#', 103, 1, sysdate, null, null, '');
|
@ -0,0 +1,20 @@
|
||||
-- 菜单 SQL
|
||||
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
|
||||
values(${table.menuIds[0]}, '${functionName}', '${parentMenuId}', '1', '${businessName}', '${moduleName}/${businessName}/index', 1, 0, 'C', '0', '0', '${permissionPrefix}:list', '#', 103, 1, now(), null, null, '${functionName}菜单');
|
||||
|
||||
-- 按钮 SQL
|
||||
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
|
||||
values(${table.menuIds[1]}, '${functionName}查询', ${table.menuIds[0]}, '1', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:query', '#', 103, 1, now(), null, null, '');
|
||||
|
||||
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
|
||||
values(${table.menuIds[2]}, '${functionName}新增', ${table.menuIds[0]}, '2', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:add', '#', 103, 1, now(), null, null, '');
|
||||
|
||||
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
|
||||
values(${table.menuIds[3]}, '${functionName}修改', ${table.menuIds[0]}, '3', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:edit', '#', 103, 1, now(), null, null, '');
|
||||
|
||||
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
|
||||
values(${table.menuIds[4]}, '${functionName}删除', ${table.menuIds[0]}, '4', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:remove', '#', 103, 1, now(), null, null, '');
|
||||
|
||||
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
|
||||
values(${table.menuIds[5]}, '${functionName}导出', ${table.menuIds[0]}, '5', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:export', '#', 103, 1, now(), null, null, '');
|
||||
|
19
ruoyi-modules/ruoyi-gen/src/main/resources/vm/sql/sql.vm
Normal file
19
ruoyi-modules/ruoyi-gen/src/main/resources/vm/sql/sql.vm
Normal file
@ -0,0 +1,19 @@
|
||||
-- 菜单 SQL
|
||||
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
|
||||
values(${table.menuIds[0]}, '${functionName}', '${parentMenuId}', '1', '${businessName}', '${moduleName}/${businessName}/index', 1, 0, 'C', '0', '0', '${permissionPrefix}:list', '#', 103, 1, sysdate(), null, null, '${functionName}菜单');
|
||||
|
||||
-- 按钮 SQL
|
||||
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
|
||||
values(${table.menuIds[1]}, '${functionName}查询', ${table.menuIds[0]}, '1', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:query', '#', 103, 1, sysdate(), null, null, '');
|
||||
|
||||
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
|
||||
values(${table.menuIds[2]}, '${functionName}新增', ${table.menuIds[0]}, '2', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:add', '#', 103, 1, sysdate(), null, null, '');
|
||||
|
||||
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
|
||||
values(${table.menuIds[3]}, '${functionName}修改', ${table.menuIds[0]}, '3', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:edit', '#', 103, 1, sysdate(), null, null, '');
|
||||
|
||||
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
|
||||
values(${table.menuIds[4]}, '${functionName}删除', ${table.menuIds[0]}, '4', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:remove', '#', 103, 1, sysdate(), null, null, '');
|
||||
|
||||
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
|
||||
values(${table.menuIds[5]}, '${functionName}导出', ${table.menuIds[0]}, '5', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:export', '#', 103, 1, sysdate(), null, null, '');
|
63
ruoyi-modules/ruoyi-gen/src/main/resources/vm/ts/api.ts.vm
Normal file
63
ruoyi-modules/ruoyi-gen/src/main/resources/vm/ts/api.ts.vm
Normal file
@ -0,0 +1,63 @@
|
||||
import request from '@/utils/request';
|
||||
import { AxiosPromise } from 'axios';
|
||||
import { ${BusinessName}VO, ${BusinessName}Form, ${BusinessName}Query } from '@/api/${moduleName}/${businessName}/types';
|
||||
|
||||
/**
|
||||
* 查询${functionName}列表
|
||||
* @param query
|
||||
* @returns {*}
|
||||
*/
|
||||
|
||||
export const list${BusinessName} = (query?: ${BusinessName}Query): AxiosPromise<${BusinessName}VO[]> => {
|
||||
return request({
|
||||
url: '/${moduleName}/${businessName}/list',
|
||||
method: 'get',
|
||||
params: query
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 查询${functionName}详细
|
||||
* @param ${pkColumn.javaField}
|
||||
*/
|
||||
export const get${BusinessName} = (${pkColumn.javaField}: string | number): AxiosPromise<${BusinessName}VO> => {
|
||||
return request({
|
||||
url: '/${moduleName}/${businessName}/' + ${pkColumn.javaField},
|
||||
method: 'get'
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 新增${functionName}
|
||||
* @param data
|
||||
*/
|
||||
export const add${BusinessName} = (data: ${BusinessName}Form) => {
|
||||
return request({
|
||||
url: '/${moduleName}/${businessName}',
|
||||
method: 'post',
|
||||
data: data
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 修改${functionName}
|
||||
* @param data
|
||||
*/
|
||||
export const update${BusinessName} = (data: ${BusinessName}Form) => {
|
||||
return request({
|
||||
url: '/${moduleName}/${businessName}',
|
||||
method: 'put',
|
||||
data: data
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 删除${functionName}
|
||||
* @param ${pkColumn.javaField}
|
||||
*/
|
||||
export const del${BusinessName} = (${pkColumn.javaField}: string | number | Array<string | number>) => {
|
||||
return request({
|
||||
url: '/${moduleName}/${businessName}/' + ${pkColumn.javaField},
|
||||
method: 'delete'
|
||||
});
|
||||
};
|
64
ruoyi-modules/ruoyi-gen/src/main/resources/vm/ts/types.ts.vm
Normal file
64
ruoyi-modules/ruoyi-gen/src/main/resources/vm/ts/types.ts.vm
Normal file
@ -0,0 +1,64 @@
|
||||
export interface ${BusinessName}VO {
|
||||
#foreach ($column in $columns)
|
||||
#if($column.list)
|
||||
/**
|
||||
* $column.columnComment
|
||||
*/
|
||||
$column.javaField:#if($column.javaField.indexOf("id") != -1 || $column.javaField.indexOf("Id") != -1) string | number;
|
||||
#elseif($column.javaType == 'Long' || $column.javaType == 'Integer' || $column.javaType == 'Double' || $column.javaType == 'Float' || $column.javaType == 'BigDecimal') number;
|
||||
#elseif($column.javaType == 'Boolean') boolean;
|
||||
#else string;
|
||||
#end
|
||||
#if($column.htmlType == "imageUpload")
|
||||
/**
|
||||
* ${column.columnComment}Url
|
||||
*/
|
||||
${column.javaField}Url: string;
|
||||
#end
|
||||
#end
|
||||
#end
|
||||
#if ($table.tree)
|
||||
/**
|
||||
* 子对象
|
||||
*/
|
||||
children: ${BusinessName}VO[];
|
||||
#end
|
||||
}
|
||||
|
||||
export interface ${BusinessName}Form extends BaseEntity {
|
||||
#foreach ($column in $columns)
|
||||
#if($column.insert || $column.edit)
|
||||
/**
|
||||
* $column.columnComment
|
||||
*/
|
||||
$column.javaField?:#if($column.javaField.indexOf("id") != -1 || $column.javaField.indexOf("Id") != -1) string | number;
|
||||
#elseif($column.javaType == 'Long' || $column.javaType == 'Integer' || $column.javaType == 'Double' || $column.javaType == 'Float' || $column.javaType == 'BigDecimal') number;
|
||||
#elseif($column.javaType == 'Boolean') boolean;
|
||||
#else string;
|
||||
#end
|
||||
#end
|
||||
#end
|
||||
}
|
||||
|
||||
export interface ${BusinessName}Query #if(!${treeCode})extends PageQuery #end{
|
||||
|
||||
#foreach ($column in $columns)
|
||||
#if($column.query)
|
||||
/**
|
||||
* $column.columnComment
|
||||
*/
|
||||
$column.javaField?:#if($column.javaField.indexOf("id") != -1 || $column.javaField.indexOf("Id") != -1) string | number;
|
||||
#elseif($column.javaType == 'Long' || $column.javaType == 'Integer' || $column.javaType == 'Double' || $column.javaType == 'Float' || $column.javaType == 'BigDecimal') number;
|
||||
#elseif($column.javaType == 'Boolean') boolean;
|
||||
#else string;
|
||||
#end
|
||||
#end
|
||||
#end
|
||||
/**
|
||||
* 日期范围参数
|
||||
*/
|
||||
params?: any;
|
||||
}
|
||||
|
||||
|
||||
|
@ -0,0 +1,499 @@
|
||||
<template>
|
||||
<div class="p-2">
|
||||
<transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
|
||||
<div v-show="showSearch" class="mb-[10px]">
|
||||
<el-card shadow="hover">
|
||||
<el-form ref="queryFormRef" :model="queryParams" :inline="true">
|
||||
#foreach($column in $columns)
|
||||
#if($column.query)
|
||||
#set($dictType=$column.dictType)
|
||||
#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)})
|
||||
#set($parentheseIndex=$column.columnComment.indexOf("("))
|
||||
#if($parentheseIndex != -1)
|
||||
#set($comment=$column.columnComment.substring(0, $parentheseIndex))
|
||||
#else
|
||||
#set($comment=$column.columnComment)
|
||||
#end
|
||||
#if($column.htmlType == "input" || $column.htmlType == "textarea")
|
||||
<el-form-item label="${comment}" prop="${column.javaField}">
|
||||
<el-input v-model="queryParams.${column.javaField}" placeholder="请输入${comment}" clearable @keyup.enter="handleQuery" />
|
||||
</el-form-item>
|
||||
#elseif(($column.htmlType == "select" || $column.htmlType == "radio") && "" != $dictType)
|
||||
<el-form-item label="${comment}" prop="${column.javaField}">
|
||||
<el-select v-model="queryParams.${column.javaField}" placeholder="请选择${comment}" clearable>
|
||||
<el-option v-for="dict in ${dictType}" :key="dict.value" :label="dict.label" :value="dict.value"/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
#elseif(($column.htmlType == "select" || $column.htmlType == "radio") && $dictType)
|
||||
<el-form-item label="${comment}" prop="${column.javaField}">
|
||||
<el-select v-model="queryParams.${column.javaField}" placeholder="请选择${comment}" clearable>
|
||||
<el-option label="请选择字典生成" value="" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
#elseif($column.htmlType == "datetime" && $column.queryType != "BETWEEN")
|
||||
<el-form-item label="${comment}" prop="${column.javaField}">
|
||||
<el-date-picker clearable
|
||||
v-model="queryParams.${column.javaField}"
|
||||
type="date"
|
||||
value-format="YYYY-MM-DD"
|
||||
placeholder="选择${comment}"
|
||||
/>
|
||||
</el-form-item>
|
||||
#elseif($column.htmlType == "datetime" && $column.queryType == "BETWEEN")
|
||||
<el-form-item label="${comment}" style="width: 308px">
|
||||
<el-date-picker
|
||||
v-model="dateRange${AttrName}"
|
||||
value-format="YYYY-MM-DD HH:mm:ss"
|
||||
type="daterange"
|
||||
range-separator="-"
|
||||
start-placeholder="开始日期"
|
||||
end-placeholder="结束日期"
|
||||
:default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
|
||||
/>
|
||||
</el-form-item>
|
||||
#end
|
||||
#end
|
||||
#end
|
||||
<el-form-item>
|
||||
<el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
|
||||
<el-button icon="Refresh" @click="resetQuery">重置</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
</el-card>
|
||||
</div>
|
||||
</transition>
|
||||
|
||||
<el-card shadow="never">
|
||||
<template #header>
|
||||
<el-row :gutter="10" class="mb8">
|
||||
<el-col :span="1.5">
|
||||
<el-button type="primary" plain icon="Plus" @click="handleAdd()" v-hasPermi="['${moduleName}:${businessName}:add']">新增</el-button>
|
||||
</el-col>
|
||||
<el-col :span="1.5">
|
||||
<el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
|
||||
</el-col>
|
||||
<right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
|
||||
</el-row>
|
||||
</template>
|
||||
<el-table
|
||||
ref="${businessName}TableRef"
|
||||
v-loading="loading"
|
||||
:data="${businessName}List"
|
||||
row-key="${treeCode}"
|
||||
border
|
||||
:default-expand-all="isExpandAll"
|
||||
:tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
|
||||
>
|
||||
#foreach($column in $columns)
|
||||
#set($javaField=$column.javaField)
|
||||
#set($parentheseIndex=$column.columnComment.indexOf("("))
|
||||
#if($parentheseIndex != -1)
|
||||
#set($comment=$column.columnComment.substring(0, $parentheseIndex))
|
||||
#else
|
||||
#set($comment=$column.columnComment)
|
||||
#end
|
||||
#if($column.pk)
|
||||
#elseif($column.list && $column.htmlType == "datetime")
|
||||
<el-table-column label="${comment}" align="center" prop="${javaField}" width="180">
|
||||
<template #default="scope">
|
||||
<span>{{ parseTime(scope.row.${javaField}, '{y}-{m}-{d}') }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
#elseif($column.list && $column.htmlType == "imageUpload")
|
||||
<el-table-column label="${comment}" align="center" prop="${javaField}Url" width="100">
|
||||
<template #default="scope">
|
||||
<image-preview :src="scope.row.${javaField}Url" :width="50" :height="50"/>
|
||||
</template>
|
||||
</el-table-column>
|
||||
#elseif($column.list && $column.dictType && "" != $column.dictType)
|
||||
<el-table-column label="${comment}" align="center" prop="${javaField}">
|
||||
<template #default="scope">
|
||||
#if($column.htmlType == "checkbox")
|
||||
<dict-tag :options="${column.dictType}" :value="scope.row.${javaField} ? scope.row.${javaField}.split(',') : []"/>
|
||||
#else
|
||||
<dict-tag :options="${column.dictType}" :value="scope.row.${javaField}"/>
|
||||
#end
|
||||
</template>
|
||||
</el-table-column>
|
||||
#elseif($column.list && "" != $javaField)
|
||||
#if(${foreach.index} == 1)
|
||||
<el-table-column label="${comment}" prop="${javaField}" />
|
||||
#else
|
||||
<el-table-column label="${comment}" align="center" prop="${javaField}" />
|
||||
#end
|
||||
#end
|
||||
#end
|
||||
<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
|
||||
<template #default="scope">
|
||||
<el-tooltip content="修改" placement="top">
|
||||
<el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['${moduleName}:${businessName}:edit']" />
|
||||
</el-tooltip>
|
||||
<el-tooltip content="新增" placement="top">
|
||||
<el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['${moduleName}:${businessName}:add']" />
|
||||
</el-tooltip>
|
||||
<el-tooltip content="删除" placement="top">
|
||||
<el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['${moduleName}:${businessName}:remove']" />
|
||||
</el-tooltip>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</el-card>
|
||||
<!-- 添加或修改${functionName}对话框 -->
|
||||
<el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
|
||||
<el-form ref="${businessName}FormRef" :model="form" :rules="rules" label-width="80px">
|
||||
#foreach($column in $columns)
|
||||
#set($field=$column.javaField)
|
||||
#if(($column.insert || $column.edit) && !$column.pk)
|
||||
#set($parentheseIndex=$column.columnComment.indexOf("("))
|
||||
#if($parentheseIndex != -1)
|
||||
#set($comment=$column.columnComment.substring(0, $parentheseIndex))
|
||||
#else
|
||||
#set($comment=$column.columnComment)
|
||||
#end
|
||||
#set($dictType=$column.dictType)
|
||||
#if("" != $treeParentCode && $column.javaField == $treeParentCode)
|
||||
<el-form-item label="${comment}" prop="${treeParentCode}">
|
||||
<el-tree-select
|
||||
v-model="form.${treeParentCode}"
|
||||
:data="${businessName}Options"
|
||||
:props="{ value: '${treeCode}', label: '${treeName}', children: 'children' }"
|
||||
value-key="${treeCode}"
|
||||
placeholder="请选择${comment}"
|
||||
check-strictly
|
||||
/>
|
||||
</el-form-item>
|
||||
#elseif($column.htmlType == "input")
|
||||
<el-form-item label="${comment}" prop="${field}">
|
||||
<el-input v-model="form.${field}" placeholder="请输入${comment}" />
|
||||
</el-form-item>
|
||||
#elseif($column.htmlType == "imageUpload")
|
||||
<el-form-item label="${comment}" prop="${field}">
|
||||
<image-upload v-model="form.${field}"/>
|
||||
</el-form-item>
|
||||
#elseif($column.htmlType == "fileUpload")
|
||||
<el-form-item label="${comment}" prop="${field}">
|
||||
<file-upload v-model="form.${field}"/>
|
||||
</el-form-item>
|
||||
#elseif($column.htmlType == "editor")
|
||||
<el-form-item label="${comment}">
|
||||
<editor v-model="form.${field}" :min-height="192"/>
|
||||
</el-form-item>
|
||||
#elseif($column.htmlType == "select" && "" != $dictType)
|
||||
<el-form-item label="${comment}" prop="${field}">
|
||||
<el-select v-model="form.${field}" placeholder="请选择${comment}">
|
||||
<el-option
|
||||
v-for="dict in ${dictType}"
|
||||
:key="dict.value"
|
||||
:label="dict.label"
|
||||
#if($column.javaType == "Integer" || $column.javaType == "Long")
|
||||
:value="parseInt(dict.value)"
|
||||
#else
|
||||
:value="dict.value"
|
||||
#end
|
||||
></el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
#elseif($column.htmlType == "select" && $dictType)
|
||||
<el-form-item label="${comment}" prop="${field}">
|
||||
<el-select v-model="form.${field}" placeholder="请选择${comment}">
|
||||
<el-option label="请选择字典生成" value="" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
#elseif($column.htmlType == "checkbox" && "" != $dictType)
|
||||
<el-form-item label="${comment}" prop="${field}">
|
||||
<el-checkbox-group v-model="form.${field}">
|
||||
<el-checkbox
|
||||
v-for="dict in ${dictType}"
|
||||
:key="dict.value"
|
||||
:label="dict.value">
|
||||
{{dict.label}}
|
||||
</el-checkbox>
|
||||
</el-checkbox-group>
|
||||
</el-form-item>
|
||||
#elseif($column.htmlType == "checkbox" && $dictType)
|
||||
<el-form-item label="${comment}" prop="${field}">
|
||||
<el-checkbox-group v-model="form.${field}">
|
||||
<el-checkbox>请选择字典生成</el-checkbox>
|
||||
</el-checkbox-group>
|
||||
</el-form-item>
|
||||
#elseif($column.htmlType == "radio" && "" != $dictType)
|
||||
<el-form-item label="${comment}" prop="${field}">
|
||||
<el-radio-group v-model="form.${field}">
|
||||
<el-radio
|
||||
v-for="dict in ${dictType}"
|
||||
:key="dict.value"
|
||||
#if($column.javaType == "Integer" || $column.javaType == "Long")
|
||||
:value="parseInt(dict.value)"
|
||||
#else
|
||||
:value="dict.value"
|
||||
#end
|
||||
>{{dict.label}}</el-radio>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
#elseif($column.htmlType == "radio" && $dictType)
|
||||
<el-form-item label="${comment}" prop="${field}">
|
||||
<el-radio-group v-model="form.${field}">
|
||||
<el-radio value="1">请选择字典生成</el-radio>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
#elseif($column.htmlType == "datetime")
|
||||
<el-form-item label="${comment}" prop="${field}">
|
||||
<el-date-picker clearable
|
||||
v-model="form.${field}"
|
||||
type="datetime"
|
||||
value-format="YYYY-MM-DD HH:mm:ss"
|
||||
placeholder="选择${comment}"
|
||||
/>
|
||||
</el-form-item>
|
||||
#elseif($column.htmlType == "textarea")
|
||||
<el-form-item label="${comment}" prop="${field}">
|
||||
<el-input v-model="form.${field}" type="textarea" placeholder="请输入内容" />
|
||||
</el-form-item>
|
||||
#end
|
||||
#end
|
||||
#end
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<div class="dialog-footer">
|
||||
<el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
|
||||
<el-button @click="cancel">取 消</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup name="${BusinessName}" lang="ts">
|
||||
import { list${BusinessName}, get${BusinessName}, del${BusinessName}, add${BusinessName}, update${BusinessName} } from "@/api/${moduleName}/${businessName}";
|
||||
import { ${BusinessName}VO, ${BusinessName}Query, ${BusinessName}Form } from '@/api/${moduleName}/${businessName}/types';
|
||||
|
||||
type ${BusinessName}Option = {
|
||||
${treeCode}: number;
|
||||
${treeName}: string;
|
||||
children?: ${BusinessName}Option[];
|
||||
}
|
||||
|
||||
const { proxy } = getCurrentInstance() as ComponentInternalInstance;;
|
||||
|
||||
#if(${dicts} != '')
|
||||
#set($dictsNoSymbol=$dicts.replace("'", ""))
|
||||
const { ${dictsNoSymbol} } = toRefs<any>(proxy?.useDict(${dicts}));
|
||||
#end
|
||||
|
||||
const ${businessName}List = ref<${BusinessName}VO[]>([]);
|
||||
const ${businessName}Options = ref<${BusinessName}Option[]>([]);
|
||||
const buttonLoading = ref(false);
|
||||
const showSearch = ref(true);
|
||||
const isExpandAll = ref(true);
|
||||
const loading = ref(false);
|
||||
|
||||
const queryFormRef = ref<ElFormInstance>();
|
||||
const ${businessName}FormRef = ref<ElFormInstance>();
|
||||
const ${businessName}TableRef = ref<ElTableInstance>()
|
||||
|
||||
const dialog = reactive<DialogOption>({
|
||||
visible: false,
|
||||
title: ''
|
||||
});
|
||||
|
||||
#foreach ($column in $columns)
|
||||
#if($column.htmlType == "datetime" && $column.queryType == "BETWEEN")
|
||||
#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)})
|
||||
const dateRange${AttrName} = ref<[DateModelType, DateModelType]>(['', '']);
|
||||
#end
|
||||
#end
|
||||
|
||||
const initFormData: ${BusinessName}Form = {
|
||||
#foreach ($column in $columns)
|
||||
#if($column.insert || $column.edit)
|
||||
#if($column.htmlType == "checkbox")
|
||||
$column.javaField: []#if($foreach.count != $columns.size()),#end
|
||||
#else
|
||||
$column.javaField: undefined#if($foreach.count != $columns.size()),#end
|
||||
#end
|
||||
#end
|
||||
#end
|
||||
}
|
||||
|
||||
const data = reactive<PageData<${BusinessName}Form, ${BusinessName}Query>>({
|
||||
form: {...initFormData},
|
||||
queryParams: {
|
||||
#foreach ($column in $columns)
|
||||
#if($column.query)
|
||||
#if($column.htmlType != "datetime" || $column.queryType != "BETWEEN")
|
||||
$column.javaField: undefined,
|
||||
#end
|
||||
#end
|
||||
#end
|
||||
params: {
|
||||
#foreach ($column in $columns)
|
||||
#if($column.query)
|
||||
#if($column.htmlType == "datetime" && $column.queryType == "BETWEEN")
|
||||
$column.javaField: undefined#if($foreach.count != $columns.size()),#end
|
||||
#end
|
||||
#end
|
||||
#end
|
||||
}
|
||||
},
|
||||
rules: {
|
||||
#foreach ($column in $columns)
|
||||
#if($column.insert || $column.edit)
|
||||
#if($column.required)
|
||||
#set($parentheseIndex=$column.columnComment.indexOf("("))
|
||||
#if($parentheseIndex != -1)
|
||||
#set($comment=$column.columnComment.substring(0, $parentheseIndex))
|
||||
#else
|
||||
#set($comment=$column.columnComment)
|
||||
#end
|
||||
$column.javaField: [
|
||||
{ required: true, message: "$comment不能为空", trigger: #if($column.htmlType == "select" || $column.htmlType == "radio")"change"#else"blur"#end }
|
||||
]#if($foreach.count != $columns.size()),#end
|
||||
#end
|
||||
#end
|
||||
#end
|
||||
}
|
||||
});
|
||||
|
||||
const { queryParams, form, rules } = toRefs(data);
|
||||
|
||||
/** 查询${functionName}列表 */
|
||||
const getList = async () => {
|
||||
loading.value = true;
|
||||
#foreach ($column in $columns)
|
||||
#if($column.htmlType == "datetime" && $column.queryType == "BETWEEN")
|
||||
queryParams.value.params = {};
|
||||
#break
|
||||
#end
|
||||
#end
|
||||
#foreach ($column in $columns)
|
||||
#if($column.htmlType == "datetime" && $column.queryType == "BETWEEN")
|
||||
#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)})
|
||||
proxy?.addDateRange(queryParams.value, dateRange${AttrName}.value, '${AttrName}');
|
||||
#end
|
||||
#end
|
||||
const res = await list${BusinessName}(queryParams.value);
|
||||
const data = proxy?.handleTree<${BusinessName}VO>(res.data, "${treeCode}", "${treeParentCode}");
|
||||
if (data) {
|
||||
${businessName}List.value = data;
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** 查询${functionName}下拉树结构 */
|
||||
const getTreeselect = async () => {
|
||||
const res = await list${BusinessName}();
|
||||
${businessName}Options.value = [];
|
||||
const data: ${BusinessName}Option = { ${treeCode}: 0, ${treeName}: '顶级节点', children: [] };
|
||||
data.children = proxy?.handleTree<${BusinessName}Option>(res.data, "${treeCode}", "${treeParentCode}");
|
||||
${businessName}Options.value.push(data);
|
||||
}
|
||||
|
||||
// 取消按钮
|
||||
const cancel = () => {
|
||||
reset();
|
||||
dialog.visible = false;
|
||||
}
|
||||
|
||||
// 表单重置
|
||||
const reset = () => {
|
||||
form.value = {...initFormData}
|
||||
${businessName}FormRef.value?.resetFields();
|
||||
}
|
||||
|
||||
/** 搜索按钮操作 */
|
||||
const handleQuery = () => {
|
||||
getList();
|
||||
}
|
||||
|
||||
/** 重置按钮操作 */
|
||||
const resetQuery = () => {
|
||||
#foreach ($column in $columns)
|
||||
#if($column.htmlType == "datetime" && $column.queryType == "BETWEEN")
|
||||
#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)})
|
||||
dateRange${AttrName}.value = ['', ''];
|
||||
#end
|
||||
#end
|
||||
queryFormRef.value?.resetFields();
|
||||
handleQuery();
|
||||
}
|
||||
|
||||
/** 新增按钮操作 */
|
||||
const handleAdd = (row?: ${BusinessName}VO) => {
|
||||
reset();
|
||||
getTreeselect();
|
||||
if (row != null && row.${treeCode}) {
|
||||
form.value.${treeParentCode} = row.${treeCode};
|
||||
} else {
|
||||
form.value.${treeParentCode} = 0;
|
||||
}
|
||||
dialog.visible = true;
|
||||
dialog.title = "添加${functionName}";
|
||||
}
|
||||
|
||||
/** 展开/折叠操作 */
|
||||
const handleToggleExpandAll = () => {
|
||||
isExpandAll.value = !isExpandAll.value;
|
||||
toggleExpandAll(${businessName}List.value, isExpandAll.value)
|
||||
}
|
||||
|
||||
/** 展开/折叠操作 */
|
||||
const toggleExpandAll = (data: ${BusinessName}VO[], status: boolean) => {
|
||||
data.forEach((item) => {
|
||||
${businessName}TableRef.value?.toggleRowExpansion(item, status)
|
||||
if (item.children && item.children.length > 0) toggleExpandAll(item.children, status)
|
||||
})
|
||||
}
|
||||
|
||||
/** 修改按钮操作 */
|
||||
const handleUpdate = async (row: ${BusinessName}VO) => {
|
||||
reset();
|
||||
await getTreeselect();
|
||||
if (row != null) {
|
||||
form.value.${treeParentCode} = row.${treeParentCode};
|
||||
}
|
||||
const res = await get${BusinessName}(row.${pkColumn.javaField});
|
||||
Object.assign(form.value, res.data);
|
||||
#foreach ($column in $columns)
|
||||
#if($column.htmlType == "checkbox")
|
||||
form.value.$column.javaField = form.value.${column.javaField}.split(",");
|
||||
#end
|
||||
#end
|
||||
dialog.visible = true;
|
||||
dialog.title = "修改${functionName}";
|
||||
}
|
||||
|
||||
/** 提交按钮 */
|
||||
const submitForm = () => {
|
||||
${businessName}FormRef.value?.validate(async (valid: boolean) => {
|
||||
if (valid) {
|
||||
buttonLoading.value = true;
|
||||
#foreach ($column in $columns)
|
||||
#if($column.htmlType == "checkbox")
|
||||
form.value.$column.javaField = form.value.${column.javaField}.join(",");
|
||||
#end
|
||||
#end
|
||||
if (form.value.${pkColumn.javaField}) {
|
||||
await update${BusinessName}(form.value).finally(() => buttonLoading.value = false);
|
||||
} else {
|
||||
await add${BusinessName}(form.value).finally(() => buttonLoading.value = false);
|
||||
}
|
||||
proxy?.#[[$modal]]#.msgSuccess("操作成功");
|
||||
dialog.visible = false;
|
||||
getList();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** 删除按钮操作 */
|
||||
const handleDelete = async (row: ${BusinessName}VO) => {
|
||||
await proxy?.#[[$modal]]#.confirm('是否确认删除${functionName}编号为"' + row.${pkColumn.javaField} + '"的数据项?');
|
||||
loading.value = true;
|
||||
await del${BusinessName}(row.${pkColumn.javaField}).finally(() => loading.value = false);
|
||||
await getList();
|
||||
proxy?.#[[$modal]]#.msgSuccess("删除成功");
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
getList();
|
||||
});
|
||||
</script>
|
459
ruoyi-modules/ruoyi-gen/src/main/resources/vm/vue/index.vue.vm
Normal file
459
ruoyi-modules/ruoyi-gen/src/main/resources/vm/vue/index.vue.vm
Normal file
@ -0,0 +1,459 @@
|
||||
<template>
|
||||
<div class="p-2">
|
||||
<transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
|
||||
<div v-show="showSearch" class="mb-[10px]">
|
||||
<el-card shadow="hover">
|
||||
<el-form ref="queryFormRef" :model="queryParams" :inline="true">
|
||||
#foreach($column in $columns)
|
||||
#if($column.query)
|
||||
#set($dictType=$column.dictType)
|
||||
#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)})
|
||||
#set($parentheseIndex=$column.columnComment.indexOf("("))
|
||||
#if($parentheseIndex != -1)
|
||||
#set($comment=$column.columnComment.substring(0, $parentheseIndex))
|
||||
#else
|
||||
#set($comment=$column.columnComment)
|
||||
#end
|
||||
#if($column.htmlType == "input" || $column.htmlType == "textarea")
|
||||
<el-form-item label="${comment}" prop="${column.javaField}">
|
||||
<el-input v-model="queryParams.${column.javaField}" placeholder="请输入${comment}" clearable @keyup.enter="handleQuery" />
|
||||
</el-form-item>
|
||||
#elseif(($column.htmlType == "select" || $column.htmlType == "radio") && "" != $dictType)
|
||||
<el-form-item label="${comment}" prop="${column.javaField}">
|
||||
<el-select v-model="queryParams.${column.javaField}" placeholder="请选择${comment}" clearable >
|
||||
<el-option v-for="dict in ${dictType}" :key="dict.value" :label="dict.label" :value="dict.value"/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
#elseif(($column.htmlType == "select" || $column.htmlType == "radio") && $dictType)
|
||||
<el-form-item label="${comment}" prop="${column.javaField}">
|
||||
<el-select v-model="queryParams.${column.javaField}" placeholder="请选择${comment}" clearable >
|
||||
<el-option label="请选择字典生成" value="" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
#elseif($column.htmlType == "datetime" && $column.queryType != "BETWEEN")
|
||||
<el-form-item label="${comment}" prop="${column.javaField}">
|
||||
<el-date-picker clearable
|
||||
v-model="queryParams.${column.javaField}"
|
||||
type="date"
|
||||
value-format="YYYY-MM-DD"
|
||||
placeholder="请选择${comment}"
|
||||
/>
|
||||
</el-form-item>
|
||||
#elseif($column.htmlType == "datetime" && $column.queryType == "BETWEEN")
|
||||
<el-form-item label="${comment}" style="width: 308px">
|
||||
<el-date-picker
|
||||
v-model="dateRange${AttrName}"
|
||||
value-format="YYYY-MM-DD HH:mm:ss"
|
||||
type="daterange"
|
||||
range-separator="-"
|
||||
start-placeholder="开始日期"
|
||||
end-placeholder="结束日期"
|
||||
:default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
|
||||
/>
|
||||
</el-form-item>
|
||||
#end
|
||||
#end
|
||||
#end
|
||||
<el-form-item>
|
||||
<el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
|
||||
<el-button icon="Refresh" @click="resetQuery">重置</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
</el-card>
|
||||
</div>
|
||||
</transition>
|
||||
|
||||
<el-card shadow="never">
|
||||
<template #header>
|
||||
<el-row :gutter="10" class="mb8">
|
||||
<el-col :span="1.5">
|
||||
<el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['${moduleName}:${businessName}:add']">新增</el-button>
|
||||
</el-col>
|
||||
<el-col :span="1.5">
|
||||
<el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['${moduleName}:${businessName}:edit']">修改</el-button>
|
||||
</el-col>
|
||||
<el-col :span="1.5">
|
||||
<el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['${moduleName}:${businessName}:remove']">删除</el-button>
|
||||
</el-col>
|
||||
<el-col :span="1.5">
|
||||
<el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['${moduleName}:${businessName}:export']">导出</el-button>
|
||||
</el-col>
|
||||
<right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
|
||||
</el-row>
|
||||
</template>
|
||||
|
||||
<el-table v-loading="loading" border :data="${businessName}List" @selection-change="handleSelectionChange">
|
||||
<el-table-column type="selection" width="55" align="center" />
|
||||
#foreach($column in $columns)
|
||||
#set($javaField=$column.javaField)
|
||||
#set($parentheseIndex=$column.columnComment.indexOf("("))
|
||||
#if($parentheseIndex != -1)
|
||||
#set($comment=$column.columnComment.substring(0, $parentheseIndex))
|
||||
#else
|
||||
#set($comment=$column.columnComment)
|
||||
#end
|
||||
#if($column.pk)
|
||||
<el-table-column label="${comment}" align="center" prop="${javaField}" v-if="${column.list}" />
|
||||
#elseif($column.list && $column.htmlType == "datetime")
|
||||
<el-table-column label="${comment}" align="center" prop="${javaField}" width="180">
|
||||
<template #default="scope">
|
||||
<span>{{ parseTime(scope.row.${javaField}, '{y}-{m}-{d}') }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
#elseif($column.list && $column.htmlType == "imageUpload")
|
||||
<el-table-column label="${comment}" align="center" prop="${javaField}Url" width="100">
|
||||
<template #default="scope">
|
||||
<image-preview :src="scope.row.${javaField}Url" :width="50" :height="50"/>
|
||||
</template>
|
||||
</el-table-column>
|
||||
#elseif($column.list && $column.dictType && "" != $column.dictType)
|
||||
<el-table-column label="${comment}" align="center" prop="${javaField}">
|
||||
<template #default="scope">
|
||||
#if($column.htmlType == "checkbox")
|
||||
<dict-tag :options="${column.dictType}" :value="scope.row.${javaField} ? scope.row.${javaField}.split(',') : []"/>
|
||||
#else
|
||||
<dict-tag :options="${column.dictType}" :value="scope.row.${javaField}"/>
|
||||
#end
|
||||
</template>
|
||||
</el-table-column>
|
||||
#elseif($column.list && "" != $javaField)
|
||||
<el-table-column label="${comment}" align="center" prop="${javaField}" />
|
||||
#end
|
||||
#end
|
||||
<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
|
||||
<template #default="scope">
|
||||
<el-tooltip content="修改" placement="top">
|
||||
<el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['${moduleName}:${businessName}:edit']"></el-button>
|
||||
</el-tooltip>
|
||||
<el-tooltip content="删除" placement="top">
|
||||
<el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['${moduleName}:${businessName}:remove']"></el-button>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
|
||||
<pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
|
||||
</el-card>
|
||||
<!-- 添加或修改${functionName}对话框 -->
|
||||
<el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
|
||||
<el-form ref="${businessName}FormRef" :model="form" :rules="rules" label-width="80px">
|
||||
#foreach($column in $columns)
|
||||
#set($field=$column.javaField)
|
||||
#if(($column.insert || $column.edit) && !$column.pk)
|
||||
#set($parentheseIndex=$column.columnComment.indexOf("("))
|
||||
#if($parentheseIndex != -1)
|
||||
#set($comment=$column.columnComment.substring(0, $parentheseIndex))
|
||||
#else
|
||||
#set($comment=$column.columnComment)
|
||||
#end
|
||||
#set($dictType=$column.dictType)
|
||||
#if($column.htmlType == "input")
|
||||
<el-form-item label="${comment}" prop="${field}">
|
||||
<el-input v-model="form.${field}" placeholder="请输入${comment}" />
|
||||
</el-form-item>
|
||||
#elseif($column.htmlType == "imageUpload")
|
||||
<el-form-item label="${comment}" prop="${field}">
|
||||
<image-upload v-model="form.${field}"/>
|
||||
</el-form-item>
|
||||
#elseif($column.htmlType == "fileUpload")
|
||||
<el-form-item label="${comment}" prop="${field}">
|
||||
<file-upload v-model="form.${field}"/>
|
||||
</el-form-item>
|
||||
#elseif($column.htmlType == "editor")
|
||||
<el-form-item label="${comment}">
|
||||
<editor v-model="form.${field}" :min-height="192"/>
|
||||
</el-form-item>
|
||||
#elseif($column.htmlType == "select" && "" != $dictType)
|
||||
<el-form-item label="${comment}" prop="${field}">
|
||||
<el-select v-model="form.${field}" placeholder="请选择${comment}">
|
||||
<el-option
|
||||
v-for="dict in ${dictType}"
|
||||
:key="dict.value"
|
||||
:label="dict.label"
|
||||
#if($column.javaType == "Integer" || $column.javaType == "Long")
|
||||
:value="parseInt(dict.value)"
|
||||
#else
|
||||
:value="dict.value"
|
||||
#end
|
||||
></el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
#elseif($column.htmlType == "select" && $dictType)
|
||||
<el-form-item label="${comment}" prop="${field}">
|
||||
<el-select v-model="form.${field}" placeholder="请选择${comment}">
|
||||
<el-option label="请选择字典生成" value="" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
#elseif($column.htmlType == "checkbox" && "" != $dictType)
|
||||
<el-form-item label="${comment}" prop="${field}">
|
||||
<el-checkbox-group v-model="form.${field}">
|
||||
<el-checkbox
|
||||
v-for="dict in ${dictType}"
|
||||
:key="dict.value"
|
||||
:label="dict.value">
|
||||
{{dict.label}}
|
||||
</el-checkbox>
|
||||
</el-checkbox-group>
|
||||
</el-form-item>
|
||||
#elseif($column.htmlType == "checkbox" && $dictType)
|
||||
<el-form-item label="${comment}" prop="${field}">
|
||||
<el-checkbox-group v-model="form.${field}">
|
||||
<el-checkbox>请选择字典生成</el-checkbox>
|
||||
</el-checkbox-group>
|
||||
</el-form-item>
|
||||
#elseif($column.htmlType == "radio" && "" != $dictType)
|
||||
<el-form-item label="${comment}" prop="${field}">
|
||||
<el-radio-group v-model="form.${field}">
|
||||
<el-radio
|
||||
v-for="dict in ${dictType}"
|
||||
:key="dict.value"
|
||||
#if($column.javaType == "Integer" || $column.javaType == "Long")
|
||||
:value="parseInt(dict.value)"
|
||||
#else
|
||||
:value="dict.value"
|
||||
#end
|
||||
>{{dict.label}}</el-radio>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
#elseif($column.htmlType == "radio" && $dictType)
|
||||
<el-form-item label="${comment}" prop="${field}">
|
||||
<el-radio-group v-model="form.${field}">
|
||||
<el-radio value="1">请选择字典生成</el-radio>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
#elseif($column.htmlType == "datetime")
|
||||
<el-form-item label="${comment}" prop="${field}">
|
||||
<el-date-picker clearable
|
||||
v-model="form.${field}"
|
||||
type="datetime"
|
||||
value-format="YYYY-MM-DD HH:mm:ss"
|
||||
placeholder="请选择${comment}">
|
||||
</el-date-picker>
|
||||
</el-form-item>
|
||||
#elseif($column.htmlType == "textarea")
|
||||
<el-form-item label="${comment}" prop="${field}">
|
||||
<el-input v-model="form.${field}" type="textarea" placeholder="请输入内容" />
|
||||
</el-form-item>
|
||||
#end
|
||||
#end
|
||||
#end
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<div class="dialog-footer">
|
||||
<el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
|
||||
<el-button @click="cancel">取 消</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup name="${BusinessName}" lang="ts">
|
||||
import { list${BusinessName}, get${BusinessName}, del${BusinessName}, add${BusinessName}, update${BusinessName} } from '@/api/${moduleName}/${businessName}';
|
||||
import { ${BusinessName}VO, ${BusinessName}Query, ${BusinessName}Form } from '@/api/${moduleName}/${businessName}/types';
|
||||
|
||||
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
|
||||
#if(${dicts} != '')
|
||||
#set($dictsNoSymbol=$dicts.replace("'", ""))
|
||||
const { ${dictsNoSymbol} } = toRefs<any>(proxy?.useDict(${dicts}));
|
||||
#end
|
||||
|
||||
const ${businessName}List = ref<${BusinessName}VO[]>([]);
|
||||
const buttonLoading = ref(false);
|
||||
const loading = ref(true);
|
||||
const showSearch = ref(true);
|
||||
const ids = ref<Array<string | number>>([]);
|
||||
const single = ref(true);
|
||||
const multiple = ref(true);
|
||||
const total = ref(0);
|
||||
#foreach ($column in $columns)
|
||||
#if($column.htmlType == "datetime" && $column.queryType == "BETWEEN")
|
||||
#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)})
|
||||
const dateRange${AttrName} = ref<[DateModelType, DateModelType]>(['', '']);
|
||||
#end
|
||||
#end
|
||||
|
||||
const queryFormRef = ref<ElFormInstance>();
|
||||
const ${businessName}FormRef = ref<ElFormInstance>();
|
||||
|
||||
const dialog = reactive<DialogOption>({
|
||||
visible: false,
|
||||
title: ''
|
||||
});
|
||||
|
||||
const initFormData: ${BusinessName}Form = {
|
||||
#foreach ($column in $columns)
|
||||
#if($column.insert || $column.edit)
|
||||
#if($column.htmlType == "checkbox")
|
||||
$column.javaField: []#if($foreach.count != $columns.size()),#end
|
||||
#else
|
||||
$column.javaField: undefined#if($foreach.count != $columns.size()),#end
|
||||
#end
|
||||
#end
|
||||
#end
|
||||
}
|
||||
const data = reactive<PageData<${BusinessName}Form, ${BusinessName}Query>>({
|
||||
form: {...initFormData},
|
||||
queryParams: {
|
||||
pageNum: 1,
|
||||
pageSize: 10,
|
||||
#foreach ($column in $columns)
|
||||
#if($column.query)
|
||||
#if($column.htmlType != "datetime" || $column.queryType != "BETWEEN")
|
||||
$column.javaField: undefined,
|
||||
#end
|
||||
#end
|
||||
#end
|
||||
params: {
|
||||
#foreach ($column in $columns)
|
||||
#if($column.query)
|
||||
#if($column.htmlType == "datetime" && $column.queryType == "BETWEEN")
|
||||
$column.javaField: undefined#if($foreach.count != $columns.size()),#end
|
||||
#end
|
||||
#end
|
||||
#end
|
||||
}
|
||||
},
|
||||
rules: {
|
||||
#foreach ($column in $columns)
|
||||
#if($column.insert || $column.edit)
|
||||
#if($column.required)
|
||||
#set($parentheseIndex=$column.columnComment.indexOf("("))
|
||||
#if($parentheseIndex != -1)
|
||||
#set($comment=$column.columnComment.substring(0, $parentheseIndex))
|
||||
#else
|
||||
#set($comment=$column.columnComment)
|
||||
#end
|
||||
$column.javaField: [
|
||||
{ required: true, message: "$comment不能为空", trigger: #if($column.htmlType == "select" || $column.htmlType == "radio")"change"#else"blur"#end }
|
||||
]#if($foreach.count != $columns.size()),#end
|
||||
#end
|
||||
#end
|
||||
#end
|
||||
}
|
||||
});
|
||||
|
||||
const { queryParams, form, rules } = toRefs(data);
|
||||
|
||||
/** 查询${functionName}列表 */
|
||||
const getList = async () => {
|
||||
loading.value = true;
|
||||
#foreach ($column in $columns)
|
||||
#if($column.htmlType == "datetime" && $column.queryType == "BETWEEN")
|
||||
queryParams.value.params = {};
|
||||
#break
|
||||
#end
|
||||
#end
|
||||
#foreach ($column in $columns)
|
||||
#if($column.htmlType == "datetime" && $column.queryType == "BETWEEN")
|
||||
#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)})
|
||||
proxy?.addDateRange(queryParams.value, dateRange${AttrName}.value, '${AttrName}');
|
||||
#end
|
||||
#end
|
||||
const res = await list${BusinessName}(queryParams.value);
|
||||
${businessName}List.value = res.rows;
|
||||
total.value = res.total;
|
||||
loading.value = false;
|
||||
}
|
||||
|
||||
/** 取消按钮 */
|
||||
const cancel = () => {
|
||||
reset();
|
||||
dialog.visible = false;
|
||||
}
|
||||
|
||||
/** 表单重置 */
|
||||
const reset = () => {
|
||||
form.value = {...initFormData};
|
||||
${businessName}FormRef.value?.resetFields();
|
||||
}
|
||||
|
||||
/** 搜索按钮操作 */
|
||||
const handleQuery = () => {
|
||||
queryParams.value.pageNum = 1;
|
||||
getList();
|
||||
}
|
||||
|
||||
/** 重置按钮操作 */
|
||||
const resetQuery = () => {
|
||||
#foreach ($column in $columns)
|
||||
#if($column.htmlType == "datetime" && $column.queryType == "BETWEEN")
|
||||
#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)})
|
||||
dateRange${AttrName}.value = ['', ''];
|
||||
#end
|
||||
#end
|
||||
queryFormRef.value?.resetFields();
|
||||
handleQuery();
|
||||
}
|
||||
|
||||
/** 多选框选中数据 */
|
||||
const handleSelectionChange = (selection: ${BusinessName}VO[]) => {
|
||||
ids.value = selection.map(item => item.${pkColumn.javaField});
|
||||
single.value = selection.length != 1;
|
||||
multiple.value = !selection.length;
|
||||
}
|
||||
|
||||
/** 新增按钮操作 */
|
||||
const handleAdd = () => {
|
||||
reset();
|
||||
dialog.visible = true;
|
||||
dialog.title = "添加${functionName}";
|
||||
}
|
||||
|
||||
/** 修改按钮操作 */
|
||||
const handleUpdate = async (row?: ${BusinessName}VO) => {
|
||||
reset();
|
||||
const _${pkColumn.javaField} = row?.${pkColumn.javaField} || ids.value[0]
|
||||
const res = await get${BusinessName}(_${pkColumn.javaField});
|
||||
Object.assign(form.value, res.data);
|
||||
#foreach ($column in $columns)
|
||||
#if($column.htmlType == "checkbox")
|
||||
form.value.$column.javaField = form.value.${column.javaField}.split(",");
|
||||
#end
|
||||
#end
|
||||
dialog.visible = true;
|
||||
dialog.title = "修改${functionName}";
|
||||
}
|
||||
|
||||
/** 提交按钮 */
|
||||
const submitForm = () => {
|
||||
${businessName}FormRef.value?.validate(async (valid: boolean) => {
|
||||
if (valid) {
|
||||
buttonLoading.value = true;
|
||||
#foreach ($column in $columns)
|
||||
#if($column.htmlType == "checkbox")
|
||||
form.value.$column.javaField = form.value.${column.javaField}.join(",");
|
||||
#end
|
||||
#end
|
||||
if (form.value.${pkColumn.javaField}) {
|
||||
await update${BusinessName}(form.value).finally(() => buttonLoading.value = false);
|
||||
} else {
|
||||
await add${BusinessName}(form.value).finally(() => buttonLoading.value = false);
|
||||
}
|
||||
proxy?.#[[$modal]]#.msgSuccess("操作成功");
|
||||
dialog.visible = false;
|
||||
await getList();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** 删除按钮操作 */
|
||||
const handleDelete = async (row?: ${BusinessName}VO) => {
|
||||
const _${pkColumn.javaField}s = row?.${pkColumn.javaField} || ids.value;
|
||||
await proxy?.#[[$modal]]#.confirm('是否确认删除${functionName}编号为"' + _${pkColumn.javaField}s + '"的数据项?').finally(() => loading.value = false);
|
||||
await del${BusinessName}(_${pkColumn.javaField}s);
|
||||
proxy?.#[[$modal]]#.msgSuccess("删除成功");
|
||||
await getList();
|
||||
}
|
||||
|
||||
/** 导出按钮操作 */
|
||||
const handleExport = () => {
|
||||
proxy?.download('${moduleName}/${businessName}/export', {
|
||||
...queryParams.value
|
||||
}, `${businessName}_#[[${new Date().getTime()}]]#.xlsx`)
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
getList();
|
||||
});
|
||||
</script>
|
@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<!DOCTYPE mapper
|
||||
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="${packageName}.mapper.${ClassName}Mapper">
|
||||
|
||||
</mapper>
|
30
ruoyi-modules/ruoyi-job/Dockerfile
Normal file
30
ruoyi-modules/ruoyi-job/Dockerfile
Normal file
@ -0,0 +1,30 @@
|
||||
# 贝尔实验室 Spring 官方推荐镜像 JDK下载地址 https://bell-sw.com/pages/downloads/
|
||||
FROM bellsoft/liberica-openjdk-rocky:17.0.15-cds
|
||||
#FROM bellsoft/liberica-openjdk-rocky:21.0.7-cds
|
||||
#FROM findepi/graalvm:java17-native
|
||||
|
||||
LABEL maintainer="Lion Li"
|
||||
|
||||
RUN mkdir -p /ruoyi/job/logs \
|
||||
/ruoyi/job/temp \
|
||||
/ruoyi/skywalking/agent
|
||||
|
||||
WORKDIR /ruoyi/job
|
||||
|
||||
ENV SERVER_PORT=9203 SNAIL_PORT=29203 LANG=C.UTF-8 LC_ALL=C.UTF-8 JAVA_OPTS=""
|
||||
|
||||
EXPOSE ${SERVER_PORT}
|
||||
# 暴露 snail job 客户端端口 用于定时任务调度中心通信
|
||||
EXPOSE ${SNAIL_PORT}
|
||||
|
||||
ADD ./target/ruoyi-job.jar ./app.jar
|
||||
|
||||
SHELL ["/bin/bash", "-c"]
|
||||
|
||||
ENTRYPOINT java -Djava.security.egd=file:/dev/./urandom -Dserver.port=${SERVER_PORT} \
|
||||
-Dsnail-job.port=${SNAIL_PORT} \
|
||||
#-Dskywalking.agent.service_name=ruoyi-job \
|
||||
#-javaagent:/ruoyi/skywalking/agent/skywalking-agent.jar \
|
||||
-XX:+HeapDumpOnOutOfMemoryError -XX:+UseZGC ${JAVA_OPTS} \
|
||||
-jar app.jar
|
||||
|
93
ruoyi-modules/ruoyi-job/pom.xml
Normal file
93
ruoyi-modules/ruoyi-job/pom.xml
Normal file
@ -0,0 +1,93 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-modules</artifactId>
|
||||
<version>${revision}</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>ruoyi-job</artifactId>
|
||||
|
||||
<description>
|
||||
ruoyi-job 任务调度模块
|
||||
</description>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-nacos</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- RuoYi Common Log -->
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-log</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-web</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-dubbo</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-mybatis</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-job</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-tenant</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-mybatis</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-security</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- RuoYi Api System -->
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-api-system</artifactId>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>${project.artifactId}</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>repackage</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
@ -0,0 +1,24 @@
|
||||
package org.dromara.job;
|
||||
|
||||
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.context.metrics.buffering.BufferingApplicationStartup;
|
||||
|
||||
/**
|
||||
* 任务调度模块
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@EnableDubbo
|
||||
@SpringBootApplication
|
||||
public class RuoYiJobApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication application = new SpringApplication(RuoYiJobApplication.class);
|
||||
application.setApplicationStartup(new BufferingApplicationStartup(2048));
|
||||
application.run(args);
|
||||
System.out.println("(♥◠‿◠)ノ゙ 任务调度模块启动成功 ლ(´ڡ`ლ)゙ ");
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,30 @@
|
||||
package org.dromara.job.entity;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
@Data
|
||||
public class BillDto {
|
||||
|
||||
/**
|
||||
* 账单ID
|
||||
*/
|
||||
private Long billId;
|
||||
|
||||
/**
|
||||
* 账单渠道
|
||||
*/
|
||||
private String billChannel;
|
||||
|
||||
/**
|
||||
* 账单日期
|
||||
*/
|
||||
private String billDate;
|
||||
|
||||
/**
|
||||
* 账单金额
|
||||
*/
|
||||
private BigDecimal billAmount;
|
||||
|
||||
}
|
@ -0,0 +1,42 @@
|
||||
package org.dromara.job.snailjob;
|
||||
|
||||
import cn.hutool.core.date.DateUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.aizuda.snailjob.client.job.core.annotation.JobExecutor;
|
||||
import com.aizuda.snailjob.client.job.core.dto.JobArgs;
|
||||
import com.aizuda.snailjob.client.model.ExecuteResult;
|
||||
import com.aizuda.snailjob.common.log.SnailJobLog;
|
||||
import org.dromara.common.json.utils.JsonUtils;
|
||||
import org.dromara.job.entity.BillDto;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* DAG工作流任务-模拟支付宝账单任务
|
||||
* <a href="https://juejin.cn/post/7487860254114644019"></a>
|
||||
*
|
||||
* @author 老马
|
||||
*/
|
||||
@Component
|
||||
@JobExecutor(name = "alipayBillTask")
|
||||
public class AlipayBillTask {
|
||||
|
||||
public ExecuteResult jobExecute(JobArgs jobArgs) throws InterruptedException {
|
||||
BillDto billDto = new BillDto();
|
||||
billDto.setBillId(23456789L);
|
||||
billDto.setBillChannel("alipay");
|
||||
// 设置清算日期
|
||||
String settlementDate = (String) jobArgs.getWfContext().get("settlementDate");
|
||||
if (StrUtil.equals(settlementDate, "sysdate")) {
|
||||
settlementDate = DateUtil.today();
|
||||
}
|
||||
billDto.setBillDate(settlementDate);
|
||||
billDto.setBillAmount(new BigDecimal("2345.67"));
|
||||
// 把billDto对象放入上下文进行传递
|
||||
jobArgs.appendContext("alipay", JsonUtils.toJsonString(billDto));
|
||||
SnailJobLog.REMOTE.info("上下文: {}", jobArgs.getWfContext());
|
||||
return ExecuteResult.success(billDto);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,45 @@
|
||||
package org.dromara.job.snailjob;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.aizuda.snailjob.client.job.core.annotation.JobExecutor;
|
||||
import com.aizuda.snailjob.client.job.core.dto.JobArgs;
|
||||
import com.aizuda.snailjob.client.model.ExecuteResult;
|
||||
import com.aizuda.snailjob.common.log.SnailJobLog;
|
||||
import org.dromara.common.json.utils.JsonUtils;
|
||||
import org.dromara.job.entity.BillDto;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* DAG工作流任务-模拟汇总账单任务
|
||||
* <a href="https://juejin.cn/post/7487860254114644019"></a>
|
||||
*
|
||||
* @author 老马
|
||||
*/
|
||||
@Component
|
||||
@JobExecutor(name = "summaryBillTask")
|
||||
public class SummaryBillTask {
|
||||
|
||||
public ExecuteResult jobExecute(JobArgs jobArgs) throws InterruptedException {
|
||||
// 获得微信账单
|
||||
BigDecimal wechatAmount = BigDecimal.valueOf(0);
|
||||
String wechat = (String) jobArgs.getWfContext("wechat");
|
||||
if (StrUtil.isNotBlank(wechat)) {
|
||||
BillDto wechatBillDto = JsonUtils.parseObject(wechat, BillDto.class);
|
||||
wechatAmount = wechatBillDto.getBillAmount();
|
||||
}
|
||||
// 获得支付宝账单
|
||||
BigDecimal alipayAmount = BigDecimal.valueOf(0);
|
||||
String alipay = (String) jobArgs.getWfContext("alipay");
|
||||
if (StrUtil.isNotBlank(alipay)) {
|
||||
BillDto alipayBillDto = JsonUtils.parseObject(alipay, BillDto.class);
|
||||
alipayAmount = alipayBillDto.getBillAmount();
|
||||
}
|
||||
// 汇总账单
|
||||
BigDecimal totalAmount = wechatAmount.add(alipayAmount);
|
||||
SnailJobLog.REMOTE.info("总金额: {}", totalAmount);
|
||||
return ExecuteResult.success(totalAmount);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
package org.dromara.job.snailjob;
|
||||
|
||||
import com.aizuda.snailjob.client.job.core.annotation.JobExecutor;
|
||||
import com.aizuda.snailjob.client.job.core.dto.JobArgs;
|
||||
import com.aizuda.snailjob.client.model.ExecuteResult;
|
||||
import com.aizuda.snailjob.common.core.util.JsonUtil;
|
||||
import com.aizuda.snailjob.common.log.SnailJobLog;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 正常任务
|
||||
* <a href="https://juejin.cn/post/7418074037392293914"></a>
|
||||
*
|
||||
* @author 老马
|
||||
*/
|
||||
@Component
|
||||
@JobExecutor(name = "testJobExecutor")
|
||||
public class TestAnnoJobExecutor {
|
||||
|
||||
public ExecuteResult jobExecute(JobArgs jobArgs) {
|
||||
SnailJobLog.LOCAL.info("testJobExecutor. jobArgs:{}", JsonUtil.toJsonString(jobArgs));
|
||||
SnailJobLog.REMOTE.info("testJobExecutor. jobArgs:{}", JsonUtil.toJsonString(jobArgs));
|
||||
return ExecuteResult.success("测试成功");
|
||||
}
|
||||
}
|
@ -0,0 +1,37 @@
|
||||
package org.dromara.job.snailjob;
|
||||
|
||||
import cn.hutool.core.util.RandomUtil;
|
||||
import com.aizuda.snailjob.client.job.core.annotation.JobExecutor;
|
||||
import com.aizuda.snailjob.client.job.core.dto.JobArgs;
|
||||
import com.aizuda.snailjob.client.model.ExecuteResult;
|
||||
import com.aizuda.snailjob.common.log.SnailJobLog;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 广播任务
|
||||
* <a href="https://juejin.cn/post/7422948006150438950"></a>
|
||||
*
|
||||
* @author 老马
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@JobExecutor(name = "testBroadcastJob")
|
||||
public class TestBroadcastJob {
|
||||
|
||||
@Value("${snail-job.port}")
|
||||
private int clientPort;
|
||||
|
||||
public ExecuteResult jobExecute(JobArgs jobArgs) {
|
||||
int randomInt = RandomUtil.randomInt(100);
|
||||
log.info("随机数: {}", randomInt);
|
||||
SnailJobLog.REMOTE.info("随机数: {},客户端端口:{}", randomInt, clientPort);
|
||||
if (randomInt < 50) {
|
||||
throw new RuntimeException("随机数小于50,收集日志任务执行失败");
|
||||
}
|
||||
// 获得jobArgs 中传入的相加的两个数
|
||||
return ExecuteResult.success("随机数大于50,收集日志任务执行成功");
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
package org.dromara.job.snailjob;
|
||||
|
||||
import com.aizuda.snailjob.client.job.core.dto.JobArgs;
|
||||
import com.aizuda.snailjob.client.job.core.executor.AbstractJobExecutor;
|
||||
import com.aizuda.snailjob.client.model.ExecuteResult;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* @author opensnail
|
||||
* @date 2024-05-17
|
||||
*/
|
||||
@Component
|
||||
public class TestClassJobExecutor extends AbstractJobExecutor {
|
||||
|
||||
@Override
|
||||
protected ExecuteResult doJobExecute(JobArgs jobArgs) {
|
||||
return ExecuteResult.success("TestJobExecutor测试成功");
|
||||
}
|
||||
}
|
@ -0,0 +1,53 @@
|
||||
package org.dromara.job.snailjob;
|
||||
|
||||
import cn.hutool.core.thread.ThreadUtil;
|
||||
import cn.hutool.extra.spring.SpringUtil;
|
||||
import com.aizuda.snailjob.client.job.core.MapHandler;
|
||||
import com.aizuda.snailjob.client.job.core.annotation.JobExecutor;
|
||||
import com.aizuda.snailjob.client.job.core.annotation.MapExecutor;
|
||||
import com.aizuda.snailjob.client.job.core.dto.MapArgs;
|
||||
import com.aizuda.snailjob.client.model.ExecuteResult;
|
||||
import com.aizuda.snailjob.common.log.SnailJobLog;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
/**
|
||||
* Map任务 动态分配 只分片不关注结果
|
||||
* <a href="https://juejin.cn/post/7446362500478894106"></a>
|
||||
*
|
||||
* @author 老马
|
||||
*/
|
||||
@Component
|
||||
@JobExecutor(name = "testMapJobAnnotation")
|
||||
public class TestMapJobAnnotation {
|
||||
|
||||
@MapExecutor
|
||||
public ExecuteResult doJobMapExecute(MapArgs mapArgs, MapHandler mapHandler) {
|
||||
// 生成1~200数值并分片
|
||||
int partitionSize = 50;
|
||||
List<List<Integer>> partition = IntStream.rangeClosed(1, 200)
|
||||
.boxed()
|
||||
.collect(Collectors.groupingBy(i -> (i - 1) / partitionSize))
|
||||
.values()
|
||||
.stream()
|
||||
.toList();
|
||||
SnailJobLog.REMOTE.info("端口:{}完成分配任务", SpringUtil.getProperty("server.port"));
|
||||
return mapHandler.doMap(partition, "doCalc");
|
||||
}
|
||||
|
||||
@MapExecutor(taskName = "doCalc")
|
||||
public ExecuteResult doCalc(MapArgs mapArgs) {
|
||||
List<Integer> sourceList = (List<Integer>) mapArgs.getMapResult();
|
||||
// 遍历sourceList的每一个元素,计算出一个累加值partitionTotal
|
||||
int partitionTotal = sourceList.stream().mapToInt(i -> i).sum();
|
||||
// 打印日志到服务器
|
||||
ThreadUtil.sleep(3, TimeUnit.SECONDS);
|
||||
SnailJobLog.REMOTE.info("端口:{},partitionTotal:{}", SpringUtil.getProperty("server.port"), partitionTotal);
|
||||
return ExecuteResult.success(partitionTotal);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,60 @@
|
||||
package org.dromara.job.snailjob;
|
||||
|
||||
import cn.hutool.core.thread.ThreadUtil;
|
||||
import cn.hutool.extra.spring.SpringUtil;
|
||||
import com.aizuda.snailjob.client.job.core.MapHandler;
|
||||
import com.aizuda.snailjob.client.job.core.annotation.JobExecutor;
|
||||
import com.aizuda.snailjob.client.job.core.annotation.MapExecutor;
|
||||
import com.aizuda.snailjob.client.job.core.annotation.ReduceExecutor;
|
||||
import com.aizuda.snailjob.client.job.core.dto.MapArgs;
|
||||
import com.aizuda.snailjob.client.job.core.dto.ReduceArgs;
|
||||
import com.aizuda.snailjob.client.model.ExecuteResult;
|
||||
import com.aizuda.snailjob.common.log.SnailJobLog;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
/**
|
||||
* MapReduce任务 动态分配 分片后合并结果
|
||||
* <a href="https://juejin.cn/post/7448551286506913802"></a>
|
||||
*
|
||||
* @author 老马
|
||||
*/
|
||||
@Component
|
||||
@JobExecutor(name = "testMapReduceAnnotation1")
|
||||
public class TestMapReduceAnnotation1 {
|
||||
|
||||
@MapExecutor
|
||||
public ExecuteResult rootMapExecute(MapArgs mapArgs, MapHandler mapHandler) {
|
||||
int partitionSize = 50;
|
||||
List<List<Integer>> partition = IntStream.rangeClosed(1, 200)
|
||||
.boxed()
|
||||
.collect(Collectors.groupingBy(i -> (i - 1) / partitionSize))
|
||||
.values()
|
||||
.stream()
|
||||
.toList();
|
||||
SnailJobLog.REMOTE.info("端口:{}完成分配任务", SpringUtil.getProperty("server.port"));
|
||||
return mapHandler.doMap(partition, "doCalc");
|
||||
}
|
||||
|
||||
@MapExecutor(taskName = "doCalc")
|
||||
public ExecuteResult doCalc(MapArgs mapArgs) {
|
||||
List<Integer> sourceList = (List<Integer>) mapArgs.getMapResult();
|
||||
// 遍历sourceList的每一个元素,计算出一个累加值partitionTotal
|
||||
int partitionTotal = sourceList.stream().mapToInt(i -> i).sum();
|
||||
// 打印日志到服务器
|
||||
ThreadUtil.sleep(3, TimeUnit.SECONDS);
|
||||
SnailJobLog.REMOTE.info("端口:{},partitionTotal:{}", SpringUtil.getProperty("server.port"), partitionTotal);
|
||||
return ExecuteResult.success(partitionTotal);
|
||||
}
|
||||
|
||||
@ReduceExecutor
|
||||
public ExecuteResult reduceExecute(ReduceArgs reduceArgs) {
|
||||
int reduceTotal = reduceArgs.getMapResult().stream().mapToInt(i -> Integer.parseInt((String) i)).sum();
|
||||
SnailJobLog.REMOTE.info("端口:{},reduceTotal:{}", SpringUtil.getProperty("server.port"), reduceTotal);
|
||||
return ExecuteResult.success(reduceTotal);
|
||||
}
|
||||
}
|
@ -0,0 +1,36 @@
|
||||
package org.dromara.job.snailjob;
|
||||
|
||||
import com.aizuda.snailjob.client.job.core.annotation.JobExecutor;
|
||||
import com.aizuda.snailjob.client.job.core.dto.JobArgs;
|
||||
import com.aizuda.snailjob.client.model.ExecuteResult;
|
||||
import com.aizuda.snailjob.common.log.SnailJobLog;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 静态分片 根据服务端任务参数分片
|
||||
* <a href="https://juejin.cn/post/7426232375703896101"></a>
|
||||
*
|
||||
* @author 老马
|
||||
*/
|
||||
@Component
|
||||
@JobExecutor(name = "testStaticShardingJob")
|
||||
public class TestStaticShardingJob {
|
||||
|
||||
public ExecuteResult jobExecute(JobArgs jobArgs) {
|
||||
String jobParams = String.valueOf(jobArgs.getJobParams());
|
||||
SnailJobLog.LOCAL.info("开始执行分片任务,参数:{}", jobParams);
|
||||
// 获得jobArgs 中传入的开始id和结束id
|
||||
String[] split = jobParams.split(",");
|
||||
Long fromId = Long.parseLong(split[0]);
|
||||
Long toId = Long.parseLong(split[1]);
|
||||
// 模拟数据库操作,对范围id,进行加密处理
|
||||
try {
|
||||
SnailJobLog.REMOTE.info("开始对id范围:{}进行加密处理", fromId + "-" + toId);
|
||||
Thread.sleep(3000);
|
||||
SnailJobLog.REMOTE.info("对id范围:{}进行加密处理完成", fromId + "-" + toId);
|
||||
} catch (InterruptedException e) {
|
||||
return ExecuteResult.failure("任务执行失败");
|
||||
}
|
||||
return ExecuteResult.success("执行分片任务完成");
|
||||
}
|
||||
}
|
@ -0,0 +1,43 @@
|
||||
package org.dromara.job.snailjob;
|
||||
|
||||
import cn.hutool.core.date.DateUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.aizuda.snailjob.client.job.core.annotation.JobExecutor;
|
||||
import com.aizuda.snailjob.client.job.core.dto.JobArgs;
|
||||
import com.aizuda.snailjob.client.model.ExecuteResult;
|
||||
import com.aizuda.snailjob.common.log.SnailJobLog;
|
||||
import org.dromara.common.json.utils.JsonUtils;
|
||||
import org.dromara.job.entity.BillDto;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* DAG工作流任务-模拟微信账单任务
|
||||
* <a href="https://juejin.cn/post/7487860254114644019"></a>
|
||||
*
|
||||
* @author 老马
|
||||
*/
|
||||
@Component
|
||||
@JobExecutor(name = "wechatBillTask")
|
||||
public class WechatBillTask {
|
||||
|
||||
public ExecuteResult jobExecute(JobArgs jobArgs) throws InterruptedException {
|
||||
BillDto billDto = new BillDto();
|
||||
billDto.setBillId(123456789L);
|
||||
billDto.setBillChannel("wechat");
|
||||
// 从上下文中获得清算日期并设置,如果上下文中清算日期
|
||||
// 是sysdate设置为当前日期;否则取管理页面设置的值
|
||||
String settlementDate = (String) jobArgs.getWfContext().get("settlementDate");
|
||||
if (StrUtil.equals(settlementDate, "sysdate")) {
|
||||
settlementDate = DateUtil.today();
|
||||
}
|
||||
billDto.setBillDate(settlementDate);
|
||||
billDto.setBillAmount(new BigDecimal("1234.56"));
|
||||
// 把billDto对象放入上下文进行传递
|
||||
jobArgs.appendContext("wechat", JsonUtils.toJsonString(billDto));
|
||||
SnailJobLog.REMOTE.info("上下文: {}", jobArgs.getWfContext());
|
||||
return ExecuteResult.success(billDto);
|
||||
}
|
||||
|
||||
}
|
34
ruoyi-modules/ruoyi-job/src/main/resources/application.yml
Normal file
34
ruoyi-modules/ruoyi-job/src/main/resources/application.yml
Normal file
@ -0,0 +1,34 @@
|
||||
# Tomcat
|
||||
server:
|
||||
port: 9203
|
||||
|
||||
# Spring
|
||||
spring:
|
||||
application:
|
||||
# 应用名称
|
||||
name: ruoyi-job
|
||||
profiles:
|
||||
# 环境配置
|
||||
active: @profiles.active@
|
||||
|
||||
--- # nacos 配置
|
||||
spring:
|
||||
cloud:
|
||||
nacos:
|
||||
# nacos 服务地址
|
||||
server-addr: @nacos.server@
|
||||
username: @nacos.username@
|
||||
password: @nacos.password@
|
||||
discovery:
|
||||
# 注册组
|
||||
group: @nacos.discovery.group@
|
||||
namespace: ${spring.profiles.active}
|
||||
config:
|
||||
# 配置组
|
||||
group: @nacos.config.group@
|
||||
namespace: ${spring.profiles.active}
|
||||
config:
|
||||
import:
|
||||
- optional:nacos:application-common.yml
|
||||
- optional:nacos:datasource.yml
|
||||
- optional:nacos:${spring.application.name}.yml
|
10
ruoyi-modules/ruoyi-job/src/main/resources/banner.txt
Normal file
10
ruoyi-modules/ruoyi-job/src/main/resources/banner.txt
Normal file
@ -0,0 +1,10 @@
|
||||
Spring Boot Version: ${spring-boot.version}
|
||||
Spring Application Name: ${spring.application.name}
|
||||
_ _ _
|
||||
(_) (_) | |
|
||||
_ __ _ _ ___ _ _ _ ______ _ ___ | |__
|
||||
| '__| | | |/ _ \| | | | |______| |/ _ \| '_ \
|
||||
| | | |_| | (_) | |_| | | | | (_) | |_) |
|
||||
|_| \__,_|\___/ \__, |_| | |\___/|_.__/
|
||||
__/ | _/ |
|
||||
|___/ |__/
|
28
ruoyi-modules/ruoyi-job/src/main/resources/logback-plus.xml
Normal file
28
ruoyi-modules/ruoyi-job/src/main/resources/logback-plus.xml
Normal file
@ -0,0 +1,28 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration scan="true" scanPeriod="60 seconds" debug="false">
|
||||
<!-- 日志存放路径 -->
|
||||
<property name="log.path" value="logs/${project.artifactId}"/>
|
||||
<!-- 日志输出格式 -->
|
||||
<property name="console.log.pattern"
|
||||
value="%cyan(%d{yyyy-MM-dd HH:mm:ss}) %green([%thread]) %highlight(%-5level) %boldMagenta(%logger{36}%n) - %msg%n"/>
|
||||
|
||||
<!-- 控制台输出 -->
|
||||
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>${console.log.pattern}</pattern>
|
||||
<charset>utf-8</charset>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<include resource="logback-common.xml" />
|
||||
|
||||
<include resource="logback-logstash.xml" />
|
||||
|
||||
<!-- 开启 skywalking 日志收集 -->
|
||||
<include resource="logback-skylog.xml" />
|
||||
|
||||
<!--系统操作日志-->
|
||||
<root level="info">
|
||||
<appender-ref ref="console"/>
|
||||
</root>
|
||||
</configuration>
|
27
ruoyi-modules/ruoyi-resource/Dockerfile
Normal file
27
ruoyi-modules/ruoyi-resource/Dockerfile
Normal file
@ -0,0 +1,27 @@
|
||||
# 贝尔实验室 Spring 官方推荐镜像 JDK下载地址 https://bell-sw.com/pages/downloads/
|
||||
FROM bellsoft/liberica-openjdk-rocky:17.0.15-cds
|
||||
#FROM bellsoft/liberica-openjdk-rocky:21.0.7-cds
|
||||
#FROM findepi/graalvm:java17-native
|
||||
|
||||
LABEL maintainer="Lion Li"
|
||||
|
||||
RUN mkdir -p /ruoyi/resource/logs \
|
||||
/ruoyi/resource/temp \
|
||||
/ruoyi/skywalking/agent
|
||||
|
||||
WORKDIR /ruoyi/resource
|
||||
|
||||
ENV SERVER_PORT=9204 LANG=C.UTF-8 LC_ALL=C.UTF-8 JAVA_OPTS=""
|
||||
|
||||
EXPOSE ${SERVER_PORT}
|
||||
|
||||
ADD ./target/ruoyi-resource.jar ./app.jar
|
||||
|
||||
SHELL ["/bin/bash", "-c"]
|
||||
|
||||
ENTRYPOINT java -Djava.security.egd=file:/dev/./urandom -Dserver.port=${SERVER_PORT} \
|
||||
#-Dskywalking.agent.service_name=ruoyi-resource \
|
||||
#-javaagent:/ruoyi/skywalking/agent/skywalking-agent.jar \
|
||||
-XX:+HeapDumpOnOutOfMemoryError -XX:+UseZGC ${JAVA_OPTS} \
|
||||
-jar app.jar
|
||||
|
141
ruoyi-modules/ruoyi-resource/pom.xml
Normal file
141
ruoyi-modules/ruoyi-resource/pom.xml
Normal file
@ -0,0 +1,141 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-modules</artifactId>
|
||||
<version>${revision}</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>ruoyi-resource</artifactId>
|
||||
|
||||
<description>
|
||||
ruoyi-resource资源服务
|
||||
</description>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-nacos</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-sentinel</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-doc</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-dubbo</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-seata</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-web</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-log</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-oss</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-ratelimiter</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-mail</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-sms</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-mybatis</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-tenant</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-security</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-translation</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-websocket</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-sse</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-service-impl</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- RuoYi Api System -->
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-api-system</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-api-resource</artifactId>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>${project.artifactId}</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>repackage</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
@ -0,0 +1,23 @@
|
||||
package org.dromara.resource;
|
||||
|
||||
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
|
||||
import org.springframework.boot.context.metrics.buffering.BufferingApplicationStartup;
|
||||
|
||||
/**
|
||||
* 资源服务
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@EnableDubbo
|
||||
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
|
||||
public class RuoYiResourceApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication application = new SpringApplication(RuoYiResourceApplication.class);
|
||||
application.setApplicationStartup(new BufferingApplicationStartup(2048));
|
||||
application.run(args);
|
||||
System.out.println("(♥◠‿◠)ノ゙ 资源服务模块启动成功 ლ(´ڡ`ლ)゙ ");
|
||||
}
|
||||
}
|
@ -0,0 +1,70 @@
|
||||
package org.dromara.resource.controller;
|
||||
|
||||
|
||||
import cn.hutool.core.util.RandomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.dromara.common.core.constant.Constants;
|
||||
import org.dromara.common.core.constant.GlobalConstants;
|
||||
import org.dromara.common.core.domain.R;
|
||||
import org.dromara.common.core.exception.ServiceException;
|
||||
import org.dromara.common.core.utils.SpringUtils;
|
||||
import org.dromara.common.ratelimiter.annotation.RateLimiter;
|
||||
import org.dromara.common.web.core.BaseController;
|
||||
import org.dromara.common.mail.config.properties.MailProperties;
|
||||
import org.dromara.common.mail.utils.MailUtils;
|
||||
import org.dromara.common.redis.utils.RedisUtils;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import java.time.Duration;
|
||||
|
||||
/**
|
||||
* 邮件功能
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Slf4j
|
||||
@Validated
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/email")
|
||||
public class SysEmailController extends BaseController {
|
||||
|
||||
private final MailProperties mailProperties;
|
||||
|
||||
/**
|
||||
* 邮箱验证码
|
||||
*
|
||||
* @param email 邮箱
|
||||
*/
|
||||
@GetMapping("/code")
|
||||
public R<Void> emailCode(@NotBlank(message = "{user.email.not.blank}") String email) {
|
||||
if (!mailProperties.getEnabled()) {
|
||||
return R.fail("当前系统没有开启邮箱功能!");
|
||||
}
|
||||
SpringUtils.getAopProxy(this).emailCodeImpl(email);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
/**
|
||||
* 邮箱验证码
|
||||
* 独立方法避免验证码关闭之后仍然走限流
|
||||
*/
|
||||
@RateLimiter(key = "#email", time = 60, count = 1)
|
||||
public void emailCodeImpl(String email) {
|
||||
String key = GlobalConstants.CAPTCHA_CODE_KEY + email;
|
||||
String code = RandomUtil.randomNumbers(4);
|
||||
RedisUtils.setCacheObject(key, code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
|
||||
try {
|
||||
MailUtils.sendText(email, "登录验证码", "您本次验证码为:" + code + ",有效性为" + Constants.CAPTCHA_EXPIRATION + "分钟,请尽快填写。");
|
||||
} catch (Exception e) {
|
||||
log.error("验证码短信发送异常 => {}", e.getMessage());
|
||||
throw new ServiceException(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,100 @@
|
||||
package org.dromara.resource.controller;
|
||||
|
||||
import cn.dev33.satoken.annotation.SaCheckPermission;
|
||||
import org.dromara.common.core.domain.R;
|
||||
import org.dromara.common.core.validate.AddGroup;
|
||||
import org.dromara.common.core.validate.EditGroup;
|
||||
import org.dromara.common.core.validate.QueryGroup;
|
||||
import org.dromara.common.web.core.BaseController;
|
||||
import org.dromara.common.log.annotation.Log;
|
||||
import org.dromara.common.log.enums.BusinessType;
|
||||
import org.dromara.common.mybatis.core.page.PageQuery;
|
||||
import org.dromara.common.mybatis.core.page.TableDataInfo;
|
||||
import org.dromara.resource.domain.bo.SysOssConfigBo;
|
||||
import org.dromara.resource.domain.vo.SysOssConfigVo;
|
||||
import org.dromara.resource.service.ISysOssConfigService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* 对象存储配置Controller
|
||||
*
|
||||
* @author Lion Li
|
||||
* @author 孤舟烟雨
|
||||
* @date 2021-08-13
|
||||
*/
|
||||
@Validated
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/oss/config")
|
||||
public class SysOssConfigController extends BaseController {
|
||||
|
||||
private final ISysOssConfigService iSysOssConfigService;
|
||||
|
||||
/**
|
||||
* 查询对象存储配置列表
|
||||
*/
|
||||
@SaCheckPermission("system:ossConfig:list")
|
||||
@GetMapping("/list")
|
||||
public TableDataInfo<SysOssConfigVo> list(@Validated(QueryGroup.class) SysOssConfigBo bo, PageQuery pageQuery) {
|
||||
return iSysOssConfigService.queryPageList(bo, pageQuery);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取对象存储配置详细信息
|
||||
*
|
||||
* @param ossConfigId OSS配置ID
|
||||
*/
|
||||
@SaCheckPermission("system:ossConfig:list")
|
||||
@GetMapping("/{ossConfigId}")
|
||||
public R<SysOssConfigVo> getInfo(@NotNull(message = "主键不能为空") @PathVariable("ossConfigId") Long ossConfigId) {
|
||||
return R.ok(iSysOssConfigService.queryById(ossConfigId));
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增对象存储配置
|
||||
*/
|
||||
@SaCheckPermission("system:ossConfig:add")
|
||||
@Log(title = "对象存储配置", businessType = BusinessType.INSERT)
|
||||
@PostMapping()
|
||||
public R<Void> add(@Validated(AddGroup.class) @RequestBody SysOssConfigBo bo) {
|
||||
return toAjax(iSysOssConfigService.insertByBo(bo));
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改对象存储配置
|
||||
*/
|
||||
@SaCheckPermission("system:ossConfig:edit")
|
||||
@Log(title = "对象存储配置", businessType = BusinessType.UPDATE)
|
||||
@PutMapping()
|
||||
public R<Void> edit(@Validated(EditGroup.class) @RequestBody SysOssConfigBo bo) {
|
||||
return toAjax(iSysOssConfigService.updateByBo(bo));
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除对象存储配置
|
||||
*
|
||||
* @param ossConfigIds OSS配置ID串
|
||||
*/
|
||||
@SaCheckPermission("system:ossConfig:remove")
|
||||
@Log(title = "对象存储配置", businessType = BusinessType.DELETE)
|
||||
@DeleteMapping("/{ossConfigIds}")
|
||||
public R<Void> remove(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ossConfigIds) {
|
||||
return toAjax(iSysOssConfigService.deleteWithValidByIds(Arrays.asList(ossConfigIds), true));
|
||||
}
|
||||
|
||||
/**
|
||||
* 状态修改
|
||||
*/
|
||||
@SaCheckPermission("system:ossConfig:edit")
|
||||
@Log(title = "对象存储状态修改", businessType = BusinessType.UPDATE)
|
||||
@PutMapping("/changeStatus")
|
||||
public R<Void> changeStatus(@RequestBody SysOssConfigBo bo) {
|
||||
return toAjax(iSysOssConfigService.updateOssConfigStatus(bo));
|
||||
}
|
||||
}
|
@ -0,0 +1,106 @@
|
||||
package org.dromara.resource.controller;
|
||||
|
||||
|
||||
import cn.dev33.satoken.annotation.SaCheckPermission;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.dromara.common.core.domain.R;
|
||||
import org.dromara.common.core.validate.QueryGroup;
|
||||
import org.dromara.common.web.core.BaseController;
|
||||
import org.dromara.common.log.annotation.Log;
|
||||
import org.dromara.common.log.enums.BusinessType;
|
||||
import org.dromara.common.mybatis.core.page.PageQuery;
|
||||
import org.dromara.common.mybatis.core.page.TableDataInfo;
|
||||
import org.dromara.resource.domain.bo.SysOssBo;
|
||||
import org.dromara.resource.domain.vo.SysOssUploadVo;
|
||||
import org.dromara.resource.domain.vo.SysOssVo;
|
||||
import org.dromara.resource.service.ISysOssService;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 文件上传 控制层
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Validated
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/oss")
|
||||
public class SysOssController extends BaseController {
|
||||
|
||||
private final ISysOssService iSysOssService;
|
||||
|
||||
/**
|
||||
* 查询OSS对象存储列表
|
||||
*/
|
||||
@SaCheckPermission("system:oss:list")
|
||||
@GetMapping("/list")
|
||||
public TableDataInfo<SysOssVo> list(@Validated(QueryGroup.class) SysOssBo bo, PageQuery pageQuery) {
|
||||
return iSysOssService.queryPageList(bo, pageQuery);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询OSS对象基于id串
|
||||
*
|
||||
* @param ossIds OSS对象ID串
|
||||
*/
|
||||
@SaCheckPermission("system:oss:query")
|
||||
@GetMapping("/listByIds/{ossIds}")
|
||||
public R<List<SysOssVo>> listByIds(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ossIds) {
|
||||
List<SysOssVo> list = iSysOssService.listByIds(Arrays.asList(ossIds));
|
||||
return R.ok(list);
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传OSS对象存储
|
||||
*
|
||||
* @param file 文件
|
||||
*/
|
||||
@SaCheckPermission("system:oss:upload")
|
||||
@Log(title = "OSS对象存储", businessType = BusinessType.INSERT)
|
||||
@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
public R<SysOssUploadVo> upload(@RequestPart("file") MultipartFile file) {
|
||||
if (ObjectUtil.isNull(file)) {
|
||||
return R.fail("上传文件不能为空");
|
||||
}
|
||||
SysOssVo oss = iSysOssService.upload(file);
|
||||
SysOssUploadVo uploadVo = new SysOssUploadVo();
|
||||
uploadVo.setUrl(oss.getUrl());
|
||||
uploadVo.setFileName(oss.getOriginalName());
|
||||
uploadVo.setOssId(oss.getOssId().toString());
|
||||
return R.ok(uploadVo);
|
||||
}
|
||||
|
||||
/**
|
||||
* 下载OSS对象存储
|
||||
*
|
||||
* @param ossId OSS对象ID
|
||||
*/
|
||||
@SaCheckPermission("system:oss:download")
|
||||
@GetMapping("/download/{ossId}")
|
||||
public void download(@PathVariable Long ossId, HttpServletResponse response) throws IOException {
|
||||
iSysOssService.download(ossId, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除OSS对象存储
|
||||
*
|
||||
* @param ossIds OSS对象ID串
|
||||
*/
|
||||
@SaCheckPermission("system:oss:remove")
|
||||
@Log(title = "OSS对象存储", businessType = BusinessType.DELETE)
|
||||
@DeleteMapping("/{ossIds}")
|
||||
public R<Void> remove(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ossIds) {
|
||||
return toAjax(iSysOssService.deleteWithValidByIds(Arrays.asList(ossIds), true));
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,61 @@
|
||||
package org.dromara.resource.controller;
|
||||
|
||||
|
||||
import cn.hutool.core.util.RandomUtil;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.dromara.common.core.constant.Constants;
|
||||
import org.dromara.common.core.constant.GlobalConstants;
|
||||
import org.dromara.common.core.domain.R;
|
||||
import org.dromara.common.ratelimiter.annotation.RateLimiter;
|
||||
import org.dromara.common.redis.utils.RedisUtils;
|
||||
import org.dromara.common.web.core.BaseController;
|
||||
import org.dromara.sms4j.api.SmsBlend;
|
||||
import org.dromara.sms4j.api.entity.SmsResponse;
|
||||
import org.dromara.sms4j.core.factory.SmsFactory;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
/**
|
||||
* 短信功能
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Slf4j
|
||||
@Validated
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/sms")
|
||||
public class SysSmsController extends BaseController {
|
||||
|
||||
/**
|
||||
* 短信验证码
|
||||
*
|
||||
* @param phonenumber 用户手机号
|
||||
*/
|
||||
@RateLimiter(key = "#phonenumber", time = 60, count = 1)
|
||||
@GetMapping("/code")
|
||||
public R<Void> smsCaptcha(@NotBlank(message = "{user.phonenumber.not.blank}") String phonenumber) {
|
||||
String key = GlobalConstants.CAPTCHA_CODE_KEY + phonenumber;
|
||||
String code = RandomUtil.randomNumbers(4);
|
||||
RedisUtils.setCacheObject(key, code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
|
||||
// 验证码模板id 自行处理 (查数据库或写死均可)
|
||||
String templateId = "";
|
||||
LinkedHashMap<String, String> map = new LinkedHashMap<>(1);
|
||||
map.put("code", code);
|
||||
SmsBlend smsBlend = SmsFactory.getSmsBlend("tx1");
|
||||
SmsResponse smsResponse = smsBlend.sendMessage(phonenumber, templateId, map);
|
||||
if (!smsResponse.isSuccess()) {
|
||||
log.error("验证码短信发送异常 => {}", smsResponse);
|
||||
return R.fail(smsResponse.getData().toString());
|
||||
}
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,55 @@
|
||||
package org.dromara.resource.domain;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import org.dromara.common.tenant.core.TenantEntity;
|
||||
|
||||
/**
|
||||
* OSS对象存储对象
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@TableName("sys_oss")
|
||||
public class SysOss extends TenantEntity {
|
||||
|
||||
/**
|
||||
* 对象存储主键
|
||||
*/
|
||||
@TableId(value = "oss_id")
|
||||
private Long ossId;
|
||||
|
||||
/**
|
||||
* 文件名
|
||||
*/
|
||||
private String fileName;
|
||||
|
||||
/**
|
||||
* 原名
|
||||
*/
|
||||
private String originalName;
|
||||
|
||||
/**
|
||||
* 文件后缀名
|
||||
*/
|
||||
private String fileSuffix;
|
||||
|
||||
/**
|
||||
* URL地址
|
||||
*/
|
||||
private String url;
|
||||
|
||||
/**
|
||||
* 扩展字段
|
||||
*/
|
||||
private String ext1;
|
||||
|
||||
/**
|
||||
* 服务商
|
||||
*/
|
||||
private String service;
|
||||
|
||||
}
|
@ -0,0 +1,91 @@
|
||||
package org.dromara.resource.domain;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import org.dromara.common.mybatis.core.domain.BaseEntity;
|
||||
|
||||
/**
|
||||
* 对象存储配置对象 sys_oss_config
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@TableName("sys_oss_config")
|
||||
public class SysOssConfig extends BaseEntity {
|
||||
|
||||
/**
|
||||
* 主键
|
||||
*/
|
||||
@TableId(value = "oss_config_id")
|
||||
private Long ossConfigId;
|
||||
|
||||
/**
|
||||
* 配置key
|
||||
*/
|
||||
private String configKey;
|
||||
|
||||
/**
|
||||
* accessKey
|
||||
*/
|
||||
private String accessKey;
|
||||
|
||||
/**
|
||||
* 秘钥
|
||||
*/
|
||||
private String secretKey;
|
||||
|
||||
/**
|
||||
* 桶名称
|
||||
*/
|
||||
private String bucketName;
|
||||
|
||||
/**
|
||||
* 前缀
|
||||
*/
|
||||
private String prefix;
|
||||
|
||||
/**
|
||||
* 访问站点
|
||||
*/
|
||||
private String endpoint;
|
||||
|
||||
/**
|
||||
* 自定义域名
|
||||
*/
|
||||
private String domain;
|
||||
|
||||
|
||||
/**
|
||||
* 是否https(0否 1是)
|
||||
*/
|
||||
private String isHttps;
|
||||
|
||||
/**
|
||||
* 域
|
||||
*/
|
||||
private String region;
|
||||
|
||||
/**
|
||||
* 是否默认(0=是,1=否)
|
||||
*/
|
||||
private String status;
|
||||
|
||||
/**
|
||||
* 扩展字段
|
||||
*/
|
||||
private String ext1;
|
||||
|
||||
/**
|
||||
* 备注
|
||||
*/
|
||||
private String remark;
|
||||
|
||||
/**
|
||||
* 桶权限类型(0private 1public 2custom)
|
||||
*/
|
||||
private String accessPolicy;
|
||||
|
||||
}
|
@ -0,0 +1,54 @@
|
||||
package org.dromara.resource.domain.bo;
|
||||
|
||||
import io.github.linpeilie.annotations.AutoMapper;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import org.dromara.common.mybatis.core.domain.BaseEntity;
|
||||
import org.dromara.resource.domain.SysOss;
|
||||
|
||||
/**
|
||||
* OSS对象存储分页查询对象 sys_oss
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@AutoMapper(target = SysOss.class, reverseConvertGenerate = false)
|
||||
public class SysOssBo extends BaseEntity {
|
||||
|
||||
/**
|
||||
* ossId
|
||||
*/
|
||||
private Long ossId;
|
||||
|
||||
/**
|
||||
* 文件名
|
||||
*/
|
||||
private String fileName;
|
||||
|
||||
/**
|
||||
* 原名
|
||||
*/
|
||||
private String originalName;
|
||||
|
||||
/**
|
||||
* 文件后缀名
|
||||
*/
|
||||
private String fileSuffix;
|
||||
|
||||
/**
|
||||
* URL地址
|
||||
*/
|
||||
private String url;
|
||||
|
||||
/**
|
||||
* 扩展字段
|
||||
*/
|
||||
private String ext1;
|
||||
|
||||
/**
|
||||
* 服务商
|
||||
*/
|
||||
private String service;
|
||||
|
||||
}
|
@ -0,0 +1,109 @@
|
||||
package org.dromara.resource.domain.bo;
|
||||
|
||||
import io.github.linpeilie.annotations.AutoMapper;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import org.dromara.common.core.validate.AddGroup;
|
||||
import org.dromara.common.core.validate.EditGroup;
|
||||
import org.dromara.common.mybatis.core.domain.BaseEntity;
|
||||
import org.dromara.resource.domain.SysOssConfig;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
/**
|
||||
* 对象存储配置业务对象 sys_oss_config
|
||||
*
|
||||
* @author Lion Li
|
||||
* @author 孤舟烟雨
|
||||
* @date 2021-08-13
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@AutoMapper(target = SysOssConfig.class, reverseConvertGenerate = false)
|
||||
public class SysOssConfigBo extends BaseEntity {
|
||||
|
||||
/**
|
||||
* 主键
|
||||
*/
|
||||
@NotNull(message = "主键不能为空", groups = {EditGroup.class})
|
||||
private Long ossConfigId;
|
||||
|
||||
/**
|
||||
* 配置key
|
||||
*/
|
||||
@NotBlank(message = "配置key不能为空", groups = {AddGroup.class, EditGroup.class})
|
||||
@Size(min = 2, max = 100, message = "configKey长度必须介于2和20 之间")
|
||||
private String configKey;
|
||||
|
||||
/**
|
||||
* accessKey
|
||||
*/
|
||||
@NotBlank(message = "accessKey不能为空", groups = {AddGroup.class, EditGroup.class})
|
||||
@Size(min = 2, max = 100, message = "accessKey长度必须介于2和100 之间")
|
||||
private String accessKey;
|
||||
|
||||
/**
|
||||
* 秘钥
|
||||
*/
|
||||
@NotBlank(message = "secretKey不能为空", groups = {AddGroup.class, EditGroup.class})
|
||||
@Size(min = 2, max = 100, message = "secretKey长度必须介于2和100 之间")
|
||||
private String secretKey;
|
||||
|
||||
/**
|
||||
* 桶名称
|
||||
*/
|
||||
@NotBlank(message = "桶名称不能为空", groups = {AddGroup.class, EditGroup.class})
|
||||
@Size(min = 2, max = 100, message = "bucketName长度必须介于2和100之间")
|
||||
private String bucketName;
|
||||
|
||||
/**
|
||||
* 前缀
|
||||
*/
|
||||
private String prefix;
|
||||
|
||||
/**
|
||||
* 访问站点
|
||||
*/
|
||||
@NotBlank(message = "访问站点不能为空", groups = {AddGroup.class, EditGroup.class})
|
||||
@Size(min = 2, max = 100, message = "endpoint长度必须介于2和100之间")
|
||||
private String endpoint;
|
||||
|
||||
/**
|
||||
* 自定义域名
|
||||
*/
|
||||
private String domain;
|
||||
|
||||
/**
|
||||
* 是否https(Y=是,N=否)
|
||||
*/
|
||||
private String isHttps;
|
||||
|
||||
/**
|
||||
* 是否默认(0=是,1=否)
|
||||
*/
|
||||
private String status;
|
||||
|
||||
/**
|
||||
* 域
|
||||
*/
|
||||
private String region;
|
||||
|
||||
/**
|
||||
* 扩展字段
|
||||
*/
|
||||
private String ext1;
|
||||
|
||||
/**
|
||||
* 备注
|
||||
*/
|
||||
private String remark;
|
||||
|
||||
/**
|
||||
* 桶权限类型(0private 1public 2custom)
|
||||
*/
|
||||
@NotBlank(message = "桶权限类型不能为空", groups = {AddGroup.class, EditGroup.class})
|
||||
private String accessPolicy;
|
||||
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
package org.dromara.resource.domain.convert;
|
||||
|
||||
import io.github.linpeilie.BaseMapper;
|
||||
import org.dromara.resource.api.domain.RemoteFile;
|
||||
import org.dromara.resource.domain.vo.SysOssVo;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
import org.mapstruct.MappingConstants;
|
||||
import org.mapstruct.ReportingPolicy;
|
||||
|
||||
/**
|
||||
* 用户信息转换器
|
||||
* @author zhujie
|
||||
*/
|
||||
@Mapper(componentModel = MappingConstants.ComponentModel.SPRING, unmappedTargetPolicy = ReportingPolicy.IGNORE)
|
||||
public interface SysOssVoConvert extends BaseMapper<SysOssVo, RemoteFile> {
|
||||
|
||||
@Mapping(target = "name", source = "fileName")
|
||||
RemoteFile convert(SysOssVo sysOssVo);
|
||||
|
||||
}
|
@ -0,0 +1,96 @@
|
||||
package org.dromara.resource.domain.vo;
|
||||
|
||||
import io.github.linpeilie.annotations.AutoMapper;
|
||||
import lombok.Data;
|
||||
import org.dromara.resource.domain.SysOssConfig;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
|
||||
|
||||
/**
|
||||
* 对象存储配置视图对象 sys_oss_config
|
||||
*
|
||||
* @author Lion Li
|
||||
* @author 孤舟烟雨
|
||||
* @date 2021-08-13
|
||||
*/
|
||||
@Data
|
||||
@AutoMapper(target = SysOssConfig.class)
|
||||
public class SysOssConfigVo implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 主键
|
||||
*/
|
||||
private Long ossConfigId;
|
||||
|
||||
/**
|
||||
* 配置key
|
||||
*/
|
||||
private String configKey;
|
||||
|
||||
/**
|
||||
* accessKey
|
||||
*/
|
||||
private String accessKey;
|
||||
|
||||
/**
|
||||
* 秘钥
|
||||
*/
|
||||
private String secretKey;
|
||||
|
||||
/**
|
||||
* 桶名称
|
||||
*/
|
||||
private String bucketName;
|
||||
|
||||
/**
|
||||
* 前缀
|
||||
*/
|
||||
private String prefix;
|
||||
|
||||
/**
|
||||
* 访问站点
|
||||
*/
|
||||
private String endpoint;
|
||||
|
||||
/**
|
||||
* 自定义域名
|
||||
*/
|
||||
private String domain;
|
||||
|
||||
/**
|
||||
* 是否https(Y=是,N=否)
|
||||
*/
|
||||
private String isHttps;
|
||||
|
||||
/**
|
||||
* 域
|
||||
*/
|
||||
private String region;
|
||||
|
||||
/**
|
||||
* 是否默认(0=是,1=否)
|
||||
*/
|
||||
private String status;
|
||||
|
||||
/**
|
||||
* 扩展字段
|
||||
*/
|
||||
private String ext1;
|
||||
|
||||
/**
|
||||
* 备注
|
||||
*/
|
||||
private String remark;
|
||||
|
||||
/**
|
||||
* 桶权限类型(0private 1public 2custom)
|
||||
*/
|
||||
private String accessPolicy;
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,34 @@
|
||||
package org.dromara.resource.domain.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* 上传对象信息
|
||||
*
|
||||
* @author Michelle.Chung
|
||||
*/
|
||||
@Data
|
||||
public class SysOssUploadVo implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* URL地址
|
||||
*/
|
||||
private String url;
|
||||
|
||||
/**
|
||||
* 文件名
|
||||
*/
|
||||
private String fileName;
|
||||
|
||||
/**
|
||||
* 对象存储主键
|
||||
*/
|
||||
private String ossId;
|
||||
|
||||
}
|
@ -0,0 +1,77 @@
|
||||
package org.dromara.resource.domain.vo;
|
||||
|
||||
import io.github.linpeilie.annotations.AutoMapper;
|
||||
import lombok.Data;
|
||||
import org.dromara.common.translation.annotation.Translation;
|
||||
import org.dromara.common.translation.constant.TransConstant;
|
||||
import org.dromara.resource.domain.SysOss;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* OSS对象存储视图对象 sys_oss
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Data
|
||||
@AutoMapper(target = SysOss.class)
|
||||
public class SysOssVo implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 对象存储主键
|
||||
*/
|
||||
private Long ossId;
|
||||
|
||||
/**
|
||||
* 文件名
|
||||
*/
|
||||
private String fileName;
|
||||
|
||||
/**
|
||||
* 原名
|
||||
*/
|
||||
private String originalName;
|
||||
|
||||
/**
|
||||
* 文件后缀名
|
||||
*/
|
||||
private String fileSuffix;
|
||||
|
||||
/**
|
||||
* URL地址
|
||||
*/
|
||||
private String url;
|
||||
|
||||
/**
|
||||
* 扩展字段
|
||||
*/
|
||||
private String ext1;
|
||||
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
private Date createTime;
|
||||
|
||||
/**
|
||||
* 上传人
|
||||
*/
|
||||
private Long createBy;
|
||||
|
||||
/**
|
||||
* 上传人名称
|
||||
*/
|
||||
@Translation(type = TransConstant.USER_ID_TO_NAME, mapper = "createBy")
|
||||
private String createByName;
|
||||
|
||||
/**
|
||||
* 服务商
|
||||
*/
|
||||
private String service;
|
||||
|
||||
|
||||
}
|
@ -0,0 +1,89 @@
|
||||
package org.dromara.resource.dubbo;
|
||||
|
||||
import cn.hutool.core.convert.Convert;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.dubbo.config.annotation.DubboService;
|
||||
import org.dromara.common.core.exception.ServiceException;
|
||||
import org.dromara.common.core.utils.MapstructUtils;
|
||||
import org.dromara.common.core.utils.StringUtils;
|
||||
import org.dromara.common.oss.core.OssClient;
|
||||
import org.dromara.common.oss.entity.UploadResult;
|
||||
import org.dromara.common.oss.factory.OssFactory;
|
||||
import org.dromara.resource.api.RemoteFileService;
|
||||
import org.dromara.resource.api.domain.RemoteFile;
|
||||
import org.dromara.resource.domain.bo.SysOssBo;
|
||||
import org.dromara.resource.domain.vo.SysOssVo;
|
||||
import org.dromara.resource.service.ISysOssService;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 文件请求处理
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@DubboService
|
||||
public class RemoteFileServiceImpl implements RemoteFileService {
|
||||
|
||||
private final ISysOssService sysOssService;
|
||||
|
||||
/**
|
||||
* 文件上传请求
|
||||
*/
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
@Override
|
||||
public RemoteFile upload(String name, String originalFilename, String contentType, byte[] file) throws ServiceException {
|
||||
try {
|
||||
String suffix = StringUtils.substring(originalFilename, originalFilename.lastIndexOf("."), originalFilename.length());
|
||||
OssClient storage = OssFactory.instance();
|
||||
UploadResult uploadResult = storage.uploadSuffix(file, suffix, contentType);
|
||||
// 保存文件信息
|
||||
SysOssBo oss = new SysOssBo();
|
||||
oss.setUrl(uploadResult.getUrl());
|
||||
oss.setFileSuffix(suffix);
|
||||
oss.setFileName(uploadResult.getFilename());
|
||||
oss.setOriginalName(originalFilename);
|
||||
oss.setService(storage.getConfigKey());
|
||||
sysOssService.insertByBo(oss);
|
||||
RemoteFile sysFile = new RemoteFile();
|
||||
sysFile.setOssId(oss.getOssId());
|
||||
sysFile.setName(uploadResult.getFilename());
|
||||
sysFile.setUrl(uploadResult.getUrl());
|
||||
sysFile.setOriginalName(originalFilename);
|
||||
sysFile.setFileSuffix(suffix);
|
||||
return sysFile;
|
||||
} catch (Exception e) {
|
||||
log.error("上传文件失败", e);
|
||||
throw new ServiceException("上传文件失败");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过ossId查询对应的url
|
||||
*
|
||||
* @param ossIds ossId串逗号分隔
|
||||
* @return url串逗号分隔
|
||||
*/
|
||||
@Override
|
||||
public String selectUrlByIds(String ossIds) {
|
||||
return sysOssService.selectUrlByIds(ossIds);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过ossId查询列表
|
||||
*
|
||||
* @param ossIds ossId串逗号分隔
|
||||
* @return 列表
|
||||
*/
|
||||
@Override
|
||||
public List<RemoteFile> selectByIds(String ossIds){
|
||||
List<SysOssVo> sysOssVos = sysOssService.listByIds(StringUtils.splitTo(ossIds, Convert::toLong));
|
||||
return MapstructUtils.convert(sysOssVos, RemoteFile.class);
|
||||
}
|
||||
}
|
@ -0,0 +1,34 @@
|
||||
package org.dromara.resource.dubbo;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.dubbo.config.annotation.DubboService;
|
||||
import org.dromara.common.core.exception.ServiceException;
|
||||
import org.dromara.common.mail.utils.MailUtils;
|
||||
import org.dromara.resource.api.RemoteMailService;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/**
|
||||
* 邮件服务
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
@DubboService
|
||||
public class RemoteMailServiceImpl implements RemoteMailService {
|
||||
|
||||
/**
|
||||
* 发送邮件
|
||||
*
|
||||
* @param to 接收人
|
||||
* @param subject 标题
|
||||
* @param text 内容
|
||||
*/
|
||||
@Override
|
||||
public void send(String to, String subject, String text) throws ServiceException {
|
||||
MailUtils.sendText(to, subject, text);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,48 @@
|
||||
package org.dromara.resource.dubbo;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.dubbo.config.annotation.DubboService;
|
||||
import org.dromara.common.sse.dto.SseMessageDto;
|
||||
import org.dromara.common.sse.utils.SseMessageUtils;
|
||||
import org.dromara.resource.api.RemoteMessageService;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 消息服务
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
@DubboService
|
||||
public class RemoteMessageServiceImpl implements RemoteMessageService {
|
||||
|
||||
/**
|
||||
* 发送消息
|
||||
*
|
||||
* @param sessionKey session主键 一般为用户id
|
||||
* @param message 消息文本
|
||||
*/
|
||||
@Override
|
||||
public void publishMessage(List<Long> sessionKey, String message) {
|
||||
SseMessageDto dto = new SseMessageDto();
|
||||
dto.setMessage(message);
|
||||
dto.setUserIds(sessionKey);
|
||||
SseMessageUtils.publishMessage(dto);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发布订阅的消息(群发)
|
||||
*
|
||||
* @param message 消息内容
|
||||
*/
|
||||
@Override
|
||||
public void publishAll(String message) {
|
||||
SseMessageUtils.publishAll(message);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,236 @@
|
||||
package org.dromara.resource.dubbo;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.dubbo.config.annotation.DubboService;
|
||||
import org.dromara.resource.api.RemoteSmsService;
|
||||
import org.dromara.resource.api.domain.RemoteSms;
|
||||
import org.dromara.sms4j.api.SmsBlend;
|
||||
import org.dromara.sms4j.api.entity.SmsResponse;
|
||||
import org.dromara.sms4j.core.factory.SmsFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 短信服务
|
||||
*
|
||||
* @author Feng
|
||||
*/
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
@DubboService
|
||||
public class RemoteSmsServiceImpl implements RemoteSmsService {
|
||||
|
||||
/**
|
||||
* 获取特定供应商类型的 SmsBlend 实例
|
||||
*
|
||||
* @return SmsBlend 实例,代表指定供应商类型
|
||||
*/
|
||||
private SmsBlend getSmsBlend() {
|
||||
// 可自定义厂商配置获取规则 例如根据租户获取 或 负载均衡多个厂商等
|
||||
return SmsFactory.getSmsBlend("config1");
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据给定的 SmsResponse 对象创建并返回一个 RemoteSms 对象,封装短信发送的响应信息
|
||||
*
|
||||
* @param smsResponse 短信发送的响应信息
|
||||
* @return 封装了短信发送结果的 RemoteSms 对象
|
||||
*/
|
||||
private RemoteSms getRemoteSms(SmsResponse smsResponse) {
|
||||
// 创建一个 RemoteSms 对象,封装响应信息
|
||||
RemoteSms sms = new RemoteSms();
|
||||
sms.setSuccess(smsResponse.isSuccess());
|
||||
sms.setResponse(smsResponse.getData().toString());
|
||||
sms.setConfigId(smsResponse.getConfigId());
|
||||
return sms;
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步方法:发送简单文本短信
|
||||
*
|
||||
* @param phone 目标手机号
|
||||
* @param message 短信内容
|
||||
* @return 封装了短信发送结果的 RemoteSms 对象
|
||||
*/
|
||||
@Override
|
||||
public RemoteSms sendMessage(String phone, String message) {
|
||||
// 调用 getSmsBlend 方法获取对应短信供应商的 SmsBlend 实例
|
||||
SmsResponse smsResponse = getSmsBlend().sendMessage(phone, message);
|
||||
return getRemoteSms(smsResponse);
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步方法:发送固定消息模板多模板参数短信
|
||||
*
|
||||
* @param phone 目标手机号
|
||||
* @param messages 短信模板参数,使用 LinkedHashMap 以保持参数顺序
|
||||
* @return 封装了短信发送结果的 RemoteSms 对象
|
||||
*/
|
||||
@Override
|
||||
public RemoteSms sendMessage(String phone, LinkedHashMap<String, String> messages) {
|
||||
SmsResponse smsResponse = getSmsBlend().sendMessage(phone, messages);
|
||||
return getRemoteSms(smsResponse);
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步方法:发送带参数的短信
|
||||
*
|
||||
* @param phone 目标手机号
|
||||
* @param templateId 短信模板ID
|
||||
* @param messages 短信模板参数,使用 LinkedHashMap 以保持参数顺序
|
||||
* @return 封装了短信发送结果的 RemoteSms 对象
|
||||
*/
|
||||
@Override
|
||||
public RemoteSms sendMessage(String phone, String templateId, LinkedHashMap<String, String> messages) {
|
||||
// 调用 getSmsBlend 方法获取对应短信供应商的 SmsBlend 实例
|
||||
SmsResponse smsResponse = getSmsBlend().sendMessage(phone, templateId, messages);
|
||||
return getRemoteSms(smsResponse);
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步方法:群发简单文本短信
|
||||
*
|
||||
* @param phones 目标手机号列表
|
||||
* @param message 短信内容
|
||||
* @return 封装了短信发送结果的 RemoteSms 对象
|
||||
*/
|
||||
@Override
|
||||
public RemoteSms messageTexting(List<String> phones, String message) {
|
||||
// 调用 getSmsBlend 方法获取对应短信供应商的 SmsBlend 实例
|
||||
SmsResponse smsResponse = getSmsBlend().massTexting(phones, message);
|
||||
return getRemoteSms(smsResponse);
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步方法:群发带参数的短信
|
||||
*
|
||||
* @param phones 目标手机号列表
|
||||
* @param templateId 短信模板ID
|
||||
* @param messages 短信模板参数,使用 LinkedHashMap 以保持参数顺序
|
||||
* @return 封装了短信发送结果的 RemoteSms 对象
|
||||
*/
|
||||
@Override
|
||||
public RemoteSms messageTexting(List<String> phones, String templateId, LinkedHashMap<String, String> messages) {
|
||||
// 调用 getSmsBlend 方法获取对应短信供应商的 SmsBlend 实例
|
||||
SmsResponse smsResponse = getSmsBlend().massTexting(phones, templateId, messages);
|
||||
return getRemoteSms(smsResponse);
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步方法:发送简单文本短信
|
||||
*
|
||||
* @param phone 目标手机号
|
||||
* @param message 短信内容
|
||||
*/
|
||||
@Override
|
||||
public void sendMessageAsync(String phone, String message) {
|
||||
getSmsBlend().sendMessageAsync(phone, message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步方法:发送带参数的短信
|
||||
*
|
||||
* @param phone 目标手机号
|
||||
* @param templateId 短信模板ID
|
||||
* @param messages 短信模板参数,使用 LinkedHashMap 以保持参数顺序
|
||||
*/
|
||||
@Override
|
||||
public void sendMessageAsync(String phone, String templateId, LinkedHashMap<String, String> messages) {
|
||||
getSmsBlend().sendMessageAsync(phone, templateId, messages);
|
||||
}
|
||||
|
||||
/**
|
||||
* 延迟发送简单文本短信
|
||||
*
|
||||
* @param phone 目标手机号
|
||||
* @param message 短信内容
|
||||
* @param delayedTime 延迟发送时间(毫秒)
|
||||
*/
|
||||
@Override
|
||||
public void delayMessage(String phone, String message, Long delayedTime) {
|
||||
getSmsBlend().delayedMessage(phone, message, delayedTime);
|
||||
}
|
||||
|
||||
/**
|
||||
* 延迟发送带参数的短信
|
||||
*
|
||||
* @param phone 目标手机号
|
||||
* @param templateId 短信模板ID
|
||||
* @param messages 短信模板参数,使用 LinkedHashMap 以保持参数顺序
|
||||
* @param delayedTime 延迟发送时间(毫秒)
|
||||
*/
|
||||
@Override
|
||||
public void delayMessage(String phone, String templateId, LinkedHashMap<String, String> messages, Long delayedTime) {
|
||||
getSmsBlend().delayedMessage(phone, templateId, messages, delayedTime);
|
||||
}
|
||||
|
||||
/**
|
||||
* 延迟群发简单文本短信
|
||||
*
|
||||
* @param phones 目标手机号列表
|
||||
* @param message 短信内容
|
||||
* @param delayedTime 延迟发送时间(毫秒)
|
||||
*/
|
||||
@Override
|
||||
public void delayMessageTexting(List<String> phones, String message, Long delayedTime) {
|
||||
getSmsBlend().delayMassTexting(phones, message, delayedTime);
|
||||
}
|
||||
|
||||
/**
|
||||
* 延迟批量发送带参数的短信
|
||||
*
|
||||
* @param phones 目标手机号列表
|
||||
* @param templateId 短信模板ID
|
||||
* @param messages 短信模板参数,使用 LinkedHashMap 以保持参数顺序
|
||||
* @param delayedTime 延迟发送时间(毫秒)
|
||||
*/
|
||||
@Override
|
||||
public void delayMessageTexting(List<String> phones, String templateId, LinkedHashMap<String, String> messages, Long delayedTime) {
|
||||
getSmsBlend().delayMassTexting(phones, templateId, messages, delayedTime);
|
||||
}
|
||||
|
||||
/**
|
||||
* 加入黑名单
|
||||
*
|
||||
* @param phone 手机号
|
||||
*/
|
||||
@Override
|
||||
public void addBlacklist(String phone) {
|
||||
getSmsBlend().joinInBlacklist(phone);
|
||||
}
|
||||
|
||||
/**
|
||||
* 加入黑名单
|
||||
*
|
||||
* @param phones 手机号列表
|
||||
*/
|
||||
@Override
|
||||
public void addBlacklist(List<String> phones) {
|
||||
getSmsBlend().batchJoinBlacklist(phones);
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除黑名单
|
||||
*
|
||||
* @param phone 手机号
|
||||
*/
|
||||
@Override
|
||||
public void removeBlacklist(String phone) {
|
||||
getSmsBlend().removeFromBlacklist(phone);
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除黑名单
|
||||
*
|
||||
* @param phones 手机号
|
||||
*/
|
||||
@Override
|
||||
public void removeBlacklist(List<String> phones) {
|
||||
getSmsBlend().batchRemovalFromBlacklist(phones);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,17 @@
|
||||
package org.dromara.resource.mapper;
|
||||
|
||||
|
||||
import org.dromara.common.mybatis.core.mapper.BaseMapperPlus;
|
||||
import org.dromara.resource.domain.SysOssConfig;
|
||||
import org.dromara.resource.domain.vo.SysOssConfigVo;
|
||||
|
||||
/**
|
||||
* 对象存储配置Mapper接口
|
||||
*
|
||||
* @author Lion Li
|
||||
* @author 孤舟烟雨
|
||||
* @date 2021-08-13
|
||||
*/
|
||||
public interface SysOssConfigMapper extends BaseMapperPlus<SysOssConfig, SysOssConfigVo> {
|
||||
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package org.dromara.resource.mapper;
|
||||
|
||||
import org.dromara.common.mybatis.core.mapper.BaseMapperPlus;
|
||||
import org.dromara.resource.domain.SysOss;
|
||||
import org.dromara.resource.domain.vo.SysOssVo;
|
||||
|
||||
/**
|
||||
* 文件上传 数据层
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
public interface SysOssMapper extends BaseMapperPlus<SysOss, SysOssVo> {
|
||||
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
package org.dromara.resource.runner;
|
||||
|
||||
import org.dromara.resource.service.ISysOssConfigService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.boot.ApplicationRunner;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 初始化 system 模块对应业务数据
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
@Component
|
||||
public class ResourceApplicationRunner implements ApplicationRunner {
|
||||
|
||||
private final ISysOssConfigService ossConfigService;
|
||||
|
||||
@Override
|
||||
public void run(ApplicationArguments args) throws Exception {
|
||||
ossConfigService.init();
|
||||
log.info("初始化OSS配置成功");
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,66 @@
|
||||
package org.dromara.resource.service;
|
||||
|
||||
|
||||
import org.dromara.common.mybatis.core.page.PageQuery;
|
||||
import org.dromara.common.mybatis.core.page.TableDataInfo;
|
||||
import org.dromara.resource.domain.bo.SysOssConfigBo;
|
||||
import org.dromara.resource.domain.vo.SysOssConfigVo;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
/**
|
||||
* 对象存储配置Service接口
|
||||
*
|
||||
* @author Lion Li
|
||||
* @author 孤舟烟雨
|
||||
* @date 2021-08-13
|
||||
*/
|
||||
public interface ISysOssConfigService {
|
||||
|
||||
/**
|
||||
* 初始化OSS配置
|
||||
*/
|
||||
void init();
|
||||
|
||||
/**
|
||||
* 查询单个
|
||||
*/
|
||||
SysOssConfigVo queryById(Long ossConfigId);
|
||||
|
||||
/**
|
||||
* 查询列表
|
||||
*/
|
||||
TableDataInfo<SysOssConfigVo> queryPageList(SysOssConfigBo bo, PageQuery pageQuery);
|
||||
|
||||
|
||||
/**
|
||||
* 根据新增业务对象插入对象存储配置
|
||||
*
|
||||
* @param bo 对象存储配置新增业务对象
|
||||
* @return 结果
|
||||
*/
|
||||
Boolean insertByBo(SysOssConfigBo bo);
|
||||
|
||||
/**
|
||||
* 根据编辑业务对象修改对象存储配置
|
||||
*
|
||||
* @param bo 对象存储配置编辑业务对象
|
||||
* @return 结果
|
||||
*/
|
||||
Boolean updateByBo(SysOssConfigBo bo);
|
||||
|
||||
/**
|
||||
* 校验并删除数据
|
||||
*
|
||||
* @param ids 主键集合
|
||||
* @param isValid 是否校验,true-删除前校验,false-不校验
|
||||
* @return 结果
|
||||
*/
|
||||
Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid);
|
||||
|
||||
/**
|
||||
* 启用停用状态
|
||||
*/
|
||||
int updateOssConfigStatus(SysOssConfigBo bo);
|
||||
|
||||
}
|
@ -0,0 +1,95 @@
|
||||
package org.dromara.resource.service;
|
||||
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.dromara.common.mybatis.core.page.PageQuery;
|
||||
import org.dromara.common.mybatis.core.page.TableDataInfo;
|
||||
import org.dromara.resource.domain.bo.SysOssBo;
|
||||
import org.dromara.resource.domain.vo.SysOssVo;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 文件上传 服务层
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
public interface ISysOssService {
|
||||
|
||||
/**
|
||||
* 查询OSS对象存储列表
|
||||
*
|
||||
* @param sysOss OSS对象存储分页查询对象
|
||||
* @param pageQuery 分页查询实体类
|
||||
* @return 结果
|
||||
*/
|
||||
TableDataInfo<SysOssVo> queryPageList(SysOssBo sysOss, PageQuery pageQuery);
|
||||
|
||||
/**
|
||||
* 根据一组 ossIds 获取对应的 SysOssVo 列表
|
||||
*
|
||||
* @param ossIds 一组文件在数据库中的唯一标识集合
|
||||
* @return 包含 SysOssVo 对象的列表
|
||||
*/
|
||||
List<SysOssVo> listByIds(Collection<Long> ossIds);
|
||||
|
||||
/**
|
||||
* 根据一组 ossIds 获取对应文件的 URL 列表
|
||||
*
|
||||
* @param ossIds 以逗号分隔的 ossId 字符串
|
||||
* @return 以逗号分隔的文件 URL 字符串
|
||||
*/
|
||||
String selectUrlByIds(String ossIds);
|
||||
|
||||
/**
|
||||
* 根据 ossId 从缓存或数据库中获取 SysOssVo 对象
|
||||
*
|
||||
* @param ossId 文件在数据库中的唯一标识
|
||||
* @return SysOssVo 对象,包含文件信息
|
||||
*/
|
||||
SysOssVo getById(Long ossId);
|
||||
|
||||
/**
|
||||
* 上传 MultipartFile 到对象存储服务,并保存文件信息到数据库
|
||||
*
|
||||
* @param file 要上传的 MultipartFile 对象
|
||||
* @return 上传成功后的 SysOssVo 对象,包含文件信息
|
||||
*/
|
||||
SysOssVo upload(MultipartFile file);
|
||||
|
||||
/**
|
||||
* 上传文件到对象存储服务,并保存文件信息到数据库
|
||||
*
|
||||
* @param file 要上传的文件对象
|
||||
* @return 上传成功后的 SysOssVo 对象,包含文件信息
|
||||
*/
|
||||
SysOssVo upload(File file);
|
||||
|
||||
/**
|
||||
* 新增OSS对象存储
|
||||
*
|
||||
* @param bo SysOssBo 对象,包含待插入的数据
|
||||
* @return 插入操作是否成功的布尔值
|
||||
*/
|
||||
Boolean insertByBo(SysOssBo bo);
|
||||
|
||||
/**
|
||||
* 文件下载方法,支持一次性下载完整文件
|
||||
*
|
||||
* @param ossId OSS对象ID
|
||||
* @param response HttpServletResponse对象,用于设置响应头和向客户端发送文件内容
|
||||
*/
|
||||
void download(Long ossId, HttpServletResponse response) throws IOException;
|
||||
|
||||
/**
|
||||
* 删除OSS对象存储
|
||||
*
|
||||
* @param ids OSS对象ID串
|
||||
* @param isValid 判断是否需要校验
|
||||
* @return 结果
|
||||
*/
|
||||
Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid);
|
||||
}
|
@ -0,0 +1,176 @@
|
||||
package org.dromara.resource.service.impl;
|
||||
|
||||
import cn.hutool.core.bean.BeanUtil;
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.dromara.common.core.constant.CacheNames;
|
||||
import org.dromara.common.core.exception.ServiceException;
|
||||
import org.dromara.common.core.utils.ObjectUtils;
|
||||
import org.dromara.common.core.utils.StringUtils;
|
||||
import org.dromara.common.json.utils.JsonUtils;
|
||||
import org.dromara.common.mybatis.core.page.PageQuery;
|
||||
import org.dromara.common.mybatis.core.page.TableDataInfo;
|
||||
import org.dromara.common.oss.constant.OssConstant;
|
||||
import org.dromara.common.redis.utils.CacheUtils;
|
||||
import org.dromara.common.redis.utils.RedisUtils;
|
||||
import org.dromara.resource.domain.SysOssConfig;
|
||||
import org.dromara.resource.domain.bo.SysOssConfigBo;
|
||||
import org.dromara.resource.domain.vo.SysOssConfigVo;
|
||||
import org.dromara.resource.mapper.SysOssConfigMapper;
|
||||
import org.dromara.resource.service.ISysOssConfigService;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 对象存储配置Service业务层处理
|
||||
*
|
||||
* @author Lion Li
|
||||
* @author 孤舟烟雨
|
||||
* @date 2021-08-13
|
||||
*/
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
public class SysOssConfigServiceImpl implements ISysOssConfigService {
|
||||
|
||||
private final SysOssConfigMapper baseMapper;
|
||||
|
||||
/**
|
||||
* 项目启动时,初始化参数到缓存,加载配置类
|
||||
*/
|
||||
@Override
|
||||
public void init() {
|
||||
List<SysOssConfig> list = baseMapper.selectList();
|
||||
// 加载OSS初始化配置
|
||||
for (SysOssConfig config : list) {
|
||||
String configKey = config.getConfigKey();
|
||||
if ("0".equals(config.getStatus())) {
|
||||
RedisUtils.setCacheObject(OssConstant.DEFAULT_CONFIG_KEY, configKey);
|
||||
}
|
||||
CacheUtils.put(CacheNames.SYS_OSS_CONFIG, config.getConfigKey(), JsonUtils.toJsonString(config));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public SysOssConfigVo queryById(Long ossConfigId) {
|
||||
return baseMapper.selectVoById(ossConfigId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TableDataInfo<SysOssConfigVo> queryPageList(SysOssConfigBo bo, PageQuery pageQuery) {
|
||||
LambdaQueryWrapper<SysOssConfig> lqw = buildQueryWrapper(bo);
|
||||
Page<SysOssConfigVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
|
||||
return TableDataInfo.build(result);
|
||||
}
|
||||
|
||||
|
||||
private LambdaQueryWrapper<SysOssConfig> buildQueryWrapper(SysOssConfigBo bo) {
|
||||
LambdaQueryWrapper<SysOssConfig> lqw = Wrappers.lambdaQuery();
|
||||
lqw.eq(StringUtils.isNotBlank(bo.getConfigKey()), SysOssConfig::getConfigKey, bo.getConfigKey());
|
||||
lqw.like(StringUtils.isNotBlank(bo.getBucketName()), SysOssConfig::getBucketName, bo.getBucketName());
|
||||
lqw.eq(StringUtils.isNotBlank(bo.getStatus()), SysOssConfig::getStatus, bo.getStatus());
|
||||
lqw.orderByAsc(SysOssConfig::getOssConfigId);
|
||||
return lqw;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean insertByBo(SysOssConfigBo bo) {
|
||||
SysOssConfig config = BeanUtil.toBean(bo, SysOssConfig.class);
|
||||
validEntityBeforeSave(config);
|
||||
boolean flag = baseMapper.insert(config) > 0;
|
||||
if (flag) {
|
||||
// 从数据库查询完整的数据做缓存
|
||||
config = baseMapper.selectById(config.getOssConfigId());
|
||||
CacheUtils.put(CacheNames.SYS_OSS_CONFIG, config.getConfigKey(), JsonUtils.toJsonString(config));
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean updateByBo(SysOssConfigBo bo) {
|
||||
SysOssConfig config = BeanUtil.toBean(bo, SysOssConfig.class);
|
||||
validEntityBeforeSave(config);
|
||||
LambdaUpdateWrapper<SysOssConfig> luw = new LambdaUpdateWrapper<>();
|
||||
luw.set(ObjectUtil.isNull(config.getPrefix()), SysOssConfig::getPrefix, "");
|
||||
luw.set(ObjectUtil.isNull(config.getRegion()), SysOssConfig::getRegion, "");
|
||||
luw.set(ObjectUtil.isNull(config.getExt1()), SysOssConfig::getExt1, "");
|
||||
luw.set(ObjectUtil.isNull(config.getRemark()), SysOssConfig::getRemark, "");
|
||||
luw.eq(SysOssConfig::getOssConfigId, config.getOssConfigId());
|
||||
boolean flag = baseMapper.update(config, luw) > 0;
|
||||
if (flag) {
|
||||
// 从数据库查询完整的数据做缓存
|
||||
config = baseMapper.selectById(config.getOssConfigId());
|
||||
CacheUtils.put(CacheNames.SYS_OSS_CONFIG, config.getConfigKey(), JsonUtils.toJsonString(config));
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存前的数据校验
|
||||
*/
|
||||
private void validEntityBeforeSave(SysOssConfig entity) {
|
||||
if (StringUtils.isNotEmpty(entity.getConfigKey()) && !checkConfigKeyUnique(entity)) {
|
||||
throw new ServiceException("操作配置'" + entity.getConfigKey() + "'失败, 配置key已存在!");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
|
||||
if (isValid) {
|
||||
if (CollUtil.containsAny(ids, OssConstant.SYSTEM_DATA_IDS)) {
|
||||
throw new ServiceException("系统内置, 不可删除!");
|
||||
}
|
||||
}
|
||||
List<SysOssConfig> list = CollUtil.newArrayList();
|
||||
for (Long configId : ids) {
|
||||
SysOssConfig config = baseMapper.selectById(configId);
|
||||
list.add(config);
|
||||
}
|
||||
boolean flag = baseMapper.deleteByIds(ids) > 0;
|
||||
if (flag) {
|
||||
list.forEach(sysOssConfig ->
|
||||
CacheUtils.evict(CacheNames.SYS_OSS_CONFIG, sysOssConfig.getConfigKey()));
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断configKey是否唯一
|
||||
*/
|
||||
private boolean checkConfigKeyUnique(SysOssConfig sysOssConfig) {
|
||||
long ossConfigId = ObjectUtils.notNull(sysOssConfig.getOssConfigId(), -1L);
|
||||
SysOssConfig info = baseMapper.selectOne(new LambdaQueryWrapper<SysOssConfig>()
|
||||
.select(SysOssConfig::getOssConfigId, SysOssConfig::getConfigKey)
|
||||
.eq(SysOssConfig::getConfigKey, sysOssConfig.getConfigKey()));
|
||||
if (ObjectUtil.isNotNull(info) && info.getOssConfigId() != ossConfigId) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 启用禁用状态
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public int updateOssConfigStatus(SysOssConfigBo bo) {
|
||||
SysOssConfig sysOssConfig = BeanUtil.toBean(bo, SysOssConfig.class);
|
||||
int row = baseMapper.update(null, new LambdaUpdateWrapper<SysOssConfig>()
|
||||
.set(SysOssConfig::getStatus, "1"));
|
||||
row += baseMapper.updateById(sysOssConfig);
|
||||
if (row > 0) {
|
||||
RedisUtils.setCacheObject(OssConstant.DEFAULT_CONFIG_KEY, sysOssConfig.getConfigKey());
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,263 @@
|
||||
package org.dromara.resource.service.impl;
|
||||
|
||||
import cn.hutool.core.bean.BeanUtil;
|
||||
import cn.hutool.core.convert.Convert;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.dromara.common.core.constant.CacheNames;
|
||||
import org.dromara.common.core.exception.ServiceException;
|
||||
import org.dromara.common.core.utils.MapstructUtils;
|
||||
import org.dromara.common.core.utils.SpringUtils;
|
||||
import org.dromara.common.core.utils.StringUtils;
|
||||
import org.dromara.common.core.utils.file.FileUtils;
|
||||
import org.dromara.common.mybatis.core.page.PageQuery;
|
||||
import org.dromara.common.mybatis.core.page.TableDataInfo;
|
||||
import org.dromara.common.oss.core.OssClient;
|
||||
import org.dromara.common.oss.entity.UploadResult;
|
||||
import org.dromara.common.oss.enums.AccessPolicyType;
|
||||
import org.dromara.common.oss.factory.OssFactory;
|
||||
import org.dromara.resource.domain.SysOss;
|
||||
import org.dromara.resource.domain.bo.SysOssBo;
|
||||
import org.dromara.resource.domain.vo.SysOssVo;
|
||||
import org.dromara.resource.mapper.SysOssMapper;
|
||||
import org.dromara.resource.service.ISysOssService;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 文件上传 服务层实现
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
public class SysOssServiceImpl implements ISysOssService {
|
||||
|
||||
private final SysOssMapper baseMapper;
|
||||
|
||||
/**
|
||||
* 查询OSS对象存储列表
|
||||
*
|
||||
* @param bo OSS对象存储分页查询对象
|
||||
* @param pageQuery 分页查询实体类
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
public TableDataInfo<SysOssVo> queryPageList(SysOssBo bo, PageQuery pageQuery) {
|
||||
LambdaQueryWrapper<SysOss> lqw = buildQueryWrapper(bo);
|
||||
Page<SysOssVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
|
||||
List<SysOssVo> filterResult = result.getRecords().stream().map(this::matchingUrl).collect(Collectors.toList());
|
||||
result.setRecords(filterResult);
|
||||
return TableDataInfo.build(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据一组 ossIds 获取对应的 SysOssVo 列表
|
||||
*
|
||||
* @param ossIds 一组文件在数据库中的唯一标识集合
|
||||
* @return 包含 SysOssVo 对象的列表
|
||||
*/
|
||||
@Override
|
||||
public List<SysOssVo> listByIds(Collection<Long> ossIds) {
|
||||
List<SysOssVo> list = new ArrayList<>();
|
||||
SysOssServiceImpl ossService = SpringUtils.getAopProxy(this);
|
||||
for (Long id : ossIds) {
|
||||
SysOssVo vo = ossService.getById(id);
|
||||
if (ObjectUtil.isNotNull(vo)) {
|
||||
try {
|
||||
list.add(this.matchingUrl(vo));
|
||||
} catch (Exception ignored) {
|
||||
// 如果oss异常无法连接则将数据直接返回
|
||||
list.add(vo);
|
||||
}
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据一组 ossIds 获取对应文件的 URL 列表
|
||||
*
|
||||
* @param ossIds 以逗号分隔的 ossId 字符串
|
||||
* @return 以逗号分隔的文件 URL 字符串
|
||||
*/
|
||||
@Override
|
||||
public String selectUrlByIds(String ossIds) {
|
||||
List<String> list = new ArrayList<>();
|
||||
SysOssServiceImpl ossService = SpringUtils.getAopProxy(this);
|
||||
for (Long id : StringUtils.splitTo(ossIds, Convert::toLong)) {
|
||||
SysOssVo vo = ossService.getById(id);
|
||||
if (ObjectUtil.isNotNull(vo)) {
|
||||
try {
|
||||
list.add(this.matchingUrl(vo).getUrl());
|
||||
} catch (Exception ignored) {
|
||||
// 如果oss异常无法连接则将数据直接返回
|
||||
list.add(vo.getUrl());
|
||||
}
|
||||
}
|
||||
}
|
||||
return String.join(StringUtils.SEPARATOR, list);
|
||||
}
|
||||
|
||||
private LambdaQueryWrapper<SysOss> buildQueryWrapper(SysOssBo bo) {
|
||||
Map<String, Object> params = bo.getParams();
|
||||
LambdaQueryWrapper<SysOss> lqw = Wrappers.lambdaQuery();
|
||||
lqw.like(StringUtils.isNotBlank(bo.getFileName()), SysOss::getFileName, bo.getFileName());
|
||||
lqw.like(StringUtils.isNotBlank(bo.getOriginalName()), SysOss::getOriginalName, bo.getOriginalName());
|
||||
lqw.eq(StringUtils.isNotBlank(bo.getFileSuffix()), SysOss::getFileSuffix, bo.getFileSuffix());
|
||||
lqw.eq(StringUtils.isNotBlank(bo.getUrl()), SysOss::getUrl, bo.getUrl());
|
||||
lqw.between(params.get("beginCreateTime") != null && params.get("endCreateTime") != null,
|
||||
SysOss::getCreateTime, params.get("beginCreateTime"), params.get("endCreateTime"));
|
||||
lqw.eq(ObjectUtil.isNotNull(bo.getCreateBy()), SysOss::getCreateBy, bo.getCreateBy());
|
||||
lqw.eq(StringUtils.isNotBlank(bo.getService()), SysOss::getService, bo.getService());
|
||||
lqw.orderByAsc(SysOss::getOssId);
|
||||
return lqw;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 ossId 从缓存或数据库中获取 SysOssVo 对象
|
||||
*
|
||||
* @param ossId 文件在数据库中的唯一标识
|
||||
* @return SysOssVo 对象,包含文件信息
|
||||
*/
|
||||
@Cacheable(cacheNames = CacheNames.SYS_OSS, key = "#ossId")
|
||||
@Override
|
||||
public SysOssVo getById(Long ossId) {
|
||||
return baseMapper.selectVoById(ossId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件下载方法,支持一次性下载完整文件
|
||||
*
|
||||
* @param ossId OSS对象ID
|
||||
* @param response HttpServletResponse对象,用于设置响应头和向客户端发送文件内容
|
||||
*/
|
||||
@Override
|
||||
public void download(Long ossId, HttpServletResponse response) throws IOException {
|
||||
SysOssVo sysOss = SpringUtils.getAopProxy(this).getById(ossId);
|
||||
if (ObjectUtil.isNull(sysOss)) {
|
||||
throw new ServiceException("文件数据不存在!");
|
||||
}
|
||||
FileUtils.setAttachmentResponseHeader(response, sysOss.getOriginalName());
|
||||
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE + "; charset=UTF-8");
|
||||
OssClient storage = OssFactory.instance(sysOss.getService());
|
||||
storage.download(sysOss.getFileName(), response.getOutputStream(), response::setContentLengthLong);
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传 MultipartFile 到对象存储服务,并保存文件信息到数据库
|
||||
*
|
||||
* @param file 要上传的 MultipartFile 对象
|
||||
* @return 上传成功后的 SysOssVo 对象,包含文件信息
|
||||
* @throws ServiceException 如果上传过程中发生异常,则抛出 ServiceException 异常
|
||||
*/
|
||||
@Override
|
||||
public SysOssVo upload(MultipartFile file) {
|
||||
String originalfileName = file.getOriginalFilename();
|
||||
String suffix = StringUtils.substring(originalfileName, originalfileName.lastIndexOf("."), originalfileName.length());
|
||||
OssClient storage = OssFactory.instance();
|
||||
UploadResult uploadResult;
|
||||
try {
|
||||
uploadResult = storage.uploadSuffix(file.getBytes(), suffix, file.getContentType());
|
||||
} catch (IOException e) {
|
||||
throw new ServiceException(e.getMessage());
|
||||
}
|
||||
// 保存文件信息
|
||||
return buildResultEntity(originalfileName, suffix, storage.getConfigKey(), uploadResult);
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传文件到对象存储服务,并保存文件信息到数据库
|
||||
*
|
||||
* @param file 要上传的文件对象
|
||||
* @return 上传成功后的 SysOssVo 对象,包含文件信息
|
||||
*/
|
||||
@Override
|
||||
public SysOssVo upload(File file) {
|
||||
String originalfileName = file.getName();
|
||||
String suffix = StringUtils.substring(originalfileName, originalfileName.lastIndexOf("."), originalfileName.length());
|
||||
OssClient storage = OssFactory.instance();
|
||||
UploadResult uploadResult = storage.uploadSuffix(file, suffix);
|
||||
// 保存文件信息
|
||||
return buildResultEntity(originalfileName, suffix, storage.getConfigKey(), uploadResult);
|
||||
}
|
||||
|
||||
private SysOssVo buildResultEntity(String originalfileName, String suffix, String configKey, UploadResult uploadResult) {
|
||||
SysOss oss = new SysOss();
|
||||
oss.setUrl(uploadResult.getUrl());
|
||||
oss.setFileSuffix(suffix);
|
||||
oss.setFileName(uploadResult.getFilename());
|
||||
oss.setOriginalName(originalfileName);
|
||||
oss.setService(configKey);
|
||||
baseMapper.insert(oss);
|
||||
SysOssVo sysOssVo = MapstructUtils.convert(oss, SysOssVo.class);
|
||||
return this.matchingUrl(sysOssVo);
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增OSS对象存储
|
||||
*
|
||||
* @param bo SysOssBo 对象,包含待插入的数据
|
||||
* @return 插入操作是否成功的布尔值
|
||||
*/
|
||||
@Override
|
||||
public Boolean insertByBo(SysOssBo bo) {
|
||||
SysOss oss = BeanUtil.toBean(bo, SysOss.class);
|
||||
boolean flag = baseMapper.insert(oss) > 0;
|
||||
if (flag) {
|
||||
bo.setOssId(oss.getOssId());
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除OSS对象存储
|
||||
*
|
||||
* @param ids OSS对象ID串
|
||||
* @param isValid 判断是否需要校验
|
||||
* @return 结果
|
||||
*/
|
||||
@Override
|
||||
public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
|
||||
if (isValid) {
|
||||
// 做一些业务上的校验,判断是否需要校验
|
||||
}
|
||||
List<SysOss> list = baseMapper.selectByIds(ids);
|
||||
for (SysOss sysOss : list) {
|
||||
OssClient storage = OssFactory.instance(sysOss.getService());
|
||||
storage.delete(sysOss.getUrl());
|
||||
}
|
||||
return baseMapper.deleteByIds(ids) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 桶类型为 private 的URL 修改为临时URL时长为120s
|
||||
*
|
||||
* @param oss OSS对象
|
||||
* @return oss 匹配Url的OSS对象
|
||||
*/
|
||||
private SysOssVo matchingUrl(SysOssVo oss) {
|
||||
OssClient storage = OssFactory.instance(oss.getService());
|
||||
// 仅修改桶类型为 private 的URL,临时URL时长为120s
|
||||
if (AccessPolicyType.PRIVATE == storage.getAccessPolicy()) {
|
||||
oss.setUrl(storage.getPrivateUrl(oss.getFileName(), Duration.ofSeconds(120)));
|
||||
}
|
||||
return oss;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,34 @@
|
||||
# Tomcat
|
||||
server:
|
||||
port: 9204
|
||||
|
||||
# Spring
|
||||
spring:
|
||||
application:
|
||||
# 应用名称
|
||||
name: ruoyi-resource
|
||||
profiles:
|
||||
# 环境配置
|
||||
active: @profiles.active@
|
||||
|
||||
--- # nacos 配置
|
||||
spring:
|
||||
cloud:
|
||||
nacos:
|
||||
# nacos 服务地址
|
||||
server-addr: @nacos.server@
|
||||
username: @nacos.username@
|
||||
password: @nacos.password@
|
||||
discovery:
|
||||
# 注册组
|
||||
group: @nacos.discovery.group@
|
||||
namespace: ${spring.profiles.active}
|
||||
config:
|
||||
# 配置组
|
||||
group: @nacos.config.group@
|
||||
namespace: ${spring.profiles.active}
|
||||
config:
|
||||
import:
|
||||
- optional:nacos:application-common.yml
|
||||
- optional:nacos:datasource.yml
|
||||
- optional:nacos:${spring.application.name}.yml
|
10
ruoyi-modules/ruoyi-resource/src/main/resources/banner.txt
Normal file
10
ruoyi-modules/ruoyi-resource/src/main/resources/banner.txt
Normal file
@ -0,0 +1,10 @@
|
||||
Spring Boot Version: ${spring-boot.version}
|
||||
Spring Application Name: ${spring.application.name}
|
||||
_
|
||||
(_)
|
||||
_ __ _ _ ___ _ _ _ ______ _ __ ___ ___ ___ _ _ _ __ ___ ___
|
||||
| '__| | | |/ _ \| | | | |______| '__/ _ \/ __|/ _ \| | | | '__/ __/ _ \
|
||||
| | | |_| | (_) | |_| | | | | | __/\__ \ (_) | |_| | | | (_| __/
|
||||
|_| \__,_|\___/ \__, |_| |_| \___||___/\___/ \__,_|_| \___\___|
|
||||
__/ |
|
||||
|___/
|
@ -0,0 +1,28 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration scan="true" scanPeriod="60 seconds" debug="false">
|
||||
<!-- 日志存放路径 -->
|
||||
<property name="log.path" value="logs/${project.artifactId}"/>
|
||||
<!-- 日志输出格式 -->
|
||||
<property name="console.log.pattern"
|
||||
value="%cyan(%d{yyyy-MM-dd HH:mm:ss}) %green([%thread]) %highlight(%-5level) %boldMagenta(%logger{36}%n) - %msg%n"/>
|
||||
|
||||
<!-- 控制台输出 -->
|
||||
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>${console.log.pattern}</pattern>
|
||||
<charset>utf-8</charset>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<include resource="logback-common.xml" />
|
||||
|
||||
<include resource="logback-logstash.xml" />
|
||||
|
||||
<!-- 开启 skywalking 日志收集 -->
|
||||
<include resource="logback-skylog.xml" />
|
||||
|
||||
<!--系统操作日志-->
|
||||
<root level="info">
|
||||
<appender-ref ref="console"/>
|
||||
</root>
|
||||
</configuration>
|
@ -0,0 +1,3 @@
|
||||
java包使用 `.` 分割 resource 目录使用 `/` 分割
|
||||
<br>
|
||||
此文件目的 防止文件夹粘连找不到 `xml` 文件
|
@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<!DOCTYPE mapper
|
||||
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="org.dromara.resource.mapper.SysOssConfigMapper">
|
||||
|
||||
</mapper>
|
@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="org.dromara.resource.mapper.SysOssMapper">
|
||||
|
||||
</mapper>
|
27
ruoyi-modules/ruoyi-system/Dockerfile
Normal file
27
ruoyi-modules/ruoyi-system/Dockerfile
Normal file
@ -0,0 +1,27 @@
|
||||
# 贝尔实验室 Spring 官方推荐镜像 JDK下载地址 https://bell-sw.com/pages/downloads/
|
||||
FROM bellsoft/liberica-openjdk-rocky:17.0.15-cds
|
||||
#FROM bellsoft/liberica-openjdk-rocky:21.0.7-cds
|
||||
#FROM findepi/graalvm:java17-native
|
||||
|
||||
LABEL maintainer="Lion Li"
|
||||
|
||||
RUN mkdir -p /ruoyi/system/logs \
|
||||
/ruoyi/system/temp \
|
||||
/ruoyi/skywalking/agent
|
||||
|
||||
WORKDIR /ruoyi/system
|
||||
|
||||
ENV SERVER_PORT=9201 LANG=C.UTF-8 LC_ALL=C.UTF-8 JAVA_OPTS=""
|
||||
|
||||
EXPOSE ${SERVER_PORT}
|
||||
|
||||
ADD ./target/ruoyi-system.jar ./app.jar
|
||||
|
||||
SHELL ["/bin/bash", "-c"]
|
||||
|
||||
ENTRYPOINT java -Djava.security.egd=file:/dev/./urandom -Dserver.port=${SERVER_PORT} \
|
||||
#-Dskywalking.agent.service_name=ruoyi-system \
|
||||
#-javaagent:/ruoyi/skywalking/agent/skywalking-agent.jar \
|
||||
-XX:+HeapDumpOnOutOfMemoryError -XX:+UseZGC ${JAVA_OPTS} \
|
||||
-jar app.jar
|
||||
|
133
ruoyi-modules/ruoyi-system/pom.xml
Normal file
133
ruoyi-modules/ruoyi-system/pom.xml
Normal file
@ -0,0 +1,133 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-modules</artifactId>
|
||||
<version>${revision}</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>ruoyi-system</artifactId>
|
||||
|
||||
<description>
|
||||
ruoyi-system系统模块
|
||||
</description>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-nacos</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-sentinel</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- RuoYi Common Log -->
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-log</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-service-impl</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-doc</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-web</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-mybatis</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-dubbo</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-seata</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-idempotent</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-tenant</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-security</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-translation</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-sensitive</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-common-encrypt</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- RuoYi Api System -->
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-api-system</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-api-resource</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- RuoYi Api System -->
|
||||
<dependency>
|
||||
<groupId>org.dromara</groupId>
|
||||
<artifactId>ruoyi-api-workflow</artifactId>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>${project.artifactId}</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>repackage</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
@ -0,0 +1,22 @@
|
||||
package org.dromara.system;
|
||||
|
||||
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.context.metrics.buffering.BufferingApplicationStartup;
|
||||
|
||||
/**
|
||||
* 系统模块
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@EnableDubbo
|
||||
@SpringBootApplication
|
||||
public class RuoYiSystemApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication application = new SpringApplication(RuoYiSystemApplication.class);
|
||||
application.setApplicationStartup(new BufferingApplicationStartup(2048));
|
||||
application.run(args);
|
||||
System.out.println("(♥◠‿◠)ノ゙ 系统模块启动成功 ლ(´ڡ`ლ)゙ ");
|
||||
}
|
||||
}
|
@ -0,0 +1,58 @@
|
||||
package org.dromara.system.controller.monitor;
|
||||
|
||||
import cn.dev33.satoken.annotation.SaCheckPermission;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.dromara.common.core.domain.R;
|
||||
import org.dromara.common.core.utils.StringUtils;
|
||||
import org.redisson.spring.data.connection.RedissonConnectionFactory;
|
||||
import org.springframework.data.redis.connection.RedisConnection;
|
||||
import org.springframework.data.redis.core.RedisConnectionUtils;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 缓存监控
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/cache")
|
||||
public class CacheController {
|
||||
|
||||
private final RedissonConnectionFactory connectionFactory;
|
||||
|
||||
/**
|
||||
* 获取缓存监控列表
|
||||
*/
|
||||
@SaCheckPermission("monitor:cache:list")
|
||||
@GetMapping()
|
||||
public R<CacheListInfoVo> getInfo() throws Exception {
|
||||
RedisConnection connection = connectionFactory.getConnection();
|
||||
try {
|
||||
Properties commandStats = connection.commands().info("commandstats");
|
||||
List<Map<String, String>> pieList = new ArrayList<>();
|
||||
if (commandStats != null) {
|
||||
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);
|
||||
});
|
||||
}
|
||||
return R.ok(new CacheListInfoVo(
|
||||
connection.commands().info(),
|
||||
connection.commands().dbSize(), pieList));
|
||||
} finally {
|
||||
// 归还连接给连接池
|
||||
RedisConnectionUtils.releaseConnection(connection, connectionFactory);
|
||||
}
|
||||
}
|
||||
|
||||
public record CacheListInfoVo(Properties info, Long dbSize, List<Map<String, String>> commandStats) {}
|
||||
|
||||
}
|
@ -0,0 +1,89 @@
|
||||
package org.dromara.system.controller.monitor;
|
||||
|
||||
import cn.dev33.satoken.annotation.SaCheckPermission;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.dromara.common.core.constant.CacheConstants;
|
||||
import org.dromara.common.core.domain.R;
|
||||
import org.dromara.common.excel.utils.ExcelUtil;
|
||||
import org.dromara.common.log.annotation.Log;
|
||||
import org.dromara.common.log.enums.BusinessType;
|
||||
import org.dromara.common.mybatis.core.page.PageQuery;
|
||||
import org.dromara.common.mybatis.core.page.TableDataInfo;
|
||||
import org.dromara.common.redis.utils.RedisUtils;
|
||||
import org.dromara.common.web.core.BaseController;
|
||||
import org.dromara.system.domain.bo.SysLogininforBo;
|
||||
import org.dromara.system.domain.vo.SysLogininforVo;
|
||||
import org.dromara.system.service.ISysLogininforService;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 系统访问记录
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Validated
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/logininfor")
|
||||
public class SysLogininforController extends BaseController {
|
||||
|
||||
private final ISysLogininforService logininforService;
|
||||
|
||||
/**
|
||||
* 获取系统访问记录列表
|
||||
*/
|
||||
@SaCheckPermission("monitor:logininfor:list")
|
||||
@GetMapping("/list")
|
||||
public TableDataInfo<SysLogininforVo> list(SysLogininforBo logininfor, PageQuery pageQuery) {
|
||||
return logininforService.selectPageLogininforList(logininfor, pageQuery);
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出系统访问记录列表
|
||||
*/
|
||||
@Log(title = "登录日志", businessType = BusinessType.EXPORT)
|
||||
@SaCheckPermission("monitor:logininfor:export")
|
||||
@PostMapping("/export")
|
||||
public void export(SysLogininforBo logininfor, HttpServletResponse response) {
|
||||
List<SysLogininforVo> list = logininforService.selectLogininforList(logininfor);
|
||||
ExcelUtil.exportExcel(list, "登录日志", SysLogininforVo.class, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量删除登录日志
|
||||
* @param infoIds 日志ids
|
||||
*/
|
||||
@SaCheckPermission("monitor:logininfor:remove")
|
||||
@Log(title = "登录日志", businessType = BusinessType.DELETE)
|
||||
@DeleteMapping("/{infoIds}")
|
||||
public R<Void> remove(@PathVariable Long[] infoIds) {
|
||||
return toAjax(logininforService.deleteLogininforByIds(infoIds));
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理系统访问记录
|
||||
*/
|
||||
@SaCheckPermission("monitor:logininfor:remove")
|
||||
@Log(title = "登录日志", businessType = BusinessType.CLEAN)
|
||||
@DeleteMapping("/clean")
|
||||
public R<Void> clean() {
|
||||
logininforService.cleanLogininfor();
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
@SaCheckPermission("monitor:logininfor:unlock")
|
||||
@Log(title = "账户解锁", businessType = BusinessType.OTHER)
|
||||
@GetMapping("/unlock/{userName}")
|
||||
public R<Void> unlock(@PathVariable("userName") String userName) {
|
||||
String loginName = CacheConstants.PWD_ERR_CNT_KEY + userName;
|
||||
if (RedisUtils.hasKey(loginName)) {
|
||||
RedisUtils.deleteObject(loginName);
|
||||
}
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,75 @@
|
||||
package org.dromara.system.controller.monitor;
|
||||
|
||||
import cn.dev33.satoken.annotation.SaCheckPermission;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.dromara.common.core.domain.R;
|
||||
import org.dromara.common.web.core.BaseController;
|
||||
import org.dromara.common.excel.utils.ExcelUtil;
|
||||
import org.dromara.common.log.annotation.Log;
|
||||
import org.dromara.common.log.enums.BusinessType;
|
||||
import org.dromara.common.mybatis.core.page.PageQuery;
|
||||
import org.dromara.common.mybatis.core.page.TableDataInfo;
|
||||
import org.dromara.system.domain.bo.SysOperLogBo;
|
||||
import org.dromara.system.domain.vo.SysOperLogVo;
|
||||
import org.dromara.system.service.ISysOperLogService;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 操作日志记录
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Validated
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/operlog")
|
||||
public class SysOperlogController extends BaseController {
|
||||
|
||||
private final ISysOperLogService operLogService;
|
||||
|
||||
/**
|
||||
* 获取操作日志记录列表
|
||||
*/
|
||||
@SaCheckPermission("monitor:operlog:list")
|
||||
@GetMapping("/list")
|
||||
public TableDataInfo<SysOperLogVo> list(SysOperLogBo operLog, PageQuery pageQuery) {
|
||||
return operLogService.selectPageOperLogList(operLog, pageQuery);
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出操作日志记录列表
|
||||
*/
|
||||
@Log(title = "操作日志", businessType = BusinessType.EXPORT)
|
||||
@SaCheckPermission("monitor:operlog:export")
|
||||
@PostMapping("/export")
|
||||
public void export(SysOperLogBo operLog, HttpServletResponse response) {
|
||||
List<SysOperLogVo> list = operLogService.selectOperLogList(operLog);
|
||||
ExcelUtil.exportExcel(list, "操作日志", SysOperLogVo.class, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量删除操作日志记录
|
||||
* @param operIds 日志ids
|
||||
*/
|
||||
@Log(title = "操作日志", businessType = BusinessType.DELETE)
|
||||
@SaCheckPermission("monitor:operlog:remove")
|
||||
@DeleteMapping("/{operIds}")
|
||||
public R<Void> remove(@PathVariable Long[] operIds) {
|
||||
return toAjax(operLogService.deleteOperLogByIds(operIds));
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理操作日志记录
|
||||
*/
|
||||
@SaCheckPermission("monitor:operlog:remove")
|
||||
@Log(title = "操作日志", businessType = BusinessType.CLEAN)
|
||||
@DeleteMapping("/clean")
|
||||
public R<Void> clean() {
|
||||
operLogService.cleanOperLog();
|
||||
return R.ok();
|
||||
}
|
||||
}
|
@ -0,0 +1,130 @@
|
||||
package org.dromara.system.controller.monitor;
|
||||
|
||||
import cn.dev33.satoken.annotation.SaCheckPermission;
|
||||
import cn.dev33.satoken.exception.NotLoginException;
|
||||
import cn.dev33.satoken.stp.StpUtil;
|
||||
import cn.hutool.core.bean.BeanUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.dromara.common.core.constant.CacheConstants;
|
||||
import org.dromara.common.core.domain.R;
|
||||
import org.dromara.common.core.utils.StreamUtils;
|
||||
import org.dromara.common.core.utils.StringUtils;
|
||||
import org.dromara.common.web.core.BaseController;
|
||||
import org.dromara.common.log.annotation.Log;
|
||||
import org.dromara.common.log.enums.BusinessType;
|
||||
import org.dromara.common.mybatis.core.page.TableDataInfo;
|
||||
import org.dromara.common.redis.utils.RedisUtils;
|
||||
import org.dromara.system.api.domain.SysUserOnline;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 在线用户监控
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/online")
|
||||
public class SysUserOnlineController extends BaseController {
|
||||
|
||||
/**
|
||||
* 获取在线用户监控列表
|
||||
*
|
||||
* @param ipaddr IP地址
|
||||
* @param userName 用户名
|
||||
*/
|
||||
@SaCheckPermission("monitor:online:list")
|
||||
@GetMapping("/list")
|
||||
public TableDataInfo<SysUserOnline> list(String ipaddr, String userName) {
|
||||
// 获取所有未过期的 token
|
||||
Collection<String> keys = RedisUtils.keys(CacheConstants.ONLINE_TOKEN_KEY + "*");
|
||||
List<SysUserOnline> userOnlineDTOList = new ArrayList<>();
|
||||
for (String key : keys) {
|
||||
String token = StringUtils.substringAfterLast(key, ":");
|
||||
// 如果已经过期则跳过
|
||||
if (StpUtil.stpLogic.getTokenActiveTimeoutByToken(token) < -1) {
|
||||
continue;
|
||||
}
|
||||
userOnlineDTOList.add(RedisUtils.getCacheObject(CacheConstants.ONLINE_TOKEN_KEY + token));
|
||||
}
|
||||
if (StringUtils.isNotEmpty(ipaddr) && StringUtils.isNotEmpty(userName)) {
|
||||
userOnlineDTOList = StreamUtils.filter(userOnlineDTOList, userOnline ->
|
||||
StringUtils.equals(ipaddr, userOnline.getIpaddr()) &&
|
||||
StringUtils.equals(userName, userOnline.getUserName())
|
||||
);
|
||||
} else if (StringUtils.isNotEmpty(ipaddr)) {
|
||||
userOnlineDTOList = StreamUtils.filter(userOnlineDTOList, userOnline ->
|
||||
StringUtils.equals(ipaddr, userOnline.getIpaddr())
|
||||
);
|
||||
} else if (StringUtils.isNotEmpty(userName)) {
|
||||
userOnlineDTOList = StreamUtils.filter(userOnlineDTOList, userOnline ->
|
||||
StringUtils.equals(userName, userOnline.getUserName())
|
||||
);
|
||||
}
|
||||
Collections.reverse(userOnlineDTOList);
|
||||
userOnlineDTOList.removeAll(Collections.singleton(null));
|
||||
List<SysUserOnline> userOnlineList = BeanUtil.copyToList(userOnlineDTOList, SysUserOnline.class);
|
||||
return TableDataInfo.build(userOnlineList);
|
||||
}
|
||||
|
||||
/**
|
||||
* 强退用户
|
||||
*
|
||||
* @param tokenId token值
|
||||
*/
|
||||
@SaCheckPermission("monitor:online:forceLogout")
|
||||
@Log(title = "在线用户", businessType = BusinessType.FORCE)
|
||||
@DeleteMapping("/{tokenId}")
|
||||
public R<Void> forceLogout(@PathVariable String tokenId) {
|
||||
try {
|
||||
StpUtil.kickoutByTokenValue(tokenId);
|
||||
} catch (NotLoginException ignored) {
|
||||
}
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前用户登录在线设备
|
||||
*/
|
||||
@GetMapping()
|
||||
public TableDataInfo<SysUserOnline> getInfo() {
|
||||
// 获取指定账号 id 的 token 集合
|
||||
List<String> tokenIds = StpUtil.getTokenValueListByLoginId(StpUtil.getLoginIdAsString());
|
||||
List<SysUserOnline> userOnlineDTOList = tokenIds.stream()
|
||||
.filter(token -> StpUtil.stpLogic.getTokenActiveTimeoutByToken(token) >= -1)
|
||||
.map(token -> (SysUserOnline) RedisUtils.getCacheObject(CacheConstants.ONLINE_TOKEN_KEY + token))
|
||||
.collect(Collectors.toList());
|
||||
//复制和处理 SysUserOnline 对象列表
|
||||
Collections.reverse(userOnlineDTOList);
|
||||
userOnlineDTOList.removeAll(Collections.singleton(null));
|
||||
List<SysUserOnline> userOnlineList = BeanUtil.copyToList(userOnlineDTOList, SysUserOnline.class);
|
||||
return TableDataInfo.build(userOnlineList);
|
||||
}
|
||||
|
||||
/**
|
||||
* 强退当前在线设备
|
||||
*
|
||||
* @param tokenId token值
|
||||
*/
|
||||
@Log(title = "在线设备", businessType = BusinessType.FORCE)
|
||||
@DeleteMapping("/myself/{tokenId}")
|
||||
public R<Void> remove(@PathVariable("tokenId") String tokenId) {
|
||||
try {
|
||||
// 获取指定账号 id 的 token 集合
|
||||
List<String> keys = StpUtil.getTokenValueListByLoginId(StpUtil.getLoginIdAsString());
|
||||
keys.stream()
|
||||
.filter(key -> key.equals(tokenId))
|
||||
.findFirst()
|
||||
.ifPresent(key -> StpUtil.kickoutByTokenValue(tokenId));
|
||||
} catch (NotLoginException ignored) {
|
||||
}
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,115 @@
|
||||
package org.dromara.system.controller.system;
|
||||
|
||||
import cn.dev33.satoken.annotation.SaCheckPermission;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.dromara.common.core.domain.R;
|
||||
import org.dromara.common.core.validate.AddGroup;
|
||||
import org.dromara.common.core.validate.EditGroup;
|
||||
import org.dromara.common.excel.utils.ExcelUtil;
|
||||
import org.dromara.common.idempotent.annotation.RepeatSubmit;
|
||||
import org.dromara.common.log.annotation.Log;
|
||||
import org.dromara.common.log.enums.BusinessType;
|
||||
import org.dromara.common.mybatis.core.page.PageQuery;
|
||||
import org.dromara.common.mybatis.core.page.TableDataInfo;
|
||||
import org.dromara.common.web.core.BaseController;
|
||||
import org.dromara.system.domain.bo.SysClientBo;
|
||||
import org.dromara.system.domain.vo.SysClientVo;
|
||||
import org.dromara.system.service.ISysClientService;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 客户端管理
|
||||
*
|
||||
* @author Michelle.Chung
|
||||
*/
|
||||
@Validated
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/client")
|
||||
public class SysClientController extends BaseController {
|
||||
|
||||
private final ISysClientService sysClientService;
|
||||
|
||||
/**
|
||||
* 查询客户端管理列表
|
||||
*/
|
||||
@SaCheckPermission("system:client:list")
|
||||
@GetMapping("/list")
|
||||
public TableDataInfo<SysClientVo> list(SysClientBo bo, PageQuery pageQuery) {
|
||||
return sysClientService.queryPageList(bo, pageQuery);
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出客户端管理列表
|
||||
*/
|
||||
@SaCheckPermission("system:client:export")
|
||||
@Log(title = "客户端管理", businessType = BusinessType.EXPORT)
|
||||
@PostMapping("/export")
|
||||
public void export(SysClientBo bo, HttpServletResponse response) {
|
||||
List<SysClientVo> list = sysClientService.queryList(bo);
|
||||
ExcelUtil.exportExcel(list, "客户端管理", SysClientVo.class, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取客户端管理详细信息
|
||||
*
|
||||
* @param id 主键
|
||||
*/
|
||||
@SaCheckPermission("system:client:query")
|
||||
@GetMapping("/{id}")
|
||||
public R<SysClientVo> getInfo(@NotNull(message = "主键不能为空")
|
||||
@PathVariable Long id) {
|
||||
return R.ok(sysClientService.queryById(id));
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增客户端管理
|
||||
*/
|
||||
@SaCheckPermission("system:client:add")
|
||||
@Log(title = "客户端管理", businessType = BusinessType.INSERT)
|
||||
@RepeatSubmit()
|
||||
@PostMapping()
|
||||
public R<Void> add(@Validated(AddGroup.class) @RequestBody SysClientBo bo) {
|
||||
return toAjax(sysClientService.insertByBo(bo));
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改客户端管理
|
||||
*/
|
||||
@SaCheckPermission("system:client:edit")
|
||||
@Log(title = "客户端管理", businessType = BusinessType.UPDATE)
|
||||
@RepeatSubmit()
|
||||
@PutMapping()
|
||||
public R<Void> edit(@Validated(EditGroup.class) @RequestBody SysClientBo bo) {
|
||||
return toAjax(sysClientService.updateByBo(bo));
|
||||
}
|
||||
|
||||
/**
|
||||
* 状态修改
|
||||
*/
|
||||
@SaCheckPermission("system:client:edit")
|
||||
@Log(title = "客户端管理", businessType = BusinessType.UPDATE)
|
||||
@PutMapping("/changeStatus")
|
||||
public R<Void> changeStatus(@RequestBody SysClientBo bo) {
|
||||
return toAjax(sysClientService.updateClientStatus(bo.getClientId(), bo.getStatus()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除客户端管理
|
||||
*
|
||||
* @param ids 主键串
|
||||
*/
|
||||
@SaCheckPermission("system:client:remove")
|
||||
@Log(title = "客户端管理", businessType = BusinessType.DELETE)
|
||||
@DeleteMapping("/{ids}")
|
||||
public R<Void> remove(@NotEmpty(message = "主键不能为空")
|
||||
@PathVariable Long[] ids) {
|
||||
return toAjax(sysClientService.deleteWithValidByIds(List.of(ids), true));
|
||||
}
|
||||
}
|
@ -0,0 +1,139 @@
|
||||
package org.dromara.system.controller.system;
|
||||
|
||||
import cn.dev33.satoken.annotation.SaCheckPermission;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.dromara.common.core.domain.R;
|
||||
import org.dromara.common.web.core.BaseController;
|
||||
import org.dromara.common.excel.utils.ExcelUtil;
|
||||
import org.dromara.common.log.annotation.Log;
|
||||
import org.dromara.common.log.enums.BusinessType;
|
||||
import org.dromara.common.mybatis.core.page.PageQuery;
|
||||
import org.dromara.common.mybatis.core.page.TableDataInfo;
|
||||
import org.dromara.system.domain.bo.SysConfigBo;
|
||||
import org.dromara.system.domain.vo.SysConfigVo;
|
||||
import org.dromara.system.service.ISysConfigService;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 参数配置 信息操作处理
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Validated
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/config")
|
||||
public class SysConfigController extends BaseController {
|
||||
|
||||
private final ISysConfigService configService;
|
||||
|
||||
/**
|
||||
* 获取参数配置列表
|
||||
*/
|
||||
@SaCheckPermission("system:config:list")
|
||||
@GetMapping("/list")
|
||||
public TableDataInfo<SysConfigVo> list(SysConfigBo config, PageQuery pageQuery) {
|
||||
return configService.selectPageConfigList(config, pageQuery);
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出参数配置列表
|
||||
*/
|
||||
@Log(title = "参数管理", businessType = BusinessType.EXPORT)
|
||||
@SaCheckPermission("system:config:export")
|
||||
@PostMapping("/export")
|
||||
public void export(SysConfigBo config, HttpServletResponse response) {
|
||||
List<SysConfigVo> list = configService.selectConfigList(config);
|
||||
ExcelUtil.exportExcel(list, "参数数据", SysConfigVo.class, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据参数编号获取详细信息
|
||||
*
|
||||
* @param configId 参数ID
|
||||
*/
|
||||
@SaCheckPermission("system:config:query")
|
||||
@GetMapping(value = "/{configId}")
|
||||
public R<SysConfigVo> getInfo(@PathVariable Long configId) {
|
||||
return R.ok(configService.selectConfigById(configId));
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据参数键名查询参数值
|
||||
*
|
||||
* @param configKey 参数Key
|
||||
*/
|
||||
@GetMapping(value = "/configKey/{configKey}")
|
||||
public R<String> getConfigKey(@PathVariable String configKey) {
|
||||
return R.ok("操作成功", configService.selectConfigByKey(configKey));
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增参数配置
|
||||
*/
|
||||
@SaCheckPermission("system:config:add")
|
||||
@Log(title = "参数管理", businessType = BusinessType.INSERT)
|
||||
@PostMapping
|
||||
public R<Void> add(@Validated @RequestBody SysConfigBo config) {
|
||||
if (!configService.checkConfigKeyUnique(config)) {
|
||||
return R.fail("新增参数'" + config.getConfigName() + "'失败,参数键名已存在");
|
||||
}
|
||||
configService.insertConfig(config);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改参数配置
|
||||
*/
|
||||
@SaCheckPermission("system:config:edit")
|
||||
@Log(title = "参数管理", businessType = BusinessType.UPDATE)
|
||||
@PutMapping
|
||||
public R<Void> edit(@Validated @RequestBody SysConfigBo config) {
|
||||
if (!configService.checkConfigKeyUnique(config)) {
|
||||
return R.fail("修改参数'" + config.getConfigName() + "'失败,参数键名已存在");
|
||||
}
|
||||
configService.updateConfig(config);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据参数键名修改参数配置
|
||||
*/
|
||||
@SaCheckPermission("system:config:edit")
|
||||
@Log(title = "参数管理", businessType = BusinessType.UPDATE)
|
||||
@PutMapping("/updateByKey")
|
||||
public R<Void> updateByKey(@RequestBody SysConfigBo config) {
|
||||
configService.updateConfig(config);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除参数配置
|
||||
*
|
||||
* @param configIds 参数ID串
|
||||
*/
|
||||
@SaCheckPermission("system:config:remove")
|
||||
@Log(title = "参数管理", businessType = BusinessType.DELETE)
|
||||
@DeleteMapping("/{configIds}")
|
||||
public R<Void> remove(@PathVariable Long[] configIds) {
|
||||
configService.deleteConfigByIds(Arrays.asList(configIds));
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新参数缓存
|
||||
*/
|
||||
@SaCheckPermission("system:config:remove")
|
||||
@Log(title = "参数管理", businessType = BusinessType.CLEAN)
|
||||
@DeleteMapping("/refreshCache")
|
||||
public R<Void> refreshCache() {
|
||||
configService.resetConfigCache();
|
||||
return R.ok();
|
||||
}
|
||||
}
|
@ -0,0 +1,140 @@
|
||||
package org.dromara.system.controller.system;
|
||||
|
||||
import cn.dev33.satoken.annotation.SaCheckPermission;
|
||||
import cn.hutool.core.convert.Convert;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.dromara.common.core.constant.SystemConstants;
|
||||
import org.dromara.common.core.domain.R;
|
||||
import org.dromara.common.core.utils.StringUtils;
|
||||
import org.dromara.common.log.annotation.Log;
|
||||
import org.dromara.common.log.enums.BusinessType;
|
||||
import org.dromara.common.web.core.BaseController;
|
||||
import org.dromara.system.domain.bo.SysDeptBo;
|
||||
import org.dromara.system.domain.vo.SysDeptVo;
|
||||
import org.dromara.system.service.ISysDeptService;
|
||||
import org.dromara.system.service.ISysPostService;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 部门信息
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Validated
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/dept")
|
||||
public class SysDeptController extends BaseController {
|
||||
|
||||
private final ISysDeptService deptService;
|
||||
private final ISysPostService postService;
|
||||
|
||||
/**
|
||||
* 获取部门列表
|
||||
*/
|
||||
@SaCheckPermission("system:dept:list")
|
||||
@GetMapping("/list")
|
||||
public R<List<SysDeptVo>> list(SysDeptBo dept) {
|
||||
List<SysDeptVo> depts = deptService.selectDeptList(dept);
|
||||
return R.ok(depts);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询部门列表(排除节点)
|
||||
*
|
||||
* @param deptId 部门ID
|
||||
*/
|
||||
@SaCheckPermission("system:dept:list")
|
||||
@GetMapping("/list/exclude/{deptId}")
|
||||
public R<List<SysDeptVo>> excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
|
||||
List<SysDeptVo> depts = deptService.selectDeptList(new SysDeptBo());
|
||||
depts.removeIf(d -> d.getDeptId().equals(deptId)
|
||||
|| StringUtils.splitList(d.getAncestors()).contains(Convert.toStr(deptId)));
|
||||
return R.ok(depts);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据部门编号获取详细信息
|
||||
*
|
||||
* @param deptId 部门ID
|
||||
*/
|
||||
@SaCheckPermission("system:dept:query")
|
||||
@GetMapping(value = "/{deptId}")
|
||||
public R<SysDeptVo> getInfo(@PathVariable Long deptId) {
|
||||
deptService.checkDeptDataScope(deptId);
|
||||
return R.ok(deptService.selectDeptById(deptId));
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增部门
|
||||
*/
|
||||
@SaCheckPermission("system:dept:add")
|
||||
@Log(title = "部门管理", businessType = BusinessType.INSERT)
|
||||
@PostMapping
|
||||
public R<Void> add(@Validated @RequestBody SysDeptBo dept) {
|
||||
if (!deptService.checkDeptNameUnique(dept)) {
|
||||
return R.fail("新增部门'" + dept.getDeptName() + "'失败,部门名称已存在");
|
||||
}
|
||||
return toAjax(deptService.insertDept(dept));
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改部门
|
||||
*/
|
||||
@SaCheckPermission("system:dept:edit")
|
||||
@Log(title = "部门管理", businessType = BusinessType.UPDATE)
|
||||
@PutMapping
|
||||
public R<Void> edit(@Validated @RequestBody SysDeptBo dept) {
|
||||
Long deptId = dept.getDeptId();
|
||||
deptService.checkDeptDataScope(deptId);
|
||||
if (!deptService.checkDeptNameUnique(dept)) {
|
||||
return R.fail("修改部门'" + dept.getDeptName() + "'失败,部门名称已存在");
|
||||
} else if (dept.getParentId().equals(deptId)) {
|
||||
return R.fail("修改部门'" + dept.getDeptName() + "'失败,上级部门不能是自己");
|
||||
} else if (StringUtils.equals(SystemConstants.DISABLE, dept.getStatus())) {
|
||||
if (deptService.selectNormalChildrenDeptById(deptId) > 0) {
|
||||
return R.fail("该部门包含未停用的子部门!");
|
||||
} else if (deptService.checkDeptExistUser(deptId)) {
|
||||
return R.fail("该部门下存在已分配用户,不能禁用!");
|
||||
}
|
||||
}
|
||||
return toAjax(deptService.updateDept(dept));
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除部门
|
||||
*
|
||||
* @param deptId 部门ID
|
||||
*/
|
||||
@SaCheckPermission("system:dept:remove")
|
||||
@Log(title = "部门管理", businessType = BusinessType.DELETE)
|
||||
@DeleteMapping("/{deptId}")
|
||||
public R<Void> remove(@PathVariable Long deptId) {
|
||||
if (deptService.hasChildByDeptId(deptId)) {
|
||||
return R.warn("存在下级部门,不允许删除");
|
||||
}
|
||||
if (deptService.checkDeptExistUser(deptId)) {
|
||||
return R.warn("部门存在用户,不允许删除");
|
||||
}
|
||||
if (postService.countPostByDeptId(deptId) > 0) {
|
||||
return R.warn("部门存在岗位,不允许删除");
|
||||
}
|
||||
deptService.checkDeptDataScope(deptId);
|
||||
return toAjax(deptService.deleteDeptById(deptId));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取部门选择框列表
|
||||
*
|
||||
* @param deptIds 部门ID串
|
||||
*/
|
||||
@SaCheckPermission("system:dept:query")
|
||||
@GetMapping("/optionselect")
|
||||
public R<List<SysDeptVo>> optionselect(@RequestParam(required = false) Long[] deptIds) {
|
||||
return R.ok(deptService.selectDeptByIds(deptIds == null ? null : List.of(deptIds)));
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,124 @@
|
||||
package org.dromara.system.controller.system;
|
||||
|
||||
import cn.dev33.satoken.annotation.SaCheckPermission;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.dromara.common.core.domain.R;
|
||||
import org.dromara.common.web.core.BaseController;
|
||||
import org.dromara.common.excel.utils.ExcelUtil;
|
||||
import org.dromara.common.log.annotation.Log;
|
||||
import org.dromara.common.log.enums.BusinessType;
|
||||
import org.dromara.common.mybatis.core.page.PageQuery;
|
||||
import org.dromara.common.mybatis.core.page.TableDataInfo;
|
||||
import org.dromara.system.domain.bo.SysDictDataBo;
|
||||
import org.dromara.system.domain.vo.SysDictDataVo;
|
||||
import org.dromara.system.service.ISysDictDataService;
|
||||
import org.dromara.system.service.ISysDictTypeService;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 数据字典信息
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Validated
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/dict/data")
|
||||
public class SysDictDataController extends BaseController {
|
||||
|
||||
private final ISysDictDataService dictDataService;
|
||||
private final ISysDictTypeService dictTypeService;
|
||||
|
||||
/**
|
||||
* 查询字典数据列表
|
||||
*/
|
||||
@SaCheckPermission("system:dict:list")
|
||||
@GetMapping("/list")
|
||||
public TableDataInfo<SysDictDataVo> list(SysDictDataBo dictData, PageQuery pageQuery) {
|
||||
return dictDataService.selectPageDictDataList(dictData, pageQuery);
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出字典数据列表
|
||||
*/
|
||||
@Log(title = "字典数据", businessType = BusinessType.EXPORT)
|
||||
@SaCheckPermission("system:dict:export")
|
||||
@PostMapping("/export")
|
||||
public void export(SysDictDataBo dictData, HttpServletResponse response) {
|
||||
List<SysDictDataVo> list = dictDataService.selectDictDataList(dictData);
|
||||
ExcelUtil.exportExcel(list, "字典数据", SysDictDataVo.class, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询字典数据详细
|
||||
*
|
||||
* @param dictCode 字典code
|
||||
*/
|
||||
@SaCheckPermission("system:dict:query")
|
||||
@GetMapping(value = "/{dictCode}")
|
||||
public R<SysDictDataVo> getInfo(@PathVariable Long dictCode) {
|
||||
return R.ok(dictDataService.selectDictDataById(dictCode));
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据字典类型查询字典数据信息
|
||||
*
|
||||
* @param dictType 字典类型
|
||||
*/
|
||||
@GetMapping(value = "/type/{dictType}")
|
||||
public R<List<SysDictDataVo>> dictType(@PathVariable String dictType) {
|
||||
List<SysDictDataVo> data = dictTypeService.selectDictDataByType(dictType);
|
||||
if (ObjectUtil.isNull(data)) {
|
||||
data = new ArrayList<>();
|
||||
}
|
||||
return R.ok(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增字典类型
|
||||
*/
|
||||
@SaCheckPermission("system:dict:add")
|
||||
@Log(title = "字典数据", businessType = BusinessType.INSERT)
|
||||
@PostMapping
|
||||
public R<Void> add(@Validated @RequestBody SysDictDataBo dict) {
|
||||
if (!dictDataService.checkDictDataUnique(dict)) {
|
||||
return R.fail("新增字典数据'" + dict.getDictValue() + "'失败,字典键值已存在");
|
||||
}
|
||||
dictDataService.insertDictData(dict);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改保存字典类型
|
||||
*/
|
||||
@SaCheckPermission("system:dict:edit")
|
||||
@Log(title = "字典数据", businessType = BusinessType.UPDATE)
|
||||
@PutMapping
|
||||
public R<Void> edit(@Validated @RequestBody SysDictDataBo dict) {
|
||||
if (!dictDataService.checkDictDataUnique(dict)) {
|
||||
return R.fail("修改字典数据'" + dict.getDictValue() + "'失败,字典键值已存在");
|
||||
}
|
||||
dictDataService.updateDictData(dict);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除字典类型
|
||||
*
|
||||
* @param dictCodes 字典code串
|
||||
*/
|
||||
@SaCheckPermission("system:dict:remove")
|
||||
@Log(title = "字典类型", businessType = BusinessType.DELETE)
|
||||
@DeleteMapping("/{dictCodes}")
|
||||
public R<Void> remove(@PathVariable Long[] dictCodes) {
|
||||
dictDataService.deleteDictDataByIds(Arrays.asList(dictCodes));
|
||||
return R.ok();
|
||||
}
|
||||
}
|
@ -0,0 +1,127 @@
|
||||
package org.dromara.system.controller.system;
|
||||
|
||||
import cn.dev33.satoken.annotation.SaCheckPermission;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.dromara.common.core.domain.R;
|
||||
import org.dromara.common.web.core.BaseController;
|
||||
import org.dromara.common.excel.utils.ExcelUtil;
|
||||
import org.dromara.common.log.annotation.Log;
|
||||
import org.dromara.common.log.enums.BusinessType;
|
||||
import org.dromara.common.mybatis.core.page.PageQuery;
|
||||
import org.dromara.common.mybatis.core.page.TableDataInfo;
|
||||
import org.dromara.system.domain.bo.SysDictTypeBo;
|
||||
import org.dromara.system.domain.vo.SysDictTypeVo;
|
||||
import org.dromara.system.service.ISysDictTypeService;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 数据字典信息
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Validated
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/dict/type")
|
||||
public class SysDictTypeController extends BaseController {
|
||||
|
||||
private final ISysDictTypeService dictTypeService;
|
||||
|
||||
/**
|
||||
* 查询字典类型列表
|
||||
*/
|
||||
@SaCheckPermission("system:dict:list")
|
||||
@GetMapping("/list")
|
||||
public TableDataInfo<SysDictTypeVo> list(SysDictTypeBo dictType, PageQuery pageQuery) {
|
||||
return dictTypeService.selectPageDictTypeList(dictType, pageQuery);
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出字典类型列表
|
||||
*/
|
||||
@Log(title = "字典类型", businessType = BusinessType.EXPORT)
|
||||
@SaCheckPermission("system:dict:export")
|
||||
@PostMapping("/export")
|
||||
public void export(SysDictTypeBo dictType, HttpServletResponse response) {
|
||||
List<SysDictTypeVo> list = dictTypeService.selectDictTypeList(dictType);
|
||||
ExcelUtil.exportExcel(list, "字典类型", SysDictTypeVo.class, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询字典类型详细
|
||||
*
|
||||
* @param dictId 字典ID
|
||||
*/
|
||||
@SaCheckPermission("system:dict:query")
|
||||
@GetMapping(value = "/{dictId}")
|
||||
public R<SysDictTypeVo> getInfo(@PathVariable Long dictId) {
|
||||
return R.ok(dictTypeService.selectDictTypeById(dictId));
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增字典类型
|
||||
*/
|
||||
@SaCheckPermission("system:dict:add")
|
||||
@Log(title = "字典类型", businessType = BusinessType.INSERT)
|
||||
@PostMapping
|
||||
public R<Void> add(@Validated @RequestBody SysDictTypeBo dict) {
|
||||
if (!dictTypeService.checkDictTypeUnique(dict)) {
|
||||
return R.fail("新增字典'" + dict.getDictName() + "'失败,字典类型已存在");
|
||||
}
|
||||
dictTypeService.insertDictType(dict);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改字典类型
|
||||
*/
|
||||
@SaCheckPermission("system:dict:edit")
|
||||
@Log(title = "字典类型", businessType = BusinessType.UPDATE)
|
||||
@PutMapping
|
||||
public R<Void> edit(@Validated @RequestBody SysDictTypeBo dict) {
|
||||
if (!dictTypeService.checkDictTypeUnique(dict)) {
|
||||
return R.fail("修改字典'" + dict.getDictName() + "'失败,字典类型已存在");
|
||||
}
|
||||
dictTypeService.updateDictType(dict);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除字典类型
|
||||
*
|
||||
* @param dictIds 字典ID串
|
||||
*/
|
||||
@SaCheckPermission("system:dict:remove")
|
||||
@Log(title = "字典类型", businessType = BusinessType.DELETE)
|
||||
@DeleteMapping("/{dictIds}")
|
||||
public R<Void> remove(@PathVariable Long[] dictIds) {
|
||||
dictTypeService.deleteDictTypeByIds(Arrays.asList(dictIds));
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新字典缓存
|
||||
*/
|
||||
@SaCheckPermission("system:dict:remove")
|
||||
@Log(title = "字典类型", businessType = BusinessType.CLEAN)
|
||||
@DeleteMapping("/refreshCache")
|
||||
public R<Void> refreshCache() {
|
||||
dictTypeService.resetDictCache();
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取字典选择框列表
|
||||
*/
|
||||
@GetMapping("/optionselect")
|
||||
public R<List<SysDictTypeVo>> optionselect() {
|
||||
List<SysDictTypeVo> dictTypes = dictTypeService.selectDictTypeAll();
|
||||
return R.ok(dictTypes);
|
||||
}
|
||||
}
|
@ -0,0 +1,200 @@
|
||||
package org.dromara.system.controller.system;
|
||||
|
||||
import cn.dev33.satoken.annotation.SaCheckPermission;
|
||||
import cn.dev33.satoken.annotation.SaCheckRole;
|
||||
import cn.dev33.satoken.annotation.SaMode;
|
||||
import cn.hutool.core.lang.tree.Tree;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.dromara.common.core.constant.SystemConstants;
|
||||
import org.dromara.common.core.constant.TenantConstants;
|
||||
import org.dromara.common.core.domain.R;
|
||||
import org.dromara.common.core.utils.StringUtils;
|
||||
import org.dromara.common.log.annotation.Log;
|
||||
import org.dromara.common.log.enums.BusinessType;
|
||||
import org.dromara.common.satoken.utils.LoginHelper;
|
||||
import org.dromara.common.web.core.BaseController;
|
||||
import org.dromara.system.domain.SysMenu;
|
||||
import org.dromara.system.domain.bo.SysMenuBo;
|
||||
import org.dromara.system.domain.vo.RouterVo;
|
||||
import org.dromara.system.domain.vo.SysMenuVo;
|
||||
import org.dromara.system.service.ISysMenuService;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 菜单信息
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Validated
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/menu")
|
||||
public class SysMenuController extends BaseController {
|
||||
|
||||
private final ISysMenuService menuService;
|
||||
|
||||
/**
|
||||
* 获取路由信息
|
||||
*
|
||||
* @return 路由信息
|
||||
*/
|
||||
@GetMapping("/getRouters")
|
||||
public R<List<RouterVo>> getRouters() {
|
||||
List<SysMenu> menus = menuService.selectMenuTreeByUserId(LoginHelper.getUserId());
|
||||
return R.ok(menuService.buildMenus(menus));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取菜单列表
|
||||
*/
|
||||
@SaCheckRole(value = {
|
||||
TenantConstants.SUPER_ADMIN_ROLE_KEY,
|
||||
TenantConstants.TENANT_ADMIN_ROLE_KEY
|
||||
}, mode = SaMode.OR)
|
||||
@SaCheckPermission("system:menu:list")
|
||||
@GetMapping("/list")
|
||||
public R<List<SysMenuVo>> list(SysMenuBo menu) {
|
||||
List<SysMenuVo> menus = menuService.selectMenuList(menu, LoginHelper.getUserId());
|
||||
return R.ok(menus);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据菜单编号获取详细信息
|
||||
*
|
||||
* @param menuId 菜单ID
|
||||
*/
|
||||
@SaCheckRole(value = {
|
||||
TenantConstants.SUPER_ADMIN_ROLE_KEY,
|
||||
TenantConstants.TENANT_ADMIN_ROLE_KEY
|
||||
}, mode = SaMode.OR)
|
||||
@SaCheckPermission("system:menu:query")
|
||||
@GetMapping(value = "/{menuId}")
|
||||
public R<SysMenuVo> getInfo(@PathVariable Long menuId) {
|
||||
return R.ok(menuService.selectMenuById(menuId));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取菜单下拉树列表
|
||||
*/
|
||||
@SaCheckPermission("system:menu:query")
|
||||
@GetMapping("/treeselect")
|
||||
public R<List<Tree<Long>>> treeselect(SysMenuBo menu) {
|
||||
List<SysMenuVo> menus = menuService.selectMenuList(menu, LoginHelper.getUserId());
|
||||
return R.ok(menuService.buildMenuTreeSelect(menus));
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载对应角色菜单列表树
|
||||
*
|
||||
* @param roleId 角色ID
|
||||
*/
|
||||
@SaCheckPermission("system:menu:query")
|
||||
@GetMapping(value = "/roleMenuTreeselect/{roleId}")
|
||||
public R<MenuTreeSelectVo> roleMenuTreeselect(@PathVariable("roleId") Long roleId) {
|
||||
List<SysMenuVo> menus = menuService.selectMenuList(LoginHelper.getUserId());
|
||||
MenuTreeSelectVo selectVo = new MenuTreeSelectVo(
|
||||
menuService.selectMenuListByRoleId(roleId),
|
||||
menuService.buildMenuTreeSelect(menus));
|
||||
return R.ok(selectVo);
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载对应租户套餐菜单列表树
|
||||
*
|
||||
* @param packageId 租户套餐ID
|
||||
*/
|
||||
@SaCheckRole(TenantConstants.SUPER_ADMIN_ROLE_KEY)
|
||||
@SaCheckPermission("system:menu:query")
|
||||
@GetMapping(value = "/tenantPackageMenuTreeselect/{packageId}")
|
||||
public R<MenuTreeSelectVo> tenantPackageMenuTreeselect(@PathVariable("packageId") Long packageId) {
|
||||
List<SysMenuVo> menus = menuService.selectMenuList(LoginHelper.getUserId());
|
||||
List<Tree<Long>> list = menuService.buildMenuTreeSelect(menus);
|
||||
// 删除租户管理菜单
|
||||
list.removeIf(menu -> menu.getId() == 6L);
|
||||
List<Long> ids = new ArrayList<>();
|
||||
if (packageId > 0L) {
|
||||
ids = menuService.selectMenuListByPackageId(packageId);
|
||||
}
|
||||
MenuTreeSelectVo selectVo = new MenuTreeSelectVo(ids, list);
|
||||
return R.ok(selectVo);
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增菜单
|
||||
*/
|
||||
@SaCheckRole(TenantConstants.SUPER_ADMIN_ROLE_KEY)
|
||||
@SaCheckPermission("system:menu:add")
|
||||
@Log(title = "菜单管理", businessType = BusinessType.INSERT)
|
||||
@PostMapping
|
||||
public R<Void> add(@Validated @RequestBody SysMenuBo menu) {
|
||||
if (!menuService.checkMenuNameUnique(menu)) {
|
||||
return R.fail("新增菜单'" + menu.getMenuName() + "'失败,菜单名称已存在");
|
||||
} else if (SystemConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath())) {
|
||||
return R.fail("新增菜单'" + menu.getMenuName() + "'失败,地址必须以http(s)://开头");
|
||||
}
|
||||
return toAjax(menuService.insertMenu(menu));
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改菜单
|
||||
*/
|
||||
@SaCheckRole(TenantConstants.SUPER_ADMIN_ROLE_KEY)
|
||||
@SaCheckPermission("system:menu:edit")
|
||||
@Log(title = "菜单管理", businessType = BusinessType.UPDATE)
|
||||
@PutMapping
|
||||
public R<Void> edit(@Validated @RequestBody SysMenuBo menu) {
|
||||
if (!menuService.checkMenuNameUnique(menu)) {
|
||||
return R.fail("修改菜单'" + menu.getMenuName() + "'失败,菜单名称已存在");
|
||||
} else if (SystemConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath())) {
|
||||
return R.fail("修改菜单'" + menu.getMenuName() + "'失败,地址必须以http(s)://开头");
|
||||
} else if (menu.getMenuId().equals(menu.getParentId())) {
|
||||
return R.fail("修改菜单'" + menu.getMenuName() + "'失败,上级菜单不能选择自己");
|
||||
}
|
||||
return toAjax(menuService.updateMenu(menu));
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除菜单
|
||||
*
|
||||
* @param menuId 菜单ID
|
||||
*/
|
||||
@SaCheckRole(TenantConstants.SUPER_ADMIN_ROLE_KEY)
|
||||
@SaCheckPermission("system:menu:remove")
|
||||
@Log(title = "菜单管理", businessType = BusinessType.DELETE)
|
||||
@DeleteMapping("/{menuId}")
|
||||
public R<Void> remove(@PathVariable("menuId") Long menuId) {
|
||||
if (menuService.hasChildByMenuId(menuId)) {
|
||||
return R.warn("存在子菜单,不允许删除");
|
||||
}
|
||||
if (menuService.checkMenuExistRole(menuId)) {
|
||||
return R.warn("菜单已分配,不允许删除");
|
||||
}
|
||||
return toAjax(menuService.deleteMenuById(menuId));
|
||||
}
|
||||
|
||||
public record MenuTreeSelectVo(List<Long> checkedKeys, List<Tree<Long>> menus) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量级联删除菜单
|
||||
*
|
||||
* @param menuIds 菜单ID串
|
||||
*/
|
||||
@SaCheckRole(TenantConstants.SUPER_ADMIN_ROLE_KEY)
|
||||
@SaCheckPermission("system:menu:remove")
|
||||
@Log(title = "菜单管理", businessType = BusinessType.DELETE)
|
||||
@DeleteMapping("/cascade/{menuIds}")
|
||||
public R<Void> remove(@PathVariable("menuIds") Long[] menuIds) {
|
||||
List<Long> menuIdList = List.of(menuIds);
|
||||
if (menuService.hasChildByMenuId(menuIdList)) {
|
||||
return R.warn("存在子菜单,不允许删除");
|
||||
}
|
||||
menuService.deleteMenuById(menuIdList);
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,94 @@
|
||||
package org.dromara.system.controller.system;
|
||||
|
||||
import cn.dev33.satoken.annotation.SaCheckPermission;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.apache.dubbo.config.annotation.DubboReference;
|
||||
import org.dromara.common.core.domain.R;
|
||||
import org.dromara.common.core.service.DictService;
|
||||
import org.dromara.common.web.core.BaseController;
|
||||
import org.dromara.common.log.annotation.Log;
|
||||
import org.dromara.common.log.enums.BusinessType;
|
||||
import org.dromara.common.mybatis.core.page.PageQuery;
|
||||
import org.dromara.common.mybatis.core.page.TableDataInfo;
|
||||
import org.dromara.resource.api.RemoteMessageService;
|
||||
import org.dromara.system.domain.bo.SysNoticeBo;
|
||||
import org.dromara.system.domain.vo.SysNoticeVo;
|
||||
import org.dromara.system.service.ISysNoticeService;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
/**
|
||||
* 公告 信息操作处理
|
||||
*
|
||||
* @author Lion Li
|
||||
*/
|
||||
@Validated
|
||||
@RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/notice")
|
||||
public class SysNoticeController extends BaseController {
|
||||
|
||||
private final ISysNoticeService noticeService;
|
||||
private final DictService dictService;
|
||||
|
||||
@DubboReference
|
||||
private RemoteMessageService remoteMessageService;
|
||||
|
||||
/**
|
||||
* 获取通知公告列表
|
||||
*/
|
||||
@SaCheckPermission("system:notice:list")
|
||||
@GetMapping("/list")
|
||||
public TableDataInfo<SysNoticeVo> list(SysNoticeBo notice, PageQuery pageQuery) {
|
||||
return noticeService.selectPageNoticeList(notice, pageQuery);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据通知公告编号获取详细信息
|
||||
*
|
||||
* @param noticeId 公告ID
|
||||
*/
|
||||
@SaCheckPermission("system:notice:query")
|
||||
@GetMapping(value = "/{noticeId}")
|
||||
public R<SysNoticeVo> getInfo(@PathVariable Long noticeId) {
|
||||
return R.ok(noticeService.selectNoticeById(noticeId));
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增通知公告
|
||||
*/
|
||||
@SaCheckPermission("system:notice:add")
|
||||
@Log(title = "通知公告", businessType = BusinessType.INSERT)
|
||||
@PostMapping
|
||||
public R<Void> add(@Validated @RequestBody SysNoticeBo notice) {
|
||||
int rows = noticeService.insertNotice(notice);
|
||||
if (rows <= 0) {
|
||||
return R.fail();
|
||||
}
|
||||
String type = dictService.getDictLabel("sys_notice_type", notice.getNoticeType());
|
||||
remoteMessageService.publishAll("[" + type + "] " + notice.getNoticeTitle());
|
||||
return R.ok();
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改通知公告
|
||||
*/
|
||||
@SaCheckPermission("system:notice:edit")
|
||||
@Log(title = "通知公告", businessType = BusinessType.UPDATE)
|
||||
@PutMapping
|
||||
public R<Void> edit(@Validated @RequestBody SysNoticeBo notice) {
|
||||
return toAjax(noticeService.updateNotice(notice));
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除通知公告
|
||||
*
|
||||
* @param noticeIds 公告ID串
|
||||
*/
|
||||
@SaCheckPermission("system:notice:remove")
|
||||
@Log(title = "通知公告", businessType = BusinessType.DELETE)
|
||||
@DeleteMapping("/{noticeIds}")
|
||||
public R<Void> remove(@PathVariable Long[] noticeIds) {
|
||||
return toAjax(noticeService.deleteNoticeByIds(noticeIds));
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user