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 {
@ApiImplicitParam(name = "id", value = "Resource ID", required = true, dataType = "Integer", paramType = "query")
@SaCheckPermission(PermissionConstants.REGISTRATION_RESOURCE_DELETE)
public Result<Void> remove(Integer id) {
resourcesService.remove(id);
return Result.succeed();
return resourcesService.remove(id) ? Result.succeed() : Result.failed();
}
}
......@@ -45,6 +45,13 @@ public class ResourcesDTO implements Serializable {
notes = "The name of the resource file")
private String fileName;
@ApiModelProperty(
value = "Parent ID",
dataType = "Integer",
example = "1",
notes = "The unique identifier of the parent resource")
private Integer pid;
@ApiModelProperty(
value = "Description",
dataType = "String",
......
......@@ -19,6 +19,8 @@
package org.dinky.data.exception;
import org.dinky.data.enums.Status;
import cn.hutool.core.exceptions.ExceptionUtil;
import lombok.Getter;
import lombok.Setter;
......@@ -50,6 +52,12 @@ public class BusException extends RuntimeException {
setMsg(message);
}
public BusException(Status status) {
super(status.getMessage());
setCode(String.valueOf(status.getCode()));
setMsg(status.getMessage());
}
public BusException(String message, Object... args) {
super();
setCode(message);
......
......@@ -86,7 +86,7 @@ public interface ResourcesService extends IService<Resources> {
*/
void uploadFile(Integer pid, String desc, MultipartFile file);
void remove(Integer id);
boolean remove(Integer id);
/**
* 递归获取所有的资源,从pid到0
......
......@@ -20,6 +20,7 @@
package org.dinky.service.resource.impl;
import org.dinky.data.dto.TreeNodeDTO;
import org.dinky.data.enums.Status;
import org.dinky.data.exception.BusException;
import org.dinky.data.model.Resources;
import org.dinky.data.result.Result;
......@@ -203,27 +204,36 @@ public class ResourceServiceImpl extends ServiceImpl<ResourcesMapper, Resources>
@Transactional(rollbackFor = Exception.class)
@Override
public void remove(Integer id) {
if (id < 1) {
getBaseResourceManager().remove("/");
// todo 删除主目录,实际是清空
remove(new LambdaQueryWrapper<Resources>().ne(Resources::getId, 0));
return;
}
Resources byId = getById(id);
if (!isExistsChildren(id)) {
removeById(id);
return;
}
getBaseResourceManager().remove(byId.getFullName());
if (byId.getIsDirectory()) {
List<Resources> resourceByPidToChildren = getResourceByPidToChildren(new ArrayList<>(), byId.getId());
removeBatchByIds(resourceByPidToChildren);
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) {
getBaseResourceManager().remove("/");
// todo 删除主目录,实际是清空
remove(new LambdaQueryWrapper<Resources>().ne(Resources::getId, 0));
}
Resources byId = getById(id);
if (!isExistsChildren(id)) {
removeById(id);
}
getBaseResourceManager().remove(byId.getFullName());
if (byId.getIsDirectory()) {
List<Resources> resourceByPidToChildren = getResourceByPidToChildren(new ArrayList<>(), byId.getId());
removeBatchByIds(resourceByPidToChildren);
}
List<Resources> resourceByPidToParent = getResourceByPidToParent(new ArrayList<>(), byId.getPid());
resourceByPidToParent.forEach(x -> x.setSize(x.getSize() - byId.getSize()));
updateBatchById(resourceByPidToParent);
} catch (Exception e) {
throw new BusException(Status.DELETE_FAILED);
}
List<Resources> resourceByPidToParent = getResourceByPidToParent(new ArrayList<>(), byId.getPid());
resourceByPidToParent.forEach(x -> x.setSize(x.getSize() - byId.getSize()));
updateBatchById(resourceByPidToParent);
removeById(id);
return removeById(id);
}
private boolean isExistsChildren(Integer id) {
......
......@@ -77,7 +77,6 @@ public enum Status {
EXECUTE_FAILED(9020, "execute.failed"),
RESTART_SUCCESS(9021, "restart.success"),
RESTART_FAILED(9022, "restart.failed"),
// 已成功停止
STOP_SUCCESS(9023, "stop.success"),
STOP_FAILED(9024, "stop.failed"),
RENAME_SUCCESS(9025, "rename.success"),
......@@ -255,6 +254,12 @@ public enum Status {
ALERT_RULE_JOB_RUN_EXCEPTION(20005, "alert.rule.jobRunException"),
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
*/
......@@ -327,12 +332,12 @@ public enum Status {
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_NOTE(155, "sys.metrics.settings.flink.gatherTimeout.note"),
SYS_RESOURCE_SETTINGS_ENABLE(156, "sys.resource.settings.enable"),
SYS_RESOURCE_SETTINGS_ENABLE_NOTE(157, "sys.resource.settings.enable.note"),
SYS_RESOURCE_SETTINGS_UPLOAD_BASE_PATH(158, "sys.resource.settings.upload.base.path"),
SYS_RESOURCE_SETTINGS_UPLOAD_BASE_PATH_NOTE(159, "sys.resource.settings.upload.base.path.note"),
SYS_RESOURCE_SETTINGS_MODEL(160, "sys.resource.settings.model"),
SYS_RESOURCE_SETTINGS_MODEL_NOTE(161, "sys.resource.settings.model.note"),
SYS_RESOURCE_SETTINGS_ENABLE(156, "sys.resource.settings.base.enable"),
SYS_RESOURCE_SETTINGS_ENABLE_NOTE(157, "sys.resource.settings.base.enable.note"),
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.base.upload.base.path.note"),
SYS_RESOURCE_SETTINGS_MODEL(160, "sys.resource.settings.base.model"),
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_NOTE(163, "sys.resource.settings.oss.endpoint.note"),
SYS_RESOURCE_SETTINGS_OSS_ACCESSKEY(164, "sys.resource.settings.oss.accessKey"),
......
......@@ -111,7 +111,7 @@ datasource.not.exist=DataSource Not Exist
datasource.clear.cache.success=DataSource Clear Cache Success
tenant.admin.already.exists=Tenant Admin Already Exists, Only One Tenant Admin
ds.work.flow.definition.online=Workflow Definition [{}] Has Been Online
test.msg.job.url=Jump to the task
test.msg.job.url=Jump to the task
savepoint.is.null=Savepoint Is Null
git.sort.success=Git Sort Success
ds.add.task.definition.success=Add Task Definition Success
......@@ -150,7 +150,7 @@ alert.rule.jobRunException=Job Run Exception
alert.rule.checkpointTimeout=Checkpoint Timeout
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
......@@ -177,11 +177,11 @@ sys.dolphinscheduler.settings.enable.note=Whether to enable DolphinScheduler, th
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.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.note=The project name specified in DolphinScheduler, case insensitive
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.note=User name for connecting to the ldap service, or the administrator DN
sys.ldap.settings.userPassword=login password
......@@ -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.note=The maximum time to connect to the ldap service is disconnected
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.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.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
......@@ -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.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.resource.settings.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.upload.base.path=The 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.model=Storage mode
sys.resource.settings.model.note=Storage mode
sys.resource.settings.base.enable=Whether to enable Resource
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.base.upload.base.path=Root path of the upload directory
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.base.model=Storage model
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.note=The URL of the object storage service, 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.note=Access key is like a user ID, which can uniquely identify your account
sys.resource.settings.oss.secretKey=Secret key is your account password
sys.resource.settings.oss.secretKey.note=Secret key is your account password
sys.resource.settings.oss.bucketName=default bucket name
sys.resource.settings.oss.bucketName.note=default bucket name
sys.resource.settings.oss.endpoint.note=For example: https://oss-cn-hangzhou.aliyuncs.com
sys.resource.settings.oss.accessKey=Access key
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
sys.resource.settings.oss.secretKey.note=Secret key is the password of your account
sys.resource.settings.oss.bucketName=Bucket name
sys.resource.settings.oss.bucketName.note=Default bucket name
sys.resource.settings.oss.region=region
sys.resource.settings.oss.region.note=region
sys.resource.settings.hdfs.root.user=HDFS operation user name
......@@ -245,4 +245,9 @@ process.submit.checkSql=Check job
process.submit.execute = execute the job
process.submit.buildConfig=Build configuration information
process.submit.execute.commSql=excute commonSql
process.submit.execute.flinkSql=excute flinkSql
\ No newline at end of file
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 采集时间粒度
sys.metrics.settings.flink.gatherTiming.note=Flink Metrics 采集时间粒度,定时任务间隔触发
sys.metrics.settings.flink.gatherTimeout=Flink Metrics 采集时间粒度,定时任务间隔触发
sys.metrics.settings.flink.gatherTimeout.note=Flink Metrics 采集超时时长,定时任务间隔触发(此配置项应小于Flink Metrics 采集时间粒度)
sys.resource.settings.enable=是否启用Resource
sys.resource.settings.enable.note=启用资源管理功能,如果切换存储模式时,需关闭此开关,相关配置完成后,再开启
sys.resource.settings.upload.base.path=上传目录的根路径
sys.resource.settings.upload.base.path.note=资源存储在HDFS/OSS路径上,资源文件将存储到此基本路径,自行配置,请确保该目录存在于hdfs上并具有读写权限。推荐
sys.resource.settings.model=存储模式:支持HDFS、OSS
sys.resource.settings.model.note=存储模式:支持HDFS、OSS,切换选项后即可生效,同时并迁移资源文件
sys.resource.settings.base.enable=是否启用Resource
sys.resource.settings.base.enable.note=启用资源管理功能,如果切换存储模式时,需关闭此开关,相关配置完成后,再开启
sys.resource.settings.base.upload.base.path=上传目录的根路径
sys.resource.settings.base.upload.base.path.note=资源存储在HDFS/OSS路径上,资源文件将存储到此基本路径,自行配置,请确保该目录存在于相关存储系统上并具有读写权限。推荐
sys.resource.settings.base.model=存储模式
sys.resource.settings.base.model.note=支持HDFS、OSS,切换选项后即可生效,同时并迁移资源文件
sys.resource.settings.oss.endpoint=对象存储服务的URL
sys.resource.settings.oss.endpoint.note=对象存储服务的URL,例如:https://oss-cn-hangzhou.aliyuncs.com
sys.resource.settings.oss.accessKey=Access key就像用户ID,可以唯一标识你的账户
sys.resource.settings.oss.endpoint.note=例如:https://oss-cn-hangzhou.aliyuncs.com
sys.resource.settings.oss.accessKey=Access key
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.bucketName=默认的存储桶名称
sys.resource.settings.oss.bucketName=存储桶名称
sys.resource.settings.oss.bucketName.note=默认的存储桶名称
sys.resource.settings.oss.region=区域
sys.resource.settings.oss.region.note=区域
......@@ -243,4 +243,8 @@ process.submit.checkSql=检查作业
process.submit.execute=执行作业
process.submit.buildConfig=构建配置信息
process.submit.execute.commSql=执行普通sql
process.submit.execute.flinkSql=执行flinkSql
\ No newline at end of file
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 {
'global.table.lifecycle.publish': 'Publish',
'global.table.lifecycle.stopped': 'Stopped',
'global.table.lifecycle.online': 'Online',
'global.table.lifecycle.offline': 'Offline',
'global.table.lifecycle.unknown': 'Unknown',
'global.table.execmode': 'Execution mode',
'global.table.runmode': 'Run Mode',
......
......@@ -807,9 +807,17 @@ export default {
'rc.gv.value': 'Value',
'rc.gv.valuePlaceholder': 'Please enter the Global Variable value',
'rc.resource.click': 'Click left file to view details',
'rc.resource.noResource':
'\t\tNo resources\nPlease Click the button above to upload folders/files',
'rc.resource.click.tip1':
'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.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.codeTypePlaceholder': 'Please select code type! ',
'rc.template.create': 'Create UDF Template',
......
......@@ -148,6 +148,7 @@ export default {
'global.table.lifecycle.publish': '已发布',
'global.table.lifecycle.stopped': '已停止',
'global.table.lifecycle.online': '已上线',
'global.table.lifecycle.offline': '已下线',
'global.table.lifecycle.unknown': '未知',
'global.table.execmode': '执行模式',
'global.table.execmode.batch': '批模式',
......
......@@ -775,8 +775,15 @@ export default {
'rc.gv.value': '变量值',
'rc.gv.valuePlaceholder': '请输入全局变量值',
'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.success': '文件 【{fileName}】 上传成功',
'rc.resource.upload.fail': '文件 【{fileName}】 上传失败',
'rc.resource.upload.tip1': '点击或拖拽文件到此区域上传',
'rc.resource.upload.tip2': '支持单个或批量上传。严禁上传公司数据或其他禁止上传的文件。',
'rc.template.codeType': '代码类型',
'rc.template.codeTypePlaceholder': '请选择代码类型!',
'rc.template.create': '创建 UDF 模板',
......
......@@ -20,8 +20,11 @@
import CodeEdit from '@/components/CustomEditor/CodeEdit';
import { renderLanguage, unSupportView } from '@/utils/function';
import { l } from '@/utils/intl';
import { Empty } from 'antd';
import { Empty, Space, Typography } from 'antd';
import React from 'react';
import { NavLink } from 'react-router-dom';
const { Text } = Typography;
const CodeEditProps = {
height: '88vh',
......@@ -60,10 +63,45 @@ const FileShow: React.FC<FileShowProps> = (props) => {
const renderContent = () => {
if (name && unSupportView(name) && isLeaf) {
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) {
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 {
return <CodeEdit {...restCodeShowProps} {...CodeEditProps} />;
}
......
import { Resource } from '@/types/RegCenter/data';
import { renderIcon } from '@/utils/function';
import { ResourceInfo } from '@/types/RegCenter/data';
import { parseByteStr, renderIcon } from '@/utils/function';
import { l } from '@/utils/intl';
const buildTitleLabel = (item: Resource) => {
const buildTitleLabel = (item: ResourceInfo) => {
return (
<>
{item.fileName}
{!item.isDirectory && (
<span style={{ color: 'gray' }}>
{' '}
&nbsp;&nbsp;{l('global.size', '', { size: item.size })}
&nbsp;&nbsp;{l('global.size', '', { size: parseByteStr(item.size) })}
</span>
)}
</>
);
};
export const buildResourceTreeData = (data: Resource[]): any =>
data.map((item: Resource) => {
export const buildResourceTreeData = (data: ResourceInfo[]): any =>
data.map((item: ResourceInfo) => {
return {
isLeaf: !item.children,
isLeaf: !item.isDirectory,
name: item.fileName,
parentId: item.pid,
label: item.fullName + '/' + item.fileName,
icon: item.leaf && renderIcon(item.fileName, '.', item.leaf),
icon: renderIcon(item.fileName, '.', item.isDirectory),
path: item.fullName,
title: buildTitleLabel(item),
fullInfo: item,
key: item.id,
id: item.id,
children: buildResourceTreeData(item.children)
children: item.children && buildResourceTreeData(item.children)
};
});
......@@ -18,48 +18,33 @@
*/
import { buildResourceTreeData } from '@/pages/RegCenter/Resource/components/FileTree/function';
import { Resource } from '@/types/RegCenter/data';
import { l } from '@/utils/intl';
import { UploadOutlined } from '@ant-design/icons';
import { Button, Tree, Typography, Upload } from 'antd';
import { ResourceInfo } from '@/types/RegCenter/data';
import { Empty, Tree } from 'antd';
import React from 'react';
const { DirectoryTree } = Tree;
const { Text } = Typography;
type FileTreeProps = {
treeData: Resource[];
treeData: ResourceInfo[];
onNodeClick: (info: any) => void;
onRightClick: (info: any) => void;
selectedKeys: string[];
loadData: ({ key, children }: any) => Promise<void>;
};
const FileTree: React.FC<FileTreeProps> = (props) => {
const { treeData, selectedKeys, onNodeClick, onRightClick, loadData } = props;
const { treeData, selectedKeys, onNodeClick, onRightClick } = props;
return (
<>
{treeData.length > 0 ? (
<DirectoryTree
loadData={loadData}
selectedKeys={selectedKeys}
onSelect={(_, info) => onNodeClick(info)}
onRightClick={(info) => onRightClick(info)}
treeData={buildResourceTreeData(treeData)}
/>
) : (
<>
<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>
</>
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
)}
</>
);
......
......@@ -26,9 +26,10 @@ import ResourceModal from '@/pages/RegCenter/Resource/components/ResourceModal';
import ResourcesUploadModal from '@/pages/RegCenter/Resource/components/ResourcesUploadModal';
import { handleOption, handleRemoveById, queryDataByParams } from '@/services/BusinessCrud';
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 { ResourceState } from '@/types/RegCenter/state.d';
import { l } from '@/utils/intl';
import { ProCard } from '@ant-design/pro-components';
import { MenuInfo } from 'rc-menu/es/interface';
import { Resizable } from 're-resizable';
......@@ -45,37 +46,15 @@ const ResourceOverView: React.FC = () => {
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 () => {
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 ?? [] }))
);
};
useEffect(() => {
refreshTree();
}, []);
}, [resourceState]);
/**
* query content by id
......@@ -107,20 +86,6 @@ const ResourceOverView: React.FC = () => {
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,
......@@ -141,30 +106,17 @@ const ResourceOverView: React.FC = () => {
if (resourceState.rightClickedNode) {
uploadValue.pid = resourceState.rightClickedNode.id;
// 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,
*/
const handleDelete = async () => {
if (resourceState.rightClickedNode) {
setResourceState((prevState) => ({ ...prevState, contextMenuOpen: false }));
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 = () => {
}));
}
};
const handleRefresh = async () => {
if (resourceState.rightClickedNode) {
// const {id, name, desc, path} = rightClickedNode;
//todo refresh
}
};
const handleMenuClick = (node: MenuInfo) => {
switch (node.key) {
......@@ -204,9 +150,6 @@ const ResourceOverView: React.FC = () => {
case 'rename':
handleRename();
break;
case 'refresh':
handleRefresh();
break;
default:
break;
}
......@@ -242,23 +185,16 @@ const ResourceOverView: React.FC = () => {
/**
* the rename ok
*/
const handleModalSubmit = async (value: Partial<Resource>) => {
const handleModalSubmit = async (value: Partial<ResourceInfo>) => {
const { id: pid } = resourceState.rightClickedNode;
if (editModal === 'createFolder') {
const d = (
await handleOption(API_CONSTANTS.RESOURCE_CREATE_FOLDER, '创建文件夹', {
...value
})
).datas;
if (getSelectedNode().children) {
getSelectedNode().children.push(d);
} else {
getSelectedNode().children = [d];
}
await handleOption(API_CONSTANTS.RESOURCE_CREATE_FOLDER, l('right.menu.createFolder'), {
...value,
pid
});
setResourceState((prevState) => ({ ...prevState, editOpen: false }));
} else if (editModal === 'rename') {
await handleOption(API_CONSTANTS.RESOURCE_RENAME, '重命名', { ...value });
getSelectedNode().fileName = value.fileName;
getSelectedNode().name = value.fileName;
await handleOption(API_CONSTANTS.RESOURCE_RENAME, l('right.menu.rename'), { ...value, pid });
}
};
const handleUploadCancel = () => {
......@@ -274,13 +210,6 @@ const ResourceOverView: React.FC = () => {
// todo: save content
};
const asyncLoadData = async ({ children, path, id }: any) => {
if (children.length > 0) {
return;
}
await refreshTreeData(path);
};
const access = useAccess();
/**
......@@ -299,7 +228,6 @@ const ResourceOverView: React.FC = () => {
>
<ProCard ghost hoverable colSpan={'18%'} className={'siderTree schemaTree'}>
<FileTree
loadData={asyncLoadData}
selectedKeys={resourceState.selectedKeys}
treeData={resourceState.treeData}
onRightClick={handleRightClick}
......@@ -320,7 +248,7 @@ const ResourceOverView: React.FC = () => {
</ProCard>
</Resizable>
<ProCard.Divider type={'vertical'} />
<ProCard ghost hoverable className={'schemaTree'}>
<ProCard ghost hoverable className={'schemaTree'} bodyStyle={{ height: '100%' }}>
<FileShow
onChange={handleContentChange}
code={resourceState.content}
......@@ -330,7 +258,13 @@ const ResourceOverView: React.FC = () => {
</ProCard>
{resourceState.editOpen && (
<ResourceModal
title={editModal}
title={
editModal === 'createFolder'
? l('right.menu.createFolder')
: editModal === 'rename'
? l('right.menu.rename')
: ''
}
formValues={resourceState.value}
onOk={handleModalSubmit}
onClose={handleModalCancel}
......
import { l } from '@/utils/intl';
import { ErrorMessageAsync, SuccessMessageAsync } from '@/utils/messages';
import { InboxOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { message, Modal, Upload } from 'antd';
import { Modal, Upload } from 'antd';
import React from 'react';
const { Dragger } = Upload;
......@@ -15,19 +17,22 @@ type ResourcesUploadModalProps = {
const ResourcesUploadModal: React.FC<ResourcesUploadModalProps> = (props) => {
const { onUpload, onClose, onOk, visible } = props;
const { url, pid, description } = onUpload;
const uploadProps: UploadProps = {
name: 'file',
multiple: true,
action: url + '?pid=' + pid,
onChange(info) {
onChange: async (info) => {
const { status } = info.file;
if (status !== 'uploading') {
console.log(info.file, info.fileList);
}
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') {
message.error(`${info.file.name} file upload failed.`);
await ErrorMessageAsync(l('rc.resource.upload.fail', '', { fileName: info.file.name }));
}
},
onDrop(e) {
......@@ -35,16 +40,13 @@ const ResourcesUploadModal: React.FC<ResourcesUploadModalProps> = (props) => {
}
};
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}>
<p className='ant-upload-drag-icon'>
<InboxOutlined />
</p>
<p className='ant-upload-text'>Click or drag file to this area to upload</p>
<p className='ant-upload-hint'>
Support for a single or bulk upload. Strictly prohibited from uploading company data or
other banned files.
</p>
<p className='ant-upload-text'>{l('rc.resource.upload.tip1')}</p>
<p className='ant-upload-hint'>{l('rc.resource.upload.tip2')}</p>
</Dragger>
</Modal>
);
......
......@@ -22,7 +22,6 @@ import {
DeleteOutlined,
EditOutlined,
PlusCircleOutlined,
UndoOutlined,
UploadOutlined
} from '@ant-design/icons';
......@@ -60,11 +59,5 @@ export const RIGHT_CONTEXT_MENU = (isDisabled = false) => [
label: l('right.menu.rename'),
disabled: isDisabled,
path: '/registration/resource/rename'
},
{
key: 'refresh',
icon: <UndoOutlined />,
label: l('right.menu.refresh'),
disabled: isDisabled
}
];
......@@ -35,7 +35,7 @@ type GeneralConfigProps = {
onSave: (data: BaseConfigProperties) => void;
loading: boolean;
toolBarRender?: any;
selectChanges?: Record<string, (value: RadioChangeEvent) => void>;
selectChanges?: (e: RadioChangeEvent) => void;
};
const GeneralConfig: React.FC<GeneralConfigProps> = (props) => {
......@@ -95,16 +95,15 @@ const GeneralConfig: React.FC<GeneralConfigProps> = (props) => {
// @ts-ignore
return (
<Radio.Group
onChange={selectChanges ? selectChanges[entity.key] : undefined}
defaultValue={entity.value.toLowerCase()}
onChange={selectChanges}
value={entity.value.toLowerCase()}
// defaultValue={entity.value.toLowerCase()}
>
{entity.example.map((item: any) => {
return (
<Radio.Button key={item} value={item.toLowerCase()}>
{item}
</Radio.Button>
);
})}
{entity.example.map((item: any) => (
<Radio.Button key={item} value={item.toLowerCase()}>
{item}
</Radio.Button>
))}
</Radio.Group>
);
} else {
......
......@@ -9,80 +9,63 @@ interface ResourcesConfigProps {
onSave: (data: BaseConfigProperties) => void;
}
type CacheEnum = {
name: string;
configs: BaseConfigProperties[];
const ModelType = {
HDFS: 'HDFS',
OSS: 'OSS'
};
type ResourceConfig = {
base: BaseConfigProperties[];
hdfs: BaseConfigProperties[];
oss: BaseConfigProperties[];
};
export const ResourcesConfig = ({ data, onSave }: ResourcesConfigProps) => {
const [loading, setLoading] = React.useState(false);
const [model, setModel] = React.useState('hdfs');
const [baseData, setBaseData] = React.useState(data);
const [enumCache] = useState({
base: [] as BaseConfigProperties[],
hdfs: [] as BaseConfigProperties[],
oss: [] as BaseConfigProperties[]
const [filterData, setFilterData] = useState<ResourceConfig>({
base: [],
hdfs: [],
oss: []
});
const modelKey: string = 'sys.resource.settings.model';
useEffect(() => {
if (data.length < 1) {
return;
// 处理 data / 规则: 前缀为 sys.resource.settings.base 的为基础配置,其他的为 hdfs/oss 配置
const base: BaseConfigProperties[] = data.filter((d) =>
d.key.startsWith('sys.resource.settings.base')
);
const hdfs: BaseConfigProperties[] = data.filter((d) =>
d.key.startsWith('sys.resource.settings.hdfs')
);
const oss: BaseConfigProperties[] = data.filter((d) =>
d.key.startsWith('sys.resource.settings.oss')
);
setFilterData({ base, hdfs, oss });
// 获取当前的 model
const currentModel = base.find((d) => d.key === 'sys.resource.settings.base.model')?.value;
if (currentModel) {
setModel(currentModel);
}
const needDeleteIndexes: number[] = [];
let m;
data.forEach((datum, index) => {
if (datum.key === modelKey) {
enumCache.base.push(datum);
const modelCase = datum.value?.toLowerCase();
m = modelCase;
setModel(modelCase);
return;
}
const v = datum.key.split('.').at(3);
if (v === 'hdfs' || v === 'oss') {
// @ts-ignore
enumCache[v].push(datum);
needDeleteIndexes.push(index);
} else {
enumCache.base.push(datum);
}
});
const baseConfigProperties = data.filter((d, index) => !needDeleteIndexes.includes(index));
// @ts-ignore
enumCache[m].forEach((x) => {
baseConfigProperties.push(x);
});
setBaseData(baseConfigProperties);
console.log('data', data, 'filterData', currentModel, 'currentModel');
}, [data]);
useEffect(() => {
const d: BaseConfigProperties[] = [];
enumCache.base.forEach((x) => {
d.push(x);
});
console.log(enumCache);
// @ts-ignore
enumCache[model].forEach((x) => {
d.push(x);
});
setBaseData(d);
}, [model]);
const modelKey: string = 'sys.resource.settings.base.model';
const onSaveHandler = async (data: BaseConfigProperties) => {
setLoading(true);
await onSave(data);
setLoading(false);
};
const selectChange = async (value: RadioChangeEvent) => {
setModel(value.target.value);
const selectChange = async (e: RadioChangeEvent) => {
const { value } = e.target;
setModel(value);
await onSaveHandler({
name: '',
example: [],
frontType: '',
key: modelKey,
note: '',
value: value.target.value.toLocaleUpperCase()
value: value.toString().toLocaleUpperCase()
});
};
return (
......@@ -91,9 +74,25 @@ export const ResourcesConfig = ({ data, onSave }: ResourcesConfigProps) => {
loading={loading}
onSave={onSaveHandler}
tag={<Tag color={'default'}>{l('sys.setting.tag.integration')}</Tag>}
data={baseData}
selectChanges={{ modelKey: selectChange }}
data={filterData.base}
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 & {
templateCode: string;
};
interface Resource {
export interface ResourceInfo {
id: number;
fileName: string;
description: string;
......@@ -233,6 +233,6 @@ interface Resource {
isDirectory: boolean;
createTime: string;
updateTime: string;
children: Resource[];
children: ResourceInfo[];
leaf: boolean;
}
......@@ -18,7 +18,6 @@
*/
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 {
Alert,
......@@ -26,6 +25,7 @@ import {
Document,
GitProject,
GlobalVar,
ResourceInfo,
UDFTemplate
} from '@/types/RegCenter/data.d';
......@@ -110,7 +110,7 @@ export interface GlobalVarState extends BaseState {
* resource state
*/
export interface ResourceState {
treeData: Resource[];
treeData: ResourceInfo[];
content: string;
clickedNode: any;
rightClickedNode: any;
......@@ -119,7 +119,7 @@ export interface ResourceState {
selectedKeys: string[];
editOpen: 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