Unverified Commit d4f0a00f authored by zhu-mingye's avatar zhu-mingye Committed by GitHub

[Optimize][Web]fix resource && resource config (#2398)

* fix resource && resource config * fix resource file * fix resource file * fix resource file * fix resource file
parent e8c0bcbc
...@@ -140,7 +140,6 @@ public class ResourceController { ...@@ -140,7 +140,6 @@ public class ResourceController {
@ApiImplicitParam(name = "id", value = "Resource ID", required = true, dataType = "Integer", paramType = "query") @ApiImplicitParam(name = "id", value = "Resource ID", required = true, dataType = "Integer", paramType = "query")
@SaCheckPermission(PermissionConstants.REGISTRATION_RESOURCE_DELETE) @SaCheckPermission(PermissionConstants.REGISTRATION_RESOURCE_DELETE)
public Result<Void> remove(Integer id) { public Result<Void> remove(Integer id) {
resourcesService.remove(id); return resourcesService.remove(id) ? Result.succeed() : Result.failed();
return Result.succeed();
} }
} }
...@@ -45,6 +45,13 @@ public class ResourcesDTO implements Serializable { ...@@ -45,6 +45,13 @@ public class ResourcesDTO implements Serializable {
notes = "The name of the resource file") notes = "The name of the resource file")
private String fileName; private String fileName;
@ApiModelProperty(
value = "Parent ID",
dataType = "Integer",
example = "1",
notes = "The unique identifier of the parent resource")
private Integer pid;
@ApiModelProperty( @ApiModelProperty(
value = "Description", value = "Description",
dataType = "String", dataType = "String",
......
...@@ -19,6 +19,8 @@ ...@@ -19,6 +19,8 @@
package org.dinky.data.exception; package org.dinky.data.exception;
import org.dinky.data.enums.Status;
import cn.hutool.core.exceptions.ExceptionUtil; import cn.hutool.core.exceptions.ExceptionUtil;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
...@@ -50,6 +52,12 @@ public class BusException extends RuntimeException { ...@@ -50,6 +52,12 @@ public class BusException extends RuntimeException {
setMsg(message); setMsg(message);
} }
public BusException(Status status) {
super(status.getMessage());
setCode(String.valueOf(status.getCode()));
setMsg(status.getMessage());
}
public BusException(String message, Object... args) { public BusException(String message, Object... args) {
super(); super();
setCode(message); setCode(message);
......
...@@ -86,7 +86,7 @@ public interface ResourcesService extends IService<Resources> { ...@@ -86,7 +86,7 @@ public interface ResourcesService extends IService<Resources> {
*/ */
void uploadFile(Integer pid, String desc, MultipartFile file); void uploadFile(Integer pid, String desc, MultipartFile file);
void remove(Integer id); boolean remove(Integer id);
/** /**
* 递归获取所有的资源,从pid到0 * 递归获取所有的资源,从pid到0
......
...@@ -20,6 +20,7 @@ ...@@ -20,6 +20,7 @@
package org.dinky.service.resource.impl; package org.dinky.service.resource.impl;
import org.dinky.data.dto.TreeNodeDTO; import org.dinky.data.dto.TreeNodeDTO;
import org.dinky.data.enums.Status;
import org.dinky.data.exception.BusException; import org.dinky.data.exception.BusException;
import org.dinky.data.model.Resources; import org.dinky.data.model.Resources;
import org.dinky.data.result.Result; import org.dinky.data.result.Result;
...@@ -203,17 +204,22 @@ public class ResourceServiceImpl extends ServiceImpl<ResourcesMapper, Resources> ...@@ -203,17 +204,22 @@ public class ResourceServiceImpl extends ServiceImpl<ResourcesMapper, Resources>
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
@Override @Override
public void remove(Integer id) { public boolean remove(Integer id) {
Assert.isFalse(
Opt.ofNullable(getById(id))
.orElseThrow(() -> new BusException(Status.RESOURCE_DIR_OR_FILE_NOT_EXIST))
.getPid()
== -1,
() -> new BusException(Status.ROOT_DIR_NOT_ALLOW_DELETE));
try {
if (id < 1) { if (id < 1) {
getBaseResourceManager().remove("/"); getBaseResourceManager().remove("/");
// todo 删除主目录,实际是清空 // todo 删除主目录,实际是清空
remove(new LambdaQueryWrapper<Resources>().ne(Resources::getId, 0)); remove(new LambdaQueryWrapper<Resources>().ne(Resources::getId, 0));
return;
} }
Resources byId = getById(id); Resources byId = getById(id);
if (!isExistsChildren(id)) { if (!isExistsChildren(id)) {
removeById(id); removeById(id);
return;
} }
getBaseResourceManager().remove(byId.getFullName()); getBaseResourceManager().remove(byId.getFullName());
if (byId.getIsDirectory()) { if (byId.getIsDirectory()) {
...@@ -223,7 +229,11 @@ public class ResourceServiceImpl extends ServiceImpl<ResourcesMapper, Resources> ...@@ -223,7 +229,11 @@ public class ResourceServiceImpl extends ServiceImpl<ResourcesMapper, Resources>
List<Resources> resourceByPidToParent = getResourceByPidToParent(new ArrayList<>(), byId.getPid()); List<Resources> resourceByPidToParent = getResourceByPidToParent(new ArrayList<>(), byId.getPid());
resourceByPidToParent.forEach(x -> x.setSize(x.getSize() - byId.getSize())); resourceByPidToParent.forEach(x -> x.setSize(x.getSize() - byId.getSize()));
updateBatchById(resourceByPidToParent); updateBatchById(resourceByPidToParent);
removeById(id); } catch (Exception e) {
throw new BusException(Status.DELETE_FAILED);
}
return removeById(id);
} }
private boolean isExistsChildren(Integer id) { private boolean isExistsChildren(Integer id) {
......
...@@ -77,7 +77,6 @@ public enum Status { ...@@ -77,7 +77,6 @@ public enum Status {
EXECUTE_FAILED(9020, "execute.failed"), EXECUTE_FAILED(9020, "execute.failed"),
RESTART_SUCCESS(9021, "restart.success"), RESTART_SUCCESS(9021, "restart.success"),
RESTART_FAILED(9022, "restart.failed"), RESTART_FAILED(9022, "restart.failed"),
// 已成功停止
STOP_SUCCESS(9023, "stop.success"), STOP_SUCCESS(9023, "stop.success"),
STOP_FAILED(9024, "stop.failed"), STOP_FAILED(9024, "stop.failed"),
RENAME_SUCCESS(9025, "rename.success"), RENAME_SUCCESS(9025, "rename.success"),
...@@ -255,6 +254,12 @@ public enum Status { ...@@ -255,6 +254,12 @@ public enum Status {
ALERT_RULE_JOB_RUN_EXCEPTION(20005, "alert.rule.jobRunException"), ALERT_RULE_JOB_RUN_EXCEPTION(20005, "alert.rule.jobRunException"),
ALERT_RULE_CHECKPOINT_TIMEOUT(20006, "alert.rule.checkpointTimeout"), ALERT_RULE_CHECKPOINT_TIMEOUT(20006, "alert.rule.checkpointTimeout"),
/**
* Resource
*/
ROOT_DIR_NOT_ALLOW_DELETE(9031, "resource.root.dir.not.allow.delete"),
RESOURCE_DIR_OR_FILE_NOT_EXIST(9032, "resource.dir.or.file.not.exist"),
/** /**
* global exception * global exception
*/ */
...@@ -327,12 +332,12 @@ public enum Status { ...@@ -327,12 +332,12 @@ public enum Status {
SYS_METRICS_SETTINGS_FLINK_GATHERTIMING_NOTE(153, "sys.metrics.settings.flink.gatherTiming.note"), SYS_METRICS_SETTINGS_FLINK_GATHERTIMING_NOTE(153, "sys.metrics.settings.flink.gatherTiming.note"),
SYS_METRICS_SETTINGS_FLINK_GATHERTIMEOUT(154, "sys.metrics.settings.flink.gatherTimeout"), SYS_METRICS_SETTINGS_FLINK_GATHERTIMEOUT(154, "sys.metrics.settings.flink.gatherTimeout"),
SYS_METRICS_SETTINGS_FLINK_GATHERTIMEOUT_NOTE(155, "sys.metrics.settings.flink.gatherTimeout.note"), SYS_METRICS_SETTINGS_FLINK_GATHERTIMEOUT_NOTE(155, "sys.metrics.settings.flink.gatherTimeout.note"),
SYS_RESOURCE_SETTINGS_ENABLE(156, "sys.resource.settings.enable"), SYS_RESOURCE_SETTINGS_ENABLE(156, "sys.resource.settings.base.enable"),
SYS_RESOURCE_SETTINGS_ENABLE_NOTE(157, "sys.resource.settings.enable.note"), SYS_RESOURCE_SETTINGS_ENABLE_NOTE(157, "sys.resource.settings.base.enable.note"),
SYS_RESOURCE_SETTINGS_UPLOAD_BASE_PATH(158, "sys.resource.settings.upload.base.path"), SYS_RESOURCE_SETTINGS_UPLOAD_BASE_PATH(158, "sys.resource.settings.base.upload.base.path"),
SYS_RESOURCE_SETTINGS_UPLOAD_BASE_PATH_NOTE(159, "sys.resource.settings.upload.base.path.note"), SYS_RESOURCE_SETTINGS_UPLOAD_BASE_PATH_NOTE(159, "sys.resource.settings.base.upload.base.path.note"),
SYS_RESOURCE_SETTINGS_MODEL(160, "sys.resource.settings.model"), SYS_RESOURCE_SETTINGS_MODEL(160, "sys.resource.settings.base.model"),
SYS_RESOURCE_SETTINGS_MODEL_NOTE(161, "sys.resource.settings.model.note"), SYS_RESOURCE_SETTINGS_MODEL_NOTE(161, "sys.resource.settings.base.model.note"),
SYS_RESOURCE_SETTINGS_OSS_ENDPOINT(162, "sys.resource.settings.oss.endpoint"), SYS_RESOURCE_SETTINGS_OSS_ENDPOINT(162, "sys.resource.settings.oss.endpoint"),
SYS_RESOURCE_SETTINGS_OSS_ENDPOINT_NOTE(163, "sys.resource.settings.oss.endpoint.note"), SYS_RESOURCE_SETTINGS_OSS_ENDPOINT_NOTE(163, "sys.resource.settings.oss.endpoint.note"),
SYS_RESOURCE_SETTINGS_OSS_ACCESSKEY(164, "sys.resource.settings.oss.accessKey"), SYS_RESOURCE_SETTINGS_OSS_ACCESSKEY(164, "sys.resource.settings.oss.accessKey"),
......
...@@ -150,7 +150,7 @@ alert.rule.jobRunException=Job Run Exception ...@@ -150,7 +150,7 @@ alert.rule.jobRunException=Job Run Exception
alert.rule.checkpointTimeout=Checkpoint Timeout alert.rule.checkpointTimeout=Checkpoint Timeout
daemon.task.config.not.exist=the thread task configuration can not be empty daemon.task.config.not.exist=the thread task configuration can not be empty
daemon.task.not.support=threaded task types are notsupported: daemon.task.not.support=threaded task types are notsupported
# system config # system config
...@@ -177,11 +177,11 @@ sys.dolphinscheduler.settings.enable.note=Whether to enable DolphinScheduler, th ...@@ -177,11 +177,11 @@ sys.dolphinscheduler.settings.enable.note=Whether to enable DolphinScheduler, th
sys.dolphinscheduler.settings.url=DolphinScheduler address sys.dolphinscheduler.settings.url=DolphinScheduler address
sys.dolphinscheduler.settings.url.note=The address must be consistent with the address configured in the DolphinScheduler background, eg: http://127.0.0.1:12345/dolphinscheduler sys.dolphinscheduler.settings.url.note=The address must be consistent with the address configured in the DolphinScheduler background, eg: http://127.0.0.1:12345/dolphinscheduler
sys.dolphinscheduler.settings.token=DolphinScheduler Token sys.dolphinscheduler.settings.token=DolphinScheduler Token
sys.dolphinscheduler.settings.token.note=DolphinScheduler‘s Token, please create a token in DolphinScheduler’s Security Center->Token Management, and fill in the configuration sys.dolphinscheduler.settings.token.note=DolphinScheduler's Token, please create a token in DolphinScheduler's Security Center->Token Management, and fill in the configuration
sys.dolphinscheduler.settings.projectName=DolphinScheduler project name sys.dolphinscheduler.settings.projectName=DolphinScheduler project name
sys.dolphinscheduler.settings.projectName.note=The project name specified in DolphinScheduler, case insensitive sys.dolphinscheduler.settings.projectName.note=The project name specified in DolphinScheduler, case insensitive
sys.ldap.settings.url=ldap address of service sys.ldap.settings.url=ldap address of service
sys.ldap.settings.url.note=ldap address of service,eg:ldap://192.168.111.1:389 sys.ldap.settings.url.note=ldap address of service, eg: ldap://192.168.111.1:389
sys.ldap.settings.userDn=Login User name (DN) sys.ldap.settings.userDn=Login User name (DN)
sys.ldap.settings.userDn.note=User name for connecting to the ldap service, or the administrator DN sys.ldap.settings.userDn.note=User name for connecting to the ldap service, or the administrator DN
sys.ldap.settings.userPassword=login password sys.ldap.settings.userPassword=login password
...@@ -189,9 +189,9 @@ sys.ldap.settings.userPassword.note=Password used to connect to the ldap service ...@@ -189,9 +189,9 @@ sys.ldap.settings.userPassword.note=Password used to connect to the ldap service
sys.ldap.settings.timeLimit=Connection Timeout sys.ldap.settings.timeLimit=Connection Timeout
sys.ldap.settings.timeLimit.note=The maximum time to connect to the ldap service is disconnected sys.ldap.settings.timeLimit.note=The maximum time to connect to the ldap service is disconnected
sys.ldap.settings.baseDn=BaseDn sys.ldap.settings.baseDn=BaseDn
sys.ldap.settings.baseDn.note=Dinky will conduct a user search on this base dn,eg:ou=users,dc=dinky,dc=com sys.ldap.settings.baseDn.note=Dinky will conduct a user search on this base dn,eg: ou=users,dc=dinky,dc=com
sys.ldap.settings.filter=User filtering rules sys.ldap.settings.filter=User filtering rules
sys.ldap.settings.filter.note=User filtering by using the filter syntax of the ldap,eg sys.ldap.settings.filter.note=User filtering by using the filter syntax of the ldap, eg
sys.ldap.settings.autoload=User atically map users when logging in sys.ldap.settings.autoload=User atically map users when logging in
sys.ldap.settings.autoload.note=When turned on, when a user logs in with LDAP, if there is no corresponding Dinky user mapping, the LDAP information is automatically pulled to create a Dinky user mapping to it. If this feature is closed, you will not be able to log in for unimported LDAP users sys.ldap.settings.autoload.note=When turned on, when a user logs in with LDAP, if there is no corresponding Dinky user mapping, the LDAP information is automatically pulled to create a Dinky user mapping to it. If this feature is closed, you will not be able to log in for unimported LDAP users
sys.ldap.settings.defaultTeant=The LDAP imports the default tenant code sys.ldap.settings.defaultTeant=The LDAP imports the default tenant code
...@@ -210,20 +210,20 @@ sys.metrics.settings.flink.gatherTiming=Flink Metrics collection time granularit ...@@ -210,20 +210,20 @@ sys.metrics.settings.flink.gatherTiming=Flink Metrics collection time granularit
sys.metrics.settings.flink.gatherTiming.note=Flink Metrics collection time granularity, scheduled task interval trigger sys.metrics.settings.flink.gatherTiming.note=Flink Metrics collection time granularity, scheduled task interval trigger
sys.metrics.settings.flink.gatherTimeout=Flink Metrics collection time granularity, scheduled task interval trigger sys.metrics.settings.flink.gatherTimeout=Flink Metrics collection time granularity, scheduled task interval trigger
sys.metrics.settings.flink.gatherTimeout.note=Flink Metrics collection timeout period, scheduled task interval trigger (this configuration item should be smaller than Flink Metrics collection time granularity) sys.metrics.settings.flink.gatherTimeout.note=Flink Metrics collection timeout period, scheduled task interval trigger (this configuration item should be smaller than Flink Metrics collection time granularity)
sys.resource.settings.enable=Whether to enable Resource sys.resource.settings.base.enable=Whether to enable Resource
sys.resource.settings.enable.note=Enable the resource management function. If you switch the storage mode, you need to turn off this switch. After the relevant configuration is completed, turn it on again. sys.resource.settings.base.enable.note=Enable resource management function. If you switch storage mode, you need to turn off this switch. After the relevant configuration is completed, turn it on again.
sys.resource.settings.upload.base.path=The root path of the upload directory sys.resource.settings.base.upload.base.path=Root path of the upload directory
sys.resource.settings.upload.base.path.note=resource store on HDFS/OSS path, resource file will store to this base path, self configuration, please make sure the directory exists on hdfs and have read write permissions. /dinky is recommended sys.resource.settings.base.upload.base.path.note=Resources are stored on the HDFS/OSS path. Resource files will be stored in this base path. Configure it by yourself. Please ensure that the directory exists on the relevant storage system and has read capabilities. Write permission. recommend
sys.resource.settings.model=Storage mode sys.resource.settings.base.model=Storage model
sys.resource.settings.model.note=Storage mode sys.resource.settings.base.model.note=Supports HDFS and OSS, it will take effect after switching the option, and resource files will be migrated at the same time.
sys.resource.settings.oss.endpoint=URL of the object storage service sys.resource.settings.oss.endpoint=URL of the object storage service
sys.resource.settings.oss.endpoint.note=The URL of the object storage service, for example: https://oss-cn-hangzhou.aliyuncs.com sys.resource.settings.oss.endpoint.note=For example: https://oss-cn-hangzhou.aliyuncs.com
sys.resource.settings.oss.accessKey=Access key is like a user ID, which can uniquely identify your account sys.resource.settings.oss.accessKey=Access key
sys.resource.settings.oss.accessKey.note=Access key is like a user ID, which can uniquely identify your account sys.resource.settings.oss.accessKey.note=Access key is like a user ID that uniquely identifies your account
sys.resource.settings.oss.secretKey=Secret key is your account password sys.resource.settings.oss.secretKey=Secret key
sys.resource.settings.oss.secretKey.note=Secret key is your account password sys.resource.settings.oss.secretKey.note=Secret key is the password of your account
sys.resource.settings.oss.bucketName=default bucket name sys.resource.settings.oss.bucketName=Bucket name
sys.resource.settings.oss.bucketName.note=default bucket name sys.resource.settings.oss.bucketName.note=Default bucket name
sys.resource.settings.oss.region=region sys.resource.settings.oss.region=region
sys.resource.settings.oss.region.note=region sys.resource.settings.oss.region.note=region
sys.resource.settings.hdfs.root.user=HDFS operation user name sys.resource.settings.hdfs.root.user=HDFS operation user name
...@@ -246,3 +246,8 @@ process.submit.execute = execute the job ...@@ -246,3 +246,8 @@ process.submit.execute = execute the job
process.submit.buildConfig=Build configuration information process.submit.buildConfig=Build configuration information
process.submit.execute.commSql=excute commonSql process.submit.execute.commSql=excute commonSql
process.submit.execute.flinkSql=excute flinkSql process.submit.execute.flinkSql=excute flinkSql
# resource
resource.root.dir.not.allow.delete=The root directory is not allowed to be deleted
resource.dir.or.file.not.exist=The directory or file does not exist
\ No newline at end of file
...@@ -208,19 +208,19 @@ sys.metrics.settings.flink.gatherTiming=Flink Metrics 采集时间粒度 ...@@ -208,19 +208,19 @@ sys.metrics.settings.flink.gatherTiming=Flink Metrics 采集时间粒度
sys.metrics.settings.flink.gatherTiming.note=Flink Metrics 采集时间粒度,定时任务间隔触发 sys.metrics.settings.flink.gatherTiming.note=Flink Metrics 采集时间粒度,定时任务间隔触发
sys.metrics.settings.flink.gatherTimeout=Flink Metrics 采集时间粒度,定时任务间隔触发 sys.metrics.settings.flink.gatherTimeout=Flink Metrics 采集时间粒度,定时任务间隔触发
sys.metrics.settings.flink.gatherTimeout.note=Flink Metrics 采集超时时长,定时任务间隔触发(此配置项应小于Flink Metrics 采集时间粒度) sys.metrics.settings.flink.gatherTimeout.note=Flink Metrics 采集超时时长,定时任务间隔触发(此配置项应小于Flink Metrics 采集时间粒度)
sys.resource.settings.enable=是否启用Resource sys.resource.settings.base.enable=是否启用Resource
sys.resource.settings.enable.note=启用资源管理功能,如果切换存储模式时,需关闭此开关,相关配置完成后,再开启 sys.resource.settings.base.enable.note=启用资源管理功能,如果切换存储模式时,需关闭此开关,相关配置完成后,再开启
sys.resource.settings.upload.base.path=上传目录的根路径 sys.resource.settings.base.upload.base.path=上传目录的根路径
sys.resource.settings.upload.base.path.note=资源存储在HDFS/OSS路径上,资源文件将存储到此基本路径,自行配置,请确保该目录存在于hdfs上并具有读写权限。推荐 sys.resource.settings.base.upload.base.path.note=资源存储在HDFS/OSS路径上,资源文件将存储到此基本路径,自行配置,请确保该目录存在于相关存储系统上并具有读写权限。推荐
sys.resource.settings.model=存储模式:支持HDFS、OSS sys.resource.settings.base.model=存储模式
sys.resource.settings.model.note=存储模式:支持HDFS、OSS,切换选项后即可生效,同时并迁移资源文件 sys.resource.settings.base.model.note=支持HDFS、OSS,切换选项后即可生效,同时并迁移资源文件
sys.resource.settings.oss.endpoint=对象存储服务的URL sys.resource.settings.oss.endpoint=对象存储服务的URL
sys.resource.settings.oss.endpoint.note=对象存储服务的URL,例如:https://oss-cn-hangzhou.aliyuncs.com sys.resource.settings.oss.endpoint.note=例如:https://oss-cn-hangzhou.aliyuncs.com
sys.resource.settings.oss.accessKey=Access key就像用户ID,可以唯一标识你的账户 sys.resource.settings.oss.accessKey=Access key
sys.resource.settings.oss.accessKey.note=Access key就像用户ID,可以唯一标识你的账户 sys.resource.settings.oss.accessKey.note=Access key就像用户ID,可以唯一标识你的账户
sys.resource.settings.oss.secretKey=Secret key是你账户的密码 sys.resource.settings.oss.secretKey=Secret key
sys.resource.settings.oss.secretKey.note=Secret key是你账户的密码 sys.resource.settings.oss.secretKey.note=Secret key是你账户的密码
sys.resource.settings.oss.bucketName=默认的存储桶名称 sys.resource.settings.oss.bucketName=存储桶名称
sys.resource.settings.oss.bucketName.note=默认的存储桶名称 sys.resource.settings.oss.bucketName.note=默认的存储桶名称
sys.resource.settings.oss.region=区域 sys.resource.settings.oss.region=区域
sys.resource.settings.oss.region.note=区域 sys.resource.settings.oss.region.note=区域
...@@ -244,3 +244,7 @@ process.submit.execute=执行作业 ...@@ -244,3 +244,7 @@ process.submit.execute=执行作业
process.submit.buildConfig=构建配置信息 process.submit.buildConfig=构建配置信息
process.submit.execute.commSql=执行普通sql process.submit.execute.commSql=执行普通sql
process.submit.execute.flinkSql=执行flinkSql process.submit.execute.flinkSql=执行flinkSql
# resource
resource.root.dir.not.allow.delete=根目录不允许删除
resource.dir.or.file.not.exist=资源目录或文件不存在
\ No newline at end of file
...@@ -152,6 +152,7 @@ export default { ...@@ -152,6 +152,7 @@ export default {
'global.table.lifecycle.publish': 'Publish', 'global.table.lifecycle.publish': 'Publish',
'global.table.lifecycle.stopped': 'Stopped', 'global.table.lifecycle.stopped': 'Stopped',
'global.table.lifecycle.online': 'Online', 'global.table.lifecycle.online': 'Online',
'global.table.lifecycle.offline': 'Offline',
'global.table.lifecycle.unknown': 'Unknown', 'global.table.lifecycle.unknown': 'Unknown',
'global.table.execmode': 'Execution mode', 'global.table.execmode': 'Execution mode',
'global.table.runmode': 'Run Mode', 'global.table.runmode': 'Run Mode',
......
...@@ -807,9 +807,17 @@ export default { ...@@ -807,9 +807,17 @@ export default {
'rc.gv.value': 'Value', 'rc.gv.value': 'Value',
'rc.gv.valuePlaceholder': 'Please enter the Global Variable value', 'rc.gv.valuePlaceholder': 'Please enter the Global Variable value',
'rc.resource.click': 'Click left file to view details', 'rc.resource.click': 'Click left file to view details',
'rc.resource.noResource': 'rc.resource.click.tip1':
'\t\tNo resources\nPlease Click the button above to upload folders/files', 'please make sure the resource configuration is correct, otherwise it will cause resource upload failure!',
'rc.resource.click.tip2':
'If the resource configuration of your configuration center does not configure the resource upload path or use the default resource upload path (/dinky)',
'rc.resource.click.tip3': 'You can click the link on the right to configure ->',
'rc.resource.upload': 'Upload Files/Folders', 'rc.resource.upload': 'Upload Files/Folders',
'rc.resource.upload.success': 'File [{fileName}] Upload successfully',
'rc.resource.upload.fail': 'File [{fileName}] Upload failed',
'rc.resource.upload.tip1': 'Click or drag file to this area to upload',
'rc.resource.upload.tip2':
'Support for a single or bulk upload. Strictly prohibited from uploading company data or\n other banned files.',
'rc.template.codeType': 'Code Type', 'rc.template.codeType': 'Code Type',
'rc.template.codeTypePlaceholder': 'Please select code type! ', 'rc.template.codeTypePlaceholder': 'Please select code type! ',
'rc.template.create': 'Create UDF Template', 'rc.template.create': 'Create UDF Template',
......
...@@ -148,6 +148,7 @@ export default { ...@@ -148,6 +148,7 @@ export default {
'global.table.lifecycle.publish': '已发布', 'global.table.lifecycle.publish': '已发布',
'global.table.lifecycle.stopped': '已停止', 'global.table.lifecycle.stopped': '已停止',
'global.table.lifecycle.online': '已上线', 'global.table.lifecycle.online': '已上线',
'global.table.lifecycle.offline': '已下线',
'global.table.lifecycle.unknown': '未知', 'global.table.lifecycle.unknown': '未知',
'global.table.execmode': '执行模式', 'global.table.execmode': '执行模式',
'global.table.execmode.batch': '批模式', 'global.table.execmode.batch': '批模式',
......
...@@ -775,8 +775,15 @@ export default { ...@@ -775,8 +775,15 @@ export default {
'rc.gv.value': '变量值', 'rc.gv.value': '变量值',
'rc.gv.valuePlaceholder': '请输入全局变量值', 'rc.gv.valuePlaceholder': '请输入全局变量值',
'rc.resource.click': '点击左侧文件查看详情', 'rc.resource.click': '点击左侧文件查看详情',
'rc.resource.noResource': '\t\t暂无资源\n请点击上方按钮上传文件夹/文件', 'rc.resource.click.tip1': '请确保资源配置正确,否则会导致资源上传失败!',
'rc.resource.click.tip2':
' 如果您的配置中心的资源配置没有配置资源上传路径/使用默认的资源上传路径(/dinky)',
'rc.resource.click.tip3': ' 您可以点击右侧链接进行配置 ->',
'rc.resource.upload': '上传文件夹/文件', 'rc.resource.upload': '上传文件夹/文件',
'rc.resource.upload.success': '文件 【{fileName}】 上传成功',
'rc.resource.upload.fail': '文件 【{fileName}】 上传失败',
'rc.resource.upload.tip1': '点击或拖拽文件到此区域上传',
'rc.resource.upload.tip2': '支持单个或批量上传。严禁上传公司数据或其他禁止上传的文件。',
'rc.template.codeType': '代码类型', 'rc.template.codeType': '代码类型',
'rc.template.codeTypePlaceholder': '请选择代码类型!', 'rc.template.codeTypePlaceholder': '请选择代码类型!',
'rc.template.create': '创建 UDF 模板', 'rc.template.create': '创建 UDF 模板',
......
...@@ -20,8 +20,11 @@ ...@@ -20,8 +20,11 @@
import CodeEdit from '@/components/CustomEditor/CodeEdit'; import CodeEdit from '@/components/CustomEditor/CodeEdit';
import { renderLanguage, unSupportView } from '@/utils/function'; import { renderLanguage, unSupportView } from '@/utils/function';
import { l } from '@/utils/intl'; import { l } from '@/utils/intl';
import { Empty } from 'antd'; import { Empty, Space, Typography } from 'antd';
import React from 'react'; import React from 'react';
import { NavLink } from 'react-router-dom';
const { Text } = Typography;
const CodeEditProps = { const CodeEditProps = {
height: '88vh', height: '88vh',
...@@ -60,10 +63,45 @@ const FileShow: React.FC<FileShowProps> = (props) => { ...@@ -60,10 +63,45 @@ const FileShow: React.FC<FileShowProps> = (props) => {
const renderContent = () => { const renderContent = () => {
if (name && unSupportView(name) && isLeaf) { if (name && unSupportView(name) && isLeaf) {
return ( return (
<Empty className={'code-content-empty'} description={l('rc.gp.codeTree.unSupportView')} /> <Empty
style={{ alignItems: 'center', justifyContent: 'center', top: '50%', height: '100%' }}
imageStyle={{
marginTop: '20vh'
}}
description={l('rc.gp.codeTree.unSupportView')}
/>
); );
} else if (code === '' || code === null || code === undefined) { } else if (code === '' || code === null || code === undefined) {
return <Empty className={'code-content-empty'} description={l('rc.resource.click')} />; return (
<>
<Empty
style={{ alignItems: 'center', justifyContent: 'center', top: '50%', height: '100%' }}
imageStyle={{
marginTop: '20vh'
}}
description={
<>
<Space direction={'vertical'}>
<Text type='success' strong>
{' '}
{l('rc.resource.click')}
</Text>
<Text type='danger' strong>
{l('rc.resource.click.tip1')}
</Text>
<Text mark ellipsis italic>
{l('rc.resource.click.tip2')}
</Text>
<Text mark ellipsis italic>
{l('rc.resource.click.tip3')}{' '}
<NavLink to={'/settings/globalsetting'}>{l('menu.settings')}</NavLink>
</Text>
</Space>
</>
}
/>
</>
);
} else { } else {
return <CodeEdit {...restCodeShowProps} {...CodeEditProps} />; return <CodeEdit {...restCodeShowProps} {...CodeEditProps} />;
} }
......
import { Resource } from '@/types/RegCenter/data'; import { ResourceInfo } from '@/types/RegCenter/data';
import { renderIcon } from '@/utils/function'; import { parseByteStr, renderIcon } from '@/utils/function';
import { l } from '@/utils/intl'; import { l } from '@/utils/intl';
const buildTitleLabel = (item: Resource) => { const buildTitleLabel = (item: ResourceInfo) => {
return ( return (
<> <>
{item.fileName} {item.fileName}
{!item.isDirectory && ( {!item.isDirectory && (
<span style={{ color: 'gray' }}> <span style={{ color: 'gray' }}>
{' '} {' '}
&nbsp;&nbsp;{l('global.size', '', { size: item.size })} &nbsp;&nbsp;{l('global.size', '', { size: parseByteStr(item.size) })}
</span> </span>
)} )}
</> </>
); );
}; };
export const buildResourceTreeData = (data: Resource[]): any => export const buildResourceTreeData = (data: ResourceInfo[]): any =>
data.map((item: Resource) => { data.map((item: ResourceInfo) => {
return { return {
isLeaf: !item.children, isLeaf: !item.isDirectory,
name: item.fileName, name: item.fileName,
parentId: item.pid, parentId: item.pid,
label: item.fullName + '/' + item.fileName, label: item.fullName + '/' + item.fileName,
icon: item.leaf && renderIcon(item.fileName, '.', item.leaf), icon: renderIcon(item.fileName, '.', item.isDirectory),
path: item.fullName, path: item.fullName,
title: buildTitleLabel(item), title: buildTitleLabel(item),
fullInfo: item, fullInfo: item,
key: item.id, key: item.id,
id: item.id, id: item.id,
children: buildResourceTreeData(item.children) children: item.children && buildResourceTreeData(item.children)
}; };
}); });
...@@ -18,48 +18,33 @@ ...@@ -18,48 +18,33 @@
*/ */
import { buildResourceTreeData } from '@/pages/RegCenter/Resource/components/FileTree/function'; import { buildResourceTreeData } from '@/pages/RegCenter/Resource/components/FileTree/function';
import { Resource } from '@/types/RegCenter/data'; import { ResourceInfo } from '@/types/RegCenter/data';
import { l } from '@/utils/intl'; import { Empty, Tree } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { Button, Tree, Typography, Upload } from 'antd';
import React from 'react'; import React from 'react';
const { DirectoryTree } = Tree; const { DirectoryTree } = Tree;
const { Text } = Typography;
type FileTreeProps = { type FileTreeProps = {
treeData: Resource[]; treeData: ResourceInfo[];
onNodeClick: (info: any) => void; onNodeClick: (info: any) => void;
onRightClick: (info: any) => void; onRightClick: (info: any) => void;
selectedKeys: string[]; selectedKeys: string[];
loadData: ({ key, children }: any) => Promise<void>;
}; };
const FileTree: React.FC<FileTreeProps> = (props) => { const FileTree: React.FC<FileTreeProps> = (props) => {
const { treeData, selectedKeys, onNodeClick, onRightClick, loadData } = props; const { treeData, selectedKeys, onNodeClick, onRightClick } = props;
return ( return (
<> <>
{treeData.length > 0 ? ( {treeData.length > 0 ? (
<DirectoryTree <DirectoryTree
loadData={loadData}
selectedKeys={selectedKeys} selectedKeys={selectedKeys}
onSelect={(_, info) => onNodeClick(info)} onSelect={(_, info) => onNodeClick(info)}
onRightClick={(info) => onRightClick(info)} onRightClick={(info) => onRightClick(info)}
treeData={buildResourceTreeData(treeData)} treeData={buildResourceTreeData(treeData)}
/> />
) : ( ) : (
<> <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
<div style={{ marginTop: '40vh', marginLeft: '1vw' }}>
<Upload action='/api/resource/uploadFile?pid=0' directory>
<Button icon={<UploadOutlined />}>{l('rc.resource.upload')}</Button>
</Upload>
<br />
</div>
<Text className={'needWrap'} type='warning'>
{l('rc.resource.noResource')}
</Text>
</>
)} )}
</> </>
); );
......
...@@ -26,9 +26,10 @@ import ResourceModal from '@/pages/RegCenter/Resource/components/ResourceModal'; ...@@ -26,9 +26,10 @@ import ResourceModal from '@/pages/RegCenter/Resource/components/ResourceModal';
import ResourcesUploadModal from '@/pages/RegCenter/Resource/components/ResourcesUploadModal'; import ResourcesUploadModal from '@/pages/RegCenter/Resource/components/ResourcesUploadModal';
import { handleOption, handleRemoveById, queryDataByParams } from '@/services/BusinessCrud'; import { handleOption, handleRemoveById, queryDataByParams } from '@/services/BusinessCrud';
import { API_CONSTANTS } from '@/services/endpoints'; import { API_CONSTANTS } from '@/services/endpoints';
import { Resource } from '@/types/RegCenter/data'; import { ResourceInfo } from '@/types/RegCenter/data';
import { InitResourceState } from '@/types/RegCenter/init.d'; import { InitResourceState } from '@/types/RegCenter/init.d';
import { ResourceState } from '@/types/RegCenter/state.d'; import { ResourceState } from '@/types/RegCenter/state.d';
import { l } from '@/utils/intl';
import { ProCard } from '@ant-design/pro-components'; import { ProCard } from '@ant-design/pro-components';
import { MenuInfo } from 'rc-menu/es/interface'; import { MenuInfo } from 'rc-menu/es/interface';
import { Resizable } from 're-resizable'; import { Resizable } from 're-resizable';
...@@ -45,37 +46,15 @@ const ResourceOverView: React.FC = () => { ...@@ -45,37 +46,15 @@ const ResourceOverView: React.FC = () => {
description: '' description: ''
}); });
const updateTreeData = (list: any[], key: React.Key, children: any[]): any[] =>
list.map((node) => {
if (node.path === key) {
return { ...node, children };
}
if (node.children) {
return {
...node,
children: updateTreeData(node.children, key, children)
};
}
return node;
});
const refreshTreeData = async (path: string) => {
const data = await queryDataByParams<Resource[]>(API_CONSTANTS.RESOURCE_SHOW_TREE);
setResourceState((prevState) => ({
...prevState,
treeData: updateTreeData(prevState.treeData, path, data ?? [])
}));
};
const refreshTree = async () => { const refreshTree = async () => {
await queryDataByParams<Resource[]>(API_CONSTANTS.RESOURCE_SHOW_TREE).then((res) => await queryDataByParams<ResourceInfo[]>(API_CONSTANTS.RESOURCE_SHOW_TREE).then((res) =>
setResourceState((prevState) => ({ ...prevState, treeData: res ?? [] })) setResourceState((prevState) => ({ ...prevState, treeData: res ?? [] }))
); );
}; };
useEffect(() => { useEffect(() => {
refreshTree(); refreshTree();
}, []); }, [resourceState]);
/** /**
* query content by id * query content by id
...@@ -107,20 +86,6 @@ const ResourceOverView: React.FC = () => { ...@@ -107,20 +86,6 @@ const ResourceOverView: React.FC = () => {
setResourceState((prevState) => ({ ...prevState, content: '' })); setResourceState((prevState) => ({ ...prevState, content: '' }));
} }
}; };
const getSelectedNode = () => {
const indexes = (resourceState.rightClickedNode.pos.split('-') as string[]).map((x) =>
parseInt(x)
);
if (indexes.length === 1) {
return resourceState.treeData[indexes[0]];
} else {
let temp = resourceState.treeData[indexes[0]];
for (let i = 1; i < indexes.length - 1; i++) {
temp = temp.children[indexes[i]];
}
return temp;
}
};
/** /**
* the node right click event OF upload, * the node right click event OF upload,
...@@ -141,30 +106,17 @@ const ResourceOverView: React.FC = () => { ...@@ -141,30 +106,17 @@ const ResourceOverView: React.FC = () => {
if (resourceState.rightClickedNode) { if (resourceState.rightClickedNode) {
uploadValue.pid = resourceState.rightClickedNode.id; uploadValue.pid = resourceState.rightClickedNode.id;
// todo: upload // todo: upload
setResourceState((prevState) => ({ ...prevState, uploadOpen: true })); setResourceState((prevState) => ({ ...prevState, uploadOpen: true, contextMenuOpen: false }));
} }
}; };
const getSelectedParentNode = () => {
const indexes = (resourceState.rightClickedNode.pos.split('-') as string[]).map((x) =>
parseInt(x)
);
let temp = resourceState.treeData[indexes[0]];
for (let i = 1; i < indexes.length - 2; i++) {
temp = temp.children[indexes[i]];
}
return { node: temp, index: indexes[indexes.length - 2] };
};
/** /**
* the node right click event OF delete, * the node right click event OF delete,
*/ */
const handleDelete = async () => { const handleDelete = async () => {
if (resourceState.rightClickedNode) { if (resourceState.rightClickedNode) {
setResourceState((prevState) => ({ ...prevState, contextMenuOpen: false }));
await handleRemoveById(API_CONSTANTS.RESOURCE_REMOVE, resourceState.rightClickedNode.id); await handleRemoveById(API_CONSTANTS.RESOURCE_REMOVE, resourceState.rightClickedNode.id);
// await refreshTree()
const { node, index } = getSelectedParentNode();
node.children.splice(index, 1);
} }
}; };
...@@ -183,12 +135,6 @@ const ResourceOverView: React.FC = () => { ...@@ -183,12 +135,6 @@ const ResourceOverView: React.FC = () => {
})); }));
} }
}; };
const handleRefresh = async () => {
if (resourceState.rightClickedNode) {
// const {id, name, desc, path} = rightClickedNode;
//todo refresh
}
};
const handleMenuClick = (node: MenuInfo) => { const handleMenuClick = (node: MenuInfo) => {
switch (node.key) { switch (node.key) {
...@@ -204,9 +150,6 @@ const ResourceOverView: React.FC = () => { ...@@ -204,9 +150,6 @@ const ResourceOverView: React.FC = () => {
case 'rename': case 'rename':
handleRename(); handleRename();
break; break;
case 'refresh':
handleRefresh();
break;
default: default:
break; break;
} }
...@@ -242,23 +185,16 @@ const ResourceOverView: React.FC = () => { ...@@ -242,23 +185,16 @@ const ResourceOverView: React.FC = () => {
/** /**
* the rename ok * the rename ok
*/ */
const handleModalSubmit = async (value: Partial<Resource>) => { const handleModalSubmit = async (value: Partial<ResourceInfo>) => {
const { id: pid } = resourceState.rightClickedNode;
if (editModal === 'createFolder') { if (editModal === 'createFolder') {
const d = ( await handleOption(API_CONSTANTS.RESOURCE_CREATE_FOLDER, l('right.menu.createFolder'), {
await handleOption(API_CONSTANTS.RESOURCE_CREATE_FOLDER, '创建文件夹', { ...value,
...value pid
}) });
).datas;
if (getSelectedNode().children) {
getSelectedNode().children.push(d);
} else {
getSelectedNode().children = [d];
}
setResourceState((prevState) => ({ ...prevState, editOpen: false })); setResourceState((prevState) => ({ ...prevState, editOpen: false }));
} else if (editModal === 'rename') { } else if (editModal === 'rename') {
await handleOption(API_CONSTANTS.RESOURCE_RENAME, '重命名', { ...value }); await handleOption(API_CONSTANTS.RESOURCE_RENAME, l('right.menu.rename'), { ...value, pid });
getSelectedNode().fileName = value.fileName;
getSelectedNode().name = value.fileName;
} }
}; };
const handleUploadCancel = () => { const handleUploadCancel = () => {
...@@ -274,13 +210,6 @@ const ResourceOverView: React.FC = () => { ...@@ -274,13 +210,6 @@ const ResourceOverView: React.FC = () => {
// todo: save content // todo: save content
}; };
const asyncLoadData = async ({ children, path, id }: any) => {
if (children.length > 0) {
return;
}
await refreshTreeData(path);
};
const access = useAccess(); const access = useAccess();
/** /**
...@@ -299,7 +228,6 @@ const ResourceOverView: React.FC = () => { ...@@ -299,7 +228,6 @@ const ResourceOverView: React.FC = () => {
> >
<ProCard ghost hoverable colSpan={'18%'} className={'siderTree schemaTree'}> <ProCard ghost hoverable colSpan={'18%'} className={'siderTree schemaTree'}>
<FileTree <FileTree
loadData={asyncLoadData}
selectedKeys={resourceState.selectedKeys} selectedKeys={resourceState.selectedKeys}
treeData={resourceState.treeData} treeData={resourceState.treeData}
onRightClick={handleRightClick} onRightClick={handleRightClick}
...@@ -320,7 +248,7 @@ const ResourceOverView: React.FC = () => { ...@@ -320,7 +248,7 @@ const ResourceOverView: React.FC = () => {
</ProCard> </ProCard>
</Resizable> </Resizable>
<ProCard.Divider type={'vertical'} /> <ProCard.Divider type={'vertical'} />
<ProCard ghost hoverable className={'schemaTree'}> <ProCard ghost hoverable className={'schemaTree'} bodyStyle={{ height: '100%' }}>
<FileShow <FileShow
onChange={handleContentChange} onChange={handleContentChange}
code={resourceState.content} code={resourceState.content}
...@@ -330,7 +258,13 @@ const ResourceOverView: React.FC = () => { ...@@ -330,7 +258,13 @@ const ResourceOverView: React.FC = () => {
</ProCard> </ProCard>
{resourceState.editOpen && ( {resourceState.editOpen && (
<ResourceModal <ResourceModal
title={editModal} title={
editModal === 'createFolder'
? l('right.menu.createFolder')
: editModal === 'rename'
? l('right.menu.rename')
: ''
}
formValues={resourceState.value} formValues={resourceState.value}
onOk={handleModalSubmit} onOk={handleModalSubmit}
onClose={handleModalCancel} onClose={handleModalCancel}
......
import { l } from '@/utils/intl';
import { ErrorMessageAsync, SuccessMessageAsync } from '@/utils/messages';
import { InboxOutlined } from '@ant-design/icons'; import { InboxOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd'; import type { UploadProps } from 'antd';
import { message, Modal, Upload } from 'antd'; import { Modal, Upload } from 'antd';
import React from 'react'; import React from 'react';
const { Dragger } = Upload; const { Dragger } = Upload;
...@@ -15,19 +17,22 @@ type ResourcesUploadModalProps = { ...@@ -15,19 +17,22 @@ type ResourcesUploadModalProps = {
const ResourcesUploadModal: React.FC<ResourcesUploadModalProps> = (props) => { const ResourcesUploadModal: React.FC<ResourcesUploadModalProps> = (props) => {
const { onUpload, onClose, onOk, visible } = props; const { onUpload, onClose, onOk, visible } = props;
const { url, pid, description } = onUpload; const { url, pid, description } = onUpload;
const uploadProps: UploadProps = { const uploadProps: UploadProps = {
name: 'file', name: 'file',
multiple: true, multiple: true,
action: url + '?pid=' + pid, action: url + '?pid=' + pid,
onChange(info) { onChange: async (info) => {
const { status } = info.file; const { status } = info.file;
if (status !== 'uploading') { if (status !== 'uploading') {
console.log(info.file, info.fileList); console.log(info.file, info.fileList);
} }
if (status === 'done') { if (status === 'done') {
message.success(`${info.file.name} file uploaded successfully.`); await SuccessMessageAsync(
l('rc.resource.upload.success', '', { fileName: info.file.name })
);
} else if (status === 'error') { } else if (status === 'error') {
message.error(`${info.file.name} file upload failed.`); await ErrorMessageAsync(l('rc.resource.upload.fail', '', { fileName: info.file.name }));
} }
}, },
onDrop(e) { onDrop(e) {
...@@ -35,16 +40,13 @@ const ResourcesUploadModal: React.FC<ResourcesUploadModalProps> = (props) => { ...@@ -35,16 +40,13 @@ const ResourcesUploadModal: React.FC<ResourcesUploadModalProps> = (props) => {
} }
}; };
return ( return (
<Modal title={'Upload File'} onOk={onOk} onCancel={onClose} open={visible}> <Modal title={l('rc.resource.upload')} onOk={onOk} onCancel={onClose} open={visible}>
<Dragger {...uploadProps}> <Dragger {...uploadProps}>
<p className='ant-upload-drag-icon'> <p className='ant-upload-drag-icon'>
<InboxOutlined /> <InboxOutlined />
</p> </p>
<p className='ant-upload-text'>Click or drag file to this area to upload</p> <p className='ant-upload-text'>{l('rc.resource.upload.tip1')}</p>
<p className='ant-upload-hint'> <p className='ant-upload-hint'>{l('rc.resource.upload.tip2')}</p>
Support for a single or bulk upload. Strictly prohibited from uploading company data or
other banned files.
</p>
</Dragger> </Dragger>
</Modal> </Modal>
); );
......
...@@ -22,7 +22,6 @@ import { ...@@ -22,7 +22,6 @@ import {
DeleteOutlined, DeleteOutlined,
EditOutlined, EditOutlined,
PlusCircleOutlined, PlusCircleOutlined,
UndoOutlined,
UploadOutlined UploadOutlined
} from '@ant-design/icons'; } from '@ant-design/icons';
...@@ -60,11 +59,5 @@ export const RIGHT_CONTEXT_MENU = (isDisabled = false) => [ ...@@ -60,11 +59,5 @@ export const RIGHT_CONTEXT_MENU = (isDisabled = false) => [
label: l('right.menu.rename'), label: l('right.menu.rename'),
disabled: isDisabled, disabled: isDisabled,
path: '/registration/resource/rename' path: '/registration/resource/rename'
},
{
key: 'refresh',
icon: <UndoOutlined />,
label: l('right.menu.refresh'),
disabled: isDisabled
} }
]; ];
...@@ -35,7 +35,7 @@ type GeneralConfigProps = { ...@@ -35,7 +35,7 @@ type GeneralConfigProps = {
onSave: (data: BaseConfigProperties) => void; onSave: (data: BaseConfigProperties) => void;
loading: boolean; loading: boolean;
toolBarRender?: any; toolBarRender?: any;
selectChanges?: Record<string, (value: RadioChangeEvent) => void>; selectChanges?: (e: RadioChangeEvent) => void;
}; };
const GeneralConfig: React.FC<GeneralConfigProps> = (props) => { const GeneralConfig: React.FC<GeneralConfigProps> = (props) => {
...@@ -95,16 +95,15 @@ const GeneralConfig: React.FC<GeneralConfigProps> = (props) => { ...@@ -95,16 +95,15 @@ const GeneralConfig: React.FC<GeneralConfigProps> = (props) => {
// @ts-ignore // @ts-ignore
return ( return (
<Radio.Group <Radio.Group
onChange={selectChanges ? selectChanges[entity.key] : undefined} onChange={selectChanges}
defaultValue={entity.value.toLowerCase()} value={entity.value.toLowerCase()}
// defaultValue={entity.value.toLowerCase()}
> >
{entity.example.map((item: any) => { {entity.example.map((item: any) => (
return (
<Radio.Button key={item} value={item.toLowerCase()}> <Radio.Button key={item} value={item.toLowerCase()}>
{item} {item}
</Radio.Button> </Radio.Button>
); ))}
})}
</Radio.Group> </Radio.Group>
); );
} else { } else {
......
...@@ -9,80 +9,63 @@ interface ResourcesConfigProps { ...@@ -9,80 +9,63 @@ interface ResourcesConfigProps {
onSave: (data: BaseConfigProperties) => void; onSave: (data: BaseConfigProperties) => void;
} }
type CacheEnum = { const ModelType = {
name: string; HDFS: 'HDFS',
configs: BaseConfigProperties[]; OSS: 'OSS'
};
type ResourceConfig = {
base: BaseConfigProperties[];
hdfs: BaseConfigProperties[];
oss: BaseConfigProperties[];
}; };
export const ResourcesConfig = ({ data, onSave }: ResourcesConfigProps) => { export const ResourcesConfig = ({ data, onSave }: ResourcesConfigProps) => {
const [loading, setLoading] = React.useState(false); const [loading, setLoading] = React.useState(false);
const [model, setModel] = React.useState('hdfs'); const [model, setModel] = React.useState('hdfs');
const [baseData, setBaseData] = React.useState(data); const [filterData, setFilterData] = useState<ResourceConfig>({
const [enumCache] = useState({ base: [],
base: [] as BaseConfigProperties[], hdfs: [],
hdfs: [] as BaseConfigProperties[], oss: []
oss: [] as BaseConfigProperties[]
}); });
const modelKey: string = 'sys.resource.settings.model';
useEffect(() => { useEffect(() => {
if (data.length < 1) { // 处理 data / 规则: 前缀为 sys.resource.settings.base 的为基础配置,其他的为 hdfs/oss 配置
return; const base: BaseConfigProperties[] = data.filter((d) =>
} d.key.startsWith('sys.resource.settings.base')
const needDeleteIndexes: number[] = []; );
let m; const hdfs: BaseConfigProperties[] = data.filter((d) =>
data.forEach((datum, index) => { d.key.startsWith('sys.resource.settings.hdfs')
if (datum.key === modelKey) { );
enumCache.base.push(datum); const oss: BaseConfigProperties[] = data.filter((d) =>
const modelCase = datum.value?.toLowerCase(); d.key.startsWith('sys.resource.settings.oss')
m = modelCase; );
setModel(modelCase); setFilterData({ base, hdfs, oss });
return; // 获取当前的 model
} const currentModel = base.find((d) => d.key === 'sys.resource.settings.base.model')?.value;
const v = datum.key.split('.').at(3); if (currentModel) {
if (v === 'hdfs' || v === 'oss') { setModel(currentModel);
// @ts-ignore
enumCache[v].push(datum);
needDeleteIndexes.push(index);
} else {
enumCache.base.push(datum);
} }
}); console.log('data', data, 'filterData', currentModel, 'currentModel');
const baseConfigProperties = data.filter((d, index) => !needDeleteIndexes.includes(index));
// @ts-ignore
enumCache[m].forEach((x) => {
baseConfigProperties.push(x);
});
setBaseData(baseConfigProperties);
}, [data]); }, [data]);
useEffect(() => {
const d: BaseConfigProperties[] = []; const modelKey: string = 'sys.resource.settings.base.model';
enumCache.base.forEach((x) => {
d.push(x);
});
console.log(enumCache);
// @ts-ignore
enumCache[model].forEach((x) => {
d.push(x);
});
setBaseData(d);
}, [model]);
const onSaveHandler = async (data: BaseConfigProperties) => { const onSaveHandler = async (data: BaseConfigProperties) => {
setLoading(true); setLoading(true);
await onSave(data); await onSave(data);
setLoading(false); setLoading(false);
}; };
const selectChange = async (value: RadioChangeEvent) => { const selectChange = async (e: RadioChangeEvent) => {
setModel(value.target.value); const { value } = e.target;
setModel(value);
await onSaveHandler({ await onSaveHandler({
name: '', name: '',
example: [], example: [],
frontType: '', frontType: '',
key: modelKey, key: modelKey,
note: '', note: '',
value: value.target.value.toLocaleUpperCase() value: value.toString().toLocaleUpperCase()
}); });
}; };
return ( return (
...@@ -91,9 +74,25 @@ export const ResourcesConfig = ({ data, onSave }: ResourcesConfigProps) => { ...@@ -91,9 +74,25 @@ export const ResourcesConfig = ({ data, onSave }: ResourcesConfigProps) => {
loading={loading} loading={loading}
onSave={onSaveHandler} onSave={onSaveHandler}
tag={<Tag color={'default'}>{l('sys.setting.tag.integration')}</Tag>} tag={<Tag color={'default'}>{l('sys.setting.tag.integration')}</Tag>}
data={baseData} data={filterData.base}
selectChanges={{ modelKey: selectChange }} selectChanges={selectChange}
/>
{model.toLocaleUpperCase() === ModelType.HDFS && (
<GeneralConfig
loading={loading}
onSave={onSaveHandler}
tag={<Tag color={'default'}>{l('sys.setting.tag.integration')}</Tag>}
data={filterData.hdfs}
/>
)}
{model.toLocaleUpperCase() === ModelType.OSS && (
<GeneralConfig
loading={loading}
onSave={onSaveHandler}
tag={<Tag color={'default'}>{l('sys.setting.tag.integration')}</Tag>}
data={filterData.oss}
/> />
)}
</> </>
); );
}; };
...@@ -221,7 +221,7 @@ export type UDFTemplate = BaseBeanColumns & { ...@@ -221,7 +221,7 @@ export type UDFTemplate = BaseBeanColumns & {
templateCode: string; templateCode: string;
}; };
interface Resource { export interface ResourceInfo {
id: number; id: number;
fileName: string; fileName: string;
description: string; description: string;
...@@ -233,6 +233,6 @@ interface Resource { ...@@ -233,6 +233,6 @@ interface Resource {
isDirectory: boolean; isDirectory: boolean;
createTime: string; createTime: string;
updateTime: string; updateTime: string;
children: Resource[]; children: ResourceInfo[];
leaf: boolean; leaf: boolean;
} }
...@@ -18,7 +18,6 @@ ...@@ -18,7 +18,6 @@
*/ */
import { BuildStepsState } from '@/pages/RegCenter/GitProject/data.d'; import { BuildStepsState } from '@/pages/RegCenter/GitProject/data.d';
import { Resource } from '@/pages/RegCenter/Resource/components/ResourceOverView';
import { BaseState, ContextMenuPosition } from '@/types/Public/state.d'; import { BaseState, ContextMenuPosition } from '@/types/Public/state.d';
import { import {
Alert, Alert,
...@@ -26,6 +25,7 @@ import { ...@@ -26,6 +25,7 @@ import {
Document, Document,
GitProject, GitProject,
GlobalVar, GlobalVar,
ResourceInfo,
UDFTemplate UDFTemplate
} from '@/types/RegCenter/data.d'; } from '@/types/RegCenter/data.d';
...@@ -110,7 +110,7 @@ export interface GlobalVarState extends BaseState { ...@@ -110,7 +110,7 @@ export interface GlobalVarState extends BaseState {
* resource state * resource state
*/ */
export interface ResourceState { export interface ResourceState {
treeData: Resource[]; treeData: ResourceInfo[];
content: string; content: string;
clickedNode: any; clickedNode: any;
rightClickedNode: any; rightClickedNode: any;
...@@ -119,7 +119,7 @@ export interface ResourceState { ...@@ -119,7 +119,7 @@ export interface ResourceState {
selectedKeys: string[]; selectedKeys: string[];
editOpen: boolean; editOpen: boolean;
uploadOpen: boolean; uploadOpen: boolean;
value: Partial<Resource>; value: Partial<ResourceInfo>;
} }
/** /**
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment