1
0

22 Commits

Author SHA1 Message Date
7e962884b1 feat(web): 适配flowable 2024-12-26 00:00:11 +08:00
6dccb0ecad feat(web): 重构工单流程 2024-12-25 18:38:00 +08:00
b774806e58 feat(web): 优化代码分层 2024-12-24 18:18:11 +08:00
bb9f87dbd2 fix(web):优化代码格式
- 修改了 visibleOn 属性的字符串格式,统一使用双引号
- 移除了不必要的反引号,简化了字符串表达式
2024-12-24 14:53:54 +08:00
381c23e94c feat(web): 增加标签展示 2024-12-24 10:07:57 +08:00
30b991cc28 feat(web): 优化页面元素变化 2024-12-23 18:18:01 +08:00
fbb0ce5da3 feat(frontend): 优化打包模式识别 2024-12-20 17:25:25 +08:00
5a0c44ff35 feat(frontend): 优化登陆页面样式 2024-12-20 17:25:25 +08:00
615edb57b8 feat(frontend): 优化页面样式,更现代化 2024-12-20 16:48:59 +08:00
74b0638a07 feat(frontend): 优化数据产品展示和详情查看功能
- 在 constants.js 中更新了信息结构,使用空值合并运算符提高代码健壮性
- 在 main.js 中添加了样式文件导入,提升页面视觉效果
- 在 tab-market.js 中增加了数据产品详情对话框,丰富了产品信息展示内容
2024-12-19 19:03:36 +08:00
91e30fefe4 fix(web): 修正停止脚本中的进程查找命令
- 将 'ps ef' 修改为 'ps -ef',以确保在所有用户进程中查找
- 优化了进程查找逻辑,提高了脚本的准确性和可靠性
2024-12-19 17:25:46 +08:00
d80659ca41 feat(web): 添加应用启动和停止脚本
- 修改 start.sh 脚本,使用 nohup 启动应用并将输出重定向到 run.log
- 新增 stop.sh 脚本,实现应用的平滑停止
2024-12-19 17:19:28 +08:00
997fc4043f fix(web): 更新管理员初始密码
- 将管理员用户的初始密码从 "administrator" 更改为复杂的加密字符串
- 此修改提高了系统的初始安全性,防止使用默认密码访问
2024-12-19 17:19:13 +08:00
0892cda203 fix(web): 优化逻辑删除 2024-12-19 17:06:48 +08:00
981f84ea2b feat(web): 修改删除按钮的禁用逻辑 2024-12-19 10:48:08 +08:00
49caded436 refactor(web): 重构逻辑删除的做法,避免真删除,在业务层解决逻辑删除 2024-12-19 10:44:41 +08:00
43e9306017 refactor(web): 将权限对话框按类型拆分为独立文件- 将 dialog-permission.js拆分为 dialog-confirmation.js 和 dialog-authentication.js
- 更新 resourceList 函数以支持 showMode 参数
- 调整 tab-data.js 和 tab-market.js 以适应新的对话框结构
2024-12-18 16:26:36 +08:00
39e4e03437 feat(web): 更新数据库配置并添加新环境配置
- 新增 dev 和 build 环境配置
- 更新 macOS 环境配置- 添加 MySQL 和 H2 数据库配置
2024-12-18 16:26:15 +08:00
7319335b67 refactor(web): 调整首页 tabs 顺序
- 将 tabData()从倒数第二个位置移动到第二个位置
- 优化了 tabs 的排列顺序,提高了用户体验
2024-12-18 15:04:18 +08:00
3cf56adeac refactor(web): 优化资源对话框布局
- 将 fieldSet 组件替换为 wrapper 组件,以改善布局结构
- 为 wrapper 组件添加 size 属性,设置为 none,以适应不同资源类型的布局需求- 此修改涉及 API、FILE、DATABASE、HDFS 和 FTP资源类型的输入框布局
2024-12-18 15:04:02 +08:00
083a8771d2 feat(web): 更新数据源配置并迁移数据库
- 修改 .idea/dataSources.xml 中的数据源配置,更新为新的 MySQL 数据源
- 更新 DataResourceController 中的属性名称,以适应新的数据库结构
- 修改 CsvResourceFormat、JsonLineResourceFormat 和 JsonResourceFormat 类中的属性名称
- 更新 application.yml 中的数据库配置,使用新的 MySQL 数据源
- 在 pom.xml 中添加 MySQL 连接器依赖,以支持新的数据库
2024-12-18 12:26:06 +08:00
cedb108049 style(web): 优化代码缩进 2024-12-18 11:20:35 +08:00
108 changed files with 5151 additions and 4865 deletions

7
.gitignore vendored
View File

@@ -1,6 +1,3 @@
### Custom
*.db
### Maven template
target/
pom.xml.tag
@@ -255,3 +252,7 @@ Network Trash Folder
Temporary Items
.apdisk
### Custom
*.db
gringotts-web/src/main/resources/static
!gringotts-web/bin

4
.idea/dataSources.xml generated
View File

@@ -13,11 +13,11 @@
</jdbc-additional-properties>
<working-dir>$ProjectFileDir$</working-dir>
</data-source>
<data-source source="LOCAL" name="homeless" uuid="9af017b2-2a8b-45b4-899c-ef4fb185b77c">
<data-source source="LOCAL" name="gringotts@132.122.1.185" uuid="91feafc5-32a2-4c28-93a7-b39754851328">
<driver-ref>mysql.8</driver-ref>
<synchronize>true</synchronize>
<jdbc-driver>com.mysql.cj.jdbc.Driver</jdbc-driver>
<jdbc-url>jdbc:mysql://frp-air.top:43458</jdbc-url>
<jdbc-url>jdbc:mysql://132.122.1.185:31000/gringotts</jdbc-url>
<jdbc-additional-properties>
<property name="com.intellij.clouds.kubernetes.db.host.port" />
<property name="com.intellij.clouds.kubernetes.db.enabled" value="false" />

View File

@@ -1,6 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://repo.maven.apache.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="mavenCentral" />
<option name="name" value="mavenCentral" />

View File

@@ -1,91 +1,90 @@
export const information = {
debug: false,
// baseUrl: '',
baseUrl: 'http://127.0.0.1:20080',
title: '可信供给中心',
debug: import.meta.env.DEV,
baseUrl: import.meta.env.DEV ? 'http://127.0.0.1:20080' : '',
title: '可信供给中心',
}
export function useAmis(amisObject) {
document.title = information.title
let amis = amisRequire('amis/embed')
let struct = amisObject(information)
if (information.debug) {
console.log(struct)
document.title = information.title
let amis = amisRequire('amis/embed')
let struct = amisObject(information)
if (information.debug) {
console.log(struct)
}
amis.embed(
'#app',
struct,
{
data: {
debug: information.debug,
base: information.baseUrl,
},
},
{
theme: 'antd',
enableAMISDebug: information.debug,
}
amis.embed(
'#app',
struct,
{
data: {
debug: information.debug,
base: information.baseUrl,
},
},
{
theme: 'antd',
enableAMISDebug: information.debug,
}
)
)
}
export function crudCommonOptions() {
return {
affixHeader: false,
stopAutoRefreshWhenModalIsOpen: true,
resizable: false,
syncLocation: false,
silentPolling: true,
}
return {
affixHeader: false,
stopAutoRefreshWhenModalIsOpen: true,
resizable: false,
syncLocation: false,
silentPolling: true,
}
}
export function readOnlyDialogOptions() {
return {
actions: [],
showCloseButton: false,
closeOnEsc: true,
closeOnOutside: true,
disabled: true,
}
return {
actions: [],
showCloseButton: false,
closeOnEsc: true,
closeOnOutside: true,
disabled: true,
}
}
export function horizontalFormOptions() {
return {
mode: 'horizontal',
canAccessSuperData: false,
horizontal: {
left: 3,
},
}
return {
mode: 'horizontal',
canAccessSuperData: false,
horizontal: {
left: 3,
},
}
}
export function paginationCommonOptions(perPage = true, maxButtons = 5) {
let option = {
type: 'pagination',
layout: [
'pager'
],
maxButtons: maxButtons,
showPageInput: false,
perPageAvailable: [10, 15, 20, 50, 100, 200],
}
if (perPage) {
option.layout.push('perPage')
}
return option
let option = {
type: 'pagination',
layout: [
'pager'
],
maxButtons: maxButtons,
showPageInput: false,
perPageAvailable: [10, 15, 20, 50, 100, 200],
}
if (perPage) {
option.layout.push('perPage')
}
return option
}
export function paginationTemplate(perPage = 20, maxButtons = 5) {
return {
perPage: perPage,
headerToolbar: [
"reload",
paginationCommonOptions(true, maxButtons),
],
footerToolbar: [
"statistics",
paginationCommonOptions(true, maxButtons),
],
}
return {
perPage: perPage,
headerToolbar: [
"reload",
paginationCommonOptions(true, maxButtons),
],
footerToolbar: [
"statistics",
paginationCommonOptions(true, maxButtons),
],
}
}
export const size5MB = 5242880
@@ -94,16 +93,16 @@ export const size500MB = 524288000
export const size1GB = 1073741824
export function inputFileFormItemCommonOptions(accept = '*', maxSize = size5MB) {
return {
useChunk: true,
accept: accept,
maxSize: maxSize,
autoUpload: false,
drag: true,
startChunkApi: apiPost('${base}/upload/start'),
chunkApi: apiPost('${base}/upload/slice'),
finishChunkApi: apiPost('${base}/upload/finish'),
}
return {
useChunk: true,
accept: accept,
maxSize: maxSize,
autoUpload: false,
drag: true,
startChunkApi: apiPost('${base}/upload/start'),
chunkApi: apiPost('${base}/upload/slice'),
finishChunkApi: apiPost('${base}/upload/finish'),
}
}
/**
@@ -114,41 +113,41 @@ export function inputFileFormItemCommonOptions(accept = '*', maxSize = size5MB)
* @param {{}} extra
*/
export function copyField(field, label, tips = '复制', ignoreLength = 0, extra = undefined) {
let tpl = ignoreLength === 0 ? `\${${field}}` : `\${TRUNCATE(${field}, ${ignoreLength})}`
let content = extra
? {
type: 'action',
level: 'link',
label: `\${${field}}`,
className: 'text-current underline',
size: 'xs',
...extra,
}
: {
type: 'tpl',
className: 'mr-1',
tpl: tpl,
}
return {
name: field,
label: label,
type: 'wrapper',
size: 'none',
className: 'nowrap',
body: [
content,
{
type: 'action',
level: 'link',
label: '',
icon: 'fa fa-copy',
size: 'xs',
actionType: 'copy',
content: `\$${field}`,
tooltip: `${tips}`,
},
]
let tpl = ignoreLength === 0 ? `\${${field}}` : `\${TRUNCATE(${field}, ${ignoreLength})}`
let content = extra
? {
type: 'action',
level: 'link',
label: `\${${field}}`,
className: 'text-current underline',
size: 'xs',
...extra,
}
: {
type: 'tpl',
className: 'mr-1',
tpl: tpl,
}
return {
name: field,
label: label,
type: 'wrapper',
size: 'none',
className: 'nowrap',
body: [
content,
{
type: 'action',
level: 'link',
label: '',
icon: 'fa fa-copy',
size: 'xs',
actionType: 'copy',
content: `\$${field}`,
tooltip: `${tips}`,
},
]
}
}
/**
@@ -157,14 +156,14 @@ export function copyField(field, label, tips = '复制', ignoreLength = 0, extra
* @param {Array} buttons
*/
export function operationField(label, width = 100, buttons = []) {
return {
label: label,
width: width,
type: 'operation',
fixed: 'right',
className: 'nowrap',
buttons: buttons,
}
return {
label: label,
width: width,
type: 'operation',
fixed: 'right',
className: 'nowrap',
buttons: buttons,
}
}
/**
@@ -173,17 +172,17 @@ export function operationField(label, width = 100, buttons = []) {
* @param {number} width
*/
export function timeField(field, label, width = 150) {
return {
label: label,
width: width,
align: 'center',
type: 'tpl',
tpl: `\${IF(${field}, DATETOSTR(${field}), '-')}`
}
return {
label: label,
width: width,
align: 'center',
type: 'tpl',
tpl: `\${IF(${field}, DATETOSTR(${field}), '-')}`
}
}
export function stringWrapField(field, label, width = undefined) {
return stringField(field, label, width, true)
return stringField(field, label, width, true)
}
/**
@@ -193,17 +192,17 @@ export function stringWrapField(field, label, width = undefined) {
* @param {boolean} wrap
*/
export function stringField(field, label, width = undefined, wrap = false) {
let data = {
name: field,
label: label,
}
if (width) {
data['width'] = width
}
if (!wrap) {
data['className'] = 'nowrap'
}
return data
let data = {
name: field,
label: label,
}
if (width) {
data['width'] = width
}
if (!wrap) {
data['className'] = 'nowrap'
}
return data
}
/**
@@ -213,107 +212,107 @@ export function stringField(field, label, width = undefined, wrap = false) {
* @param {number} width
*/
export function mappingField(field, label, mapping, width = 80) {
let mapData = {
'*': `<span class='label bg-gray-300'>\${${field}}</span>`,
}
mapping.forEach(item => {
mapData[item['value']] = `<span class='label ${item['color']}'>${item['label']}</span>`
})
return {
label: label,
type: 'mapping',
width: width,
value: `\${${field}}`,
align: 'center',
map: mapData,
}
let mapData = {
'*': `<span class='label bg-gray-300'>\${${field}}</span>`,
}
mapping.forEach(item => {
mapData[item['value']] = `<span class='label ${item['color']}'>${item['label']}</span>`
})
return {
label: label,
type: 'mapping',
width: width,
value: `\${${field}}`,
align: 'center',
map: mapData,
}
}
function mappingItem(label, value, color = 'bg-info') {
return {
label: label,
value: value,
color: color,
}
return {
label: label,
value: value,
color: color,
}
}
export const userRoleMapping = [
mappingItem('数据提供方', 'PROVIDER', 'bg-blue-500'),
mappingItem('数据使用方', 'CUSTOMER', 'bg-purple-500'),
mappingItem('审核监管方', 'CHECKER', 'bg-cyan-500'),
mappingItem('系统管理员', 'ADMINISTRATOR', 'bg-green-500'),
mappingItem('数据提供方', 'PROVIDER', 'bg-blue-500'),
mappingItem('数据使用方', 'CUSTOMER', 'bg-purple-500'),
mappingItem('审核监管方', 'CHECKER', 'bg-cyan-500'),
mappingItem('系统管理员', 'ADMINISTRATOR', 'bg-green-500'),
]
export const userStateMapping = [
mappingItem('审查中', 'CHECKING', 'bg-warning'),
mappingItem('正常', 'NORMAL', 'bg-success'),
mappingItem('禁用', 'DISABLED', 'bg-danger'),
mappingItem('审查中', 'CHECKING', 'bg-warning'),
mappingItem('正常', 'NORMAL', 'bg-success'),
mappingItem('禁用', 'DISABLED', 'bg-danger'),
]
export const permissionStateMapping = [
mappingItem('未确权', 'NONE'),
mappingItem('草稿', 'DRAFT', 'bg-primary'),
mappingItem('审查中', 'CHECKING', 'bg-warning'),
mappingItem('用户审查中', 'OWNER_CHECKING', 'bg-warning'),
mappingItem('通过', 'NORMAL', 'bg-success'),
mappingItem('驳回', 'REJECT', 'bg-danger'),
mappingItem('未确权', 'NONE'),
mappingItem('草稿', 'DRAFT', 'bg-primary'),
mappingItem('审查中', 'CHECKING', 'bg-warning'),
mappingItem('用户审查中', 'OWNER_CHECKING', 'bg-warning'),
mappingItem('通过', 'NORMAL', 'bg-success'),
mappingItem('驳回', 'REJECT', 'bg-danger'),
]
export const checkTypeMapping = [
mappingItem('确权审查', 'CONFIRMATION', 'bg-blue-500'),
mappingItem('授权审查', 'AUTHENTICATION', 'bg-purple-500'),
mappingItem('上架审查', 'MARKET', 'bg-green-500'),
mappingItem('确权审查', 'CONFIRMATION', 'bg-blue-500'),
mappingItem('授权审查', 'AUTHENTICATION', 'bg-purple-500'),
mappingItem('上架审查', 'MARKET', 'bg-green-500'),
]
export const checkOverMapping = [
mappingItem('进行中', 'CHECKING', 'bg-warning'),
mappingItem('已撤销', 'RETRACT', 'bg-primary'),
mappingItem('已办结', 'OVER', 'bg-success'),
mappingItem('进行中', 'CHECKING', 'bg-warning'),
mappingItem('已撤销', 'RETRACT', 'bg-primary'),
mappingItem('已办结', 'OVER', 'bg-success'),
]
function api(method, url) {
return {
method: method,
url: url,
headers: {
token: '${token|default:undefined}',
}
return {
method: method,
url: url,
headers: {
token: '${token|default:undefined}',
}
}
}
export function apiGet(url) {
return api('get', url)
return api('get', url)
}
export function apiPost(url) {
return api('post', url)
return api('post', url)
}
export function arrayInCheck(array, field) {
return `\${ARRAYINCLUDES(['${array.join("','")}'], ${field})}`
return `\${ARRAYINCLUDES(['${array.join("','")}'], ${field})}`
}
export function arrayOutCheck(array, field) {
return `\${!ARRAYINCLUDES(['${array.join("','")}'], ${field})}`
return `\${!ARRAYINCLUDES(['${array.join("','")}'], ${field})}`
}
export const checkState = {
none: 'NONE',
draft: 'DRAFT',
checking: 'CHECKING',
ownerChecking: 'OWNER_CHECKING',
normal: 'NORMAL',
none: 'NONE',
draft: 'DRAFT',
checking: 'CHECKING',
ownerChecking: 'OWNER_CHECKING',
normal: 'NORMAL',
}
export function roleCheck(roles) {
return `\${ARRAYINCLUDES(['${roles.join("','")}'], role)}`
return `\${ARRAYINCLUDES(['${roles.join("','")}'], role)}`
}
export const role = {
administrator: 'ADMINISTRATOR',
checker: 'CHECKER',
provider: 'PROVIDER',
customer: 'CUSTOMER',
administrator: 'ADMINISTRATOR',
checker: 'CHECKER',
provider: 'PROVIDER',
customer: 'CUSTOMER',
}
export const administratorOnly = roleCheck([role.administrator])
@@ -324,98 +323,98 @@ export const customerOnly = roleCheck([role.administrator, role.customer])
export const formInputClearable = {
clearable: true,
clearValueOnEmpty: true,
clearable: true,
clearValueOnEmpty: true,
}
const formInputFileStaticColumns = [
{
name: 'filename',
label: '文件名',
},
{
type: 'operation',
label: '操作',
width: 140,
buttons: [
{
type: 'action',
label: '预览',
level: 'link',
icon: 'fas fa-eye'
},
{
type: 'action',
label: '下载',
level: 'link',
icon: 'fa fa-download',
actionType: 'ajax',
api: {
...apiGet('${base}/upload/download/${id}'),
responseType: 'blob',
}
}
]
}
{
name: 'filename',
label: '文件名',
},
{
type: 'operation',
label: '操作',
width: 140,
buttons: [
{
type: 'action',
label: '预览',
level: 'link',
icon: 'fas fa-eye'
},
{
type: 'action',
label: '下载',
level: 'link',
icon: 'fa fa-download',
actionType: 'ajax',
api: {
...apiGet('${base}/upload/download/${id}'),
responseType: 'blob',
}
}
]
}
]
export function formInputSingleFileStatic(field, label) {
return {
visibleOn: '${detail}',
type: 'control',
label: label,
required: true,
body: {
type: 'table',
source: `\${${field}|asArray}`,
columns: formInputFileStaticColumns,
}
return {
visibleOn: '${detail}',
type: 'control',
label: label,
required: true,
body: {
type: 'table',
source: `\${${field}|asArray}`,
columns: formInputFileStaticColumns,
}
}
}
export function formInputMultiFileStatic(field, label) {
return {
visibleOn: '${detail}',
type: 'input-table',
label: label,
name: field,
required: true,
resizable: false,
columns: formInputFileStaticColumns,
}
return {
visibleOn: '${detail}',
type: 'input-table',
label: label,
name: field,
required: true,
resizable: false,
columns: formInputFileStaticColumns,
}
}
export function formCreatedUserAndModifiedUser() {
return [
return [
{
type: 'group',
body: [
{
type: 'group',
body: [
{
type: 'input-text',
name: 'createdUsername',
label: '创建人',
},
{
type: 'input-datetime',
name: 'createdTime',
label: '创建时间',
},
]
type: 'input-text',
name: 'createdUsername',
label: '创建人',
},
{
type: 'group',
body: [
{
type: 'input-text',
name: 'modifiedUsername',
label: '最后修改人',
},
{
type: 'input-datetime',
name: 'modifiedTime',
label: '最后修改时间',
},
]
type: 'input-datetime',
name: 'createdTime',
label: '创建时间',
},
]
]
},
{
type: 'group',
body: [
{
type: 'input-text',
name: 'modifiedUsername',
label: '最后修改人',
},
{
type: 'input-datetime',
name: 'modifiedTime',
label: '最后修改时间',
},
]
},
]
}

View File

@@ -0,0 +1,167 @@
import './dialog-permission.css'
import {
apiGet,
apiPost,
formCreatedUserAndModifiedUser,
formInputClearable,
formInputMultiFileStatic,
horizontalFormOptions,
information,
inputFileFormItemCommonOptions,
size100MB
} from "../constants.js";
import {resourceList} from "../../pages/index/tab-data.js";
import {resourceDetailDialog} from "../resource/dialog-resource.js";
function detailForm(showCreatedUserAndModifiedUser = false) {
return {
debug: information.debug,
id: 'permission_form',
type: 'form',
...horizontalFormOptions(),
horizontal: {
left: 2,
},
body: [
{
type: 'hidden',
name: 'id',
},
{
type: 'picker',
name: 'targetId',
label: '数据资源',
required: true,
multiple: false,
size: 'md',
valueField: 'id',
labelField: 'name',
source: apiGet('${base}/data_resource/list_no_authentication'),
pickerSchema: {
...resourceList(),
},
staticSchema: {
type: 'tpl',
tpl: "<span class='text-primary' style='cursor: pointer'>${targetName}</span>",
onEvent: {
click: {
actions: [
{
actionType: 'dialog',
...resourceDetailDialog('targetId'),
}
]
}
}
}
},
{
type: 'textarea',
placeholder: '请输入确权说明',
label: '确权说明',
name: 'description',
...formInputClearable,
},
formInputMultiFileStatic('evidenceFiles', '相关材料'),
{
visibleOn: '${!detail}',
type: 'input-file',
label: '相关材料',
name: 'evidenceFiles',
multiple: true,
required: true,
joinValues: false,
...inputFileFormItemCommonOptions(undefined, size100MB),
},
{
type: 'input-datetime-range',
name: 'activeTime',
extraName: 'expiredTime',
label: '授权时间',
required: true,
format: 'YYYY-MM-DD HH:mm:ss',
shortcuts: [
'7dayslater',
'14dayslater',
'30dayslater',
'180dayslater',
'365dayslater',
]
},
...(showCreatedUserAndModifiedUser ? formCreatedUserAndModifiedUser() : [])
]
}
}
export function authenticationAddDialog() {
let data = {add: true, authentication: true}
return {
actionType: 'dialog',
dialog: {
title: '新增授权申请',
size: 'md',
actions: [
{
type: 'reset',
label: '重置',
},
{
type: 'submit',
label: '确定',
level: 'primary',
}
],
body: {
...detailForm(),
api: apiPost(`\${base}/authentication/save`),
data: data,
}
}
}
}
export function authenticationDetailDialog(field = 'id', actions = []) {
let data = {detail: true, authentication: true}
return {
actionType: 'dialog',
dialog: {
title: '授权申请详情',
size: 'md',
actions: actions,
body: {
...detailForm(true),
initApi: apiGet(`\${base}/authentication/detail/\${${field}}`),
static: true,
data: data,
}
}
}
}
export function authenticationEditeDialog(field = 'id') {
let data = {edit: true, authentication: true}
return {
actionType: 'dialog',
dialog: {
title: '授权申请详情',
size: 'md',
actions: [
{
type: 'reset',
label: '重置',
},
{
type: 'submit',
label: '确定',
level: 'primary',
}
],
body: {
...detailForm(),
api: apiPost(`\${base}/authentication/save`),
initApi: apiGet(`\${base}/authentication/detail/\${${field}}`),
data: data,
},
}
}
}

View File

@@ -0,0 +1,152 @@
import './dialog-permission.css'
import {
apiGet,
apiPost,
formCreatedUserAndModifiedUser,
formInputClearable,
formInputMultiFileStatic,
horizontalFormOptions,
information,
inputFileFormItemCommonOptions,
size100MB
} from "../constants.js";
import {resourceList} from "../../pages/index/tab-data.js";
import {resourceDetailDialog} from "../resource/dialog-resource.js";
function detailForm(showCreatedUserAndModifiedUser = false) {
return {
debug: information.debug,
id: 'permission_form',
type: 'form',
...horizontalFormOptions(),
horizontal: {
left: 2,
},
body: [
{
type: 'hidden',
name: 'id',
},
{
type: 'picker',
name: 'targetId',
label: '数据资源',
required: true,
multiple: false,
size: 'md',
valueField: 'id',
labelField: 'name',
source: apiGet('${base}/data_resource/list_no_confirmation'),
pickerSchema: {
...resourceList(true),
},
staticSchema: {
type: 'tpl',
tpl: "<span class='text-primary' style='cursor: pointer'>${targetName}</span>",
onEvent: {
click: {
actions: [
{
actionType: 'dialog',
...resourceDetailDialog('targetId'),
}
]
}
}
}
},
{
type: 'textarea',
placeholder: '请输入确权说明',
label: '确权说明',
name: 'description',
...formInputClearable,
},
formInputMultiFileStatic('evidenceFiles', '相关材料'),
{
visibleOn: '${!detail}',
type: 'input-file',
label: '相关材料',
name: 'evidenceFiles',
multiple: true,
required: true,
joinValues: false,
...inputFileFormItemCommonOptions(undefined, size100MB),
},
...(showCreatedUserAndModifiedUser ? formCreatedUserAndModifiedUser() : [])
]
}
}
export function confirmationAddDialog() {
let data = {add: true, confirmation: true}
return {
actionType: 'dialog',
dialog: {
title: '新增确权申请',
size: 'md',
actions: [
{
type: 'reset',
label: '重置',
},
{
type: 'submit',
label: '确定',
level: 'primary',
}
],
body: {
...detailForm(),
api: apiPost(`\${base}/confirmation/save`),
data: data,
}
}
}
}
export function confirmationDetailDialog(field = 'id', actions = []) {
let data = {detail: true, confirmation: true}
return {
actionType: 'dialog',
dialog: {
title: '确权申请详情',
size: 'md',
actions: actions,
body: {
...detailForm(true),
initApi: apiGet(`\${base}/confirmation/detail/\${${field}}`),
static: true,
data: data,
}
}
}
}
export function confirmationEditeDialog(field = 'id') {
let data = {edit: true, confirmation: true}
return {
actionType: 'dialog',
dialog: {
title: '确权申请详情',
size: 'md',
actions: [
{
type: 'reset',
label: '重置',
},
{
type: 'submit',
label: '确定',
level: 'primary',
}
],
body: {
...detailForm(),
api: apiPost(`\${base}/confirmation/save`),
initApi: apiGet(`\${base}/confirmation/detail/\${${field}}`),
data: data,
},
}
}
}

View File

@@ -1,208 +1,2 @@
import './dialog-permission.css'
import {
apiGet,
apiPost,
formCreatedUserAndModifiedUser,
formInputClearable,
formInputMultiFileStatic,
horizontalFormOptions,
information,
inputFileFormItemCommonOptions,
size100MB
} from "../constants.js";
import {resourceList} from "../../pages/index/tab-data.js";
import {resourceDetailDialog} from "../resource/dialog-resource.js";
const CONFIRMATION_TYPE = 'confirmation'
const AUTHENTICATION_TYPE = 'authentication'
const CONFIRMATION = {
type: 'confirmation',
pickerApi: apiGet('${base}/data_resource/list_no_confirmation')
}
const AUTHENTICATION = {
type: 'authentication',
pickerApi: apiGet('${base}/data_resource/list_no_authentication')
}
function detailForm(pickerApi = apiGet('${base}/data_resource/list'), showCreatedUserAndModifiedUser = false) {
return {
debug: information.debug,
id: 'permission_form',
type: 'form',
...horizontalFormOptions(),
horizontal: {
left: 2,
},
body: [
{
type: 'hidden',
name: 'id',
},
{
type: 'picker',
name: 'targetId',
label: '数据资源',
required: true,
multiple: false,
size: 'md',
valueField: 'id',
labelField: 'name',
source: pickerApi,
pickerSchema: {
...resourceList(),
},
staticSchema: {
type: 'tpl',
tpl: "<span class='text-primary' style='cursor: pointer'>${targetName}</span>",
onEvent: {
click: {
actions: [
{
actionType: 'dialog',
...resourceDetailDialog('targetId'),
}
]
}
}
}
},
{
type: 'textarea',
placeholder: '请输入确权说明',
label: '确权说明',
name: 'description',
...formInputClearable,
},
formInputMultiFileStatic('evidenceFiles', '相关材料'),
{
visibleOn: '${!detail}',
type: 'input-file',
label: '相关材料',
name: 'evidenceFiles',
multiple: true,
required: true,
joinValues: false,
...inputFileFormItemCommonOptions(undefined, size100MB),
},
{
visibleOn: `\${${AUTHENTICATION_TYPE}}`,
type: 'input-datetime-range',
name: 'activeTime',
extraName: 'expiredTime',
label: '授权时间',
required: true,
format: 'YYYY-MM-DD HH:mm:ss',
shortcuts: [
'7dayslater',
'14dayslater',
'30dayslater',
'180dayslater',
'365dayslater',
]
},
...(showCreatedUserAndModifiedUser ? formCreatedUserAndModifiedUser() : [])
]
}
}
export function confirmationAddDialog() {
return permissionAddDialog(CONFIRMATION)
}
export function authenticationAddDialog() {
return permissionAddDialog(AUTHENTICATION)
}
function permissionAddDialog(config) {
let data = {add: true}
data[config.type] = true
return {
actionType: 'dialog',
dialog: {
title: '新增确权申请',
size: 'md',
actions: [
{
type: 'reset',
label: '重置',
},
{
type: 'submit',
label: '确定',
level: 'primary',
}
],
body: {
...detailForm(config.pickerApi),
api: apiPost(`\${base}/${config.type}/save`),
data: data,
}
}
}
}
export function confirmationDetailDialog(field = 'id', actions = []) {
return permissionDetailDialog(CONFIRMATION, field, actions)
}
export function authenticationDetailDialog(field = 'id', actions = []) {
return permissionDetailDialog(AUTHENTICATION, field, actions)
}
function permissionDetailDialog(config, field = 'id', actions = []) {
let data = {detail: true}
data[config.type] = true
return {
actionType: 'dialog',
dialog: {
title: '确权申请详情',
size: 'md',
actions: actions,
body: {
...detailForm(config.pickerApi, true),
initApi: apiGet(`\${base}/${config.type}/detail/\${${field}}`),
static: true,
data: data,
}
}
}
}
export function confirmationEditeDialog(field = 'id') {
return permissionEditeDialog(CONFIRMATION, field)
}
export function authenticationEditeDialog(field = 'id') {
return permissionEditeDialog(AUTHENTICATION, field)
}
function permissionEditeDialog(config, field = 'id') {
let data = {edit: true}
data[config.type] = true
return {
actionType: 'dialog',
dialog: {
title: '确权申请详情',
size: 'md',
actions: [
{
type: 'reset',
label: '重置',
},
{
type: 'submit',
label: '确定',
level: 'primary',
}
],
body: {
...detailForm(config.pickerApi),
api: apiPost(`\${base}/${config.type}/save`),
initApi: apiGet(`\${base}/${config.type}/detail/\${${field}}`),
data: data,
},
}
}
}
export * from './dialog-confirmation'
export * from './dialog-authentication'

View File

@@ -1,378 +1,383 @@
import './dialog-resource.css'
import {
apiGet,
apiPost,
formCreatedUserAndModifiedUser,
formInputClearable,
formInputSingleFileStatic,
horizontalFormOptions,
inputFileFormItemCommonOptions,
size1GB,
size500MB
apiGet,
apiPost,
formCreatedUserAndModifiedUser,
formInputClearable,
formInputSingleFileStatic,
horizontalFormOptions,
inputFileFormItemCommonOptions,
size1GB,
size500MB
} from "../constants.js";
function detailForm(showCreatedUserAndModifiedUser = false) {
return {
type: 'form',
...horizontalFormOptions(),
horizontal: {
left: 2,
},
return {
type: 'form',
...horizontalFormOptions(),
horizontal: {
left: 2,
},
body: [
{
type: 'hidden',
name: 'id',
},
{
type: 'input-text',
name: 'name',
label: '资源名称',
maxLength: 10,
showCounter: true,
required: true,
...formInputClearable,
},
{
type: 'textarea',
name: 'description',
label: '资源描述',
...formInputClearable,
showCounter: true,
trimContents: true,
minRows: 2,
maxRows: 2,
},
{
type: 'fieldSet',
title: '资源类型定义',
body: [
{
type: 'hidden',
name: 'id',
},
{
{
name: 'resourceType',
type: 'select',
label: '资源类型',
selectFirst: true,
required: true,
options: [
{label: 'API', value: 'API'},
{label: '文件', value: 'FILE'},
{label: '数据库', value: 'DATABASE'},
{label: 'HDFS', value: 'HDFS'},
{label: 'FTP', value: 'FTP'},
]
},
{
visibleOn: "${resourceType === 'API'}",
type: 'wrapper',
size: 'none',
body: [
{
type: 'input-text',
name: 'name',
label: '资源名称',
maxLength: 10,
showCounter: true,
label: 'API地址',
name: 'apiUrl',
required: true,
...formInputClearable,
},
{
type: 'textarea',
name: 'description',
label: '资源描述',
},
{
type: 'input-text',
label: '用户名',
name: 'apiUsername',
...formInputClearable,
showCounter: true,
trimContents: true,
minRows: 2,
maxRows: 2,
},
{
type: 'fieldSet',
title: '资源类型定义',
body: [
{
name: 'resourceType',
type: 'select',
label: '资源类型',
selectFirst: true,
required: true,
options: [
{label: 'API', value: 'API'},
{label: '文件', value: 'FILE'},
{label: '数据库', value: 'DATABASE'},
{label: 'HDFS', value: 'HDFS'},
{label: 'FTP', value: 'FTP'},
]
},
{
visibleOn: "${resourceType === 'API'}",
type: 'fieldSet',
body: [
{
type: 'input-text',
label: 'API地址',
name: 'apiUrl',
required: true,
...formInputClearable,
},
{
type: 'input-text',
label: '用户名',
name: 'apiUsername',
...formInputClearable,
},
{
type: 'input-password',
label: '密码',
name: 'apiPassword',
...formInputClearable,
},
]
},
{
visibleOn: "${resourceType === 'FILE'}",
type: 'fieldSet',
body: [
formInputSingleFileStatic('file', '数据文件'),
{
visibleOn: "${!detail}",
type: 'input-file',
label: '数据文件',
description: '只适合小于1GB的资源文件使用大文件请使用其他资源类型',
name: 'file',
multiple: false,
required: true,
joinValues: false,
...inputFileFormItemCommonOptions('.zip', size1GB),
},
]
},
{
visibleOn: "${resourceType === 'DATABASE'}",
type: 'fieldSet',
body: [
{
type: 'select',
label: '数据库类型',
name: 'databaseType',
required: true,
options: [
{label: 'MySQL', value: 'MYSQL'},
{label: 'Oracle', value: 'ORACLE'},
{label: 'PostgreSQL', value: 'POSTGRESQL'},
]
},
{
type: 'input-text',
label: 'JDBC',
name: 'databaseJdbc',
required: true,
...formInputClearable,
},
{
type: 'input-text',
label: '用户名',
name: 'databaseUsername',
...formInputClearable,
},
{
type: 'input-password',
label: '密码',
name: 'databasePassword',
...formInputClearable,
},
]
},
{
visibleOn: "${resourceType === 'HDFS'}",
type: 'fieldSet',
body: [
formInputSingleFileStatic('coreSiteFile', 'core-site.xml'),
{
visibleOn: "${!detail}",
type: 'input-file',
label: 'core-site.xml',
name: 'coreSiteFile',
multiple: false,
required: true,
joinValues: false,
...inputFileFormItemCommonOptions('.xml'),
},
formInputSingleFileStatic('hdfsSiteFile', 'hdfs-site.xml'),
{
visibleOn: "${!detail}",
type: 'input-file',
label: 'hdfs-site.xml',
name: 'hdfsSiteFile',
multiple: false,
required: true,
joinValues: false,
...inputFileFormItemCommonOptions('.xml'),
},
]
},
{
visibleOn: "${resourceType === 'FTP'}",
type: 'fieldSet',
body: [
{
type: 'input-text',
label: 'FTP地址',
name: 'ftpUrl',
required: true,
...formInputClearable,
},
{
type: 'input-text',
label: 'FTP账号',
name: 'ftpUsername',
...formInputClearable,
},
{
type: 'input-password',
label: 'FTP密码',
name: 'ftpPassword',
...formInputClearable,
},
{
type: 'input-text',
label: '相对路径',
name: 'ftpPath',
description: '若为空,则使用用户根目录',
...formInputClearable,
},
{
type: 'input-text',
label: '文件筛选',
name: 'ftpRegexFilter',
description: '正则表达式,用于匹配文件的路径,只有符合筛选条件的文件才会被采集;若为空则默认采集全部文件',
...formInputClearable,
},
]
},
},
{
type: 'input-password',
label: '密码',
name: 'apiPassword',
...formInputClearable,
},
]
},
{
visibleOn: "${resourceType === 'FILE'}",
type: 'wrapper',
size: 'none',
body: [
formInputSingleFileStatic('file', '数据文件'),
{
visibleOn: "${!detail}",
type: 'input-file',
label: '数据文件',
description: '只适合小于1GB的资源文件使用大文件请使用其他资源类型',
name: 'file',
multiple: false,
required: true,
joinValues: false,
...inputFileFormItemCommonOptions('.zip', size1GB),
},
]
},
{
visibleOn: "${resourceType === 'DATABASE'}",
type: 'wrapper',
size: 'none',
body: [
{
type: 'select',
label: '数据库类型',
name: 'databaseType',
required: true,
options: [
{label: 'MySQL', value: 'MYSQL'},
{label: 'Oracle', value: 'ORACLE'},
{label: 'PostgreSQL', value: 'POSTGRESQL'},
]
},
{
type: 'fieldSet',
title: '资源格式定义',
className: 'mt-5',
body: [
{
name: 'formatType',
type: 'select',
label: '资源格式',
selectFirst: true,
required: true,
options: [
{label: '无', value: 'NONE'},
{label: 'Line', value: 'LINE'},
{label: 'JSON', value: 'JSON'},
{label: 'JSON Line', value: 'JSON_LINE'},
{label: 'CSV', value: 'CSV'},
]
},
{
visibleOn: "${formatType === 'JSON' && !detail}",
type: 'json-schema-editor',
name: 'jsonSchema',
label: 'JSON格式',
description: '使用JSON Schema格式',
required: true,
enableAdvancedSetting: true,
mini: true,
},
{
visibleOn: "${formatType === 'JSON' && detail}",
type: 'editor',
name: 'jsonSchemaText',
label: 'JSON格式',
language: 'json',
},
{
visibleOn: "${formatType === 'JSON_LINE' && !detail}",
type: 'json-schema-editor',
name: 'jsonLineSchema',
label: 'JSON格式',
description: 'JSON Line类型请定义单行JSON数据格式使用JSON Schema格式',
required: true,
enableAdvancedSetting: true,
mini: true,
},
{
visibleOn: "${formatType === 'JSON_LINE' && detail}",
type: 'editor',
name: 'jsonLineSchemaText',
label: 'JSON格式',
language: 'json',
},
{
visibleOn: "${formatType === 'CSV' && !detail}",
type: 'json-schema-editor',
name: 'csvSchema',
label: 'CSV格式',
description: '请定义单行数据中各个字段的格式使用JSON Schema格式',
required: true,
enableAdvancedSetting: true,
mini: true,
disabledTypes: [
'object',
'array',
'null',
]
},
{
visibleOn: "${formatType === 'CSV' && detail}",
type: 'editor',
name: 'csvSchemaText',
label: 'JSON格式',
language: 'json',
},
formInputSingleFileStatic('exampleFile', '资源示例'),
{
visibleOn: "${!detail}",
type: 'input-file',
label: '资源示例',
name: 'exampleFile',
description: '可以上传用于作为格式示范的样例数据',
multiple: false,
joinValues: false,
...inputFileFormItemCommonOptions(undefined, size500MB),
},
]
},
...(showCreatedUserAndModifiedUser ? formCreatedUserAndModifiedUser() : [])
},
{
type: 'input-text',
label: 'JDBC',
name: 'databaseJdbc',
required: true,
...formInputClearable,
},
{
type: 'input-text',
label: '用户名',
name: 'databaseUsername',
...formInputClearable,
},
{
type: 'input-password',
label: '密码',
name: 'databasePassword',
...formInputClearable,
},
]
},
{
visibleOn: "${resourceType === 'HDFS'}",
type: 'wrapper',
size: 'none',
body: [
formInputSingleFileStatic('coreSiteFile', 'core-site.xml'),
{
visibleOn: "${!detail}",
type: 'input-file',
label: 'core-site.xml',
name: 'coreSiteFile',
multiple: false,
required: true,
joinValues: false,
...inputFileFormItemCommonOptions('.xml'),
},
formInputSingleFileStatic('hdfsSiteFile', 'hdfs-site.xml'),
{
visibleOn: "${!detail}",
type: 'input-file',
label: 'hdfs-site.xml',
name: 'hdfsSiteFile',
multiple: false,
required: true,
joinValues: false,
...inputFileFormItemCommonOptions('.xml'),
},
]
},
{
visibleOn: "${resourceType === 'FTP'}",
type: 'wrapper',
size: 'none',
body: [
{
type: 'input-text',
label: 'FTP地址',
name: 'ftpUrl',
required: true,
...formInputClearable,
},
{
type: 'input-text',
label: 'FTP账号',
name: 'ftpUsername',
...formInputClearable,
},
{
type: 'input-password',
label: 'FTP密码',
name: 'ftpPassword',
...formInputClearable,
},
{
type: 'input-text',
label: '相对路径',
name: 'ftpPath',
description: '若为空,则使用用户根目录',
...formInputClearable,
},
{
type: 'input-text',
label: '文件筛选',
name: 'ftpRegexFilter',
description: '正则表达式,用于匹配文件的路径,只有符合筛选条件的文件才会被采集;若为空则默认采集全部文件',
...formInputClearable,
},
]
},
]
}
},
{
type: 'fieldSet',
title: '资源格式定义',
className: 'mt-5',
body: [
{
name: 'formatType',
type: 'select',
label: '资源格式',
selectFirst: true,
required: true,
options: [
{label: '无', value: 'NONE'},
{label: 'Line', value: 'LINE'},
{label: 'JSON', value: 'JSON'},
{label: 'JSON Line', value: 'JSON_LINE'},
{label: 'CSV', value: 'CSV'},
]
},
{
visibleOn: "${formatType === 'JSON' && !detail}",
type: 'json-schema-editor',
name: 'jsonSchema',
label: 'JSON格式',
description: '使用JSON Schema格式',
required: true,
enableAdvancedSetting: true,
mini: true,
},
{
visibleOn: "${formatType === 'JSON' && detail}",
type: 'editor',
name: 'jsonSchemaText',
label: 'JSON格式',
language: 'json',
},
{
visibleOn: "${formatType === 'JSON_LINE' && !detail}",
type: 'json-schema-editor',
name: 'jsonLineSchema',
label: 'JSON格式',
description: 'JSON Line类型请定义单行JSON数据格式使用JSON Schema格式',
required: true,
enableAdvancedSetting: true,
mini: true,
},
{
visibleOn: "${formatType === 'JSON_LINE' && detail}",
type: 'editor',
name: 'jsonLineSchemaText',
label: 'JSON格式',
language: 'json',
},
{
visibleOn: "${formatType === 'CSV' && !detail}",
type: 'json-schema-editor',
name: 'csvSchema',
label: 'CSV格式',
description: '请定义单行数据中各个字段的格式使用JSON Schema格式',
required: true,
enableAdvancedSetting: true,
mini: true,
disabledTypes: [
'object',
'array',
'null',
]
},
{
visibleOn: "${formatType === 'CSV' && detail}",
type: 'editor',
name: 'csvSchemaText',
label: 'JSON格式',
language: 'json',
},
formInputSingleFileStatic('exampleFile', '资源示例'),
{
visibleOn: "${!detail}",
type: 'input-file',
label: '资源示例',
name: 'exampleFile',
description: '可以上传用于作为格式示范的样例数据',
multiple: false,
joinValues: false,
...inputFileFormItemCommonOptions(undefined, size500MB),
},
]
},
...(showCreatedUserAndModifiedUser ? formCreatedUserAndModifiedUser() : [])
]
}
}
export function resourceAddDialog() {
return {
actionType: 'dialog',
dialog: {
title: '新增数据资源',
size: 'md',
actions: [
{
type: 'reset',
label: '重置',
},
{
type: 'submit',
label: '确定',
level: 'primary',
}
],
body: {
...detailForm(),
api: apiPost('${base}/data_resource/save'),
data: {
add: true,
}
}
return {
actionType: 'dialog',
dialog: {
title: '新增数据资源',
size: 'md',
actions: [
{
type: 'reset',
label: '重置',
},
{
type: 'submit',
label: '确定',
level: 'primary',
}
],
body: {
...detailForm(),
api: apiPost('${base}/data_resource/save'),
data: {
add: true,
}
}
}
}
}
export function resourceDetailDialog(field = 'id') {
return {
actionType: 'dialog',
dialog: {
title: '账号详情',
actions: [],
size: 'md',
body: {
...detailForm(true),
static: true,
initApi: apiGet(`\${base}/data_resource/detail/\${${field}}`),
data: {
detail: true,
}
},
return {
actionType: 'dialog',
dialog: {
title: '账号详情',
actions: [],
size: 'md',
body: {
...detailForm(true),
static: true,
initApi: apiGet(`\${base}/data_resource/detail/\${${field}}`),
data: {
detail: true,
}
},
}
}
}
export function resourceEditeDialog() {
return {
actionType: 'dialog',
dialog: {
title: '账号详情',
size: 'md',
actions: [
{
type: 'reset',
label: '重置',
},
{
type: 'submit',
label: '确定',
level: 'primary',
}
],
body: {
...detailForm(),
api: apiPost('${base}/data_resource/save'),
initApi: apiGet('${base}/data_resource/detail/${id}'),
data: {
edit: true,
}
},
return {
actionType: 'dialog',
dialog: {
title: '账号详情',
size: 'md',
actions: [
{
type: 'reset',
label: '重置',
},
{
type: 'submit',
label: '确定',
level: 'primary',
}
],
body: {
...detailForm(),
api: apiPost('${base}/data_resource/save'),
initApi: apiGet('${base}/data_resource/detail/${id}'),
data: {
edit: true,
}
},
}
}
}

View File

@@ -1,38 +1,38 @@
import {horizontalFormOptions, apiPost} from '../constants.js'
import {apiPost, horizontalFormOptions} from '../constants.js'
import {confirmPasswordFormItem, passwordFormItem} from "./dialog-user-item.js";
export function userChangePasswordDialog() {
return {
actionType: 'dialog',
dialog: {
title: '修改密码',
actions: [
{
type: 'reset',
label: '清空',
},
{
type: 'submit',
label: '修改',
level: 'primary',
}
],
body: {
type: 'form',
api: apiPost('${base}/user_management/change_password'),
...horizontalFormOptions(),
body: [
{
type: 'input-password',
name: 'oldPassword',
label: '旧密码',
placeholder: '请输入旧密码',
required: true,
},
passwordFormItem('newPassword', '新密码'),
confirmPasswordFormItem('confirmNewPassword', 'newPassword', '新密码'),
]
}
return {
actionType: 'dialog',
dialog: {
title: '修改密码',
actions: [
{
type: 'reset',
label: '清空',
},
{
type: 'submit',
label: '修改',
level: 'primary',
}
],
body: {
type: 'form',
api: apiPost('${base}/user_management/change_password'),
...horizontalFormOptions(),
body: [
{
type: 'input-password',
name: 'oldPassword',
label: '旧密码',
placeholder: '请输入旧密码',
required: true,
},
passwordFormItem('newPassword', '新密码'),
confirmPasswordFormItem('confirmNewPassword', 'newPassword', '新密码'),
]
}
}
}
}

View File

@@ -1,106 +1,106 @@
import {
apiGet,
formCreatedUserAndModifiedUser,
horizontalFormOptions,
mappingField,
userRoleMapping,
userStateMapping
apiGet,
formCreatedUserAndModifiedUser,
horizontalFormOptions,
mappingField,
userRoleMapping,
userStateMapping
} from "../constants.js";
const dialogBody = [
{
type: 'input-email',
name: 'username',
label: '邮箱',
},
{
type: 'group',
body: [
{
type: 'control',
label: '角色',
body: mappingField('role', '角色', userRoleMapping, 120),
},
{
type: 'control',
label: '账号状态',
body: mappingField('state', '账号状态', userStateMapping),
}
]
},
...formCreatedUserAndModifiedUser(),
{
type: 'group',
body: [
{
type: 'input-text',
name: 'checkedUsername',
label: '审核人',
},
{
type: 'input-datetime',
name: 'checkedTime',
label: '审核时间',
},
]
},
{
type: 'input-email',
name: 'username',
label: '邮箱',
},
{
type: 'group',
body: [
{
type: 'control',
label: '角色',
body: mappingField('role', '角色', userRoleMapping, 120),
},
{
type: 'control',
label: '账号状态',
body: mappingField('state', '账号状态', userStateMapping),
}
]
},
...formCreatedUserAndModifiedUser(),
{
type: 'group',
body: [
{
type: 'input-text',
name: 'checkedUsername',
label: '审核人',
},
{
type: 'input-datetime',
name: 'checkedTime',
label: '审核时间',
},
]
},
]
export function userDetailDialog() {
return {
actionType: 'dialog',
dialog: {
title: '账号详情',
actions: [],
size: 'md',
body: {
type: 'form',
initApi: apiGet('${base}/user_management/detail/${username}'),
...horizontalFormOptions(),
horizontal: {
left: 2,
},
static: true,
body: [
...dialogBody,
{
type: 'input-datetime',
name: 'lastLoginTime',
label: '上次登陆时间',
},
],
}
}
return {
actionType: 'dialog',
dialog: {
title: '账号详情',
actions: [],
size: 'md',
body: {
type: 'form',
initApi: apiGet('${base}/user_management/detail/${username}'),
...horizontalFormOptions(),
horizontal: {
left: 2,
},
static: true,
body: [
...dialogBody,
{
type: 'input-datetime',
name: 'lastLoginTime',
label: '上次登陆时间',
},
],
}
}
}
}
export function userCheckDialog() {
return {
actionType: 'dialog',
dialog: {
title: '账号审核',
actions: [
{
type: 'action',
label: '同意',
level: 'primary',
actionType: 'submit',
confirmTitle: '审核通过',
confirmText: '确认通过账号为${username}通过审核吗?审核通过后将无法撤销。',
},
],
size: 'md',
body: {
type: 'form',
api: apiGet('${base}/user_management/check/${username}'),
initApi: apiGet('${base}/user_management/detail/${username}'),
...horizontalFormOptions(),
horizontal: {
left: 2,
},
static: true,
body: dialogBody,
}
}
return {
actionType: 'dialog',
dialog: {
title: '账号审核',
actions: [
{
type: 'action',
label: '同意',
level: 'primary',
actionType: 'submit',
confirmTitle: '审核通过',
confirmText: '确认通过账号为${username}通过审核吗?审核通过后将无法撤销。',
},
],
size: 'md',
body: {
type: 'form',
api: apiGet('${base}/user_management/check/${username}'),
initApi: apiGet('${base}/user_management/detail/${username}'),
...horizontalFormOptions(),
horizontal: {
left: 2,
},
static: true,
body: dialogBody,
}
}
}
}

View File

@@ -1,49 +1,49 @@
export function emailFormItem(name) {
return {
type: 'input-email',
name: name,
label: '邮箱',
placeholder: '请输入邮箱',
required: true,
clearable: true,
clearValueOnEmpty: true,
validateApi: '${base}/user/exists_username/${username}',
}
return {
type: 'input-email',
name: name,
label: '邮箱',
placeholder: '请输入邮箱',
required: true,
clearable: true,
clearValueOnEmpty: true,
validateApi: '${base}/user/exists_username/${username}',
}
}
export function passwordFormItem(name, label = '密码') {
return {
type: 'input-password',
name: name,
label: label,
placeholder: `请输入${label}`,
required: true,
clearable: true,
clearValueOnEmpty: true,
validations: {
matchRegexp:
/^(?=.*\d)(?!.*(\d)\1{2})(?!.*(012|123|234|345|456|567|678|789|987|876|765|654|543|432|321|210))(?=.*[a-zA-Z])(?=.*[^\da-zA-Z\s]).{8,16}$/,
},
validationErrors: {
matchRegexp:
`${label}至少包含字母、数字、特殊字符8-16位并且不能连续出现3个大小连续或相同的数字`,
},
}
return {
type: 'input-password',
name: name,
label: label,
placeholder: `请输入${label}`,
required: true,
clearable: true,
clearValueOnEmpty: true,
validations: {
matchRegexp:
/^(?=.*\d)(?!.*(\d)\1{2})(?!.*(012|123|234|345|456|567|678|789|987|876|765|654|543|432|321|210))(?=.*[a-zA-Z])(?=.*[^\da-zA-Z\s]).{8,16}$/,
},
validationErrors: {
matchRegexp:
`${label}至少包含字母、数字、特殊字符8-16位并且不能连续出现3个大小连续或相同的数字`,
},
}
}
export function confirmPasswordFormItem(name, target, label = '密码') {
return {
type: 'input-password',
name: name,
label: `确认${label}`,
placeholder: `请再次输入${label}`,
required: true,
clearable: true,
validations: {
equalsField: target,
},
validationErrors: {
equalsField: `两次输入${label}不一致`,
},
}
return {
type: 'input-password',
name: name,
label: `确认${label}`,
placeholder: `请再次输入${label}`,
required: true,
clearable: true,
validations: {
equalsField: target,
},
validationErrors: {
equalsField: `两次输入${label}不一致`,
},
}
}

View File

@@ -32,9 +32,9 @@ export function userRegisterDialog() {
required: true,
selectFirst: true,
options: [
{ label: '数据提供方', value: 'PROVIDER' },
{ label: '数据使用方', value: 'CUSTOMER' },
{ label: '审查监管方', value: 'CHECKER' },
{label: '数据提供方', value: 'PROVIDER'},
{label: '数据使用方', value: 'CUSTOMER'},
{label: '审查监管方', value: 'CHECKER'},
],
},
],
@@ -76,9 +76,9 @@ export function userAdministratorRegisterDialog() {
inline: false,
columnsCount: 2,
options: [
{ label: '数据提供方', value: 'PROVIDER' },
{ label: '数据使用方', value: 'CUSTOMER' },
{ label: '审查监管方', value: 'CHECKER' },
{label: '数据提供方', value: 'PROVIDER'},
{label: '数据使用方', value: 'CUSTOMER'},
{label: '审查监管方', value: 'CHECKER'},
],
},
],

View File

@@ -4,188 +4,198 @@ import {resourceList} from '../../pages/index/tab-data.js'
import {resourceDetailDialog} from '../resource/dialog-resource.js'
function detailForm() {
return {
id: 'ware-form',
debug: information.debug,
type: 'form',
...horizontalFormOptions(),
horizontal: {
left: 2,
return {
id: 'ware-form',
debug: information.debug,
type: 'form',
...horizontalFormOptions(),
horizontal: {
left: 2,
},
body: [
{
type: 'hidden',
name: 'id',
},
{
visibleOn: '${!detail}',
type: 'input-image',
name: 'icon',
label: '图标',
required: true,
receiver: apiPost("${base}/upload"),
onEvent: {
success: {
actions: [
{
actionType: 'setValue',
componentId: 'ware-form',
args: {
value: {
iconId: '${event.data.result.id}'
}
}
}
]
}
}
},
{
visibleOn: '${detail}',
type: 'control',
name: 'icon',
label: '图标',
required: true,
body: {
type: 'image',
src: '${icon}',
innerClassName: 'no-border',
}
},
{
type: 'picker',
name: 'resourceId',
label: '数据资源',
required: true,
multiple: false,
size: 'md',
valueField: 'id',
labelField: 'name',
source: apiGet('${base}/data_resource/list_no_ware'),
pickerSchema: {
...resourceList(),
},
body: [
{
type: 'hidden',
name: 'id',
},
{
visibleOn: '${!detail}',
type: 'input-image',
name: 'icon',
label: '图标',
required: true,
receiver: apiPost("${base}/upload"),
onEvent: {
success: {
actions: [
{
actionType: 'setValue',
componentId: 'ware-form',
args: {
value: {
iconId: '${event.data.result.id}'
}
}
}
]
}
}
},
{
visibleOn: '${detail}',
type: 'control',
name: 'icon',
label: '图标',
required: true,
body: {
type: 'image',
src: '${icon}',
innerClassName: 'no-border',
}
},
{
type: 'picker',
name: 'resourceId',
label: '数据资源',
required: true,
multiple: false,
size: 'md',
valueField: 'id',
labelField: 'name',
source: apiGet('${base}/data_resource/list_no_ware'),
pickerSchema: {
...resourceList(),
},
staticSchema: {
type: 'tpl',
tpl: "<span class='text-primary' style='cursor: pointer'>${resourceName}</span>",
onEvent: {
click: {
actions: [
{
actionType: 'dialog',
...resourceDetailDialog('resourceId'),
}
]
}
}
}
},
{
type: 'input-text',
name: 'name',
label: '商品名称',
maxLength: 10,
showCounter: true,
required: true,
...formInputClearable,
},
{
type: 'textarea',
name: 'description',
label: '商品简介',
required: true,
...formInputClearable,
showCounter: true,
trimContents: true,
minRows: 2,
maxRows: 2,
},
{
type: 'input-rich-text',
name: 'content',
label: '商品详情',
required: true,
receiver: apiPost("${base}/upload"),
options: {
min_height: 300,
staticSchema: {
type: 'tpl',
tpl: "<span class='text-primary' style='cursor: pointer'>${resourceName}</span>",
onEvent: {
click: {
actions: [
{
actionType: 'dialog',
...resourceDetailDialog('resourceId'),
}
]
}
]
}
}
}
},
{
type: 'input-text',
name: 'name',
label: '商品名称',
maxLength: 10,
showCounter: true,
required: true,
...formInputClearable,
},
{
type: 'textarea',
name: 'description',
label: '商品简介',
required: true,
...formInputClearable,
showCounter: true,
trimContents: true,
minRows: 2,
maxRows: 2,
maxLength: 100,
},
{
type: 'input-tag',
name: 'tags',
label: '标签',
max: 10,
maxTagLength: 10,
joinValues: false,
extractValue: true,
},
{
type: 'input-rich-text',
name: 'content',
label: '商品详情',
required: true,
receiver: apiPost("${base}/upload"),
options: {
min_height: 300,
}
}
]
}
}
export function wareAddDialog() {
return {
actionType: 'dialog',
dialog: {
title: '上架数据产品',
size: 'md',
actions: [
{
type: 'reset',
label: '重置',
},
{
type: 'submit',
label: '确定',
level: 'primary',
}
],
body: {
...detailForm(),
api: apiPost(`\${base}/ware/save`),
data: {
add: true,
}
}
return {
actionType: 'dialog',
dialog: {
title: '上架数据产品',
size: 'md',
actions: [
{
type: 'reset',
label: '重置',
},
{
type: 'submit',
label: '确定',
level: 'primary',
}
],
body: {
...detailForm(),
api: apiPost(`\${base}/ware/save`),
data: {
add: true,
}
}
}
}
}
export function wareDetailDialog(field = 'id', actions = []) {
return {
actionType: 'dialog',
dialog: {
title: '数据产品详情',
size: 'md',
actions: actions,
body: {
...detailForm(),
initApi: apiGet(`\${base}/ware/detail/\${${field}}`),
static: true,
data: {
detail: true,
}
}
return {
actionType: 'dialog',
dialog: {
title: '数据产品详情',
size: 'md',
actions: actions,
body: {
...detailForm(),
initApi: apiGet(`\${base}/ware/detail/\${${field}}`),
static: true,
data: {
detail: true,
}
}
}
}
}
export function wareEditeDialog() {
return {
actionType: 'dialog',
dialog: {
title: '数据产品详情',
size: 'md',
actions: [
{
type: 'reset',
label: '重置',
},
{
type: 'submit',
label: '确定',
level: 'primary',
}
],
body: {
...detailForm(),
api: apiPost(`\${base}/ware/save`),
initApi: apiGet(`\${base}/ware/detail/\${id}`),
data: {
edit: true
}
},
return {
actionType: 'dialog',
dialog: {
title: '数据产品详情',
size: 'md',
actions: [
{
type: 'reset',
label: '重置',
},
{
type: 'submit',
label: '确定',
level: 'primary',
}
],
body: {
...detailForm(),
api: apiPost(`\${base}/ware/save`),
initApi: apiGet(`\${base}/ware/detail/\${id}`),
data: {
edit: true
}
},
}
}
}

View File

@@ -2,7 +2,7 @@
<html lang="zh">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
<title></title>
<link href="/assets/sdk/antd.css" rel="stylesheet"/>
<link href="/assets/sdk/helper.css" rel="stylesheet"/>
@@ -20,6 +20,6 @@
<body>
<div id="app"></div>
<script src="/assets/sdk/sdk.js"></script>
<script type="module" src="./main.js"></script>
<script src="./main.js" type="module"></script>
</body>
</html>

View File

@@ -1,73 +1,200 @@
import {apiGet, useAmis} from '../../components/constants.js'
import {userChangePasswordDialog} from "../../components/user/dialog-user-change-password.js";
import {tabUser} from "./tab-user.js";
import {tabData} from "./tab-data.js";
import {tabSettings} from "./tab-settings.js";
import {tabCheck} from "./tab-check.js";
import {tabPermissions} from "./tab-permissions.js";
import {tabMarket} from "./tab-market.js";
import './style.css'
import {administratorOnly, apiGet, checkerOnly, useAmis, userOnly} from '../../components/constants.js'
import {userChangePasswordDialog} from '../../components/user/dialog-user-change-password.js'
import {tabUser} from './tab-user.js'
import {tabData} from './tab-data.js'
import {tabSettings} from './tab-settings.js'
import {tabCheck} from './tab-check.js'
import {tabPermissions} from './tab-permissions.js'
import {tabMarket} from './tab-market.js'
useAmis(information => {
return {
id: 'header-service',
className: 'h-full',
type: 'service',
api: apiGet('${base}/user/state'),
onEvent: {
fetchInited: {
actions: [
{
expression: '${!event.data.responseData.token}',
actionType: 'url',
args: {
url: '/pages/login/index.html',
blank: false,
}
}
]
useAmis((information) => {
return {
id: 'header-service',
className: 'h-full',
type: 'service',
api: apiGet('${base}/user/state'),
onEvent: {
fetchInited: {
actions: [
{
expression: '${!event.data.responseData.token}',
actionType: 'url',
args: {
url: '/pages/login/index.html',
blank: false,
},
},
],
},
},
body: [
{
id: 'root-page',
type: 'page',
title: {
type: 'flex',
justify: 'flex-start',
items: [
{
type: 'avatar',
className: 'mr-2 bg-transparent',
src: '/logo.svg',
shape: 'square',
fit: 'contain',
},
{
type: 'flex',
className: 'w-50',
direction: 'column',
items: [
{
type: 'tpl',
className: 'font-bold text-white',
tpl: information.title,
},
{
type: 'tpl',
className: 'font-bold text-xs text-gray-200',
tpl: '提供合法合规的数据要素可信供给工具',
},
]
}
]
},
// subTitle: '提供合法合规的数据要素可信供给工具',
headerClassName: 'bg-gray-800 text-white',
toolbarClassName: 'bg-gray-800',
toolbar: [
{
type: 'action',
label: '数据市场',
icon: 'fa fa-store',
level: 'link',
className: "text-bold ${IF(activePage === 'market', 'text-primary', 'text-white')}",
onEvent: {
click: {
actions: [
{
actionType: 'setValue',
componentId: 'root-page',
args: {
value: {
activePage: 'market',
}
}
}
]
}
}
},
{
type: 'action',
label: '我的资源',
icon: 'fa fa-database',
level: 'link',
className: "text-bold ${IF(activePage === 'tab', 'text-primary', 'text-white')}",
onEvent: {
click: {
actions: [
{
actionType: 'setValue',
componentId: 'root-page',
args: {
value: {
activePage: 'tab',
}
}
}
]
}
}
},
{
type: 'divider',
direction: 'vertical',
color: '#4d4d4d',
},
{
type: 'dropdown-button',
label: '${username}',
align: 'right',
trigger: 'hover',
btnClassName: 'text-white',
level: 'link',
buttons: [
{
label: '修改密码',
...userChangePasswordDialog(),
},
{
label: '退出登陆',
actionType: 'ajax',
api: apiGet('${base}/user/logout'),
reload: 'header-service',
},
],
},
],
bodyClassName: 'p-0',
data: {
activePage: 'tab',
tabActiveKey: 'data'
},
body: [
{
type: 'page',
title: information.title,
subTitle: '提供合法合规的数据要素可信供给工具',
toolbar: [
{
type: 'dropdown-button',
label: '${username}',
align: 'right',
trigger: 'hover',
buttons: [
{
label: '修改密码',
...userChangePasswordDialog(),
},
{
label: '退出登陆',
actionType: 'ajax',
api: apiGet('${base}/user/logout'),
reload: 'header-service',
}
]
}
],
bodyClassName: 'p-0',
body: {
className: 'h-full border-0',
type: 'tabs',
tabsMode: 'vertical',
tabs: [
// tabOverview(),
tabMarket(),
tabPermissions(),
tabCheck(),
tabData(),
tabUser(),
tabSettings(),
]
},
}
]
}
{
visibleOn: "${activePage === 'market'}",
type: 'wrapper',
body: tabMarket(),
},
{
visibleOn: "${activePage === 'tab'}",
className: 'h-full border-0',
type: 'tabs',
tabsMode: 'vertical',
activeKey: '${tabActiveKey}',
tabs: [
// tabOverview(),
{
hash: 'data',
visibleOn: userOnly,
title: '数据资源',
icon: 'fa fa-database',
reload: true,
body: tabData()
},
{
hash: 'permission',
visibleOn: userOnly,
title: '权属管理',
icon: 'fa fa-key',
reload: true,
body: tabPermissions(),
},
{
hash: 'check',
visibleOn: checkerOnly,
title: '审核审查',
icon: 'fa fa-shield-halved',
reload: true,
body: tabCheck(),
},
{
hash: 'user',
visibleOn: administratorOnly,
title: '用户管理',
icon: 'fa fa-user',
reload: true,
body: tabUser(),
},
{
hash: 'settings',
...tabSettings(),
}
],
}
],
},
],
}
})

View File

View File

@@ -1,146 +1,139 @@
import {
apiGet,
checkerOnly,
checkOverMapping,
checkTypeMapping,
crudCommonOptions,
mappingField,
operationField,
stringField,
timeField,
apiGet,
checkOverMapping,
checkTypeMapping,
crudCommonOptions,
mappingField,
operationField,
stringField,
timeField,
} from "../../components/constants.js";
import {authenticationDetailDialog, confirmationDetailDialog} from "../../components/permission/dialog-permission.js";
import {wareDetailDialog} from "../../components/ware/dialog-ware.js";
export function tabCheck() {
return {
visibleOn: checkerOnly,
title: '审核审查',
icon: 'fa fa-shield-halved',
reload: true,
body: [
{
name: 'check_order_list',
type: 'crud',
api: apiGet('${base}/check_order/list'),
...crudCommonOptions(),
headerToolbar: [
'reload',
],
columns: [
stringField('description', '描述'),
mappingField('type', '类型', checkTypeMapping),
mappingField('state', '状态', checkOverMapping),
timeField('createdTime', '创建时间'),
stringField('createdUsername', '创建人', 100),
timeField('modifiedTime', '最后修改时间'),
stringField('modifiedUsername', '最后操作人', 100),
operationField('操作', undefined, [
{
visibleOn: `\${type === 'CONFIRMATION' && state === 'CHECKING'}`,
type: 'action',
label: '处理',
level: 'link',
...confirmationDetailDialog(
'parameters.confirmationId',
[
{
type: 'action',
label: '同意',
actionType: 'ajax',
close: true,
api: apiGet('${base}/check_order/operation/${checkOrderId}/APPLY'),
reload: 'check_order_list',
},
{
type: 'action',
label: '拒绝',
actionType: 'ajax',
close: true,
api: apiGet('${base}/check_order/operation/${checkOrderId}/REJECT'),
reload: 'check_order_list',
},
],
),
},
{
visibleOn: `\${type === 'CONFIRMATION' && state !== NORMAL}`,
type: 'action',
label: '查看',
level: 'link',
...confirmationDetailDialog('parameters.confirmationId'),
},
{
visibleOn: `\${type === 'AUTHENTICATION' && state === 'CHECKING'}`,
type: 'action',
label: '处理',
level: 'link',
...authenticationDetailDialog(
'parameters.authenticationId',
[
{
type: 'action',
label: '同意',
actionType: 'ajax',
close: true,
api: apiGet('${base}/check_order/operation/${checkOrderId}/APPLY'),
reload: 'check_order_list',
},
{
type: 'action',
label: '拒绝',
actionType: 'ajax',
close: true,
api: apiGet('${base}/check_order/operation/${checkOrderId}/REJECT'),
reload: 'check_order_list',
},
],
),
},
{
visibleOn: `\${type === 'AUTHENTICATION' && state !== NORMAL}`,
type: 'action',
label: '查看',
level: 'link',
...authenticationDetailDialog('parameters.authenticationId'),
},
{
visibleOn: `\${type === 'MARKET' && state === 'CHECKING'}`,
type: 'action',
label: '处理',
level: 'link',
...wareDetailDialog(
'parameters.wareId',
[
{
type: 'action',
label: '同意',
actionType: 'ajax',
close: true,
api: apiGet('${base}/check_order/operation/${checkOrderId}/APPLY'),
reload: 'check_order_list',
},
{
type: 'action',
label: '拒绝',
actionType: 'ajax',
close: true,
api: apiGet('${base}/check_order/operation/${checkOrderId}/REJECT'),
reload: 'check_order_list',
},
],
),
},
{
visibleOn: `\${type === 'MARKET' && state !== NORMAL}`,
type: 'action',
label: '查看',
level: 'link',
...wareDetailDialog('parameters.wareId'),
},
]),
],
},
],
}
return [
{
name: 'check_order_list',
type: 'crud',
api: apiGet('${base}/check_order/list'),
...crudCommonOptions(),
headerToolbar: [
'reload',
],
columns: [
stringField('description', '描述'),
mappingField('type', '类型', checkTypeMapping),
mappingField('state', '状态', checkOverMapping),
timeField('createdTime', '创建时间'),
stringField('createdUsername', '创建人', 100),
timeField('modifiedTime', '最后修改时间'),
stringField('modifiedUsername', '最后操作人', 100),
operationField('操作', undefined, [
{
visibleOn: "${type === 'CONFIRMATION' && state === 'CHECKING'}",
type: 'action',
label: '处理',
level: 'link',
...confirmationDetailDialog(
'parameters.confirmationId',
[
{
type: 'action',
label: '同意',
actionType: 'ajax',
close: true,
api: apiGet('${base}/check_order/operation/${checkOrderId}/APPLY'),
reload: 'check_order_list',
},
{
type: 'action',
label: '拒绝',
actionType: 'ajax',
close: true,
api: apiGet('${base}/check_order/operation/${checkOrderId}/REJECT'),
reload: 'check_order_list',
},
],
),
},
{
visibleOn: "${type === 'CONFIRMATION' && state !== NORMAL}",
type: 'action',
label: '查看',
level: 'link',
...confirmationDetailDialog('parameters.confirmationId'),
},
{
visibleOn: "${type === 'AUTHENTICATION' && state === 'CHECKING'}",
type: 'action',
label: '处理',
level: 'link',
...authenticationDetailDialog(
'parameters.authenticationId',
[
{
type: 'action',
label: '同意',
actionType: 'ajax',
close: true,
api: apiGet('${base}/check_order/operation/${checkOrderId}/APPLY'),
reload: 'check_order_list',
},
{
type: 'action',
label: '拒绝',
actionType: 'ajax',
close: true,
api: apiGet('${base}/check_order/operation/${checkOrderId}/REJECT'),
reload: 'check_order_list',
},
],
),
},
{
visibleOn: "${type === 'AUTHENTICATION' && state !== NORMAL}",
type: 'action',
label: '查看',
level: 'link',
...authenticationDetailDialog('parameters.authenticationId'),
},
{
visibleOn: "${type === 'MARKET' && state === 'CHECKING'}",
type: 'action',
label: '处理',
level: 'link',
...wareDetailDialog(
'parameters.wareId',
[
{
type: 'action',
label: '同意',
actionType: 'ajax',
close: true,
api: apiGet('${base}/check_order/operation/${checkOrderId}/APPLY'),
reload: 'check_order_list',
},
{
type: 'action',
label: '拒绝',
actionType: 'ajax',
close: true,
api: apiGet('${base}/check_order/operation/${checkOrderId}/REJECT'),
reload: 'check_order_list',
},
],
),
},
{
visibleOn: "${type === 'MARKET' && state !== NORMAL}",
type: 'action',
label: '查看',
level: 'link',
...wareDetailDialog('parameters.wareId'),
},
]),
],
},
]
}

View File

@@ -1,94 +1,181 @@
import {
resourceAddDialog,
resourceDetailDialog,
resourceEditeDialog
resourceAddDialog,
resourceDetailDialog,
resourceEditeDialog
} from "../../components/resource/dialog-resource.js";
import {
apiGet,
arrayInCheck,
arrayOutCheck,
checkState,
crudCommonOptions,
mappingField,
operationField,
permissionStateMapping,
timeField,
userOnly
apiGet,
arrayOutCheck,
checkState,
crudCommonOptions,
mappingField,
operationField,
permissionStateMapping,
timeField
} from "../../components/constants.js";
import {wareAddDialog, wareDetailDialog, wareEditeDialog} from "../../components/ware/dialog-ware.js";
export function resourceList() {
return {
type: 'crud',
api: apiGet('${base}/data_resource/list'),
...crudCommonOptions(),
headerToolbar: [
'reload',
export function resourceList(showMode = false) {
return {
type: 'crud',
api: apiGet('${base}/data_resource/list'),
...crudCommonOptions(),
headerToolbar: [
'reload',
{
type: 'action',
label: '',
icon: 'fa fa-plus',
...resourceAddDialog()
},
],
columns: [
{
label: '名称',
name: 'name',
width: 150,
},
{
label: '描述',
name: 'description',
},
mappingField('confirmationState', '确权状态', permissionStateMapping),
timeField('createdTime', '创建时间'),
operationField('操作', undefined, [
{
type: 'action',
label: '详情',
level: 'link',
...resourceDetailDialog(),
},
{
visibleOn: !showMode,
type: 'dropdown-button',
level: 'link',
icon: 'fa fa-ellipsis-h',
hideCaret: true,
trigger: 'hover',
buttons: [
{
type: 'action',
label: '',
icon: 'fa fa-plus',
...resourceAddDialog()
},
],
columns: [
{
label: '名称',
name: 'name',
width: 150,
disabledOn: arrayOutCheck([checkState.none, checkState.draft], 'confirmationState'),
disabledTip: '审查或确权成功后无法编辑',
tooltipPlacement: 'top',
type: 'action',
label: '编辑',
level: 'link',
...resourceEditeDialog(),
},
{
label: '描述',
name: 'description',
disabledOn: arrayOutCheck([checkState.none, checkState.draft], 'confirmationState'),
disabledTip: '审查或确权成功后无法删除',
tooltipPlacement: 'bottom',
type: 'action',
label: "删除",
confirmTitle: '确认删除',
confirmText: '确认删除名称为「${name}」的数据资源吗?',
actionType: 'ajax',
api: apiGet('${base}/data_resource/remove/${id}')
},
mappingField('confirmationState', '确权状态', permissionStateMapping),
timeField('createdTime', '创建时间'),
operationField('操作', undefined, [
{
type: 'action',
label: '详情',
level: 'link',
...resourceDetailDialog(),
},
{
type: 'dropdown-button',
level: 'link',
icon: 'fa fa-ellipsis-h',
hideCaret: true,
trigger: 'hover',
buttons: [
{
disabledOn: arrayOutCheck([checkState.none, checkState.draft], 'confirmationState'),
disabledTip: '审查或确权成功后无法编辑',
tooltipPlacement: 'top',
type: 'action',
label: '编辑',
level: 'link',
...resourceEditeDialog(),
},
{
disabledOn: arrayInCheck([checkState.checking], 'confirmationState'),
disabledTip: '审查中无法删除',
tooltipPlacement: 'bottom',
type: 'action',
label: "删除",
confirmTitle: '确认删除',
confirmText: '确认删除名称为「${name}」的数据资源吗?',
actionType: 'ajax',
api: apiGet('${base}/data_resource/remove/${id}')
},
]
},
]),
]
}
]
},
]),
]
}
}
export function tabData() {
return {
visibleOn: userOnly,
title: '数据资源',
icon: 'fa fa-database',
reload: true,
body: resourceList(),
}
return {
type: 'tabs',
tabs: [
{
title: '资源定义',
tab: resourceList()
},
{
title: '资源上架',
tab: {
type: 'crud',
api: apiGet('${base}/ware/list'),
...crudCommonOptions(),
headerToolbar: [
'reload',
{
type: 'action',
label: '',
icon: 'fa fa-plus',
...wareAddDialog()
},
],
columns: [
{
name: 'name',
label: '名称',
width: 200,
},
{
name: 'description',
label: '描述',
type: 'tpl',
tpl: '${TRUNCATE(description, 100)}',
},
mappingField('state', '状态', permissionStateMapping),
timeField('createdTime', '创建时间'),
operationField('操作', undefined, [
{
type: 'action',
label: '查看',
level: 'link',
...wareDetailDialog(),
},
{
visibleOn: "${state === 'CHECKING'}",
type: 'action',
label: '撤销',
level: 'link',
confirmTitle: '确认撤销',
confirmText: '确认撤销名称为「${name}」的确权申请吗?',
actionType: 'ajax',
api: apiGet('${base}/ware/retract/${id}'),
},
{
visibleOn: "${state === 'DRAFT' || state === 'REJECT'}",
type: 'action',
label: '提交',
level: 'link',
confirmTitle: '确认提交',
confirmText: '确认提交名称为「${name}」的确权申请吗?',
actionType: 'ajax',
api: apiGet('${base}/ware/submit/${id}'),
},
{
type: 'dropdown-button',
level: 'link',
icon: 'fa fa-ellipsis-h',
hideCaret: true,
trigger: 'hover',
buttons: [
{
disabledOn: "${state !== 'DRAFT'}",
type: 'action',
label: '编辑',
level: 'link',
...wareEditeDialog(),
},
{
disabledOn: "${state === 'CHECKING'}",
type: 'action',
label: "删除",
confirmTitle: '确认删除',
confirmText: '确认删除名称为「${name}」的确权申请吗?删除后对应的数据资源处于未确权状态。',
actionType: 'ajax',
api: apiGet('${base}/ware/remove/${id}'),
},
]
},
]),
]
}
}
]
}
}

View File

@@ -1,153 +1,85 @@
import {wareAddDialog, wareDetailDialog, wareEditeDialog} from "../../components/ware/dialog-ware.js";
import {
apiGet,
crudCommonOptions,
mappingField,
operationField,
permissionStateMapping,
timeField
} from "../../components/constants.js";
import {apiGet, crudCommonOptions} from "../../components/constants.js";
import {authenticationAddDialog} from "../../components/permission/dialog-permission.js";
export function tabMarket() {
return {
title: '数据市场',
icon: 'fa fa-store',
reload: true,
body: [
{
type: 'tabs',
tabs: [
return {
type: 'crud',
api: {
...apiGet('${base}/ware/list_public'),
adaptor: (payload, response, api, context) => {
payload.data = payload.data.map(i => {
return {
...i,
targetId: i.resourceId,
}
})
return payload
}
},
...crudCommonOptions(),
headerToolbar: [
'reload',
],
mode: 'cards',
columnsCount: 3,
card: {
header: {
title: '${name}',
subTitle: '${createdTime}',
avatar: '${icon}',
avatarClassName: 'pull-left thumb-md avatar b-3x m-r'
},
body: '${TRUNCATE(description, 50)}',
actions: [
{
type: 'action',
label: '查看',
actionType: 'dialog',
dialog: {
title: '数据产品详情',
size: 'md',
actions: [],
body: {
type: 'service',
api: apiGet(`\${base}/ware/detail/\${id}`),
body: [
{
type: 'property',
title: '产品信息',
items: [
{
title: '公开数据',
body: {
type: 'crud',
api: {
...apiGet('${base}/ware/list_public'),
adaptor: (payload, response, api, context) => {
payload.data = payload.data.map(i => {
return {
...i,
targetId: i.resourceId,
}
})
return payload
}
},
...crudCommonOptions(),
headerToolbar: [
'reload',
],
mode: 'cards',
card: {
header: {
title: '${name}',
subTitle: '${createdTime}',
description: '${description}',
avatar: '${icon}',
avatarClassName: 'pull-left thumb-md avatar b-3x m-r'
},
actions: [
{
type: 'action',
label: '查看',
...wareDetailDialog(),
},
{
type: 'action',
label: '申请授权',
...authenticationAddDialog(),
}
]
},
}
label: '名称',
content: '${name}',
},
{
title: '我的数据',
body: {
type: 'crud',
api: apiGet('${base}/ware/list'),
...crudCommonOptions(),
headerToolbar: [
'reload',
{
type: 'action',
label: '',
icon: 'fa fa-plus',
...wareAddDialog()
},
],
columns: [
{
name: 'name',
label: '名称',
width: 200,
},
{
name: 'description',
label: '描述',
},
mappingField('state', '状态', permissionStateMapping),
timeField('createdTime', '创建时间'),
operationField('操作', undefined, [
{
type: 'action',
label: '查看',
level: 'link',
...wareDetailDialog(),
},
{
visibleOn: "${state === 'CHECKING'}",
type: 'action',
label: '撤销',
level: 'link',
confirmTitle: '确认撤销',
confirmText: '确认撤销名称为「${name}」的确权申请吗?',
actionType: 'ajax',
api: apiGet('${base}/ware/retract/${id}'),
},
{
visibleOn: "${state === 'DRAFT' || state === 'REJECT'}",
type: 'action',
label: '提交',
level: 'link',
confirmTitle: '确认提交',
confirmText: '确认提交名称为「${name}」的确权申请吗?',
actionType: 'ajax',
api: apiGet('${base}/ware/submit/${id}'),
},
{
visibleOn: "${!public}",
type: 'dropdown-button',
level: 'link',
icon: 'fa fa-ellipsis-h',
hideCaret: true,
trigger: 'hover',
buttons: [
{
disabledOn: "${state !== 'DRAFT'}",
type: 'action',
label: '编辑',
level: 'link',
...wareEditeDialog(),
},
{
disabledOn: "${state === 'CHECKING'}",
type: 'action',
label: "删除",
confirmTitle: '确认删除',
confirmText: '确认删除名称为「${name}」的确权申请吗?删除后对应的数据资源处于未确权状态。',
actionType: 'ajax',
api: apiGet('${base}/ware/remove/${id}'),
},
]
},
]),
]
}
label: '归属',
content: '${createdUsername}',
},
]
{
label: '创建时间',
content: '${createdTime}',
},
{
span: 3,
label: '描述',
content: '${description}',
},
]
},
{
type: 'tpl',
tpl: '${content|raw}'
}
]
}
]
}
},
{
type: 'action',
label: '申请授权',
...authenticationAddDialog(),
}
]
}
}
}

View File

@@ -1,9 +1,9 @@
export function tabOverview() {
return {
title: '概览',
icon: 'fa fa-house',
body: [
'hello world'
]
}
return {
title: '概览',
icon: 'fa fa-house',
body: [
'hello world'
]
}
}

View File

@@ -1,196 +1,189 @@
import {
apiGet,
arrayInCheck,
arrayOutCheck,
checkState,
crudCommonOptions,
customerOnly,
mappingField,
operationField,
permissionStateMapping,
providerOnly,
stringField,
stringWrapField,
timeField,
userOnly,
apiGet,
arrayInCheck,
arrayOutCheck,
checkState,
crudCommonOptions,
customerOnly,
mappingField,
operationField,
permissionStateMapping,
providerOnly,
stringField,
stringWrapField,
timeField,
} from "../../components/constants.js";
import {
authenticationAddDialog,
authenticationDetailDialog,
authenticationEditeDialog,
confirmationAddDialog,
confirmationDetailDialog,
confirmationEditeDialog,
authenticationAddDialog,
authenticationDetailDialog,
authenticationEditeDialog,
confirmationAddDialog,
confirmationDetailDialog,
confirmationEditeDialog,
} from "../../components/permission/dialog-permission.js";
export function tabPermissions() {
return {
visibleOn: userOnly,
title: '权属管理',
icon: 'fa fa-key',
reload: true,
return {
type: 'tabs',
tabs: [
{
visibleOn: providerOnly,
title: '确权管理',
body: {
type: 'tabs',
tabs: [
{
visibleOn: providerOnly,
title: '确权管理',
body: {
type: 'crud',
api: {
...apiGet('${base}/confirmation/list')
},
...crudCommonOptions(),
headerToolbar: [
'reload',
{
type: 'action',
label: '',
icon: 'fa fa-plus',
...confirmationAddDialog()
},
],
columns: [
stringField('name', '名称', 200),
stringWrapField('description', '描述'),
mappingField('state', '状态', permissionStateMapping),
timeField('createdTime', '创建时间'),
operationField('操作', undefined, [
{
type: 'action',
label: '查看',
level: 'link',
...confirmationDetailDialog(),
},
{
visibleOn: "${state === 'CHECKING'}",
type: 'action',
label: '撤销',
level: 'link',
confirmTitle: '确认撤销',
confirmText: '确认撤销名称为「${name}」的确权申请吗?',
actionType: 'ajax',
api: apiGet('${base}/confirmation/retract/${id}'),
},
{
visibleOn: "${state === 'DRAFT' || state === 'REJECT'}",
type: 'action',
label: '提交',
level: 'link',
confirmTitle: '确认提交',
confirmText: '确认提交名称为「${name}」的确权申请吗?',
actionType: 'ajax',
api: apiGet('${base}/confirmation/submit/${id}'),
},
{
type: 'dropdown-button',
level: 'link',
icon: 'fa fa-ellipsis-h',
hideCaret: true,
trigger: 'hover',
buttons: [
{
disabledOn: "${state !== 'DRAFT'}",
type: 'action',
label: '编辑',
level: 'link',
...confirmationEditeDialog(),
},
{
disabledOn: "${state === 'CHECKING'}",
type: 'action',
label: "删除",
confirmTitle: '确认删除',
confirmText: '确认删除名称为「${name}」的确权申请吗?删除后对应的数据资源处于未确权状态。',
actionType: 'ajax',
api: apiGet('${base}/confirmation/remove/${id}'),
},
]
},
]),
]
}
},
{
visibleOn: customerOnly,
title: '授权管理',
body: {
type: 'crud',
api: {
...apiGet('${base}/authentication/list')
},
...crudCommonOptions(),
headerToolbar: [
'reload',
{
type: 'action',
label: '',
icon: 'fa fa-plus',
...authenticationAddDialog()
},
],
columns: [
stringField('name', '名称', 200),
stringWrapField('description', '描述'),
mappingField('state', '状态', permissionStateMapping),
timeField('createdTime', '创建时间'),
operationField('操作', undefined, [
{
type: 'action',
label: '查看',
level: 'link',
...authenticationDetailDialog(),
},
{
visibleOn: arrayInCheck([checkState.ownerChecking, checkState.checking], 'state'),
type: 'action',
label: '撤销',
level: 'link',
confirmTitle: '确认撤销',
confirmText: '确认撤销名称为「${name}」的授权申请吗?',
actionType: 'ajax',
api: apiGet('${base}/authentication/retract/${id}'),
},
{
visibleOn: arrayInCheck([checkState.draft], 'state'),
type: 'action',
label: '提交',
level: 'link',
confirmTitle: '确认提交',
confirmText: '确认提交名称为「${name}」的授权申请吗?',
actionType: 'ajax',
api: apiGet('${base}/authentication/submit/${id}'),
},
{
type: 'dropdown-button',
level: 'link',
icon: 'fa fa-ellipsis-h',
hideCaret: true,
trigger: 'hover',
buttons: [
{
disabledOn: arrayOutCheck([checkState.draft], 'state'),
type: 'action',
label: '编辑',
level: 'link',
...authenticationEditeDialog(),
},
{
disabledOn: arrayInCheck([checkState.ownerChecking, checkState.checking], 'state'),
type: 'action',
label: "删除",
confirmTitle: '确认删除',
confirmText: '确认删除名称为「${name}」的确权申请吗?删除后对应的数据资源处于未确权状态。',
actionType: 'ajax',
api: apiGet('${base}/authentication/remove/${id}'),
},
]
},
]),
]
}
},
]
type: 'crud',
api: {
...apiGet('${base}/confirmation/list')
},
...crudCommonOptions(),
headerToolbar: [
'reload',
{
type: 'action',
label: '',
icon: 'fa fa-plus',
...confirmationAddDialog()
},
],
columns: [
stringField('name', '名称', 200),
stringWrapField('description', '描述'),
mappingField('state', '状态', permissionStateMapping),
timeField('createdTime', '创建时间'),
operationField('操作', undefined, [
{
type: 'action',
label: '查看',
level: 'link',
...confirmationDetailDialog(),
},
{
visibleOn: "${state === 'CHECKING'}",
type: 'action',
label: '撤销',
level: 'link',
confirmTitle: '确认撤销',
confirmText: '确认撤销名称为「${name}」的确权申请吗?',
actionType: 'ajax',
api: apiGet('${base}/confirmation/retract/${id}'),
},
{
visibleOn: "${state === 'DRAFT' || state === 'REJECT'}",
type: 'action',
label: '提交',
level: 'link',
confirmTitle: '确认提交',
confirmText: '确认提交名称为「${name}」的确权申请吗?',
actionType: 'ajax',
api: apiGet('${base}/confirmation/submit/${id}'),
},
{
type: 'dropdown-button',
level: 'link',
icon: 'fa fa-ellipsis-h',
hideCaret: true,
trigger: 'hover',
buttons: [
{
disabledOn: "${state !== 'DRAFT'}",
type: 'action',
label: '编辑',
level: 'link',
...confirmationEditeDialog(),
},
{
disabledOn: "${state === 'CHECKING'}",
type: 'action',
label: "删除",
confirmTitle: '确认删除',
confirmText: '确认删除名称为「${name}」的确权申请吗?删除后对应的数据资源处于未确权状态。',
actionType: 'ajax',
api: apiGet('${base}/confirmation/remove/${id}'),
},
]
},
]),
]
}
}
},
{
visibleOn: customerOnly,
title: '授权管理',
body: {
type: 'crud',
api: {
...apiGet('${base}/authentication/list')
},
...crudCommonOptions(),
headerToolbar: [
'reload',
{
type: 'action',
label: '',
icon: 'fa fa-plus',
...authenticationAddDialog()
},
],
columns: [
stringField('name', '名称', 200),
stringWrapField('description', '描述'),
mappingField('state', '状态', permissionStateMapping),
timeField('createdTime', '创建时间'),
operationField('操作', undefined, [
{
type: 'action',
label: '查看',
level: 'link',
...authenticationDetailDialog(),
},
{
visibleOn: arrayInCheck([checkState.ownerChecking, checkState.checking], 'state'),
type: 'action',
label: '撤销',
level: 'link',
confirmTitle: '确认撤销',
confirmText: '确认撤销名称为「${name}」的授权申请吗?',
actionType: 'ajax',
api: apiGet('${base}/authentication/retract/${id}'),
},
{
visibleOn: arrayInCheck([checkState.draft], 'state'),
type: 'action',
label: '提交',
level: 'link',
confirmTitle: '确认提交',
confirmText: '确认提交名称为「${name}」的授权申请吗?',
actionType: 'ajax',
api: apiGet('${base}/authentication/submit/${id}'),
},
{
type: 'dropdown-button',
level: 'link',
icon: 'fa fa-ellipsis-h',
hideCaret: true,
trigger: 'hover',
buttons: [
{
disabledOn: arrayOutCheck([checkState.draft], 'state'),
type: 'action',
label: '编辑',
level: 'link',
...authenticationEditeDialog(),
},
{
disabledOn: arrayInCheck([checkState.ownerChecking, checkState.checking], 'state'),
type: 'action',
label: "删除",
confirmTitle: '确认删除',
confirmText: '确认删除名称为「${name}」的确权申请吗?删除后对应的数据资源处于未确权状态。',
actionType: 'ajax',
api: apiGet('${base}/authentication/remove/${id}'),
},
]
},
]),
]
}
},
]
}
}

View File

@@ -1,12 +1,12 @@
import {administratorOnly} from "../../components/constants.js";
export function tabSettings() {
return {
visibleOn: administratorOnly,
title: '系统管理',
icon: 'fa fa-gear',
body: [
'hello world'
]
}
return {
visibleOn: administratorOnly,
title: '系统管理',
icon: 'fa fa-gear',
body: [
'hello world'
]
}
}

View File

@@ -1,83 +1,76 @@
import {
administratorOnly,
apiGet,
copyField,
crudCommonOptions,
mappingField,
operationField,
timeField,
userRoleMapping,
userStateMapping
apiGet,
copyField,
crudCommonOptions,
mappingField,
operationField,
timeField,
userRoleMapping,
userStateMapping
} from '../../components/constants.js'
import {userCheckDialog, userDetailDialog} from "../../components/user/dialog-user-check.js";
import {userAdministratorRegisterDialog} from "../../components/user/dialog-user-register.js";
export function tabUser() {
return {
visibleOn: administratorOnly,
title: '用户管理',
icon: 'fa fa-user',
reload: true,
body: [
{
type: 'crud',
api: apiGet('${base}/user_management/list'),
...crudCommonOptions(),
headerToolbar: [
'reload',
{
type: 'action',
icon: 'fa fa-plus',
tooltip: '新增账号',
...userAdministratorRegisterDialog(),
},
],
columns: [
copyField(
'username',
'邮箱',
undefined,
undefined,
userDetailDialog(),
),
mappingField('role', '角色', userRoleMapping, 120),
mappingField('state', '账号状态', userStateMapping),
timeField('createdTime', '创建时间'),
timeField('lastLoginTime', '上次登陆时间'),
operationField('操作', undefined, [
{
visibleOn: "${state === 'CHECKING'}",
label: '审核',
icon: 'fa fa-fingerprint',
level: 'primary',
size: 'xs',
...userCheckDialog(),
},
{
visibleOn: "${state === 'NORMAL' && role !== 'ADMINISTRATOR'}",
label: '禁用',
icon: 'fa fa-ban',
level: 'danger',
size: 'xs',
confirmText: '确认禁用账号${username}',
confirmTitle: '禁用账号',
actionType: 'ajax',
api: apiGet('${base}/user_management/disable/${username}'),
},
{
visibleOn: "${state === 'DISABLED' && role !== 'ADMINISTRATOR'}",
label: '启用',
icon: 'fa fa-check',
level: 'success',
size: 'xs',
confirmText: '确认启用账号${username}',
confirmTitle: '启用账号',
actionType: 'ajax',
api: apiGet('${base}/user_management/enable/${username}'),
}
]),
]
}
]
return [
{
type: 'crud',
api: apiGet('${base}/user_management/list'),
...crudCommonOptions(),
headerToolbar: [
'reload',
{
type: 'action',
icon: 'fa fa-plus',
tooltip: '新增账号',
...userAdministratorRegisterDialog(),
},
],
columns: [
copyField(
'username',
'邮箱',
undefined,
undefined,
userDetailDialog(),
),
mappingField('role', '角色', userRoleMapping, 120),
mappingField('state', '账号状态', userStateMapping),
timeField('createdTime', '创建时间'),
timeField('lastLoginTime', '上次登陆时间'),
operationField('操作', undefined, [
{
visibleOn: "${state === 'CHECKING'}",
label: '审核',
icon: 'fa fa-fingerprint',
level: 'primary',
size: 'xs',
...userCheckDialog(),
},
{
visibleOn: "${state === 'NORMAL' && role !== 'ADMINISTRATOR'}",
label: '禁用',
icon: 'fa fa-ban',
level: 'danger',
size: 'xs',
confirmText: '确认禁用账号${username}',
confirmTitle: '禁用账号',
actionType: 'ajax',
api: apiGet('${base}/user_management/disable/${username}'),
},
{
visibleOn: "${state === 'DISABLED' && role !== 'ADMINISTRATOR'}",
label: '启用',
icon: 'fa fa-check',
level: 'success',
size: 'xs',
confirmText: '确认启用账号${username}',
confirmTitle: '启用账号',
actionType: 'ajax',
api: apiGet('${base}/user_management/enable/${username}'),
}
]),
]
}
]
}

View File

@@ -4,74 +4,103 @@ import {userRegisterDialog} from '../../components/user/dialog-user-register.js'
useAmis(information => {
return {
type: 'page',
title: information.title,
subTitle: '统一登陆入口',
className: 'h-screen bg-gray-900',
bodyClassName: 'h-full flex items-start mt-20',
body: [
{
type: 'grid',
columns: [
type: 'wrapper',
className: 'relative w-full max-w-md mx-auto',
body: [
{
xs: 0,
sm: 0,
md: 4,
body: [],
type: 'flex',
justify: 'center',
className: 'mb-8',
items: [
{
type: 'avatar',
src: '/logo.svg',
shape: 'square',
size: 64,
fit: 'contain',
className: 'mr-4 bg-transparent'
},
{
type: 'flex',
direction: 'column',
justify: 'center',
items: [
{
type: 'tpl',
tpl: information.title,
className: 'text-2xl font-bold text-white'
},
{
type: 'tpl',
tpl: '统一登录入口',
className: 'text-lg ml-1 mt-1 text-gray-100'
}
]
}
]
},
{
xs: 12,
sm: 12,
md: 4,
type: 'form',
className: 'bg-white rounded-xl p-10 shadow-2xl',
api: '${base}/user/login',
redirect: '/pages/index/index.html?token=${token}',
mode: 'normal',
wrapWithPanel: false,
body: [
{
type: 'form',
title: '用户登陆',
api: '${base}/user/login',
redirect: '/pages/index/index.html?token=${token}',
mode: 'horizontal',
horizontal: {
left: 2,
},
actions: [
type: 'input-email',
name: 'username',
label: false,
placeholder: '请输入邮箱',
required: true,
clearable: true,
className: 'mb-4',
inputClassName: 'rounded-lg',
},
{
type: 'input-password',
name: 'password',
label: false,
placeholder: '请输入密码',
required: true,
className: 'mb-4',
inputClassName: 'rounded-lg',
},
{
type: 'flex',
justify: 'space-between',
className: 'mb-4',
items: [
{
type: 'action',
label: '注册',
type: 'button',
label: '注册账号',
className: 'text-blue-600 hover:text-blue-700',
level: 'link',
...userRegisterDialog(),
},
{
type: 'action',
actionType: 'submit',
label: '登陆',
level: 'primary',
},
],
body: [
{
type: 'input-email',
name: 'username',
label: '邮箱',
placeholder: '请输入邮箱',
required: true,
clearable: true,
clearValueOnEmpty: true,
},
{
type: 'input-password',
name: 'password',
label: '密码',
placeholder: '请再次输入密码',
required: true,
},
],
type: 'button',
label: '忘记密码?',
level: 'link',
className: 'text-gray-600 hover:text-gray-700'
}
]
},
],
},
{
xs: 0,
sm: 0,
md: 4,
body: [],
},
],
},
],
{
type: 'submit',
label: '登录',
level: 'primary',
className: 'w-full rounded-lg',
size: 'lg'
}
]
}
]
}
]
}
})

View File

@@ -0,0 +1,8 @@
<svg version="1.2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1589 1540" width="1589" height="1540">
<title>China_Telecom_Logo-svg</title>
<style>
.s0 { fill: #FFFFFF }
</style>
<path id="path8564" class="s0"
d="m1004.4 258.8c0 0-27.8-30.7-64.4-30.7 0 0-80.2 0-134.7 173.4 0 0-46.5 151.5-46.5 376.4 0 0 0 212 43.6 361.6 0 0 43.5 151.6 106.9 151.6 0 0 44.6 0 82.2-83.2 0 0 37.6-83.2 53.5-219l118.8-29.7c0 0-30.7 252.7-125.8 416.1 0 0-98 164.5-221.8 164.5 0 0-148.5 0-253.4-222.9 0 0-105-222.9-105-539 0 0 0-316 105-540.9 0 0 104.9-223.9 253.4-223.9 0 0 148.6 0 254.5 227.9zm417.8 304.1c0 0-204.9 169.4-531.7 251.6 0 0-327.7 81.3-588.1 27.8 0 0-260.4-55.5-299-215 0 0-32.7-132.8 110.9-279.4 0 0 141.6-145.6 396-242.7l16.9 65.4c0 0-148.5 63.4-230.7 143.6 0 0-84.2 84.2-65.4 156.6 0 0 24.8 92.1 199 119.8 0 0 173.3 26.8 398.1-28.7 0 0 222.7-55.5 365.3-161.5 0 0 140.6-107 116.8-200.1 0 0-19.8-80.2-162.3-114.9l-21.8-85.2c0 0 185.1 6.9 307.9 68.3 0 0 125.7 61.5 151.5 165.5 0 0 40.6 158.5-163.4 328.9z"/>
</svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

2
gringotts-web/bin/start.sh Executable file
View File

@@ -0,0 +1,2 @@
export JASYPT_ENCRYPTOR_PASSWORD='r#(R,P"Dp^A47>WSn:Wn].gs/+"v:q_Q*An~zF*g-@j@jtSTv5H/,S-3:R?r9R}.'
nohup /home/iap/gringotts/jdk/jdk-11.0.25+9/bin/java -jar /home/iap/gringotts/gringotts-web-1.0.0-SNAPSHOT.jar --spring.profiles.active=build > run.log 2>&1 &

40
gringotts-web/bin/stop.sh Executable file
View File

@@ -0,0 +1,40 @@
#!/bin/bash
original_command="$0"
application_name="gringotts-web-1.0.0-SNAPSHOT.jar"
function get_pid() {
ID=$(ps -ef | grep "$application_name" | grep -v grep | grep -v $original_command | awk '{ print $2 }')
if [[ -z "$ID" ]]; then
ID=$(ps aux | grep "$application_name" | grep -v grep | grep -v $original_command | awk '{print $2}')
if [[ -z "$ID" ]]; then
ID=$(/home/iap/gringotts/jdk/jdk-11.0.25+9/bin/jps -lmvV | grep "$application_name" | awk '{print $1}')
fi
fi
echo $ID
}
pid=$(get_pid)
if [[ -z "$pid" ]]; then
echo "Application is already stopped."
exit 0
fi
echo "Stopping $pid..."
kill $pid
LOOPS=0
while (true); do
cpid=$(get_pid)
if [[ -z "$cpid" ]]; then
echo "Oook! cost:$LOOPS"
break
fi
LOOPS=$(($LOOPS+1))
if [[ $(($LOOPS%15)) -eq 0 ]]; then
echo "Wait timeout, try to force kill $pid..."
kill -9 $pid
fi
sleep 1s
done

View File

@@ -12,6 +12,11 @@
<artifactId>gringotts-web</artifactId>
<dependencies>
<dependency>
<groupId>com.lanyuanxiaoyao</groupId>
<artifactId>flowable</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.eshore</groupId>
<artifactId>gringotts-configuration</artifactId>
@@ -34,6 +39,10 @@
<version>${hibernate.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>

View File

@@ -29,24 +29,24 @@ import org.springframework.scheduling.annotation.EnableAsync;
@EnableConfigurationProperties
@EnableEncryptableProperties
public class WebApplication implements ApplicationRunner {
private final UserService userService;
private final UserService userService;
public WebApplication(UserService userService) {
this.userService = userService;
}
public WebApplication(UserService userService) {
this.userService = userService;
}
public static void main(String[] args) {
SpringApplication.run(WebApplication.class, args);
}
public static void main(String[] args) {
SpringApplication.run(WebApplication.class, args);
}
@Override
public void run(ApplicationArguments args) throws Exception {
// 初始化系统管理员
userService.initial();
}
@Override
public void run(ApplicationArguments args) throws Exception {
// 初始化系统管理员
userService.initial();
}
@Bean
public AuditorAware<User> auditorAware(UserService userService) {
return userService::currentLoginUserOptional;
}
@Bean
public AuditorAware<User> auditorAware(UserService userService) {
return userService::currentLoginUserOptional;
}
}

View File

@@ -16,12 +16,12 @@ import org.springframework.web.bind.annotation.RestControllerAdvice;
*/
@RestControllerAdvice
public class ErrorController {
private static final Logger logger = LoggerFactory.getLogger(ErrorController.class);
private static final Logger logger = LoggerFactory.getLogger(ErrorController.class);
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Throwable.class)
public AmisResponse<Object> errorHandler(Throwable throwable) {
logger.error("Error", throwable);
return AmisResponse.responseError(throwable.getMessage());
}
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Throwable.class)
public AmisResponse<Object> errorHandler(Throwable throwable) {
logger.error("Error", throwable);
return AmisResponse.responseError(throwable.getMessage());
}
}

View File

@@ -12,5 +12,5 @@ import org.springframework.context.annotation.Configuration;
@ConfigurationProperties(prefix = "gringotts.host")
@Configuration
public class HostConfiguration {
private String prefix = "http://127.0.0.1:20080";
private String prefix = "http://127.0.0.1:20080";
}

View File

@@ -12,33 +12,33 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
* web配置
*
* @author wn
* @since 2024-11-14
* @since 2024-11-14
*/
@Slf4j
@Configuration
public class SaTokenConfiguration implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry
.addInterceptor(
new SaInterceptor(handler -> {
SaRouter
.match("/**")
.notMatch("/")
.notMatch("/index.html")
.notMatch("/assets/**")
.notMatch("/pages/**")
.notMatch("/user/**")
.notMatch("/upload/download/**")
.check(r -> {
try {
StpUtil.checkLogin();
} catch (Exception e) {
throw new RuntimeException("账号未登陆", e);
}
});
})
)
.addPathPatterns("/**");
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry
.addInterceptor(
new SaInterceptor(handler -> {
SaRouter
.match("/**")
.notMatch("/")
.notMatch("/index.html")
.notMatch("/assets/**")
.notMatch("/pages/**")
.notMatch("/user/**")
.notMatch("/upload/download/**")
.check(r -> {
try {
StpUtil.checkLogin();
} catch (Exception e) {
throw new RuntimeException("账号未登陆", e);
}
});
})
)
.addPathPatterns("/**");
}
}

View File

@@ -14,80 +14,80 @@ import org.slf4j.LoggerFactory;
* @date 2024-11-14
*/
public class SnowflakeIdGenerator implements IdentifierGenerator {
private static final Logger logger = LoggerFactory.getLogger(SnowflakeIdGenerator.class);
private static final Logger logger = LoggerFactory.getLogger(SnowflakeIdGenerator.class);
@Override
public Serializable generate(SharedSessionContractImplementor session, Object object) {
try {
return Snowflake.next();
} catch (Exception e) {
logger.error("Generate snowflake id failed", e);
throw new RuntimeException(e);
@Override
public Serializable generate(SharedSessionContractImplementor session, Object object) {
try {
return Snowflake.next();
} catch (Exception e) {
logger.error("Generate snowflake id failed", e);
throw new RuntimeException(e);
}
}
private static class Snowflake {
/**
* 起始的时间戳
*/
private final static long START_TIMESTAMP = 1;
/**
* 序列号占用的位数
*/
private final static long SEQUENCE_BIT = 11;
/**
* 序列号最大值
*/
private final static long MAX_SEQUENCE_BIT = ~(-1 << SEQUENCE_BIT);
/**
* 时间戳值向左位移
*/
private final static long TIMESTAMP_OFFSET = SEQUENCE_BIT;
/**
* 序列号
*/
private static long sequence = 0;
/**
* 上一次时间戳
*/
private static long lastTimestamp = -1;
public static synchronized long next() {
long currentTimestamp = nowTimestamp();
if (currentTimestamp < lastTimestamp) {
throw new RuntimeException("Clock have moved backwards.");
}
if (currentTimestamp == lastTimestamp) {
// 相同毫秒内, 序列号自增
sequence = (sequence + 1) & MAX_SEQUENCE_BIT;
// 同一毫秒的序列数已经达到最大
if (sequence == 0) {
currentTimestamp = nextTimestamp();
}
} else {
// 不同毫秒内, 序列号置为0
sequence = 0;
}
lastTimestamp = currentTimestamp;
return (currentTimestamp - START_TIMESTAMP) << TIMESTAMP_OFFSET | sequence;
}
private static class Snowflake {
/**
* 起始的时间戳
*/
private final static long START_TIMESTAMP = 1;
/**
* 序列号占用的位数
*/
private final static long SEQUENCE_BIT = 11;
/**
* 序列号最大值
*/
private final static long MAX_SEQUENCE_BIT = ~(-1 << SEQUENCE_BIT);
/**
* 时间戳值向左位移
*/
private final static long TIMESTAMP_OFFSET = SEQUENCE_BIT;
/**
* 序列号
*/
private static long sequence = 0;
/**
* 上一次时间戳
*/
private static long lastTimestamp = -1;
public static synchronized long next() {
long currentTimestamp = nowTimestamp();
if (currentTimestamp < lastTimestamp) {
throw new RuntimeException("Clock have moved backwards.");
}
if (currentTimestamp == lastTimestamp) {
// 相同毫秒内, 序列号自增
sequence = (sequence + 1) & MAX_SEQUENCE_BIT;
// 同一毫秒的序列数已经达到最大
if (sequence == 0) {
currentTimestamp = nextTimestamp();
}
} else {
// 不同毫秒内, 序列号置为0
sequence = 0;
}
lastTimestamp = currentTimestamp;
return (currentTimestamp - START_TIMESTAMP) << TIMESTAMP_OFFSET | sequence;
}
private static long nextTimestamp() {
long milli = nowTimestamp();
while (milli <= lastTimestamp) {
milli = nowTimestamp();
}
return milli;
}
private static long nowTimestamp() {
return Instant.now().toEpochMilli();
}
private static long nextTimestamp() {
long milli = nowTimestamp();
while (milli <= lastTimestamp) {
milli = nowTimestamp();
}
return milli;
}
private static long nowTimestamp() {
return Instant.now().toEpochMilli();
}
}
}

View File

@@ -14,5 +14,5 @@ import org.springframework.context.annotation.Configuration;
@ConfigurationProperties(prefix = "gringotts.upload")
@Configuration
public class UploadConfiguration {
private String uploadPath = "./upload";
private String uploadPath = "./upload";
}

View File

@@ -7,7 +7,7 @@ package com.eshore.gringotts.web.configuration.amis;
* @date 2023-07-06
*/
public class AmisItemResponse extends AmisMapResponse {
public void setDetail(Object detail) {
getData().put("item", detail);
}
public void setDetail(Object detail) {
getData().put("item", detail);
}
}

View File

@@ -7,24 +7,24 @@ package com.eshore.gringotts.web.configuration.amis;
* @date 2023-07-06
*/
public class AmisListResponse extends AmisMapResponse {
public void setData(Iterable<?> list) {
getData().put("items", list);
}
public void setData(Iterable<?> list) {
getData().put("items", list);
}
public void setTotal(Long total) {
getData().put("total", total);
}
public void setTotal(Long total) {
getData().put("total", total);
}
public void setTotal(Integer total) {
setTotal(total.longValue());
}
public void setTotal(Integer total) {
setTotal(total.longValue());
}
public void setData(Iterable<?> list, Long total) {
setData(list);
setTotal(total);
}
public void setData(Iterable<?> list, Long total) {
setData(list);
setTotal(total);
}
public void setData(Iterable<?> list, Integer total) {
setData(list, total.longValue());
}
public void setData(Iterable<?> list, Integer total) {
setData(list, total.longValue());
}
}

View File

@@ -10,12 +10,12 @@ import java.util.Map;
* @date 2023-07-06
*/
public class AmisMapResponse extends AmisResponse<Map<String, Object>> {
public AmisMapResponse() {
setData(new HashMap<>());
}
public AmisMapResponse() {
setData(new HashMap<>());
}
public AmisMapResponse setData(String key, Object value) {
getData().put(key, value);
return this;
}
public AmisMapResponse setData(String key, Object value) {
getData().put(key, value);
return this;
}
}

View File

@@ -16,91 +16,91 @@ import lombok.ToString;
@Getter
@Setter
public class AmisResponse<T> {
private static final int SUCCESS_STATUS = 0;
private static final int ERROR_STATUS = 500;
private static final String SUCCESS_MESSAGE = "成功";
private static final String ERROR_MESSAGE = "错误";
private Integer status;
@JsonProperty("msg")
private String message;
private T data;
private static final int SUCCESS_STATUS = 0;
private static final int ERROR_STATUS = 500;
private static final String SUCCESS_MESSAGE = "成功";
private static final String ERROR_MESSAGE = "错误";
private Integer status;
@JsonProperty("msg")
private String message;
private T data;
public static AmisResponse<Object> responseError() {
return responseError(ERROR_MESSAGE);
}
public static AmisResponse<Object> responseError() {
return responseError(ERROR_MESSAGE);
}
public static AmisResponse<Object> responseError(String message) {
AmisResponse<Object> response = new AmisResponse<>();
response.setStatus(ERROR_STATUS);
response.setMessage(message);
return response;
}
public static AmisResponse<Object> responseError(String message) {
AmisResponse<Object> response = new AmisResponse<>();
response.setStatus(ERROR_STATUS);
response.setMessage(message);
return response;
}
public static AmisResponse<Object> responseSuccess() {
return responseSuccess(SUCCESS_MESSAGE);
}
public static AmisResponse<Object> responseSuccess() {
return responseSuccess(SUCCESS_MESSAGE);
}
public static AmisResponse<Object> responseSuccess(String message) {
AmisResponse<Object> response = new AmisResponse<>();
response.setStatus(SUCCESS_STATUS);
response.setMessage(message);
return response;
}
public static AmisResponse<Object> responseSuccess(String message) {
AmisResponse<Object> response = new AmisResponse<>();
response.setStatus(SUCCESS_STATUS);
response.setMessage(message);
return response;
}
public static <E> AmisResponse<E> responseSuccess(String message, E data) {
AmisResponse<E> response = new AmisResponse<>();
response.setStatus(SUCCESS_STATUS);
response.setMessage(message);
response.setData(data);
return response;
}
public static <E> AmisResponse<E> responseSuccess(String message, E data) {
AmisResponse<E> response = new AmisResponse<>();
response.setStatus(SUCCESS_STATUS);
response.setMessage(message);
response.setData(data);
return response;
}
public static <E> AmisResponse<E> responseSuccess(E data) {
return responseSuccess(SUCCESS_MESSAGE, data);
}
public static <E> AmisResponse<E> responseSuccess(E data) {
return responseSuccess(SUCCESS_MESSAGE, data);
}
public static AmisMapResponse responseMapData() {
AmisMapResponse response = new AmisMapResponse();
response.setStatus(SUCCESS_STATUS);
response.setMessage(SUCCESS_MESSAGE);
return response;
}
public static AmisMapResponse responseMapData() {
AmisMapResponse response = new AmisMapResponse();
response.setStatus(SUCCESS_STATUS);
response.setMessage(SUCCESS_MESSAGE);
return response;
}
public static AmisMapResponse responseMapData(Map<String, Object> data) {
AmisMapResponse response = responseMapData();
response.setData(data);
return response;
}
public static AmisMapResponse responseMapData(Map<String, Object> data) {
AmisMapResponse response = responseMapData();
response.setData(data);
return response;
}
public static AmisMapResponse responseMapData(String key, Object value) {
AmisMapResponse response = responseMapData();
response.setData(key, value);
return response;
}
public static AmisMapResponse responseMapData(String key, Object value) {
AmisMapResponse response = responseMapData();
response.setData(key, value);
return response;
}
public static AmisListResponse responseListData(Iterable<?> data) {
AmisListResponse response = new AmisListResponse();
response.setStatus(SUCCESS_STATUS);
response.setMessage(SUCCESS_MESSAGE);
response.setData(data);
return response;
}
public static AmisListResponse responseListData(Iterable<?> data) {
AmisListResponse response = new AmisListResponse();
response.setStatus(SUCCESS_STATUS);
response.setMessage(SUCCESS_MESSAGE);
response.setData(data);
return response;
}
public static AmisListResponse responseListData(Iterable<?> data, Integer total) {
AmisListResponse response = responseListData(data);
response.setTotal(total);
return response;
}
public static AmisListResponse responseListData(Iterable<?> data, Integer total) {
AmisListResponse response = responseListData(data);
response.setTotal(total);
return response;
}
public static AmisListResponse responseListData(Iterable<?> data, Long total) {
AmisListResponse response = responseListData(data);
response.setTotal(total);
return response;
}
public static AmisListResponse responseListData(Iterable<?> data, Long total) {
AmisListResponse response = responseListData(data);
response.setTotal(total);
return response;
}
public static AmisItemResponse responseItemData(Object detail) {
AmisItemResponse response = new AmisItemResponse();
response.setDetail(detail);
return response;
}
public static AmisItemResponse responseItemData(Object detail) {
AmisItemResponse response = new AmisItemResponse();
response.setDetail(detail);
return response;
}
}

View File

@@ -7,5 +7,5 @@ import com.eshore.gringotts.web.configuration.amis.AmisResponse;
* @date 2024-11-28
*/
public interface DetailController<DETAIL_ITEM> {
AmisResponse<DETAIL_ITEM> detail(Long id) throws Exception;
AmisResponse<DETAIL_ITEM> detail(Long id) throws Exception;
}

View File

@@ -9,7 +9,7 @@ import org.eclipse.collections.api.list.ImmutableList;
* @date 2024-11-28
*/
public interface ListController<LIST_ITEM> {
AmisResponse<ImmutableList<LIST_ITEM>> list() throws Exception;
AmisResponse<ImmutableList<LIST_ITEM>> list() throws Exception;
AmisResponse<ImmutableList<LIST_ITEM>> list(Query query) throws Exception;
AmisResponse<ImmutableList<LIST_ITEM>> list(Query query) throws Exception;
}

View File

@@ -7,5 +7,5 @@ import com.eshore.gringotts.web.configuration.amis.AmisResponse;
* @date 2024-11-28
*/
public interface RemoveController {
AmisResponse<Object> remove(Long id) throws Exception;
AmisResponse<Object> remove(Long id) throws Exception;
}

View File

@@ -7,5 +7,5 @@ import com.eshore.gringotts.web.configuration.amis.AmisResponse;
* @date 2024-11-28
*/
public interface SaveController<SAVE_ITEM> {
AmisResponse<Long> save(SAVE_ITEM item) throws Exception;
AmisResponse<Long> save(SAVE_ITEM item) throws Exception;
}

View File

@@ -19,66 +19,66 @@ import org.springframework.web.bind.annotation.RequestBody;
*/
@Slf4j
public abstract class SimpleControllerSupport<ENTITY extends SimpleEntity, SAVE_ITEM, LIST_ITEM, DETAIL_ITEM> implements SimpleController<SAVE_ITEM, LIST_ITEM, DETAIL_ITEM> {
protected static final String SAVE = "/save";
protected static final String LIST = "/list";
protected static final String DETAIL = "/detail/{id}";
protected static final String REMOVE = "/remove/{id}";
protected static final String SAVE = "/save";
protected static final String LIST = "/list";
protected static final String DETAIL = "/detail/{id}";
protected static final String REMOVE = "/remove/{id}";
private final SimpleServiceSupport<ENTITY> service;
protected final SimpleServiceSupport<ENTITY> service;
public SimpleControllerSupport(SimpleServiceSupport<ENTITY> service) {
this.service = service;
public SimpleControllerSupport(SimpleServiceSupport<ENTITY> service) {
this.service = service;
}
@PostMapping(SAVE)
@Override
public AmisResponse<Long> save(@RequestBody SAVE_ITEM item) throws Exception {
return AmisResponse.responseSuccess(service.save(fromSaveItem(item)));
}
@GetMapping(LIST)
@Override
public AmisResponse<ImmutableList<LIST_ITEM>> list() throws Exception {
return AmisResponse.responseSuccess(service.list().collect(entity -> {
try {
return toListItem(entity);
} catch (Exception e) {
throw new RuntimeException(e);
}
}));
}
@PostMapping(LIST)
@Override
public AmisResponse<ImmutableList<LIST_ITEM>> list(@RequestBody Query query) throws Exception {
if (ObjectUtil.isNull(query)) {
return AmisResponse.responseSuccess(Lists.immutable.empty());
}
return AmisResponse.responseSuccess(service.list(query).collect(entity -> {
try {
return toListItem(entity);
} catch (Exception e) {
throw new RuntimeException(e);
}
}));
}
@PostMapping(SAVE)
@Override
public AmisResponse<Long> save(@RequestBody SAVE_ITEM item) throws Exception {
return AmisResponse.responseSuccess(service.save(fromSaveItem(item)));
}
@GetMapping(DETAIL)
@Override
public AmisResponse<DETAIL_ITEM> detail(@PathVariable Long id) throws Exception {
return AmisResponse.responseSuccess(toDetailItem(service.detailOrThrow(id)));
}
@GetMapping(LIST)
@Override
public AmisResponse<ImmutableList<LIST_ITEM>> list() throws Exception {
return AmisResponse.responseSuccess(service.list().collect(entity -> {
try {
return toListItem(entity);
} catch (Exception e) {
throw new RuntimeException(e);
}
}));
}
@GetMapping(REMOVE)
@Override
public AmisResponse<Object> remove(@PathVariable Long id) {
service.remove(id);
return AmisResponse.responseSuccess();
}
@PostMapping(LIST)
@Override
public AmisResponse<ImmutableList<LIST_ITEM>> list(@RequestBody Query query) throws Exception {
if (ObjectUtil.isNull(query)) {
return AmisResponse.responseSuccess(Lists.immutable.empty());
}
return AmisResponse.responseSuccess(service.list(query).collect(entity -> {
try {
return toListItem(entity);
} catch (Exception e) {
throw new RuntimeException(e);
}
}));
}
protected abstract ENTITY fromSaveItem(SAVE_ITEM item) throws Exception;
@GetMapping(DETAIL)
@Override
public AmisResponse<DETAIL_ITEM> detail(@PathVariable Long id) throws Exception {
return AmisResponse.responseSuccess(toDetailItem(service.detailOrThrow(id)));
}
protected abstract LIST_ITEM toListItem(ENTITY entity) throws Exception;
@GetMapping(REMOVE)
@Override
public AmisResponse<Object> remove(@PathVariable Long id) {
service.remove(id);
return AmisResponse.responseSuccess();
}
protected abstract ENTITY fromSaveItem(SAVE_ITEM item) throws Exception;
protected abstract LIST_ITEM toListItem(ENTITY entity) throws Exception;
protected abstract DETAIL_ITEM toDetailItem(ENTITY entity) throws Exception;
protected abstract DETAIL_ITEM toDetailItem(ENTITY entity) throws Exception;
}

View File

@@ -12,50 +12,50 @@ import org.eclipse.collections.api.map.ImmutableMap;
*/
@Data
public class Query {
private Queryable query;
private ImmutableList<Sortable> sort;
private Pageable page;
private Queryable query;
private ImmutableList<Sortable> sort;
private Pageable page;
@Data
public static class Queryable {
private ImmutableList<String> nullEqual;
private ImmutableList<String> notNullEqual;
private ImmutableList<String> empty;
private ImmutableList<String> notEmpty;
private ImmutableMap<String, ?> equal;
private ImmutableMap<String, ?> notEqual;
private ImmutableMap<String, String> like;
private ImmutableMap<String, String> notLike;
private ImmutableMap<String, ?> great;
private ImmutableMap<String, ?> less;
private ImmutableMap<String, ?> greatEqual;
private ImmutableMap<String, ?> lessEqual;
private ImmutableMap<String, ImmutableList<?>> in;
private ImmutableMap<String, ImmutableList<?>> notIn;
private ImmutableMap<String, Between> between;
private ImmutableMap<String, Between> notBetween;
@Data
public static class Queryable {
private ImmutableList<String> nullEqual;
private ImmutableList<String> notNullEqual;
private ImmutableList<String> empty;
private ImmutableList<String> notEmpty;
private ImmutableMap<String, ?> equal;
private ImmutableMap<String, ?> notEqual;
private ImmutableMap<String, String> like;
private ImmutableMap<String, String> notLike;
private ImmutableMap<String, ?> great;
private ImmutableMap<String, ?> less;
private ImmutableMap<String, ?> greatEqual;
private ImmutableMap<String, ?> lessEqual;
private ImmutableMap<String, ImmutableList<?>> in;
private ImmutableMap<String, ImmutableList<?>> notIn;
private ImmutableMap<String, Between> between;
private ImmutableMap<String, Between> notBetween;
@Data
public static class Between {
private String start;
private String end;
}
public static class Between {
private String start;
private String end;
}
}
@Data
public static class Sortable {
private String column;
private Direction direction;
@Data
public static class Sortable {
private String column;
private Direction direction;
public enum Direction {
ASC,
DESC,
}
public enum Direction {
ASC,
DESC,
}
}
@Data
public static class Pageable {
private Integer page;
private Integer size;
}
@Data
public static class Pageable {
private Integer page;
private Integer size;
}
}

View File

@@ -1,6 +1,6 @@
package com.eshore.gringotts.web.domain.base.entity;
import com.eshore.gringotts.web.domain.entity.CheckOrder;
import com.eshore.gringotts.web.domain.entity.order.CheckOrder;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.EntityListeners;
@@ -20,40 +20,40 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class CheckingNeededEntity extends LogicDeleteEntity {
private String description;
private String description;
@Column(nullable = false)
@Enumerated(EnumType.STRING)
private State state = State.DRAFT;
@Column(nullable = false)
@Enumerated(EnumType.STRING)
private State state = State.DRAFT;
@OneToOne(cascade = CascadeType.DETACH, fetch = FetchType.LAZY)
@ToString.Exclude
private CheckOrder order;
@OneToOne(cascade = CascadeType.DETACH, fetch = FetchType.LAZY)
@ToString.Exclude
private CheckOrder order;
public enum State {
/**
* 无确权
*/
NONE,
/**
* 草稿
*/
DRAFT,
/**
* 审查中
*/
CHECKING,
/**
* 用户审核
*/
OWNER_CHECKING,
/**
* 正常
*/
NORMAL,
/**
* 驳回
*/
REJECT,
}
public enum State {
/**
* 无确权
*/
NONE,
/**
* 草稿
*/
DRAFT,
/**
* 审查中
*/
CHECKING,
/**
* 用户审核
*/
OWNER_CHECKING,
/**
* 正常
*/
NORMAL,
/**
* 驳回
*/
REJECT,
}
}

View File

@@ -17,35 +17,35 @@ import lombok.NoArgsConstructor;
@AllArgsConstructor
@JsonDeserialize(using = FileInfo.FileInfoDeserializer.class)
public final class FileInfo {
private String id;
private String name;
private String filename;
private Long value;
private String state;
private String id;
private String name;
private String filename;
private Long value;
private String state;
public FileInfo(DataFile dataFile) {
this.id = dataFile.getId().toString();
this.name = dataFile.getFilename();
this.filename = dataFile.getFilename();
this.value = dataFile.getId();
this.state = "uploaded";
}
public FileInfo(DataFile dataFile) {
this.id = dataFile.getId().toString();
this.name = dataFile.getFilename();
this.filename = dataFile.getFilename();
this.value = dataFile.getId();
this.state = "uploaded";
}
public static final class FileInfoDeserializer extends JsonDeserializer<FileInfo> {
@Override
public FileInfo deserialize(JsonParser parser, DeserializationContext context) throws IOException {
TreeNode root = parser.readValueAsTree();
if (root instanceof ObjectNode) {
ObjectNode node = (ObjectNode) root;
return new FileInfo(
node.get("id").asText(),
node.get("name").asText(),
node.get("filename").asText(),
node.get("value").asLong(),
node.get("state").asText()
);
}
return null;
}
public static final class FileInfoDeserializer extends JsonDeserializer<FileInfo> {
@Override
public FileInfo deserialize(JsonParser parser, DeserializationContext context) throws IOException {
TreeNode root = parser.readValueAsTree();
if (root instanceof ObjectNode) {
ObjectNode node = (ObjectNode) root;
return new FileInfo(
node.get("id").asText(),
node.get("name").asText(),
node.get("filename").asText(),
node.get("value").asLong(),
node.get("state").asText()
);
}
return null;
}
}
}

View File

@@ -22,24 +22,24 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class IdOnlyEntity {
@Id
@GeneratedValue(generator = "snowflake")
@GenericGenerator(name = "snowflake", strategy = "com.eshore.gringotts.web.configuration.SnowflakeIdGenerator")
private Long id;
@Id
@GeneratedValue(generator = "snowflake")
@GenericGenerator(name = "snowflake", strategy = "com.eshore.gringotts.web.configuration.SnowflakeIdGenerator")
private Long id;
@Override
public final boolean equals(Object object) {
if (this == object)
return true;
if (!(object instanceof IdOnlyEntity))
return false;
@Override
public final boolean equals(Object object) {
if (this == object)
return true;
if (!(object instanceof IdOnlyEntity))
return false;
IdOnlyEntity that = (IdOnlyEntity) object;
return id.equals(that.id);
}
IdOnlyEntity that = (IdOnlyEntity) object;
return id.equals(that.id);
}
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public int hashCode() {
return id.hashCode();
}
}

View File

@@ -20,8 +20,8 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class LogicDeleteEntity extends SimpleEntity {
public static final String LOGIC_DELETE_CLAUSE = "deleted = false";
public static final String LOGIC_DELETE_CLAUSE = "deleted = false";
@Column(nullable = false)
private Boolean deleted = false;
@Column(nullable = false)
private Boolean deleted = false;
}

View File

@@ -20,8 +20,8 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class LogicDeleteIdOnlyEntity extends IdOnlyEntity {
public static final String LOGIC_DELETE_CLAUSE = "deleted = false";
public static final String LOGIC_DELETE_CLAUSE = "deleted = false";
@Column(nullable = false)
private Boolean deleted = false;
@Column(nullable = false)
private Boolean deleted = false;
}

View File

@@ -10,5 +10,5 @@ import lombok.Data;
*/
@Data
public abstract class SimpleDetailItem<ENTITY> {
private Long id;
private Long id;
}

View File

@@ -30,18 +30,18 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class SimpleEntity extends IdOnlyEntity {
@CreatedDate
private LocalDateTime createdTime;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
@ToString.Exclude
@CreatedBy
private User createdUser;
@LastModifiedDate
private LocalDateTime modifiedTime;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
@ToString.Exclude
@LastModifiedBy
private User modifiedUser;
@CreatedDate
private LocalDateTime createdTime;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
@ToString.Exclude
@CreatedBy
private User createdUser;
@LastModifiedDate
private LocalDateTime modifiedTime;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
@ToString.Exclude
@LastModifiedBy
private User modifiedUser;
}

View File

@@ -11,7 +11,7 @@ import lombok.Data;
*/
@Data
public abstract class SimpleListItem<ENTITY> {
private Long id;
private String createdUsername;
private LocalDateTime createdTime;
private Long id;
private String createdUsername;
private LocalDateTime createdTime;
}

View File

@@ -10,5 +10,5 @@ import lombok.Data;
*/
@Data
public abstract class SimpleSaveItem<ENTITY> {
private Long id;
private Long id;
}

View File

@@ -1,6 +1,10 @@
package com.eshore.gringotts.web.domain.base.service;
import com.eshore.gringotts.web.domain.entity.CheckOrder;
import com.eshore.gringotts.web.domain.base.entity.LogicDeleteEntity;
import com.eshore.gringotts.web.domain.base.repository.SimpleRepository;
import com.eshore.gringotts.web.domain.entity.order.CheckOrder;
import com.eshore.gringotts.web.domain.service.UserService;
import javax.persistence.EntityManager;
import org.eclipse.collections.api.map.ImmutableMap;
/**
@@ -9,6 +13,16 @@ import org.eclipse.collections.api.map.ImmutableMap;
* @author lanyuanxiaoyao
* @date 2024-11-28
*/
public interface CheckingService {
void onChecked(CheckOrder order, CheckOrder.Operation operation, ImmutableMap<String, Object> parameters);
public abstract class CheckingService<ENTITY extends LogicDeleteEntity> extends LogicDeleteService<ENTITY> {
public CheckingService(SimpleRepository<ENTITY, Long> repository, UserService userService, EntityManager manager) {
super(repository, userService, manager);
}
abstract public void submit(Long id) throws Exception;
abstract public void retract(Long id) throws Exception;
abstract public void onChecked(CheckOrder order, CheckOrder.Operation operation, ImmutableMap<String, Object> parameters);
abstract public ImmutableMap<String, Object> archive(ENTITY entity);
}

View File

@@ -7,13 +7,8 @@ import com.eshore.gringotts.web.domain.base.repository.SimpleRepository;
import com.eshore.gringotts.web.domain.service.UserService;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.collections.api.list.ImmutableList;
/**
* @author lanyuanxiaoyao
@@ -21,24 +16,19 @@ import org.eclipse.collections.api.list.ImmutableList;
*/
@Slf4j
public abstract class LogicDeleteService<ENTITY extends LogicDeleteEntity> extends SimpleServiceSupport<ENTITY> {
private final EntityManager manager;
private final EntityManager manager;
public LogicDeleteService(SimpleRepository<ENTITY, Long> repository, UserService userService, EntityManager manager) {
super(repository, userService);
this.manager = manager;
}
public LogicDeleteService(SimpleRepository<ENTITY, Long> repository, UserService userService, EntityManager manager) {
super(repository, userService);
this.manager = manager;
}
@Override
protected ImmutableList<Predicate> listPredicate(Root<ENTITY> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
return super.listPredicate(root, query, builder).newWith(builder.equal(root.get("deleted"), false));
}
@Transactional(rollbackOn = Throwable.class)
@Override
public void remove(Long id) {
String entityName = ClassUtil.getTypeArgument(this.getClass()).getSimpleName();
Query query = manager.createQuery(StrUtil.format("update {} entity set deleted=true where id=?1", entityName));
query.setParameter(1, id);
query.executeUpdate();
}
@Transactional(rollbackOn = Throwable.class)
@Override
public void remove(Long id) {
String entityName = ClassUtil.getTypeArgument(this.getClass()).getSimpleName();
Query query = manager.createQuery(StrUtil.format("update {} entity set entity.deleted = true where id = ?1", entityName));
query.setParameter(1, id);
query.executeUpdate();
}
}

View File

@@ -11,21 +11,23 @@ import org.eclipse.collections.api.set.ImmutableSet;
* @date 2024-11-28
*/
public interface SimpleService<ENTITY extends SimpleEntity> {
Long save(ENTITY entity) throws Exception;
Long save(ENTITY entity) throws Exception;
ImmutableList<ENTITY> list() throws Exception;
Long count() throws Exception;
ImmutableList<ENTITY> list(ImmutableSet<Long> ids) throws Exception;
ImmutableList<ENTITY> list() throws Exception;
ImmutableList<ENTITY> list(Query query) throws Exception;
ImmutableList<ENTITY> list(ImmutableSet<Long> ids) throws Exception;
Optional<ENTITY> detailOptional(Long id) throws Exception;
ImmutableList<ENTITY> list(Query query) throws Exception;
ENTITY detail(Long id) throws Exception;
Optional<ENTITY> detailOptional(Long id) throws Exception;
ENTITY detailOrThrow(Long id) throws Exception;
ENTITY detail(Long id) throws Exception;
ENTITY detailOrNull(Long id) throws Exception;
ENTITY detailOrThrow(Long id) throws Exception;
void remove(Long id) throws Exception;
ENTITY detailOrNull(Long id) throws Exception;
void remove(Long id) throws Exception;
}

View File

@@ -32,206 +32,218 @@ import org.springframework.data.domain.Sort;
*/
@Slf4j
public abstract class SimpleServiceSupport<ENTITY extends SimpleEntity> implements SimpleService<ENTITY> {
protected final SimpleRepository<ENTITY, Long> repository;
protected final UserService userService;
protected final SimpleRepository<ENTITY, Long> repository;
protected final UserService userService;
public SimpleServiceSupport(SimpleRepository<ENTITY, Long> repository, UserService userService) {
this.repository = repository;
this.userService = userService;
public SimpleServiceSupport(SimpleRepository<ENTITY, Long> repository, UserService userService) {
this.repository = repository;
this.userService = userService;
}
@Transactional(rollbackOn = Throwable.class)
@Override
public Long save(ENTITY entity) {
if (ObjectUtil.isNotNull(entity.getId())) {
Long id = entity.getId();
ENTITY targetEntity = repository.findById(entity.getId()).orElseThrow(() -> new IdNotFoundException(id));
BeanUtil.copyProperties(
entity,
targetEntity,
CopyOptions.create()
.setIgnoreProperties(
IdOnlyEntity_.ID,
SimpleEntity_.CREATED_USER,
SimpleEntity_.CREATED_TIME,
SimpleEntity_.MODIFIED_USER,
SimpleEntity_.MODIFIED_TIME
)
);
entity = targetEntity;
}
entity = repository.save(entity);
return entity.getId();
}
@Override
public Long count() throws Exception {
return repository.count(
(root, query, builder) ->
builder.and(
listPredicate(root, query, builder)
.reject(ObjectUtil::isNull)
.toArray(new Predicate[]{})
)
);
}
@Override
public ImmutableList<ENTITY> list() throws Exception {
return Lists.immutable.ofAll(repository.findAll(
(root, query, builder) ->
builder.and(
listPredicate(root, query, builder)
.reject(ObjectUtil::isNull)
.toArray(new Predicate[]{})
)
));
}
@Override
public ImmutableList<ENTITY> list(ImmutableSet<Long> ids) throws Exception {
return Lists.immutable.ofAll(repository.findAll(
(root, query, builder) -> {
MutableList<Predicate> predicates = Lists.mutable.ofAll(listPredicate(root, query, builder));
predicates.add(builder.in(root.get("id")).value(ids));
return builder.and(predicates.reject(ObjectUtil::isNull).toArray(new Predicate[predicates.size()]));
}
));
}
private <Y> Path<Y> column(Root<ENTITY> root, String column) {
String[] columns = StrUtil.splitToArray(column, "/");
Path<Y> path = root.get(columns[0]);
for (int i = 1; i < columns.length; i++) {
path = path.get(columns[i]);
}
return path;
}
@SuppressWarnings({"unchecked", "rawtypes"})
private <Y> Object value(Path<Y> column, Object value) {
Class<?> javaType = column.getJavaType();
if (EnumUtil.isEnum(javaType)) {
return EnumUtil.fromString((Class<Enum>) javaType, (String) value);
}
return value;
}
@SuppressWarnings("unchecked")
protected ImmutableList<Predicate> queryPredicates(Query.Queryable queryable, Root<ENTITY> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
MutableList<Predicate> predicates = Lists.mutable.empty();
if (ObjectUtil.isEmpty(queryable)) {
return predicates.toImmutable();
}
if (ObjectUtil.isNotEmpty(queryable.getNullEqual())) {
queryable.getNullEqual().forEach(column -> predicates.add(builder.isNull(column(root, column))));
}
if (ObjectUtil.isNotEmpty(queryable.getNotNullEqual())) {
queryable.getNotNullEqual().forEach(column -> predicates.add(builder.isNull(column(root, column))));
}
if (ObjectUtil.isNotEmpty(queryable.getEmpty())) {
queryable.getEmpty().forEach(column -> predicates.add(builder.isEmpty(column(root, column))));
}
if (ObjectUtil.isNotEmpty(queryable.getNotEmpty())) {
queryable.getNotEmpty().forEach(column -> predicates.add(builder.isNotEmpty(column(root, column))));
}
if (ObjectUtil.isNotEmpty(queryable.getEqual())) {
queryable.getEqual().forEachKeyValue((column, value) -> {
Path<Object> path = column(root, column);
predicates.add(builder.equal(path, value(path, value)));
});
}
if (ObjectUtil.isNotEmpty(queryable.getNotEqual())) {
queryable.getEqual().forEachKeyValue((column, value) -> {
Path<Object> path = column(root, column);
predicates.add(builder.notEqual(path, value(path, value)));
});
}
if (ObjectUtil.isNotEmpty(queryable.getLike())) {
queryable.getLike().forEachKeyValue((column, value) -> predicates.add(builder.like(column(root, column), value)));
}
if (ObjectUtil.isNotEmpty(queryable.getNotLike())) {
queryable.getNotLike().forEachKeyValue((column, value) -> predicates.add(builder.notLike(column(root, column), value)));
}
if (ObjectUtil.isNotEmpty(queryable.getGreat())) {
queryable.getGreat().forEachKeyValue((column, value) -> predicates.add(builder.greaterThan(column(root, column), (Comparable<Object>) value)));
}
if (ObjectUtil.isNotEmpty(queryable.getLess())) {
queryable.getLess().forEachKeyValue((column, value) -> predicates.add(builder.lessThan(column(root, column), (Comparable<Object>) value)));
}
if (ObjectUtil.isNotEmpty(queryable.getGreatEqual())) {
queryable.getGreatEqual().forEachKeyValue((column, value) -> predicates.add(builder.greaterThanOrEqualTo(column(root, column), (Comparable<Object>) value)));
}
if (ObjectUtil.isNotEmpty(queryable.getLessEqual())) {
queryable.getLessEqual().forEachKeyValue((column, value) -> predicates.add(builder.lessThanOrEqualTo(column(root, column), (Comparable<Object>) value)));
}
if (ObjectUtil.isNotEmpty(queryable.getIn())) {
queryable.getIn().forEachKeyValue((column, value) -> predicates.add(builder.in(column(root, column)).value(value)));
}
if (ObjectUtil.isNotEmpty(queryable.getNotIn())) {
queryable.getNotIn().forEachKeyValue((column, value) -> predicates.add(builder.in(column(root, column)).value(value).not()));
}
if (ObjectUtil.isNotEmpty(queryable.getBetween())) {
queryable.getBetween().forEachKeyValue((column, value) -> predicates.add(builder.between(column(root, column), value.getStart(), value.getEnd())));
}
if (ObjectUtil.isNotEmpty(queryable.getNotBetween())) {
queryable.getNotBetween().forEachKeyValue((column, value) -> predicates.add(builder.between(column(root, column), value.getStart(), value.getEnd())));
}
return predicates.toImmutable();
}
protected ImmutableList<Predicate> listPredicate(Root<ENTITY> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
User user = userService.currentLoginUser();
if (User.isNotAdministrator(user)) {
return Lists.immutable.of(builder.equal(root.get(SimpleEntity_.createdUser), user));
}
return Lists.immutable.empty();
}
@Override
public ImmutableList<ENTITY> list(Query listQuery) throws Exception {
return Lists.immutable.ofAll(repository.findAll(
(root, query, builder) -> {
MutableList<Predicate> predicates = Lists.mutable.ofAll(listPredicate(root, query, builder));
predicates.addAllIterable(queryPredicates(listQuery.getQuery(), root, query, builder));
return builder.and(predicates.reject(ObjectUtil::isNull).toArray(new Predicate[predicates.size()]));
},
Sort.by(SimpleEntity_.CREATED_TIME).descending()
));
}
@Override
public Optional<ENTITY> detailOptional(Long id) {
if (ObjectUtil.isNull(id)) {
return Optional.empty();
}
return repository.findOne(
(root, query, builder) -> {
MutableList<Predicate> predicates = Lists.mutable.ofAll(listPredicate(root, query, builder));
predicates.add(builder.equal(root.get(IdOnlyEntity_.id), id));
return builder.and(predicates.reject(ObjectUtil::isNull).toArray(new Predicate[predicates.size()]));
}
);
}
@Override
public ENTITY detail(Long id) {
return detailOrNull(id);
}
@Override
public ENTITY detailOrThrow(Long id) {
return detailOptional(id).orElseThrow(() -> new IdNotFoundException(id));
}
@Override
public ENTITY detailOrNull(Long id) {
return detailOptional(id).orElse(null);
}
@Transactional(rollbackOn = Throwable.class)
@Override
public void remove(Long id) {
if (ObjectUtil.isNotNull(id)) {
repository.deleteById(id);
}
}
public static final class IdNotFoundException extends RuntimeException {
public IdNotFoundException() {
super("资源不存在");
}
@Transactional(rollbackOn = Throwable.class)
@Override
public Long save(ENTITY entity) {
if (ObjectUtil.isNotNull(entity.getId())) {
Long id = entity.getId();
ENTITY targetEntity = repository.findById(entity.getId()).orElseThrow(() -> new IdNotFoundException(id));
BeanUtil.copyProperties(
entity,
targetEntity,
CopyOptions.create()
.setIgnoreProperties(
IdOnlyEntity_.ID,
SimpleEntity_.CREATED_USER,
SimpleEntity_.CREATED_TIME,
SimpleEntity_.MODIFIED_USER,
SimpleEntity_.MODIFIED_TIME
)
);
entity = targetEntity;
}
entity = repository.save(entity);
return entity.getId();
}
@Override
public ImmutableList<ENTITY> list() throws Exception {
return Lists.immutable.ofAll(repository.findAll(
(root, query, builder) ->
builder.and(
listPredicate(root, query, builder)
.reject(ObjectUtil::isNull)
.toArray(new Predicate[]{})
)
));
}
@Override
public ImmutableList<ENTITY> list(ImmutableSet<Long> ids) throws Exception {
return Lists.immutable.ofAll(repository.findAll(
(root, query, builder) -> {
MutableList<Predicate> predicates = Lists.mutable.ofAll(listPredicate(root, query, builder));
predicates.add(builder.in(root.get("id")).value(ids));
return builder.and(predicates.reject(ObjectUtil::isNull).toArray(new Predicate[predicates.size()]));
}
));
}
private <Y> Path<Y> column(Root<ENTITY> root, String column) {
String[] columns = StrUtil.splitToArray(column, "/");
Path<Y> path = root.get(columns[0]);
for (int i = 1; i < columns.length; i++) {
path = path.get(columns[i]);
}
return path;
}
@SuppressWarnings({"unchecked", "rawtypes"})
private <Y> Object value(Path<Y> column, Object value) {
Class<?> javaType = column.getJavaType();
if (EnumUtil.isEnum(javaType)) {
return EnumUtil.fromString((Class<Enum>) javaType, (String) value);
}
return value;
}
@SuppressWarnings("unchecked")
private ImmutableList<Predicate> queryPredicates(Query.Queryable queryable, Root<ENTITY> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
MutableList<Predicate> predicates = Lists.mutable.empty();
if (ObjectUtil.isEmpty(queryable)) {
return predicates.toImmutable();
}
if (ObjectUtil.isNotEmpty(queryable.getNullEqual())) {
queryable.getNullEqual().forEach(column -> predicates.add(builder.isNull(column(root, column))));
}
if (ObjectUtil.isNotEmpty(queryable.getNotNullEqual())) {
queryable.getNotNullEqual().forEach(column -> predicates.add(builder.isNull(column(root, column))));
}
if (ObjectUtil.isNotEmpty(queryable.getEmpty())) {
queryable.getEmpty().forEach(column -> predicates.add(builder.isEmpty(column(root, column))));
}
if (ObjectUtil.isNotEmpty(queryable.getNotEmpty())) {
queryable.getNotEmpty().forEach(column -> predicates.add(builder.isNotEmpty(column(root, column))));
}
if (ObjectUtil.isNotEmpty(queryable.getEqual())) {
queryable.getEqual().forEachKeyValue((column, value) -> {
Path<Object> path = column(root, column);
predicates.add(builder.equal(path, value(path, value)));
});
}
if (ObjectUtil.isNotEmpty(queryable.getNotEqual())) {
queryable.getEqual().forEachKeyValue((column, value) -> {
Path<Object> path = column(root, column);
predicates.add(builder.notEqual(path, value(path, value)));
});
}
if (ObjectUtil.isNotEmpty(queryable.getLike())) {
queryable.getLike().forEachKeyValue((column, value) -> predicates.add(builder.like(column(root, column), value)));
}
if (ObjectUtil.isNotEmpty(queryable.getNotLike())) {
queryable.getNotLike().forEachKeyValue((column, value) -> predicates.add(builder.notLike(column(root, column), value)));
}
if (ObjectUtil.isNotEmpty(queryable.getGreat())) {
queryable.getGreat().forEachKeyValue((column, value) -> predicates.add(builder.greaterThan(column(root, column), (Comparable<Object>) value)));
}
if (ObjectUtil.isNotEmpty(queryable.getLess())) {
queryable.getLess().forEachKeyValue((column, value) -> predicates.add(builder.lessThan(column(root, column), (Comparable<Object>) value)));
}
if (ObjectUtil.isNotEmpty(queryable.getGreatEqual())) {
queryable.getGreatEqual().forEachKeyValue((column, value) -> predicates.add(builder.greaterThanOrEqualTo(column(root, column), (Comparable<Object>) value)));
}
if (ObjectUtil.isNotEmpty(queryable.getLessEqual())) {
queryable.getLessEqual().forEachKeyValue((column, value) -> predicates.add(builder.lessThanOrEqualTo(column(root, column), (Comparable<Object>) value)));
}
if (ObjectUtil.isNotEmpty(queryable.getIn())) {
queryable.getIn().forEachKeyValue((column, value) -> predicates.add(builder.in(column(root, column)).value(value)));
}
if (ObjectUtil.isNotEmpty(queryable.getNotIn())) {
queryable.getNotIn().forEachKeyValue((column, value) -> predicates.add(builder.in(column(root, column)).value(value).not()));
}
if (ObjectUtil.isNotEmpty(queryable.getBetween())) {
queryable.getBetween().forEachKeyValue((column, value) -> predicates.add(builder.between(column(root, column), value.getStart(), value.getEnd())));
}
if (ObjectUtil.isNotEmpty(queryable.getNotBetween())) {
queryable.getNotBetween().forEachKeyValue((column, value) -> predicates.add(builder.between(column(root, column), value.getStart(), value.getEnd())));
}
return predicates.toImmutable();
}
protected ImmutableList<Predicate> listPredicate(Root<ENTITY> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
User user = userService.currentLoginUser();
if (User.isNotAdministrator(user)) {
return Lists.immutable.of(builder.equal(root.get(SimpleEntity_.createdUser), user));
}
return Lists.immutable.empty();
}
@Override
public ImmutableList<ENTITY> list(Query listQuery) throws Exception {
return Lists.immutable.ofAll(repository.findAll(
(root, query, builder) -> {
MutableList<Predicate> predicates = Lists.mutable.ofAll(listPredicate(root, query, builder));
predicates.addAllIterable(queryPredicates(listQuery.getQuery(), root, query, builder));
return builder.and(predicates.reject(ObjectUtil::isNull).toArray(new Predicate[predicates.size()]));
},
Sort.by(SimpleEntity_.CREATED_TIME).descending()
));
}
@Override
public Optional<ENTITY> detailOptional(Long id) {
if (ObjectUtil.isNull(id)) {
return Optional.empty();
}
return repository.findOne(
(root, query, builder) -> {
MutableList<Predicate> predicates = Lists.mutable.ofAll(listPredicate(root, query, builder));
predicates.add(builder.equal(root.get(IdOnlyEntity_.id), id));
return builder.and(predicates.reject(ObjectUtil::isNull).toArray(new Predicate[predicates.size()]));
}
);
}
@Override
public ENTITY detail(Long id) {
return detailOrNull(id);
}
@Override
public ENTITY detailOrThrow(Long id) {
return detailOptional(id).orElseThrow(() -> new IdNotFoundException(id));
}
@Override
public ENTITY detailOrNull(Long id) {
return detailOptional(id).orElse(null);
}
@Transactional(rollbackOn = Throwable.class)
@Override
public void remove(Long id) {
if (ObjectUtil.isNotNull(id)) {
repository.deleteById(id);
}
}
public static final class IdNotFoundException extends RuntimeException {
public IdNotFoundException() {
super("资源不存在");
}
public IdNotFoundException(Long id) {
super(StrUtil.format("ID为{}的资源不存在", id));
}
public IdNotFoundException(Long id) {
super(StrUtil.format("ID为{}的资源不存在", id));
}
}
}

View File

@@ -1,6 +1,5 @@
package com.eshore.gringotts.web.domain.controller;
import com.eshore.gringotts.web.configuration.amis.AmisResponse;
import com.eshore.gringotts.web.domain.base.controller.SimpleControllerSupport;
import com.eshore.gringotts.web.domain.base.entity.FileInfo;
import com.eshore.gringotts.web.domain.base.entity.SimpleListItem;
@@ -9,7 +8,6 @@ import com.eshore.gringotts.web.domain.entity.Authentication;
import com.eshore.gringotts.web.domain.service.AuthenticationService;
import com.eshore.gringotts.web.domain.service.DataFileService;
import com.eshore.gringotts.web.domain.service.DataResourceService;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.time.LocalDateTime;
import lombok.Data;
import lombok.EqualsAndHashCode;
@@ -17,8 +15,6 @@ import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.collections.api.factory.Sets;
import org.eclipse.collections.api.set.ImmutableSet;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@@ -30,101 +26,87 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("authentication")
public class AuthenticationController extends SimpleControllerSupport<Authentication, AuthenticationController.SaveItem, AuthenticationController.ListItem, AuthenticationController.DetailItem> {
private final AuthenticationService authenticationService;
private final DataResourceService dataResourceService;
private final DataFileService dataFileService;
private final DataResourceService dataResourceService;
private final DataFileService dataFileService;
public AuthenticationController(AuthenticationService service, DataResourceService dataResourceService, DataFileService dataFileService) {
super(service);
this.authenticationService = service;
this.dataResourceService = dataResourceService;
this.dataFileService = dataFileService;
public AuthenticationController(AuthenticationService service, DataResourceService dataResourceService, DataFileService dataFileService) {
super(service);
this.dataResourceService = dataResourceService;
this.dataFileService = dataFileService;
}
@Override
protected Authentication fromSaveItem(SaveItem item) throws Exception {
Authentication authentication = new Authentication();
authentication.setId(item.getId());
authentication.setDescription(item.getDescription());
authentication.setTarget(dataResourceService.detailOrThrow(item.getTargetId()));
authentication.setEvidences(dataFileService.list(item.getEvidenceFiles().collect(FileInfo::getValue)).toSet());
authentication.setActiveTime(item.getActiveTime());
authentication.setExpiredTime(item.getExpiredTime());
return authentication;
}
@Override
protected ListItem toListItem(Authentication entity) {
return new ListItem(entity);
}
@Override
protected DetailItem toDetailItem(Authentication entity) {
return new DetailItem(entity);
}
@Data
@EqualsAndHashCode(callSuper = true)
public static class SaveItem extends SimpleSaveItem<Authentication> {
private Long targetId;
private String description;
private ImmutableSet<FileInfo> evidenceFiles;
private LocalDateTime activeTime;
private LocalDateTime expiredTime;
}
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
public static final class ListItem extends SimpleListItem<Authentication> {
private String name;
private String description;
private String state;
public ListItem(Authentication authentication) {
this.setId(authentication.getId());
this.setName(authentication.getTarget().getName());
this.setDescription(authentication.getDescription());
this.setState(authentication.getState().name());
this.setCreatedUsername(authentication.getCreatedUser().getUsername());
this.setCreatedTime(authentication.getCreatedTime());
}
}
@GetMapping("/submit/{id}")
public AmisResponse<Object> submit(@PathVariable Long id) throws JsonProcessingException {
authenticationService.submit(id);
return AmisResponse.responseSuccess();
}
@GetMapping("/retract/{id}")
public AmisResponse<Object> retract(@PathVariable Long id) {
authenticationService.retract(id);
return AmisResponse.responseSuccess();
}
@Override
protected Authentication fromSaveItem(SaveItem item) throws Exception {
Authentication authentication = new Authentication();
authentication.setId(item.getId());
authentication.setDescription(item.getDescription());
authentication.setTarget(dataResourceService.detailOrThrow(item.getTargetId()));
authentication.setEvidences(dataFileService.list(item.getEvidenceFiles().collect(FileInfo::getValue)).toSet());
authentication.setActiveTime(item.getActiveTime());
authentication.setExpiredTime(item.getExpiredTime());
return authentication;
}
@Override
protected ListItem toListItem(Authentication entity) {
return new ListItem(entity);
}
@Override
protected DetailItem toDetailItem(Authentication entity) {
return new DetailItem(entity);
}
@Data
@EqualsAndHashCode(callSuper = true)
public static class SaveItem extends SimpleSaveItem<Authentication> {
private Long targetId;
private String description;
private ImmutableSet<FileInfo> evidenceFiles;
private LocalDateTime activeTime;
private LocalDateTime expiredTime;
}
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
public static final class ListItem extends SimpleListItem<Authentication> {
private String name;
private String description;
private String state;
public ListItem(Authentication authentication) {
this.setId(authentication.getId());
this.setName(authentication.getTarget().getName());
this.setDescription(authentication.getDescription());
this.setState(authentication.getState().name());
this.setCreatedUsername(authentication.getCreatedUser().getUsername());
this.setCreatedTime(authentication.getCreatedTime());
}
}
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
public static final class DetailItem extends SaveItem {
private String targetName;
private LocalDateTime createdTime;
private String createdUsername;
private LocalDateTime modifiedTime;
private String modifiedUsername;
public DetailItem(Authentication authentication) {
this.setId(authentication.getId());
this.setTargetId(authentication.getTarget().getId());
this.setTargetName(authentication.getTarget().getName());
this.setDescription(authentication.getDescription());
this.setEvidenceFiles(Sets.immutable.ofAll(authentication.getEvidences()).collect(FileInfo::new));
this.setActiveTime(authentication.getActiveTime());
this.setExpiredTime(authentication.getExpiredTime());
this.setCreatedTime(authentication.getCreatedTime());
this.setCreatedUsername(authentication.getCreatedUser().getUsername());
this.setModifiedTime(authentication.getModifiedTime());
this.setModifiedUsername(authentication.getModifiedUser().getUsername());
}
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
public static final class DetailItem extends SaveItem {
private String targetName;
private LocalDateTime createdTime;
private String createdUsername;
private LocalDateTime modifiedTime;
private String modifiedUsername;
public DetailItem(Authentication authentication) {
this.setId(authentication.getId());
this.setTargetId(authentication.getTarget().getId());
this.setTargetName(authentication.getTarget().getName());
this.setDescription(authentication.getDescription());
this.setEvidenceFiles(Sets.immutable.ofAll(authentication.getEvidences()).collect(FileInfo::new));
this.setActiveTime(authentication.getActiveTime());
this.setExpiredTime(authentication.getExpiredTime());
this.setCreatedTime(authentication.getCreatedTime());
this.setCreatedUsername(authentication.getCreatedUser().getUsername());
this.setModifiedTime(authentication.getModifiedTime());
this.setModifiedUsername(authentication.getModifiedUser().getUsername());
}
}
}

View File

@@ -3,9 +3,9 @@ package com.eshore.gringotts.web.domain.controller;
import com.eshore.gringotts.web.configuration.amis.AmisResponse;
import com.eshore.gringotts.web.domain.base.controller.ListController;
import com.eshore.gringotts.web.domain.base.controller.query.Query;
import com.eshore.gringotts.web.domain.entity.CheckOrder;
import com.eshore.gringotts.web.domain.entity.order.CheckOrder;
import com.eshore.gringotts.web.domain.entity.order.node.CheckOrderNode;
import com.eshore.gringotts.web.domain.service.CheckOrderService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.time.LocalDateTime;
@@ -32,58 +32,63 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("check_order")
public class CheckOrderController implements ListController<CheckOrderController.ListItem> {
private final CheckOrderService checkOrderService;
private final ObjectMapper mapper;
private final CheckOrderService checkOrderService;
private final ObjectMapper mapper;
public CheckOrderController(CheckOrderService checkOrderService, Jackson2ObjectMapperBuilder builder) {
this.checkOrderService = checkOrderService;
this.mapper = builder.build();
}
public CheckOrderController(CheckOrderService checkOrderService, Jackson2ObjectMapperBuilder builder) {
this.checkOrderService = checkOrderService;
this.mapper = builder.build();
}
@GetMapping("/list")
@Override
public AmisResponse<ImmutableList<CheckOrderController.ListItem>> list() throws Exception {
return AmisResponse.responseSuccess(checkOrderService.list().collect(this::toListItem));
}
@GetMapping("/list")
@Override
public AmisResponse<ImmutableList<CheckOrderController.ListItem>> list() throws Exception {
return AmisResponse.responseSuccess(checkOrderService.list().collect(this::toListItem));
}
@PostMapping("/list")
@Override
public AmisResponse<ImmutableList<ListItem>> list(@RequestBody Query query) throws Exception {
return AmisResponse.responseSuccess(checkOrderService.list().collect(this::toListItem));
}
@PostMapping("/list")
@Override
public AmisResponse<ImmutableList<ListItem>> list(@RequestBody Query query) throws Exception {
return AmisResponse.responseSuccess(checkOrderService.list().collect(this::toListItem));
}
@SneakyThrows
private ListItem toListItem(CheckOrder order) {
ListItem item = new ListItem();
item.setCheckOrderId(order.getId());
item.setDescription(order.getDescription());
item.setType(order.getType());
item.setParameters(mapper.readValue(order.getParameters(), new TypeReference<>() {}));
item.setState(order.getState());
item.setCreatedUsername(order.getCreatedUser().getUsername());
item.setCreatedTime(order.getCreatedTime());
item.setModifiedUsername(order.getModifiedUser().getUsername());
item.setModifiedTime(order.getModifiedTime());
return item;
}
@GetMapping("/approve/{id}")
public AmisResponse<Object> approve(@PathVariable Long id) {
checkOrderService.approve(id);
return AmisResponse.responseSuccess();
}
@GetMapping("/operation/{id}/{operation}")
public AmisResponse<Object> operation(@PathVariable Long id, @PathVariable CheckOrder.Operation operation) throws JsonProcessingException {
log.info("id:{}, operation:{}", id, operation);
checkOrderService.operation(id, operation);
return AmisResponse.responseSuccess();
}
@GetMapping("/reject/{id}")
public AmisResponse<Object> reject(@PathVariable Long id) {
checkOrderService.reject(id);
return AmisResponse.responseSuccess();
}
@Data
public static final class ListItem {
private Long checkOrderId;
private String description;
private CheckOrder.Type type;
private ImmutableMap<String, Object> parameters;
private CheckOrder.State state;
private LocalDateTime createdTime;
private String createdUsername;
private LocalDateTime modifiedTime;
private String modifiedUsername;
}
@SneakyThrows
private ListItem toListItem(CheckOrder order) {
ListItem item = new ListItem();
item.setCheckOrderId(order.getId());
item.setDescription(order.getDescription());
item.setCurrentNode(order.getCurrentNode());
item.setParameters(mapper.readValue(order.getContext(), new TypeReference<>() {}));
item.setState(order.getState());
item.setCreatedUsername(order.getCreatedUser().getUsername());
item.setCreatedTime(order.getCreatedTime());
item.setModifiedUsername(order.getModifiedUser().getUsername());
item.setModifiedTime(order.getModifiedTime());
return item;
}
@Data
public static final class ListItem {
private Long checkOrderId;
private String description;
private CheckOrderNode currentNode;
private ImmutableMap<String, Object> parameters;
private CheckOrder.State state;
private LocalDateTime createdTime;
private String createdUsername;
private LocalDateTime modifiedTime;
private String modifiedUsername;
}
}

View File

@@ -29,93 +29,87 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("confirmation")
public class ConfirmationController extends SimpleControllerSupport<Confirmation, ConfirmationController.SaveItem, ConfirmationController.ListItem, ConfirmationController.DetailItem> {
private final ConfirmationService confirmationService;
private final DataResourceService dataResourceService;
private final DataFileService dataFileService;
private final ConfirmationService confirmationService;
private final DataResourceService dataResourceService;
private final DataFileService dataFileService;
public ConfirmationController(ConfirmationService service, ConfirmationService confirmationService, DataResourceService dataResourceService, DataFileService dataFileService) {
super(service);
this.confirmationService = confirmationService;
this.dataResourceService = dataResourceService;
this.dataFileService = dataFileService;
public ConfirmationController(ConfirmationService service, DataResourceService dataResourceService, DataFileService dataFileService) {
super(service);
this.confirmationService = service;
this.dataResourceService = dataResourceService;
this.dataFileService = dataFileService;
}
@GetMapping("submit/{id}")
public AmisResponse<Object> submit(@PathVariable Long id) throws JsonProcessingException {
confirmationService.submit(id);
return AmisResponse.responseSuccess();
}
@Override
protected Confirmation fromSaveItem(SaveItem item) throws Exception {
Confirmation confirmation = new Confirmation();
confirmation.setId(item.getId());
confirmation.setDescription(item.getDescription());
confirmation.setTarget(dataResourceService.detailOrThrow(item.getTargetId()));
confirmation.setEvidences(dataFileService.list(item.getEvidenceFiles().collect(FileInfo::getValue)).toSet());
return confirmation;
}
@Override
protected ListItem toListItem(Confirmation entity) {
return new ListItem(entity);
}
@Override
protected DetailItem toDetailItem(Confirmation entity) {
return new DetailItem(entity);
}
@Data
@EqualsAndHashCode(callSuper = true)
public static class SaveItem extends SimpleSaveItem<Confirmation> {
private Long targetId;
private String description;
private ImmutableSet<FileInfo> evidenceFiles;
}
@Data
@EqualsAndHashCode(callSuper = true)
public static final class ListItem extends SimpleListItem<Confirmation> {
private String name;
private String description;
private String state;
public ListItem(Confirmation confirmation) {
this.setId(confirmation.getId());
this.setName(confirmation.getTarget().getName());
this.setDescription(confirmation.getDescription());
this.setState(confirmation.getState().name());
this.setCreatedUsername(confirmation.getCreatedUser().getUsername());
this.setCreatedTime(confirmation.getCreatedTime());
}
}
@GetMapping("/submit/{id}")
public AmisResponse<Object> submit(@PathVariable Long id) throws JsonProcessingException {
confirmationService.submit(id);
return AmisResponse.responseSuccess();
}
@GetMapping("/retract/{id}")
public AmisResponse<Object> retract(@PathVariable Long id) {
confirmationService.retract(id);
return AmisResponse.responseSuccess();
}
@Override
protected Confirmation fromSaveItem(SaveItem item) throws Exception {
Confirmation confirmation = new Confirmation();
confirmation.setId(item.getId());
confirmation.setDescription(item.getDescription());
confirmation.setTarget(dataResourceService.detailOrThrow(item.getTargetId()));
confirmation.setEvidences(dataFileService.list(item.getEvidenceFiles().collect(FileInfo::getValue)).toSet());
return confirmation;
}
@Override
protected ListItem toListItem(Confirmation entity) {
return new ListItem(entity);
}
@Override
protected DetailItem toDetailItem(Confirmation entity) {
return new DetailItem(entity);
}
@Data
@EqualsAndHashCode(callSuper = true)
public static class SaveItem extends SimpleSaveItem<Confirmation> {
private Long targetId;
private String description;
private ImmutableSet<FileInfo> evidenceFiles;
}
@Data
@EqualsAndHashCode(callSuper = true)
public static final class ListItem extends SimpleListItem<Confirmation> {
private String name;
private String description;
private String state;
public ListItem(Confirmation confirmation) {
this.setId(confirmation.getId());
this.setName(confirmation.getTarget().getName());
this.setDescription(confirmation.getDescription());
this.setState(confirmation.getState().name());
this.setCreatedUsername(confirmation.getCreatedUser().getUsername());
this.setCreatedTime(confirmation.getCreatedTime());
}
}
@Data
@EqualsAndHashCode(callSuper = true)
public static final class DetailItem extends SaveItem {
private String targetName;
private LocalDateTime createdTime;
private String createdUsername;
private LocalDateTime modifiedTime;
private String modifiedUsername;
public DetailItem(Confirmation confirmation) {
this.setId(confirmation.getId());
this.setTargetId(confirmation.getTarget().getId());
this.setTargetName(confirmation.getTarget().getName());
this.setDescription(confirmation.getDescription());
this.setEvidenceFiles(Sets.immutable.ofAll(confirmation.getEvidences()).collect(FileInfo::new));
this.setCreatedTime(confirmation.getCreatedTime());
this.setCreatedUsername(confirmation.getCreatedUser().getUsername());
this.setModifiedTime(confirmation.getModifiedTime());
this.setModifiedUsername(confirmation.getModifiedUser().getUsername());
}
@Data
@EqualsAndHashCode(callSuper = true)
public static final class DetailItem extends SaveItem {
private String targetName;
private LocalDateTime createdTime;
private String createdUsername;
private LocalDateTime modifiedTime;
private String modifiedUsername;
public DetailItem(Confirmation confirmation) {
this.setId(confirmation.getId());
this.setTargetId(confirmation.getTarget().getId());
this.setTargetName(confirmation.getTarget().getName());
this.setDescription(confirmation.getDescription());
this.setEvidenceFiles(Sets.immutable.ofAll(confirmation.getEvidences()).collect(FileInfo::new));
this.setCreatedTime(confirmation.getCreatedTime());
this.setCreatedUsername(confirmation.getCreatedUser().getUsername());
this.setModifiedTime(confirmation.getModifiedTime());
this.setModifiedUsername(confirmation.getModifiedUser().getUsername());
}
}
}

View File

@@ -41,179 +41,179 @@ import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/upload")
public class DataFileController {
private final HostConfiguration hostConfiguration;
private final DataFileService dataFileService;
private final String uploadFolderPath;
private final String cacheFolderPath;
private final String sliceFolderPath;
private final HostConfiguration hostConfiguration;
private final DataFileService dataFileService;
private final String uploadFolderPath;
private final String cacheFolderPath;
private final String sliceFolderPath;
public DataFileController(HostConfiguration hostConfiguration, UploadConfiguration uploadConfiguration, DataFileService dataFileService) {
this.hostConfiguration = hostConfiguration;
this.dataFileService = dataFileService;
public DataFileController(HostConfiguration hostConfiguration, UploadConfiguration uploadConfiguration, DataFileService dataFileService) {
this.hostConfiguration = hostConfiguration;
this.dataFileService = dataFileService;
this.uploadFolderPath = uploadConfiguration.getUploadPath();
this.cacheFolderPath = StrUtil.format("{}/cache", uploadFolderPath);
this.sliceFolderPath = StrUtil.format("{}/slice", uploadFolderPath);
this.uploadFolderPath = uploadConfiguration.getUploadPath();
this.cacheFolderPath = StrUtil.format("{}/cache", uploadFolderPath);
this.sliceFolderPath = StrUtil.format("{}/slice", uploadFolderPath);
}
@PostMapping("")
public AmisResponse<FinishResponse> upload(@RequestParam("file") MultipartFile file) throws IOException {
String filename = file.getOriginalFilename();
Long id = dataFileService.initialDataFile(filename);
String url = StrUtil.format("{}/upload/download/{}", hostConfiguration.getPrefix(), id);
byte[] bytes = file.getBytes();
String originMd5 = SecureUtil.md5(new ByteArrayInputStream(bytes));
File targetFile = new File(StrUtil.format("{}/{}", uploadFolderPath, originMd5));
if (targetFile.exists()) {
dataFileService.updateDataFile(id, FileUtil.getAbsolutePath(targetFile), FileUtil.size(targetFile), originMd5, file.getContentType());
return AmisResponse.responseSuccess(new FinishResponse(id, filename, url, url));
}
@PostMapping("")
public AmisResponse<FinishResponse> upload(@RequestParam("file") MultipartFile file) throws IOException {
String filename = file.getOriginalFilename();
Long id = dataFileService.initialDataFile(filename);
String url = StrUtil.format("{}/upload/download/{}", hostConfiguration.getPrefix(), id);
byte[] bytes = file.getBytes();
String originMd5 = SecureUtil.md5(new ByteArrayInputStream(bytes));
File targetFile = new File(StrUtil.format("{}/{}", uploadFolderPath, originMd5));
if (targetFile.exists()) {
dataFileService.updateDataFile(id, FileUtil.getAbsolutePath(targetFile), FileUtil.size(targetFile), originMd5, file.getContentType());
return AmisResponse.responseSuccess(new FinishResponse(id, filename, url, url));
}
File cacheFile = new File(StrUtil.format("{}/{}", cacheFolderPath, id));
cacheFile = FileUtil.writeBytes(bytes, cacheFile);
String targetMd5 = SecureUtil.md5(cacheFile);
if (!StrUtil.equals(originMd5, targetMd5)) {
throw new RuntimeException("文件上传失败,校验不匹配");
}
FileUtil.move(cacheFile, targetFile, true);
dataFileService.updateDataFile(id, FileUtil.getAbsolutePath(targetFile), FileUtil.size(targetFile), targetMd5, file.getContentType());
return AmisResponse.responseSuccess(new FinishResponse(id, filename, url, url));
File cacheFile = new File(StrUtil.format("{}/{}", cacheFolderPath, id));
cacheFile = FileUtil.writeBytes(bytes, cacheFile);
String targetMd5 = SecureUtil.md5(cacheFile);
if (!StrUtil.equals(originMd5, targetMd5)) {
throw new RuntimeException("文件上传失败,校验不匹配");
}
FileUtil.move(cacheFile, targetFile, true);
dataFileService.updateDataFile(id, FileUtil.getAbsolutePath(targetFile), FileUtil.size(targetFile), targetMd5, file.getContentType());
return AmisResponse.responseSuccess(new FinishResponse(id, filename, url, url));
}
@GetMapping("/download/{id}")
public void download(@PathVariable Long id, HttpServletResponse response) throws IOException {
DataFile dataFile = dataFileService.downloadFile(id);
File targetFile = new File(dataFile.getPath());
response.setHeader("Access-Control-Expose-Headers", "Content-Type");
response.setHeader("Content-Type", dataFile.getType());
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setHeader("Content-Disposition", StrUtil.format("attachment; filename={}", dataFile.getFilename()));
IoUtil.copy(new FileInputStream(targetFile), response.getOutputStream());
@GetMapping("/download/{id}")
public void download(@PathVariable Long id, HttpServletResponse response) throws IOException {
DataFile dataFile = dataFileService.downloadFile(id);
File targetFile = new File(dataFile.getPath());
response.setHeader("Access-Control-Expose-Headers", "Content-Type");
response.setHeader("Content-Type", dataFile.getType());
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setHeader("Content-Disposition", StrUtil.format("attachment; filename={}", dataFile.getFilename()));
IoUtil.copy(new FileInputStream(targetFile), response.getOutputStream());
}
@PostMapping("/start")
public AmisResponse<StartResponse> start(@RequestBody StartRequest request) {
log.info("Request: {}", request);
Long id = dataFileService.initialDataFile(request.filename);
return AmisResponse.responseSuccess(new StartResponse(id.toString()));
}
@PostMapping("/slice")
public AmisResponse<SliceResponse> slice(
@RequestParam("uploadId")
Long uploadId,
@RequestParam("partNumber")
Integer sequence,
@RequestParam("partSize")
Long size,
@RequestParam("file")
MultipartFile file
) throws IOException {
byte[] bytes = file.getBytes();
String md5 = SecureUtil.md5(new ByteArrayInputStream(bytes));
String targetFilename = StrUtil.format("{}-{}", sequence, md5);
String targetFilePath = sliceFilePath(uploadId, targetFilename);
FileUtil.mkParentDirs(targetFilePath);
FileUtil.writeBytes(bytes, targetFilePath);
return AmisResponse.responseSuccess(new SliceResponse(targetFilename));
}
private String sliceFilePath(Long uploadId, String sliceFilename) {
return StrUtil.format("{}/{}/{}", sliceFolderPath, uploadId, sliceFilename);
}
@PostMapping("finish")
public AmisResponse<FinishResponse> finish(@RequestBody FinishRequest request) {
if (request.partList.anySatisfy(part -> !FileUtil.exist(sliceFilePath(request.uploadId, part.eTag)))) {
throw new RuntimeException("文件校验失败,请重新上传");
}
@PostMapping("/start")
public AmisResponse<StartResponse> start(@RequestBody StartRequest request) {
log.info("Request: {}", request);
Long id = dataFileService.initialDataFile(request.filename);
return AmisResponse.responseSuccess(new StartResponse(id.toString()));
}
@PostMapping("/slice")
public AmisResponse<SliceResponse> slice(
@RequestParam("uploadId")
Long uploadId,
@RequestParam("partNumber")
Integer sequence,
@RequestParam("partSize")
Long size,
@RequestParam("file")
MultipartFile file
) throws IOException {
byte[] bytes = file.getBytes();
String md5 = SecureUtil.md5(new ByteArrayInputStream(bytes));
String targetFilename = StrUtil.format("{}-{}", sequence, md5);
String targetFilePath = sliceFilePath(uploadId, targetFilename);
FileUtil.mkParentDirs(targetFilePath);
FileUtil.writeBytes(bytes, targetFilePath);
return AmisResponse.responseSuccess(new SliceResponse(targetFilename));
}
private String sliceFilePath(Long uploadId, String sliceFilename) {
return StrUtil.format("{}/{}/{}", sliceFolderPath, uploadId, sliceFilename);
}
@PostMapping("finish")
public AmisResponse<FinishResponse> finish(@RequestBody FinishRequest request) {
if (request.partList.anySatisfy(part -> !FileUtil.exist(sliceFilePath(request.uploadId, part.eTag)))) {
throw new RuntimeException("文件校验失败,请重新上传");
}
try {
File cacheFile = new File(StrUtil.format("{}/{}", cacheFolderPath, request.uploadId));
FileUtil.mkParentDirs(cacheFile);
if (cacheFile.createNewFile()) {
try (FileOutputStream fos = new FileOutputStream(cacheFile)) {
try (FileChannel fosChannel = fos.getChannel()) {
for (FinishRequest.Part part : request.partList) {
File sliceFile = new File(sliceFilePath(request.uploadId, part.eTag));
try (FileInputStream fis = new FileInputStream(sliceFile)) {
try (FileChannel fisChannel = fis.getChannel()) {
fisChannel.transferTo(0, fisChannel.size(), fosChannel);
}
}
}
}
try {
File cacheFile = new File(StrUtil.format("{}/{}", cacheFolderPath, request.uploadId));
FileUtil.mkParentDirs(cacheFile);
if (cacheFile.createNewFile()) {
try (FileOutputStream fos = new FileOutputStream(cacheFile)) {
try (FileChannel fosChannel = fos.getChannel()) {
for (FinishRequest.Part part : request.partList) {
File sliceFile = new File(sliceFilePath(request.uploadId, part.eTag));
try (FileInputStream fis = new FileInputStream(sliceFile)) {
try (FileChannel fisChannel = fis.getChannel()) {
fisChannel.transferTo(0, fisChannel.size(), fosChannel);
}
String md5 = SecureUtil.md5(cacheFile);
File targetFile = new File(StrUtil.format("{}/{}", uploadFolderPath, md5));
if (!targetFile.exists()) {
FileUtil.move(cacheFile, targetFile, true);
}
String absolutePath = FileUtil.getAbsolutePath(targetFile);
dataFileService.updateDataFile(
request.uploadId,
absolutePath,
FileUtil.size(targetFile),
SecureUtil.md5(targetFile),
FileUtil.getMimeType(absolutePath)
);
return AmisResponse.responseSuccess(new FinishResponse(
request.uploadId,
request.filename,
request.uploadId.toString(),
StrUtil.format("{}/upload/download/{}", hostConfiguration.getPrefix(), request.uploadId)
));
} else {
throw new RuntimeException("合并文件失败");
}
}
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
} finally {
FileUtil.del(StrUtil.format("{}/{}", cacheFolderPath, request.uploadId));
FileUtil.del(StrUtil.format("{}/{}", sliceFolderPath, request.uploadId));
}
}
}
@Data
public static final class StartRequest {
private String name;
private String filename;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public static final class StartResponse {
private String uploadId;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public static final class SliceResponse {
@JsonProperty("eTag")
private String eTag;
}
@Data
public static final class FinishRequest {
private String filename;
private Long uploadId;
private ImmutableList<Part> partList;
@Data
public static final class Part {
private Integer partNumber;
@JsonProperty("eTag")
private String eTag;
String md5 = SecureUtil.md5(cacheFile);
File targetFile = new File(StrUtil.format("{}/{}", uploadFolderPath, md5));
if (!targetFile.exists()) {
FileUtil.move(cacheFile, targetFile, true);
}
String absolutePath = FileUtil.getAbsolutePath(targetFile);
dataFileService.updateDataFile(
request.uploadId,
absolutePath,
FileUtil.size(targetFile),
SecureUtil.md5(targetFile),
FileUtil.getMimeType(absolutePath)
);
return AmisResponse.responseSuccess(new FinishResponse(
request.uploadId,
request.filename,
request.uploadId.toString(),
StrUtil.format("{}/upload/download/{}", hostConfiguration.getPrefix(), request.uploadId)
));
} else {
throw new RuntimeException("合并文件失败");
}
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
} finally {
FileUtil.del(StrUtil.format("{}/{}", cacheFolderPath, request.uploadId));
FileUtil.del(StrUtil.format("{}/{}", sliceFolderPath, request.uploadId));
}
}
@Data
public static final class StartRequest {
private String name;
private String filename;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public static final class StartResponse {
private String uploadId;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public static final class SliceResponse {
@JsonProperty("eTag")
private String eTag;
}
@Data
public static final class FinishRequest {
private String filename;
private Long uploadId;
private ImmutableList<Part> partList;
@Data
@NoArgsConstructor
@AllArgsConstructor
public static final class FinishResponse {
private Long id;
private String filename;
private String value;
private String url;
public static final class Part {
private Integer partNumber;
@JsonProperty("eTag")
private String eTag;
}
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public static final class FinishResponse {
private Long id;
private String filename;
private String value;
private String url;
}
}

View File

@@ -47,262 +47,262 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/data_resource")
public class DataResourceController extends SimpleControllerSupport<DataResource, DataResourceController.SaveItem, DataResourceController.ListItem, DataResourceController.DetailItem> {
private final ObjectMapper mapper;
private final DataResourceService dataResourceService;
private final DataFileService dataFileService;
private final ObjectMapper mapper;
private final DataResourceService dataResourceService;
private final DataFileService dataFileService;
public DataResourceController(DataResourceService dataResourceService, DataFileService dataFileService, Jackson2ObjectMapperBuilder builder) {
super(dataResourceService);
this.dataResourceService = dataResourceService;
this.dataFileService = dataFileService;
this.mapper = builder.build();
}
public DataResourceController(DataResourceService dataResourceService, DataFileService dataFileService, Jackson2ObjectMapperBuilder builder) {
super(dataResourceService);
this.dataResourceService = dataResourceService;
this.dataFileService = dataFileService;
this.mapper = builder.build();
}
@GetMapping(LIST + "_no_confirmation")
public AmisResponse<ImmutableList<ListItem>> listNoConfirmation() {
return AmisResponse.responseSuccess(dataResourceService.listNoConfirmation().collect(entity -> {
try {
return toListItem(entity);
} catch (Exception e) {
throw new RuntimeException(e);
}
}));
}
@GetMapping(LIST + "_no_confirmation")
public AmisResponse<ImmutableList<ListItem>> listNoConfirmation() {
return AmisResponse.responseSuccess(dataResourceService.listNoConfirmation().collect(entity -> {
try {
return toListItem(entity);
} catch (Exception e) {
throw new RuntimeException(e);
}
}));
}
@GetMapping(LIST + "_no_authentication")
public AmisResponse<ImmutableList<ListItem>> listNoAuthentication() {
return AmisResponse.responseSuccess(dataResourceService.listNoAuthentication().collect(entity -> {
try {
return toListItem(entity);
} catch (Exception e) {
throw new RuntimeException(e);
}
}));
}
@GetMapping(LIST + "_no_authentication")
public AmisResponse<ImmutableList<ListItem>> listNoAuthentication() {
return AmisResponse.responseSuccess(dataResourceService.listNoAuthentication().collect(entity -> {
try {
return toListItem(entity);
} catch (Exception e) {
throw new RuntimeException(e);
}
}));
}
@GetMapping(LIST + "_no_ware")
public AmisResponse<ImmutableList<ListItem>> listNoWare() {
return AmisResponse.responseSuccess(dataResourceService.listNoWare().collect(entity -> {
try {
return toListItem(entity);
} catch (Exception e) {
throw new RuntimeException(e);
}
}));
}
@GetMapping(LIST + "_no_ware")
public AmisResponse<ImmutableList<ListItem>> listNoWare() {
return AmisResponse.responseSuccess(dataResourceService.listNoWare().collect(entity -> {
try {
return toListItem(entity);
} catch (Exception e) {
throw new RuntimeException(e);
}
}));
}
@Override
protected DataResource fromSaveItem(SaveItem item) throws JsonProcessingException {
ResourceType type = generateResourceType(item);
ResourceFormat format = generateResourceFormat(item);
DataResource dataResource = new DataResource();
dataResource.setId(item.getId());
dataResource.setName(item.getName());
dataResource.setDescription(item.getDescription());
dataResource.setType(type);
dataResource.setFormat(format);
if (ObjectUtil.isNotNull(item.getExampleFile())) {
dataResource.setExample(dataFileService.detail(item.getExampleFile().getValue()));
}
return dataResource;
@Override
protected DataResource fromSaveItem(SaveItem item) throws JsonProcessingException {
ResourceType type = generateResourceType(item);
ResourceFormat format = generateResourceFormat(item);
DataResource dataResource = new DataResource();
dataResource.setId(item.getId());
dataResource.setName(item.getName());
dataResource.setDescription(item.getDescription());
dataResource.setType(type);
dataResource.setFormat(format);
if (ObjectUtil.isNotNull(item.getExampleFile())) {
dataResource.setExample(dataFileService.detail(item.getExampleFile().getValue()));
}
return dataResource;
}
@Override
protected ListItem toListItem(DataResource dataResource) {
ListItem item = new ListItem();
item.setId(dataResource.getId());
item.setName(dataResource.getName());
item.setDescription(dataResource.getDescription());
item.setType(dataResource.getType().getResourceType().name());
item.setFormat(dataResource.getFormat().getFormatType().name());
if (ObjectUtil.isNotNull(dataResource.getConfirmation())) {
item.setConfirmationId(dataResource.getConfirmation().getId());
item.setConfirmationState(dataResource.getConfirmation().getState());
} else {
item.setConfirmationState(Confirmation.State.NONE);
}
item.setCreatedUser(dataResource.getCreatedUser().getUsername());
item.setCreatedTime(dataResource.getCreatedTime());
return item;
@Override
protected ListItem toListItem(DataResource dataResource) {
ListItem item = new ListItem();
item.setId(dataResource.getId());
item.setName(dataResource.getName());
item.setDescription(dataResource.getDescription());
item.setType(dataResource.getType().getResourceType().name());
item.setFormat(dataResource.getFormat().getFormatType().name());
if (ObjectUtil.isNotNull(dataResource.getConfirmation())) {
item.setConfirmationId(dataResource.getConfirmation().getId());
item.setConfirmationState(dataResource.getConfirmation().getState());
} else {
item.setConfirmationState(Confirmation.State.NONE);
}
item.setCreatedUser(dataResource.getCreatedUser().getUsername());
item.setCreatedTime(dataResource.getCreatedTime());
return item;
}
@Override
protected DetailItem toDetailItem(DataResource dataResource) throws Exception {
DetailItem item = new DetailItem();
item.setId(dataResource.getId());
item.setResourceTypeId(dataResource.getType().getId());
item.setResourceFormatId(dataResource.getFormat().getId());
item.setName(dataResource.getName());
item.setDescription(dataResource.getDescription());
item.setResourceType(dataResource.getType().getResourceType());
switch (dataResource.getType().getResourceType()) {
case API:
ApiResourceType apiType = (ApiResourceType) dataResource.getType();
item.setApiUrl(apiType.getUrl());
item.setApiUsername(apiType.getUsername());
item.setApiPassword(apiType.getPassword());
break;
case FILE:
FileResourceType fileType = (FileResourceType) dataResource.getType();
item.setFile(new FileInfo(fileType.getFile()));
break;
case DATABASE:
DatabaseResourceType databaseType = (DatabaseResourceType) dataResource.getType();
item.setDatabaseType(databaseType.getDatabaseType().name());
item.setDatabaseJdbc(databaseType.getJdbc());
item.setDatabaseUsername(databaseType.getUsername());
item.setDatabasePassword(databaseType.getPassword());
break;
case HDFS:
HDFSResourceType hdfsType = (HDFSResourceType) dataResource.getType();
item.setCoreSiteFile(new FileInfo(hdfsType.getCoreSite()));
item.setHdfsSiteFile(new FileInfo(hdfsType.getHdfsSite()));
break;
case FTP:
FtpResourceType ftpType = (FtpResourceType) dataResource.getType();
item.setFtpUrl(ftpType.getUrl());
item.setFtpUsername(ftpType.getUsername());
item.setFtpPassword(ftpType.getPassword());
item.setFtpPath(ftpType.getPath());
item.setFtpRegexFilter(ftpType.getRegexFilter());
break;
}
item.setFormatType(dataResource.getFormat().getFormatType());
switch (dataResource.getFormat().getFormatType()) {
case NONE:
case LINE:
break;
case JSON:
JsonResourceFormat jsonFormat = (JsonResourceFormat) dataResource.getFormat();
item.setJsonSchemaText(jsonFormat.getSchema());
item.setJsonSchema(mapper.readValue(jsonFormat.getSchema(), Map.class));
break;
case JSON_LINE:
JsonLineResourceFormat jsonLineFormat = (JsonLineResourceFormat) dataResource.getFormat();
item.setJsonLineSchemaText(jsonLineFormat.getSchema());
item.setJsonLineSchema(mapper.readValue(jsonLineFormat.getSchema(), Map.class));
break;
case CSV:
CsvResourceFormat csvFormat = (CsvResourceFormat) dataResource.getFormat();
item.setCsvSchemaText(csvFormat.getSchema());
item.setCsvSchema(mapper.readValue(csvFormat.getSchema(), Map.class));
break;
}
if (ObjectUtil.isNotNull(dataResource.getExample())) {
item.setExampleFile(new FileInfo(dataResource.getExample()));
}
item.setCreatedUsername(dataResource.getCreatedUser().getUsername());
item.setCreatedTime(dataResource.getCreatedTime());
item.setModifiedUsername(dataResource.getModifiedUser().getUsername());
item.setModifiedTime(dataResource.getModifiedTime());
return item;
@Override
protected DetailItem toDetailItem(DataResource dataResource) throws Exception {
DetailItem item = new DetailItem();
item.setId(dataResource.getId());
item.setResourceTypeId(dataResource.getType().getId());
item.setResourceFormatId(dataResource.getFormat().getId());
item.setName(dataResource.getName());
item.setDescription(dataResource.getDescription());
item.setResourceType(dataResource.getType().getResourceType());
switch (dataResource.getType().getResourceType()) {
case API:
ApiResourceType apiType = (ApiResourceType) dataResource.getType();
item.setApiUrl(apiType.getUrl());
item.setApiUsername(apiType.getUsername());
item.setApiPassword(apiType.getPassword());
break;
case FILE:
FileResourceType fileType = (FileResourceType) dataResource.getType();
item.setFile(new FileInfo(fileType.getFile()));
break;
case DATABASE:
DatabaseResourceType databaseType = (DatabaseResourceType) dataResource.getType();
item.setDatabaseType(databaseType.getDatabaseType().name());
item.setDatabaseJdbc(databaseType.getJdbc());
item.setDatabaseUsername(databaseType.getUsername());
item.setDatabasePassword(databaseType.getPassword());
break;
case HDFS:
HDFSResourceType hdfsType = (HDFSResourceType) dataResource.getType();
item.setCoreSiteFile(new FileInfo(hdfsType.getCoreSite()));
item.setHdfsSiteFile(new FileInfo(hdfsType.getHdfsSite()));
break;
case FTP:
FtpResourceType ftpType = (FtpResourceType) dataResource.getType();
item.setFtpUrl(ftpType.getUrl());
item.setFtpUsername(ftpType.getUsername());
item.setFtpPassword(ftpType.getPassword());
item.setFtpPath(ftpType.getPath());
item.setFtpRegexFilter(ftpType.getRegexFilter());
break;
}
item.setFormatType(dataResource.getFormat().getFormatType());
switch (dataResource.getFormat().getFormatType()) {
case NONE:
case LINE:
break;
case JSON:
JsonResourceFormat jsonFormat = (JsonResourceFormat) dataResource.getFormat();
item.setJsonSchemaText(jsonFormat.getJsonSchema());
item.setJsonSchema(mapper.readValue(jsonFormat.getJsonSchema(), Map.class));
break;
case JSON_LINE:
JsonLineResourceFormat jsonLineFormat = (JsonLineResourceFormat) dataResource.getFormat();
item.setJsonLineSchemaText(jsonLineFormat.getJsonSchema());
item.setJsonLineSchema(mapper.readValue(jsonLineFormat.getJsonSchema(), Map.class));
break;
case CSV:
CsvResourceFormat csvFormat = (CsvResourceFormat) dataResource.getFormat();
item.setCsvSchemaText(csvFormat.getCsvSchema());
item.setCsvSchema(mapper.readValue(csvFormat.getCsvSchema(), Map.class));
break;
}
if (ObjectUtil.isNotNull(dataResource.getExample())) {
item.setExampleFile(new FileInfo(dataResource.getExample()));
}
item.setCreatedUsername(dataResource.getCreatedUser().getUsername());
item.setCreatedTime(dataResource.getCreatedTime());
item.setModifiedUsername(dataResource.getModifiedUser().getUsername());
item.setModifiedTime(dataResource.getModifiedTime());
return item;
}
private ResourceType generateResourceType(SaveItem item) {
ResourceType type = null;
switch (item.getResourceType()) {
case API:
type = new ApiResourceType(item.getApiUrl(), item.getApiUsername(), item.getApiPassword());
break;
case FILE:
DataFile dataFile = dataFileService.detail(item.getFile().getValue());
type = new FileResourceType(dataFile);
break;
case DATABASE:
type = new DatabaseResourceType(
item.getDatabaseJdbc(),
item.getDatabaseUsername(),
item.getDatabasePassword(),
EnumUtil.fromString(DatabaseResourceType.DatabaseType.class, item.getDatabaseType())
);
break;
case HDFS:
type = new HDFSResourceType(dataFileService.detail(item.getCoreSiteFile().getValue()), dataFileService.detail(item.getHdfsSiteFile().getValue()));
break;
case FTP:
type = new FtpResourceType(item.getFtpUrl(), item.getFtpUsername(), item.getFtpPassword(), item.getFtpPath(), item.getFtpRegexFilter());
break;
}
type.setId(item.getResourceTypeId());
return type;
private ResourceType generateResourceType(SaveItem item) {
ResourceType type = null;
switch (item.getResourceType()) {
case API:
type = new ApiResourceType(item.getApiUrl(), item.getApiUsername(), item.getApiPassword());
break;
case FILE:
DataFile dataFile = dataFileService.detail(item.getFile().getValue());
type = new FileResourceType(dataFile);
break;
case DATABASE:
type = new DatabaseResourceType(
item.getDatabaseJdbc(),
item.getDatabaseUsername(),
item.getDatabasePassword(),
EnumUtil.fromString(DatabaseResourceType.DatabaseType.class, item.getDatabaseType())
);
break;
case HDFS:
type = new HDFSResourceType(dataFileService.detail(item.getCoreSiteFile().getValue()), dataFileService.detail(item.getHdfsSiteFile().getValue()));
break;
case FTP:
type = new FtpResourceType(item.getFtpUrl(), item.getFtpUsername(), item.getFtpPassword(), item.getFtpPath(), item.getFtpRegexFilter());
break;
}
type.setId(item.getResourceTypeId());
return type;
}
private ResourceFormat generateResourceFormat(SaveItem item) throws JsonProcessingException {
ResourceFormat format = null;
switch (item.getFormatType()) {
case NONE:
format = new NoneResourceFormat();
break;
case LINE:
format = new LineResourceFormat();
break;
case JSON:
format = new JsonResourceFormat(mapper.writeValueAsString(item.getJsonSchema()));
break;
case JSON_LINE:
format = new JsonLineResourceFormat(mapper.writeValueAsString(item.getJsonLineSchema()));
break;
case CSV:
format = new CsvResourceFormat(mapper.writeValueAsString(item.getCsvSchema()));
break;
}
format.setId(item.getResourceFormatId());
return format;
private ResourceFormat generateResourceFormat(SaveItem item) throws JsonProcessingException {
ResourceFormat format = null;
switch (item.getFormatType()) {
case NONE:
format = new NoneResourceFormat();
break;
case LINE:
format = new LineResourceFormat();
break;
case JSON:
format = new JsonResourceFormat(mapper.writeValueAsString(item.getJsonSchema()));
break;
case JSON_LINE:
format = new JsonLineResourceFormat(mapper.writeValueAsString(item.getJsonLineSchema()));
break;
case CSV:
format = new CsvResourceFormat(mapper.writeValueAsString(item.getCsvSchema()));
break;
}
format.setId(item.getResourceFormatId());
return format;
}
@Data
@EqualsAndHashCode(callSuper = true)
public static class SaveItem extends SimpleSaveItem<DataResource> {
private String name;
private String description;
private Long resourceTypeId;
private ResourceType.Type resourceType;
private String apiUrl;
private String apiUsername;
private String apiPassword;
private FileInfo file;
private String databaseType;
private String databaseJdbc;
private String databaseUsername;
private String databasePassword;
private FileInfo coreSiteFile;
private FileInfo hdfsSiteFile;
private String ftpUrl;
private String ftpUsername;
private String ftpPassword;
private String ftpPath;
private String ftpRegexFilter;
private Long resourceFormatId;
private ResourceFormat.Type formatType;
private Map<?, ?> jsonSchema;
private String jsonSchemaText;
private Map<?, ?> jsonLineSchema;
private String jsonLineSchemaText;
private Map<?, ?> csvSchema;
private String csvSchemaText;
private FileInfo exampleFile;
}
@Data
@EqualsAndHashCode(callSuper = true)
public static class SaveItem extends SimpleSaveItem<DataResource> {
private String name;
private String description;
private Long resourceTypeId;
private ResourceType.Type resourceType;
private String apiUrl;
private String apiUsername;
private String apiPassword;
private FileInfo file;
private String databaseType;
private String databaseJdbc;
private String databaseUsername;
private String databasePassword;
private FileInfo coreSiteFile;
private FileInfo hdfsSiteFile;
private String ftpUrl;
private String ftpUsername;
private String ftpPassword;
private String ftpPath;
private String ftpRegexFilter;
private Long resourceFormatId;
private ResourceFormat.Type formatType;
private Map<?, ?> jsonSchema;
private String jsonSchemaText;
private Map<?, ?> jsonLineSchema;
private String jsonLineSchemaText;
private Map<?, ?> csvSchema;
private String csvSchemaText;
private FileInfo exampleFile;
}
@Data
@EqualsAndHashCode(callSuper = true)
public static final class ListItem extends SimpleListItem<DataResource> {
private Long id;
private String name;
private String description;
private String type;
private String format;
private Long confirmationId;
private Confirmation.State confirmationState;
private String createdUser;
private LocalDateTime createdTime;
}
@Data
@EqualsAndHashCode(callSuper = true)
public static final class ListItem extends SimpleListItem<DataResource> {
private Long id;
private String name;
private String description;
private String type;
private String format;
private Long confirmationId;
private Confirmation.State confirmationState;
private String createdUser;
private LocalDateTime createdTime;
}
@Data
@EqualsAndHashCode(callSuper = true)
public static final class DetailItem extends SaveItem {
private LocalDateTime createdTime;
private String createdUsername;
private LocalDateTime modifiedTime;
private String modifiedUsername;
}
@Data
@EqualsAndHashCode(callSuper = true)
public static final class DetailItem extends SaveItem {
private LocalDateTime createdTime;
private String createdUsername;
private LocalDateTime modifiedTime;
private String modifiedUsername;
}
}

View File

@@ -23,54 +23,54 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
public class UserController {
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
private final UserService userService;
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/state")
public AmisResponse<UserService.UserInformation> state() {
return AmisResponse.responseSuccess(userService.state());
}
@PostMapping("/register")
public void register(@RequestBody RegisterRequest request) {
logger.info("Register request: {}", request);
userService.register(request.username, request.password, request.role);
}
@PostMapping("/login")
public AmisResponse<UserService.UserInformation> login(@RequestBody LoginRequest request) {
logger.info("Login request: {}", request);
return AmisResponse.responseSuccess(userService.login(request.username, request.password));
}
@GetMapping("/logout")
public void logout() {
userService.logout();
}
@GetMapping("/exists_username/{username}")
public void existsUsername(@PathVariable("username") String username) {
if (userService.exitsUsername(username)) {
throw new RuntimeException(StrUtil.format("{} 已存在", username));
}
}
@GetMapping("/state")
public AmisResponse<UserService.UserInformation> state() {
return AmisResponse.responseSuccess(userService.state());
}
@Data
public static final class LoginRequest {
private String username;
private String password;
private String checkCode;
}
@PostMapping("/register")
public void register(@RequestBody RegisterRequest request) {
logger.info("Register request: {}", request);
userService.register(request.username, request.password, request.role);
}
@PostMapping("/login")
public AmisResponse<UserService.UserInformation> login(@RequestBody LoginRequest request) {
logger.info("Login request: {}", request);
return AmisResponse.responseSuccess(userService.login(request.username, request.password));
}
@GetMapping("/logout")
public void logout() {
userService.logout();
}
@GetMapping("/exists_username/{username}")
public void existsUsername(@PathVariable("username") String username) {
if (userService.exitsUsername(username)) {
throw new RuntimeException(StrUtil.format("{} 已存在", username));
}
}
@Data
public static final class LoginRequest {
private String username;
private String password;
private String checkCode;
}
@Data
public static final class RegisterRequest {
private String username;
private String password;
private User.Role role;
}
@Data
public static final class RegisterRequest {
private String username;
private String password;
private User.Role role;
}
}

View File

@@ -25,112 +25,112 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user_management")
public class UserManagementController {
private static final Logger logger = LoggerFactory.getLogger(UserManagementController.class);
private static final Logger logger = LoggerFactory.getLogger(UserManagementController.class);
private final UserService userService;
private final UserService userService;
public UserManagementController(UserService userService) {
this.userService = userService;
public UserManagementController(UserService userService) {
this.userService = userService;
}
@GetMapping("/list")
public AmisListResponse list() {
return AmisListResponse.responseListData(userService.list().collect(UserListItem::new));
}
@GetMapping("/detail/{username}")
public AmisResponse<UserDetail> detail(@PathVariable String username) {
return AmisResponse.responseSuccess(new UserDetail(userService.detail(username)));
}
@PostMapping("/register")
public void register(@RequestBody RegisterRequest request) {
logger.info("Register request: {}", request);
userService.registerFromAdministrator(request.username, request.password, request.role);
}
@PostMapping("/change_password")
public AmisResponse<Object> changePassword(@RequestBody ChangePasswordRequest request) {
userService.changePassword(request.oldPassword, request.newPassword);
return AmisResponse.responseSuccess();
}
@GetMapping("/disable/{username}")
public AmisResponse<Object> disable(@PathVariable String username) {
userService.disable(username);
return AmisResponse.responseSuccess();
}
@GetMapping("/enable/{username}")
public AmisResponse<Object> enable(@PathVariable String username) {
userService.enable(username);
return AmisResponse.responseSuccess();
}
@GetMapping("/check/{username}")
public AmisResponse<Object> check(@PathVariable String username) {
userService.check(username);
return AmisResponse.responseSuccess();
}
@Data
public static final class ChangePasswordRequest {
private String oldPassword;
private String newPassword;
}
@Data
public static final class RegisterRequest {
private String username;
private String password;
private User.Role role;
}
@Data
public static final class UserListItem {
private Long id;
private String username;
private User.Role role;
private User.State state;
private LocalDateTime lastLoginTime;
private LocalDateTime createdTime;
public UserListItem(User user) {
this.id = user.getId();
this.username = user.getUsername();
this.role = user.getRole();
this.state = user.getState();
this.lastLoginTime = user.getLastLoginTime();
this.createdTime = user.getCreatedTime();
}
}
@GetMapping("/list")
public AmisListResponse list() {
return AmisListResponse.responseListData(userService.list().collect(UserListItem::new));
}
@GetMapping("/detail/{username}")
public AmisResponse<UserDetail> detail(@PathVariable String username) {
return AmisResponse.responseSuccess(new UserDetail(userService.detail(username)));
}
@PostMapping("/register")
public void register(@RequestBody RegisterRequest request) {
logger.info("Register request: {}", request);
userService.registerFromAdministrator(request.username, request.password, request.role);
}
@PostMapping("/change_password")
public AmisResponse<Object> changePassword(@RequestBody ChangePasswordRequest request) {
userService.changePassword(request.oldPassword, request.newPassword);
return AmisResponse.responseSuccess();
}
@GetMapping("/disable/{username}")
public AmisResponse<Object> disable(@PathVariable String username) {
userService.disable(username);
return AmisResponse.responseSuccess();
}
@GetMapping("/enable/{username}")
public AmisResponse<Object> enable(@PathVariable String username) {
userService.enable(username);
return AmisResponse.responseSuccess();
}
@GetMapping("/check/{username}")
public AmisResponse<Object> check(@PathVariable String username) {
userService.check(username);
return AmisResponse.responseSuccess();
}
@Data
public static final class ChangePasswordRequest {
private String oldPassword;
private String newPassword;
}
@Data
public static final class RegisterRequest {
private String username;
private String password;
private User.Role role;
}
@Data
public static final class UserListItem {
private Long id;
private String username;
private User.Role role;
private User.State state;
private LocalDateTime lastLoginTime;
private LocalDateTime createdTime;
public UserListItem(User user) {
this.id = user.getId();
this.username = user.getUsername();
this.role = user.getRole();
this.state = user.getState();
this.lastLoginTime = user.getLastLoginTime();
this.createdTime = user.getCreatedTime();
}
}
@Data
public static final class UserDetail {
private String username;
private User.Role role;
private User.State state;
private LocalDateTime lastLoginTime;
private LocalDateTime createdTime;
private String createdUsername;
private LocalDateTime modifiedTime;
private String modifiedUsername;
private LocalDateTime checkedTime;
private String checkedUsername;
public UserDetail(User user) {
this.username = user.getUsername();
this.role = user.getRole();
this.state = user.getState();
this.lastLoginTime = user.getLastLoginTime();
this.createdTime = user.getCreatedTime();
this.createdUsername = user.getCreatedUser().getUsername();
this.modifiedTime = user.getModifiedTime();
this.modifiedUsername = user.getModifiedUser().getUsername();
if (ObjectUtil.isNotNull(user.getCheckedUser())) {
this.checkedTime = user.getCheckedTime();
this.checkedUsername = user.getCheckedUser().getUsername();
}
}
@Data
public static final class UserDetail {
private String username;
private User.Role role;
private User.State state;
private LocalDateTime lastLoginTime;
private LocalDateTime createdTime;
private String createdUsername;
private LocalDateTime modifiedTime;
private String modifiedUsername;
private LocalDateTime checkedTime;
private String checkedUsername;
public UserDetail(User user) {
this.username = user.getUsername();
this.role = user.getRole();
this.state = user.getState();
this.lastLoginTime = user.getLastLoginTime();
this.createdTime = user.getCreatedTime();
this.createdUsername = user.getCreatedUser().getUsername();
this.modifiedTime = user.getModifiedTime();
this.modifiedUsername = user.getModifiedUser().getUsername();
if (ObjectUtil.isNotNull(user.getCheckedUser())) {
this.checkedTime = user.getCheckedTime();
this.checkedUsername = user.getCheckedUser().getUsername();
}
}
}
}

View File

@@ -10,14 +10,12 @@ import com.eshore.gringotts.web.domain.entity.Ware;
import com.eshore.gringotts.web.domain.service.DataFileService;
import com.eshore.gringotts.web.domain.service.DataResourceService;
import com.eshore.gringotts.web.domain.service.WareService;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.time.LocalDateTime;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.collections.api.list.ImmutableList;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@@ -29,108 +27,96 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("ware")
public class WareController extends SimpleControllerSupport<Ware, WareController.SaveItem, WareController.ListItem, WareController.DetailItem> {
private final HostConfiguration hostConfiguration;
private final WareService wareService;
private final DataResourceService dataResourceService;
private final DataFileService dataFileService;
private final HostConfiguration hostConfiguration;
private final WareService wareService;
private final DataResourceService dataResourceService;
private final DataFileService dataFileService;
public WareController(HostConfiguration hostConfiguration, WareService service, DataResourceService dataResourceService, DataFileService dataFileService) {
super(service);
this.hostConfiguration = hostConfiguration;
this.wareService = service;
this.dataResourceService = dataResourceService;
this.dataFileService = dataFileService;
}
public WareController(HostConfiguration hostConfiguration, WareService service, DataResourceService dataResourceService, DataFileService dataFileService) {
super(service);
this.hostConfiguration = hostConfiguration;
this.wareService = service;
this.dataResourceService = dataResourceService;
this.dataFileService = dataFileService;
}
@GetMapping(LIST + "_public")
public AmisResponse<ImmutableList<ListItem>> listPublic() {
return AmisResponse.responseSuccess(wareService.listPublic().collect(this::toListItem));
}
@GetMapping(LIST + "_public")
public AmisResponse<ImmutableList<ListItem>> listPublic() {
return AmisResponse.responseSuccess(wareService.listPublic().collect(this::toListItem));
}
@GetMapping("/submit/{id}")
public AmisResponse<Object> submit(@PathVariable Long id) throws JsonProcessingException {
wareService.submit(id);
return AmisResponse.responseSuccess();
}
@Override
protected Ware fromSaveItem(SaveItem saveItem) {
Ware ware = new Ware();
ware.setId(saveItem.getId());
ware.setResource(dataResourceService.detailOrThrow(saveItem.getResourceId()));
ware.setName(saveItem.getName());
ware.setDescription(saveItem.getDescription());
ware.setIcon(dataFileService.detailOrThrow(saveItem.getIconId()));
ware.setContent(saveItem.getContent());
return ware;
}
@GetMapping("/retract/{id}")
public AmisResponse<Object> retract(@PathVariable Long id) {
wareService.retract(id);
return AmisResponse.responseSuccess();
}
@Override
protected ListItem toListItem(Ware entity) {
ListItem item = new ListItem();
item.setId(entity.getId());
item.setName(entity.getName());
item.setDescription(entity.getDescription());
item.setIcon(StrUtil.format("{}/upload/download/{}", hostConfiguration.getPrefix(), entity.getIcon().getId()));
item.setState(entity.getState().name());
item.setResourceId(entity.getResource().getId());
item.setCreatedTime(entity.getCreatedTime());
item.setCreatedUsername(entity.getCreatedUser().getUsername());
return item;
}
@Override
protected Ware fromSaveItem(SaveItem saveItem) {
Ware ware = new Ware();
ware.setId(saveItem.getId());
ware.setResource(dataResourceService.detailOrThrow(saveItem.getResourceId()));
ware.setName(saveItem.getName());
ware.setDescription(saveItem.getDescription());
ware.setIcon(dataFileService.detailOrThrow(saveItem.getIconId()));
ware.setContent(saveItem.getContent());
return ware;
}
@Override
protected DetailItem toDetailItem(Ware entity) {
DetailItem item = new DetailItem();
item.setId(entity.getId());
item.setResourceId(entity.getResource().getId());
item.setResourceName(entity.getResource().getName());
item.setName(entity.getName());
item.setDescription(entity.getDescription());
item.setIconId(entity.getIcon().getId());
item.setContent(entity.getContent());
item.setIcon(StrUtil.format("{}/upload/download/{}", hostConfiguration.getPrefix(), entity.getIcon().getId()));
item.setCreatedTime(entity.getCreatedTime());
item.setCreatedUsername(entity.getCreatedUser().getUsername());
item.setModifiedTime(entity.getModifiedTime());
item.setModifiedUsername(entity.getModifiedUser().getUsername());
return item;
}
@Override
protected ListItem toListItem(Ware entity) {
ListItem item = new ListItem();
item.setId(entity.getId());
item.setName(entity.getName());
item.setDescription(entity.getDescription());
item.setIcon(StrUtil.format("{}/upload/download/{}", hostConfiguration.getPrefix(), entity.getIcon().getId()));
item.setState(entity.getState().name());
item.setResourceId(entity.getResource().getId());
item.setCreatedTime(entity.getCreatedTime());
item.setCreatedUsername(entity.getCreatedUser().getUsername());
return item;
}
@Data
@EqualsAndHashCode(callSuper = true)
public static class SaveItem extends SimpleSaveItem<Ware> {
private Long resourceId;
private String name;
private String description;
private Long iconId;
private String content;
}
@Override
protected DetailItem toDetailItem(Ware entity) {
DetailItem item = new DetailItem();
item.setId(entity.getId());
item.setResourceId(entity.getResource().getId());
item.setResourceName(entity.getResource().getName());
item.setName(entity.getName());
item.setDescription(entity.getDescription());
item.setIconId(entity.getIcon().getId());
item.setContent(entity.getContent());
item.setIcon(StrUtil.format("{}/upload/download/{}", hostConfiguration.getPrefix(), entity.getIcon().getId()));
item.setCreatedTime(entity.getCreatedTime());
item.setCreatedUsername(entity.getCreatedUser().getUsername());
item.setModifiedTime(entity.getModifiedTime());
item.setModifiedUsername(entity.getModifiedUser().getUsername());
return item;
}
@Data
@EqualsAndHashCode(callSuper = true)
public static class ListItem extends SimpleListItem<Ware> {
private String name;
private String description;
private String state;
private String icon;
private Long resourceId;
}
@Data
@EqualsAndHashCode(callSuper = true)
public static class SaveItem extends SimpleSaveItem<Ware> {
private Long resourceId;
private String name;
private String description;
private Long iconId;
private String content;
}
@Data
@EqualsAndHashCode(callSuper = true)
public static class ListItem extends SimpleListItem<Ware> {
private String name;
private String description;
private String state;
private String icon;
private Long resourceId;
}
@Data
@EqualsAndHashCode(callSuper = true)
public static class DetailItem extends SaveItem {
private String icon;
private String resourceName;
private LocalDateTime createdTime;
private String createdUsername;
private LocalDateTime modifiedTime;
private String modifiedUsername;
}
@Data
@EqualsAndHashCode(callSuper = true)
public static class DetailItem extends SaveItem {
private String icon;
private String resourceName;
private LocalDateTime createdTime;
private String createdUsername;
private LocalDateTime modifiedTime;
private String modifiedUsername;
}
}

View File

@@ -5,7 +5,6 @@ import com.eshore.gringotts.web.domain.base.entity.CheckingNeededEntity;
import com.eshore.gringotts.web.domain.base.entity.LogicDeleteEntity;
import java.time.LocalDateTime;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.ConstraintMode;
import javax.persistence.Entity;
@@ -23,7 +22,6 @@ import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@@ -41,33 +39,32 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@EntityListeners(AuditingEntityListener.class)
@Table(name = Constants.TABLE_PREFIX + "authentication")
@NamedEntityGraph(name = "authentication.list", attributeNodes = {
@NamedAttributeNode(value = "target"),
@NamedAttributeNode(value = "createdUser"),
@NamedAttributeNode(value = "target"),
@NamedAttributeNode(value = "createdUser"),
})
@NamedEntityGraph(name = "authentication.detail", attributeNodes = {
@NamedAttributeNode(value = "target"),
@NamedAttributeNode(value = "evidences"),
@NamedAttributeNode(value = "createdUser"),
@NamedAttributeNode(value = "modifiedUser"),
@NamedAttributeNode(value = "target"),
@NamedAttributeNode(value = "evidences"),
@NamedAttributeNode(value = "createdUser"),
@NamedAttributeNode(value = "modifiedUser"),
})
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "authentication" + " set deleted = true where id = ?")
@Where(clause = LogicDeleteEntity.LOGIC_DELETE_CLAUSE)
public class Authentication extends CheckingNeededEntity {
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
private DataResource target;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT), inverseForeignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
@ToString.Exclude
private Set<DataFile> evidences;
/**
* 生效时间
*/
@Column(nullable = false)
private LocalDateTime activeTime = LocalDateTime.now();
/**
* 过期时间
*/
@Column(nullable = false)
private LocalDateTime expiredTime = LocalDateTime.now().plusDays(1);
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
private DataResource target;
@OneToMany(fetch = FetchType.LAZY)
@JoinTable(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT), inverseForeignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
@ToString.Exclude
private Set<DataFile> evidences;
/**
* 生效时间
*/
@Column(nullable = false)
private LocalDateTime activeTime = LocalDateTime.now();
/**
* 过期时间
*/
@Column(nullable = false)
private LocalDateTime expiredTime = LocalDateTime.now().plusDays(1);
}

View File

@@ -1,130 +0,0 @@
package com.eshore.gringotts.web.domain.entity;
import com.eshore.gringotts.core.Constants;
import com.eshore.gringotts.web.domain.base.entity.SimpleEntity;
import javax.persistence.Column;
import javax.persistence.ConstraintMode;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.ForeignKey;
import javax.persistence.JoinColumn;
import javax.persistence.NamedAttributeNode;
import javax.persistence.NamedEntityGraph;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.DynamicUpdate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
/**
* @author lanyuanxiaoyao
* @date 2024-11-29
*/
@Getter
@Setter
@ToString
@Entity
@DynamicUpdate
@EntityListeners(AuditingEntityListener.class)
@Table(name = Constants.TABLE_PREFIX + "check_order")
@NamedEntityGraph(name = "check_order.list", attributeNodes = {
@NamedAttributeNode(value = "createdUser"),
@NamedAttributeNode(value = "modifiedUser"),
})
@NamedEntityGraph(name = "check_order.detail", attributeNodes = {
@NamedAttributeNode(value = "createdUser"),
@NamedAttributeNode(value = "modifiedUser"),
})
@NoArgsConstructor
public class CheckOrder extends SimpleEntity {
@Column(nullable = false)
private String keyword;
@Column(nullable = false)
private String description;
@Column(nullable = false)
@Enumerated(EnumType.STRING)
private Type type;
/**
* JSON 结构 Map<String, Object>
*/
@Column(nullable = false)
private String parameters;
@Column(nullable = false)
@Enumerated(EnumType.STRING)
private Target target;
@Column(nullable = false)
private String targetClass;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
@ToString.Exclude
private User targetUser;
@Enumerated(EnumType.STRING)
private User.Role targetRole;
@Column(nullable = false)
@Enumerated(EnumType.STRING)
private State state = State.CHECKING;
public CheckOrder(
String keyword,
String description,
Type type,
String parameters,
String targetClass,
User targetUser
) {
this.keyword = keyword;
this.description = description;
this.type = type;
this.parameters = parameters;
this.target = Target.USER;
this.targetClass = targetClass;
this.targetUser = targetUser;
}
public CheckOrder(
String keyword,
String description,
Type type,
String parameters,
String targetClass,
User.Role targetRole
) {
this.keyword = keyword;
this.description = description;
this.type = type;
this.parameters = parameters;
this.target = Target.ROLE;
this.targetClass = targetClass;
this.targetRole = targetRole;
}
public enum Operation {
APPLY,
REJECT,
}
public enum Type {
CONFIRMATION,
AUTHENTICATION,
MARKET,
}
public enum Target {
USER,
ROLE,
}
public enum State {
CHECKING,
RETRACT,
OVER,
}
}

View File

@@ -4,7 +4,6 @@ import com.eshore.gringotts.core.Constants;
import com.eshore.gringotts.web.domain.base.entity.CheckingNeededEntity;
import com.eshore.gringotts.web.domain.base.entity.LogicDeleteEntity;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.ConstraintMode;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
@@ -21,7 +20,6 @@ import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@@ -39,23 +37,22 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@EntityListeners(AuditingEntityListener.class)
@Table(name = Constants.TABLE_PREFIX + "confirmation")
@NamedEntityGraph(name = "confirmation.list", attributeNodes = {
@NamedAttributeNode(value = "target"),
@NamedAttributeNode(value = "createdUser"),
@NamedAttributeNode(value = "target"),
@NamedAttributeNode(value = "createdUser"),
})
@NamedEntityGraph(name = "confirmation.detail", attributeNodes = {
@NamedAttributeNode(value = "target"),
@NamedAttributeNode(value = "evidences"),
@NamedAttributeNode(value = "createdUser"),
@NamedAttributeNode(value = "modifiedUser"),
@NamedAttributeNode(value = "target"),
@NamedAttributeNode(value = "evidences"),
@NamedAttributeNode(value = "createdUser"),
@NamedAttributeNode(value = "modifiedUser"),
})
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "confirmation" + " set deleted = true where id = ?")
@Where(clause = LogicDeleteEntity.LOGIC_DELETE_CLAUSE)
public class Confirmation extends CheckingNeededEntity {
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
private DataResource target;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT), inverseForeignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
@ToString.Exclude
private Set<DataFile> evidences;
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
private DataResource target;
@OneToMany(fetch = FetchType.LAZY)
@JoinTable(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT), inverseForeignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
@ToString.Exclude
private Set<DataFile> evidences;
}

View File

@@ -1,15 +1,13 @@
package com.eshore.gringotts.web.domain.entity;
import com.eshore.gringotts.core.Constants;
import com.eshore.gringotts.web.domain.base.entity.LogicDeleteEntity;
import com.eshore.gringotts.web.domain.base.entity.SimpleEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
/**
* 上传文件
@@ -23,12 +21,10 @@ import org.hibernate.annotations.Where;
@Entity
@DynamicUpdate
@Table(name = Constants.TABLE_PREFIX + "data_file")
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "data_file" + " set deleted = true where id = ?")
@Where(clause = LogicDeleteEntity.LOGIC_DELETE_CLAUSE)
public class DataFile extends LogicDeleteEntity {
private String filename;
private Long size;
private String md5;
private String path;
private String type;
public class DataFile extends SimpleEntity {
private String filename;
private Long size;
private String md5;
private String path;
private String type;
}

View File

@@ -5,7 +5,6 @@ import com.eshore.gringotts.web.domain.base.entity.LogicDeleteEntity;
import com.eshore.gringotts.web.domain.entity.format.ResourceFormat;
import com.eshore.gringotts.web.domain.entity.type.ResourceType;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.ConstraintMode;
import javax.persistence.Entity;
@@ -22,7 +21,6 @@ import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@@ -34,44 +32,43 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@DynamicUpdate
@Table(name = Constants.TABLE_PREFIX + "data_resource")
@NamedEntityGraph(name = "data_resource.list", attributeNodes = {
@NamedAttributeNode(value = "type"),
@NamedAttributeNode(value = "format"),
@NamedAttributeNode(value = "confirmation"),
@NamedAttributeNode(value = "createdUser"),
@NamedAttributeNode(value = "type"),
@NamedAttributeNode(value = "format"),
@NamedAttributeNode(value = "confirmation"),
@NamedAttributeNode(value = "createdUser"),
})
@NamedEntityGraph(name = "data_resource.detail", attributeNodes = {
@NamedAttributeNode(value = "type"),
@NamedAttributeNode(value = "format"),
@NamedAttributeNode(value = "example"),
@NamedAttributeNode(value = "confirmation"),
@NamedAttributeNode(value = "createdUser"),
@NamedAttributeNode(value = "modifiedUser"),
@NamedAttributeNode(value = "type"),
@NamedAttributeNode(value = "format"),
@NamedAttributeNode(value = "example"),
@NamedAttributeNode(value = "confirmation"),
@NamedAttributeNode(value = "createdUser"),
@NamedAttributeNode(value = "modifiedUser"),
})
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "data_resource" + " set deleted = true where id = ?")
@Where(clause = LogicDeleteEntity.LOGIC_DELETE_CLAUSE)
public class DataResource extends LogicDeleteEntity {
@Column(nullable = false)
private String name;
private String description;
@OneToOne(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY)
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
@ToString.Exclude
private ResourceType type;
@OneToOne(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY)
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
@ToString.Exclude
private ResourceFormat format;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
@ToString.Exclude
private DataFile example;
@OneToOne(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER, mappedBy = "target")
@ToString.Exclude
private Confirmation confirmation;
@OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER, mappedBy = "target")
@ToString.Exclude
private Set<Authentication> authentications;
@OneToOne(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER, mappedBy = "resource")
@ToString.Exclude
private Ware ware;
@Column(nullable = false)
private String name;
private String description;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
@ToString.Exclude
private ResourceType type;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
@ToString.Exclude
private ResourceFormat format;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
@ToString.Exclude
private DataFile example;
@OneToOne(fetch = FetchType.EAGER, mappedBy = "target")
@ToString.Exclude
private Confirmation confirmation;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "target")
@ToString.Exclude
private Set<Authentication> authentications;
@OneToOne(fetch = FetchType.EAGER, mappedBy = "resource")
@ToString.Exclude
private Ware ware;
}

View File

@@ -33,98 +33,98 @@ import org.hibernate.annotations.DynamicUpdate;
@DynamicUpdate
@Table(name = Constants.TABLE_PREFIX + "user")
@NamedEntityGraph(name = "user.list", attributeNodes = {
@NamedAttributeNode(value = "createdUser"),
@NamedAttributeNode(value = "createdUser"),
})
@NamedEntityGraph(name = "user.detail", attributeNodes = {
@NamedAttributeNode(value = "createdUser"),
@NamedAttributeNode(value = "modifiedUser"),
@NamedAttributeNode(value = "checkedUser"),
@NamedAttributeNode(value = "createdUser"),
@NamedAttributeNode(value = "modifiedUser"),
@NamedAttributeNode(value = "checkedUser"),
})
public class User extends SimpleEntity {
@Column(unique = true, nullable = false)
private String username;
@Column(nullable = false)
private String password;
@Column(nullable = false)
@Enumerated(EnumType.STRING)
private Role role;
@Column(nullable = false)
@Enumerated(EnumType.STRING)
private State state = State.CHECKING;
private LocalDateTime lastLoginTime;
private LocalDateTime checkedTime;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
@ToString.Exclude
private User checkedUser;
@Column(unique = true, nullable = false)
private String username;
@Column(nullable = false)
private String password;
@Column(nullable = false)
@Enumerated(EnumType.STRING)
private Role role;
@Column(nullable = false)
@Enumerated(EnumType.STRING)
private State state = State.CHECKING;
private LocalDateTime lastLoginTime;
private LocalDateTime checkedTime;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
@ToString.Exclude
private User checkedUser;
public static boolean isAdministrator(User user) {
return Role.ADMINISTRATOR.equals(user.role);
}
public static boolean isAdministrator(User user) {
return Role.ADMINISTRATOR.equals(user.role);
}
public static boolean isNotAdministrator(User user) {
return !isAdministrator(user);
}
public static boolean isNotAdministrator(User user) {
return !isAdministrator(user);
}
public static boolean isChecker(User user) {
return Role.CHECKER.equals(user.role);
}
public static boolean isChecker(User user) {
return Role.CHECKER.equals(user.role);
}
public static boolean isNotChecker(User user) {
return !isChecker(user);
}
public static boolean isNotChecker(User user) {
return !isChecker(user);
}
public static boolean isProvider(User user) {
return Role.PROVIDER.equals(user.role);
}
public static boolean isProvider(User user) {
return Role.PROVIDER.equals(user.role);
}
public static boolean isNotProvider(User user) {
return !isProvider(user);
}
public static boolean isNotProvider(User user) {
return !isProvider(user);
}
public static boolean isCustomer(User user) {
return Role.CUSTOMER.equals(user.role);
}
public static boolean isCustomer(User user) {
return Role.CUSTOMER.equals(user.role);
}
public static boolean isNotCustomer(User user) {
return !isCustomer(user);
}
public static boolean isNotCustomer(User user) {
return !isCustomer(user);
}
public static boolean isUser(User user) {
return isProvider(user) || isCustomer(user);
}
public static boolean isUser(User user) {
return isProvider(user) || isCustomer(user);
}
public enum State {
/**
* 审查中
*/
CHECKING,
/**
* 正常
*/
NORMAL,
/**
* 禁用
*/
DISABLED,
}
public enum State {
/**
* 审查中
*/
CHECKING,
/**
* 正常
*/
NORMAL,
/**
* 禁用
*/
DISABLED,
}
public enum Role {
/**
* 数据提供方
*/
PROVIDER,
/**
* 数据使用方
*/
CUSTOMER,
/**
* 数据监管方
*/
CHECKER,
/**
* 系统管理员
*/
ADMINISTRATOR,
}
public enum Role {
/**
* 数据提供方
*/
PROVIDER,
/**
* 数据使用方
*/
CUSTOMER,
/**
* 数据监管方
*/
CHECKER,
/**
* 系统管理员
*/
ADMINISTRATOR,
}
}

View File

@@ -21,7 +21,6 @@ import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@@ -39,33 +38,32 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@DynamicUpdate
@Table(name = Constants.TABLE_PREFIX + "ware")
@NamedEntityGraph(name = "ware.list", attributeNodes = {
@NamedAttributeNode(value = "icon"),
@NamedAttributeNode(value = "createdUser"),
@NamedAttributeNode(value = "icon"),
@NamedAttributeNode(value = "createdUser"),
})
@NamedEntityGraph(name = "ware.detail", attributeNodes = {
@NamedAttributeNode(value = "icon"),
@NamedAttributeNode(value = "content"),
@NamedAttributeNode(value = "createdUser"),
@NamedAttributeNode(value = "modifiedUser"),
@NamedAttributeNode(value = "icon"),
@NamedAttributeNode(value = "content"),
@NamedAttributeNode(value = "createdUser"),
@NamedAttributeNode(value = "modifiedUser"),
})
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "ware" + " set deleted = true where id = ?")
@Where(clause = LogicDeleteEntity.LOGIC_DELETE_CLAUSE)
public class Ware extends CheckingNeededEntity {
@OneToOne(cascade = CascadeType.DETACH, fetch = FetchType.EAGER)
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
@ToString.Exclude
private DataResource resource;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String description;
@OneToOne(cascade = CascadeType.DETACH, fetch = FetchType.LAZY)
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
@ToString.Exclude
private DataFile icon;
@Lob
@Basic(fetch = FetchType.LAZY)
@ToString.Exclude
@Column(nullable = false)
private String content;
@OneToOne(cascade = CascadeType.DETACH, fetch = FetchType.EAGER)
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
@ToString.Exclude
private DataResource resource;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String description;
@OneToOne(cascade = CascadeType.DETACH, fetch = FetchType.LAZY)
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
@ToString.Exclude
private DataFile icon;
@Lob
@Basic(fetch = FetchType.LAZY)
@ToString.Exclude
@Column(nullable = false)
private String content;
}

View File

@@ -1,7 +1,5 @@
package com.eshore.gringotts.web.domain.entity.format;
import com.eshore.gringotts.core.Constants;
import com.eshore.gringotts.web.domain.base.entity.LogicDeleteIdOnlyEntity;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import lombok.AllArgsConstructor;
@@ -9,8 +7,6 @@ import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
/**
* CSV格式
@@ -25,13 +21,11 @@ import org.hibernate.annotations.Where;
@NoArgsConstructor
@Entity
@DiscriminatorValue("CSV")
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_format" + " set deleted = true where id = ?")
@Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE)
public class CsvResourceFormat extends ResourceFormat {
private String schema;
private String csvSchema;
@Override
public Type getFormatType() {
return Type.CSV;
}
@Override
public Type getFormatType() {
return Type.CSV;
}
}

View File

@@ -1,7 +1,5 @@
package com.eshore.gringotts.web.domain.entity.format;
import com.eshore.gringotts.core.Constants;
import com.eshore.gringotts.web.domain.base.entity.LogicDeleteIdOnlyEntity;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import lombok.AllArgsConstructor;
@@ -9,8 +7,6 @@ import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
/**
* JSON line格式
@@ -25,13 +21,11 @@ import org.hibernate.annotations.Where;
@NoArgsConstructor
@Entity
@DiscriminatorValue("JSON_LINE")
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_format" + " set deleted = true where id = ?")
@Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE)
public class JsonLineResourceFormat extends ResourceFormat {
private String schema;
private String jsonSchema;
@Override
public Type getFormatType() {
return Type.JSON_LINE;
}
@Override
public Type getFormatType() {
return Type.JSON_LINE;
}
}

View File

@@ -1,7 +1,5 @@
package com.eshore.gringotts.web.domain.entity.format;
import com.eshore.gringotts.core.Constants;
import com.eshore.gringotts.web.domain.base.entity.LogicDeleteIdOnlyEntity;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import lombok.AllArgsConstructor;
@@ -9,8 +7,6 @@ import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
/**
* 一个文件就是一个JSON
@@ -25,13 +21,11 @@ import org.hibernate.annotations.Where;
@NoArgsConstructor
@Entity
@DiscriminatorValue("JSON")
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_format" + " set deleted = true where id = ?")
@Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE)
public class JsonResourceFormat extends ResourceFormat {
private String schema;
private String jsonSchema;
@Override
public Type getFormatType() {
return Type.JSON;
}
@Override
public Type getFormatType() {
return Type.JSON;
}
}

View File

@@ -1,14 +1,10 @@
package com.eshore.gringotts.web.domain.entity.format;
import com.eshore.gringotts.core.Constants;
import com.eshore.gringotts.web.domain.base.entity.LogicDeleteIdOnlyEntity;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
/**
* 无格式,文件每行就是一份数据
@@ -21,11 +17,9 @@ import org.hibernate.annotations.Where;
@ToString
@Entity
@DiscriminatorValue("LINE")
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_format" + " set deleted = true where id = ?")
@Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE)
public class LineResourceFormat extends ResourceFormat {
@Override
public Type getFormatType() {
return Type.LINE;
}
@Override
public Type getFormatType() {
return Type.LINE;
}
}

View File

@@ -1,14 +1,10 @@
package com.eshore.gringotts.web.domain.entity.format;
import com.eshore.gringotts.core.Constants;
import com.eshore.gringotts.web.domain.base.entity.LogicDeleteIdOnlyEntity;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
/**
* 无格式,整个文件就是一份数据
@@ -21,11 +17,9 @@ import org.hibernate.annotations.Where;
@ToString
@Entity
@DiscriminatorValue("NONE")
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_format" + " set deleted = true where id = ?")
@Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE)
public class NoneResourceFormat extends ResourceFormat {
@Override
public Type getFormatType() {
return Type.NONE;
}
@Override
public Type getFormatType() {
return Type.NONE;
}
}

View File

@@ -9,8 +9,6 @@ import javax.persistence.Table;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
/**
* 资源格式
@@ -24,16 +22,14 @@ import org.hibernate.annotations.Where;
@Entity
@Table(name = Constants.TABLE_PREFIX + "resource_format")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_format" + " set deleted = true where id = ?")
@Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE)
public abstract class ResourceFormat extends LogicDeleteIdOnlyEntity {
public abstract Type getFormatType();
public abstract Type getFormatType();
public enum Type {
NONE,
LINE,
JSON,
JSON_LINE,
CSV,
}
public enum Type {
NONE,
LINE,
JSON,
JSON_LINE,
CSV,
}
}

View File

@@ -0,0 +1,93 @@
package com.eshore.gringotts.web.domain.entity.order;
import com.eshore.gringotts.core.Constants;
import com.eshore.gringotts.web.domain.base.entity.SimpleEntity;
import com.eshore.gringotts.web.domain.entity.order.node.CheckOrderNode;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.ConstraintMode;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.ForeignKey;
import javax.persistence.JoinColumn;
import javax.persistence.NamedAttributeNode;
import javax.persistence.NamedEntityGraph;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.DynamicUpdate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
/**
* @author lanyuanxiaoyao
* @date 2024-11-29
*/
@Getter
@Setter
@ToString
@Entity
@DynamicUpdate
@EntityListeners(AuditingEntityListener.class)
@Table(name = Constants.TABLE_PREFIX + "check_order")
@NamedEntityGraph(name = "check_order.list", attributeNodes = {
@NamedAttributeNode(value = "createdUser"),
@NamedAttributeNode(value = "modifiedUser"),
})
@NamedEntityGraph(name = "check_order.detail", attributeNodes = {
@NamedAttributeNode(value = "nodes"),
@NamedAttributeNode(value = "createdUser"),
@NamedAttributeNode(value = "modifiedUser"),
})
@NoArgsConstructor
public class CheckOrder extends SimpleEntity {
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String description;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
@ToString.Exclude
private CheckOrderNode currentNode;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "order")
@ToString.Exclude
private List<CheckOrderNode> nodes;
/**
* JSON 结构 Map<String, Object>
*/
@Column(nullable = false)
private String context = "{}";
@Column(nullable = false)
@Enumerated(EnumType.STRING)
private State state = State.CHECKING;
public enum Operation {
APPLY,
REJECT,
}
public enum Type {
CONFIRMATION,
AUTHENTICATION,
MARKET,
}
public enum Target {
USER,
ROLE,
}
public enum State {
CHECKING,
RETRACT,
OVER,
}
}

View File

@@ -0,0 +1,49 @@
package com.eshore.gringotts.web.domain.entity.order.node;
import com.eshore.gringotts.core.Constants;
import com.eshore.gringotts.web.domain.base.entity.IdOnlyEntity;
import com.eshore.gringotts.web.domain.entity.order.CheckOrder;
import javax.persistence.Column;
import javax.persistence.ConstraintMode;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.FetchType;
import javax.persistence.ForeignKey;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.DynamicUpdate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
/**
* @author lanyuanxiaoyao
* @version 20241225
*/
@Getter
@Setter
@ToString
@Entity
@DynamicUpdate
@EntityListeners(AuditingEntityListener.class)
@Table(name = Constants.TABLE_PREFIX + "check_order_node")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class CheckOrderNode extends IdOnlyEntity {
@Column(nullable = false)
private Integer sequence;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
@ToString.Exclude
private CheckOrder order;
public abstract Type getCheckType();
public enum Type {
USER,
ROLE,
}
}

View File

@@ -0,0 +1,38 @@
package com.eshore.gringotts.web.domain.entity.order.node;
import com.eshore.gringotts.core.Constants;
import com.eshore.gringotts.web.domain.entity.User;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
/**
* 指定用户审核
*
* @author lanyuanxiaoyao
* @version 20241225
*/
@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = Constants.TABLE_PREFIX + "check_order_node_role")
public class RoleCheckOrderNode extends CheckOrderNode {
@Column(nullable = false)
@Enumerated(EnumType.STRING)
private User.Role target;
@Override
public Type getCheckType() {
return Type.ROLE;
}
}

View File

@@ -0,0 +1,41 @@
package com.eshore.gringotts.web.domain.entity.order.node;
import com.eshore.gringotts.core.Constants;
import com.eshore.gringotts.web.domain.entity.User;
import javax.persistence.ConstraintMode;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ForeignKey;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
/**
* 指定用户审核
*
* @author lanyuanxiaoyao
* @version 20241225
*/
@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = Constants.TABLE_PREFIX + "check_order_node_user")
public class UserCheckOrderNode extends CheckOrderNode {
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
@ToString.Exclude
private User target;
@Override
public Type getCheckType() {
return Type.USER;
}
}

View File

@@ -1,7 +1,6 @@
package com.eshore.gringotts.web.domain.entity.type;
import com.eshore.gringotts.core.Constants;
import com.eshore.gringotts.web.domain.base.entity.LogicDeleteIdOnlyEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@@ -10,8 +9,6 @@ import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
@Getter
@Setter
@@ -20,16 +17,14 @@ import org.hibernate.annotations.Where;
@NoArgsConstructor
@Entity
@Table(name = Constants.TABLE_PREFIX + "resource_type_api")
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_type_api" + " set deleted = true where id = ?")
@Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE)
public class ApiResourceType extends ResourceType {
@Column(nullable = false)
private String url;
private String username;
private String password;
@Column(nullable = false)
private String url;
private String username;
private String password;
@Override
public Type getResourceType() {
return Type.API;
}
@Override
public Type getResourceType() {
return Type.API;
}
}

View File

@@ -1,7 +1,6 @@
package com.eshore.gringotts.web.domain.entity.type;
import com.eshore.gringotts.core.Constants;
import com.eshore.gringotts.web.domain.base.entity.LogicDeleteIdOnlyEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
@@ -12,8 +11,6 @@ import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
@Getter
@Setter
@@ -22,25 +19,23 @@ import org.hibernate.annotations.Where;
@NoArgsConstructor
@Entity
@Table(name = Constants.TABLE_PREFIX + "resource_type_database")
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_type_database" + " set deleted = true where id = ?")
@Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE)
public class DatabaseResourceType extends ResourceType {
@Column(nullable = false)
private String jdbc;
private String username;
private String password;
@Column(nullable = false)
@Enumerated(EnumType.STRING)
private DatabaseType databaseType;
@Column(nullable = false)
private String jdbc;
private String username;
private String password;
@Column(nullable = false)
@Enumerated(EnumType.STRING)
private DatabaseType databaseType;
@Override
public Type getResourceType() {
return Type.DATABASE;
}
@Override
public Type getResourceType() {
return Type.DATABASE;
}
public enum DatabaseType {
MYSQL,
POSTGRESQL,
ORACLE,
}
public enum DatabaseType {
MYSQL,
POSTGRESQL,
ORACLE,
}
}

View File

@@ -1,7 +1,6 @@
package com.eshore.gringotts.web.domain.entity.type;
import com.eshore.gringotts.core.Constants;
import com.eshore.gringotts.web.domain.base.entity.LogicDeleteIdOnlyEntity;
import com.eshore.gringotts.web.domain.entity.DataFile;
import javax.persistence.ConstraintMode;
import javax.persistence.Entity;
@@ -14,8 +13,6 @@ import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
@Getter
@Setter
@@ -24,15 +21,13 @@ import org.hibernate.annotations.Where;
@NoArgsConstructor
@Entity
@Table(name = Constants.TABLE_PREFIX + "resource_type_file")
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_type_file" + " set deleted = true where id = ?")
@Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE)
public class FileResourceType extends ResourceType {
@OneToOne
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
private DataFile file;
@OneToOne
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
private DataFile file;
@Override
public Type getResourceType() {
return Type.FILE;
}
@Override
public Type getResourceType() {
return Type.FILE;
}
}

View File

@@ -1,7 +1,6 @@
package com.eshore.gringotts.web.domain.entity.type;
import com.eshore.gringotts.core.Constants;
import com.eshore.gringotts.web.domain.base.entity.LogicDeleteIdOnlyEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@@ -10,8 +9,6 @@ import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
@Getter
@Setter
@@ -20,18 +17,16 @@ import org.hibernate.annotations.Where;
@NoArgsConstructor
@Entity
@Table(name = Constants.TABLE_PREFIX + "resource_type_ftp")
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_type_ftp" + " set deleted = true where id = ?")
@Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE)
public class FtpResourceType extends ResourceType {
@Column(nullable = false)
private String url;
private String username;
private String password;
private String path;
private String regexFilter;
@Column(nullable = false)
private String url;
private String username;
private String password;
private String path;
private String regexFilter;
@Override
public Type getResourceType() {
return Type.FTP;
}
@Override
public Type getResourceType() {
return Type.FTP;
}
}

View File

@@ -1,7 +1,6 @@
package com.eshore.gringotts.web.domain.entity.type;
import com.eshore.gringotts.core.Constants;
import com.eshore.gringotts.web.domain.base.entity.LogicDeleteIdOnlyEntity;
import com.eshore.gringotts.web.domain.entity.DataFile;
import javax.persistence.ConstraintMode;
import javax.persistence.Entity;
@@ -14,8 +13,6 @@ import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
@Getter
@Setter
@@ -24,18 +21,16 @@ import org.hibernate.annotations.Where;
@NoArgsConstructor
@Entity
@Table(name = Constants.TABLE_PREFIX + "resource_type_hdfs")
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_type_hdfs" + " set deleted = true where id = ?")
@Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE)
public class HDFSResourceType extends ResourceType {
@OneToOne
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
private DataFile coreSite;
@OneToOne
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
private DataFile hdfsSite;
@OneToOne
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
private DataFile coreSite;
@OneToOne
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
private DataFile hdfsSite;
@Override
public Type getResourceType() {
return Type.HDFS;
}
@Override
public Type getResourceType() {
return Type.HDFS;
}
}

View File

@@ -9,8 +9,6 @@ import javax.persistence.Table;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
/**
* 资源类型
@@ -24,16 +22,14 @@ import org.hibernate.annotations.Where;
@Entity
@Table(name = Constants.TABLE_PREFIX + "resource_type")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_type" + " set deleted = true where id = ?")
@Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE)
public abstract class ResourceType extends LogicDeleteIdOnlyEntity {
public abstract Type getResourceType();
public abstract Type getResourceType();
public enum Type {
API,
DATABASE,
FILE,
FTP,
HDFS,
}
public enum Type {
API,
DATABASE,
FILE,
FTP,
HDFS,
}
}

View File

@@ -0,0 +1,126 @@
package com.eshore.gringotts.web.domain.flowable;
import com.eshore.gringotts.web.domain.entity.order.CheckOrder;
import com.eshore.gringotts.web.domain.entity.order.node.CheckOrderNode;
import com.eshore.gringotts.web.domain.entity.order.node.RoleCheckOrderNode;
import com.eshore.gringotts.web.domain.entity.order.node.UserCheckOrderNode;
import com.eshore.gringotts.web.domain.flowable.node.RoleCheckFlowNode;
import com.eshore.gringotts.web.domain.flowable.node.UserCheckFlowNode;
import com.eshore.gringotts.web.domain.repository.CheckOrderNodeRepository;
import com.eshore.gringotts.web.domain.service.CheckOrderService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lanyuanxiaoyao.flowable.model.Flow;
import com.lanyuanxiaoyao.flowable.model.FlowStatus;
import com.lanyuanxiaoyao.flowable.node.FlowNode;
import com.lanyuanxiaoyao.flowable.repository.FlowRepository;
import java.util.stream.Collectors;
import lombok.SneakyThrows;
import org.eclipse.collections.api.factory.Lists;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.stereotype.Service;
/**
* @author lanyuanxiaoyao
* @version 20241225
*/
@Service
public class FlowDatabaseRepository implements FlowRepository {
private final CheckOrderService checkOrderService;
private final CheckOrderNodeRepository checkOrderNodeRepository;
private final ObjectMapper mapper;
public FlowDatabaseRepository(CheckOrderService checkOrderService, CheckOrderNodeRepository checkOrderNodeRepository, Jackson2ObjectMapperBuilder builder) {
this.checkOrderService = checkOrderService;
this.checkOrderNodeRepository = checkOrderNodeRepository;
this.mapper = builder.build();
}
private FlowNode mapTo(CheckOrderNode source) {
switch (source.getCheckType()) {
case USER:
return new UserCheckFlowNode(source.getId().toString(), ((UserCheckOrderNode) source).getTarget());
case ROLE:
return new RoleCheckFlowNode(source.getId().toString(), ((RoleCheckOrderNode) source).getTarget());
default:
throw new IllegalArgumentException("Unsupported check type: " + source.getCheckType());
}
}
private CheckOrderNode mapTo(FlowNode source) {
return checkOrderNodeRepository.findById(Long.valueOf(source.getNodeId())).orElseThrow(() -> new RuntimeException(""));
}
private Flow mapTo(CheckOrder order) throws JsonProcessingException {
Flow flow = new Flow();
flow.setName(order.getName());
flow.setDescription(order.getDescription());
flow.setNodes(order.getNodes()
.stream()
.map(this::mapTo)
.collect(Collectors.toList())
);
flow.setCurrentNode(mapTo(order.getCurrentNode()).getNodeId());
switch (order.getState()) {
case CHECKING:
flow.setStatus(FlowStatus.PENDING);
break;
case RETRACT:
flow.setStatus(FlowStatus.REJECTED);
break;
case OVER:
flow.setStatus(FlowStatus.APPROVED);
break;
}
flow.setContextVariables(mapper.readValue(order.getContext(), new TypeReference<>() {}));
flow.setCreateTime(order.getCreatedTime());
flow.setUpdateTime(order.getModifiedTime());
return flow;
}
private void mapTo(Flow flow, CheckOrder order) throws JsonProcessingException {
order.setName(flow.getName());
order.setDescription(flow.getDescription());
order.setNodes(Lists.mutable.ofAll(flow.getNodes()).collect(this::mapTo));
order.setCurrentNode(mapTo(flow.getCurrentNodeObject()));
switch (flow.getStatus()) {
case APPROVED:
order.setState(CheckOrder.State.OVER);
break;
case PENDING:
order.setState(CheckOrder.State.CHECKING);
break;
case REJECTED:
order.setState(CheckOrder.State.RETRACT);
break;
}
order.setContext(mapper.writeValueAsString(flow.getContextVariables()));
}
@SneakyThrows
@Override
public Flow save(Flow flow) {
CheckOrder order = new CheckOrder();
mapTo(flow, order);
Long id = checkOrderService.save(order);
flow.setId(id.toString());
return flow;
}
@SneakyThrows
@Override
public Flow update(Flow flow) {
CheckOrder order = checkOrderService.detailOrThrow(Long.parseLong(flow.getId()));
mapTo(flow, order);
checkOrderService.save(order);
return flow;
}
@SneakyThrows
@Override
public Flow findById(String id) {
CheckOrder order = checkOrderService.detailOrThrow(Long.parseLong(id));
return mapTo(order);
}
}

View File

@@ -0,0 +1,19 @@
package com.eshore.gringotts.web.domain.flowable.node;
import com.eshore.gringotts.web.domain.entity.User;
import com.lanyuanxiaoyao.flowable.node.AbstractFlowNode;
import lombok.Getter;
/**
* @author lanyuanxiaoyao
* @version 20241225
*/
@Getter
public class RoleCheckFlowNode extends AbstractFlowNode {
private final User.Role role;
public RoleCheckFlowNode(String nodeId, User.Role role) {
super(nodeId);
this.role = role;
}
}

View File

@@ -0,0 +1,34 @@
package com.eshore.gringotts.web.domain.flowable.node;
import com.eshore.gringotts.web.domain.entity.User;
import com.eshore.gringotts.web.domain.service.ConfirmationService;
import com.lanyuanxiaoyao.flowable.model.FlowContext;
import com.lanyuanxiaoyao.flowable.node.AbstractFlowNode;
import lombok.Getter;
/**
* @author lanyuanxiaoyao
* @version 20241225
*/
@Getter
public class UserCheckFlowNode extends AbstractFlowNode {
private final User user;
private final ConfirmationService confirmationService;
public UserCheckFlowNode(String nodeId, User user, ConfirmationService confirmationService) {
super(nodeId);
this.user = user;
this.confirmationService = confirmationService;
}
@Override
public void onApprove(FlowContext context) {
super.onApprove(context);
Long confirmationId = context.getVariable("confirmationId", Long.class);
}
@Override
public void onReject(FlowContext context) {
super.onReject(context);
}
}

View File

@@ -16,15 +16,15 @@ import org.springframework.stereotype.Repository;
@SuppressWarnings("NullableProblems")
@Repository
public interface AuthenticationRepository extends SimpleRepository<Authentication, Long> {
@Override
@EntityGraph(value = "authentication.list", type = EntityGraph.EntityGraphType.FETCH)
List<Authentication> findAll(Specification<Authentication> specification);
@Override
@EntityGraph(value = "authentication.list", type = EntityGraph.EntityGraphType.FETCH)
List<Authentication> findAll(Specification<Authentication> specification);
@Override
@EntityGraph(value = "authentication.list", type = EntityGraph.EntityGraphType.FETCH)
List<Authentication> findAll(Specification<Authentication> specification, Sort sort);
@Override
@EntityGraph(value = "authentication.list", type = EntityGraph.EntityGraphType.FETCH)
List<Authentication> findAll(Specification<Authentication> specification, Sort sort);
@Override
@EntityGraph(value = "authentication.detail", type = EntityGraph.EntityGraphType.FETCH)
Optional<Authentication> findOne(Specification<Authentication> specification);
@Override
@EntityGraph(value = "authentication.detail", type = EntityGraph.EntityGraphType.FETCH)
Optional<Authentication> findOne(Specification<Authentication> specification);
}

View File

@@ -0,0 +1,13 @@
package com.eshore.gringotts.web.domain.repository;
import com.eshore.gringotts.web.domain.base.repository.SimpleRepository;
import com.eshore.gringotts.web.domain.entity.order.node.CheckOrderNode;
import org.springframework.stereotype.Repository;
/**
* @author lanyuanxiaoyao
* @version 20241225
*/
@Repository
public interface CheckOrderNodeRepository extends SimpleRepository<CheckOrderNode, Long> {
}

View File

@@ -1,8 +1,8 @@
package com.eshore.gringotts.web.domain.repository;
import com.eshore.gringotts.web.domain.base.repository.SimpleRepository;
import com.eshore.gringotts.web.domain.entity.CheckOrder;
import com.eshore.gringotts.web.domain.entity.User;
import com.eshore.gringotts.web.domain.entity.order.CheckOrder;
import java.util.List;
import java.util.Optional;
import javax.transaction.Transactional;
@@ -20,20 +20,20 @@ import org.springframework.stereotype.Repository;
@SuppressWarnings("NullableProblems")
@Repository
public interface CheckOrderRepository extends SimpleRepository<CheckOrder, Long> {
@Override
@EntityGraph(value = "check_order.list", type = EntityGraph.EntityGraphType.FETCH)
List<CheckOrder> findAll(Specification<CheckOrder> specification);
@Override
@EntityGraph(value = "check_order.list", type = EntityGraph.EntityGraphType.FETCH)
List<CheckOrder> findAll(Specification<CheckOrder> specification);
@Override
@EntityGraph(value = "check_order.list", type = EntityGraph.EntityGraphType.FETCH)
List<CheckOrder> findAll(Specification<CheckOrder> specification, Sort sort);
@Override
@EntityGraph(value = "check_order.list", type = EntityGraph.EntityGraphType.FETCH)
List<CheckOrder> findAll(Specification<CheckOrder> specification, Sort sort);
@Override
@EntityGraph(value = "check_order.detail", type = EntityGraph.EntityGraphType.FETCH)
Optional<CheckOrder> findOne(Specification<CheckOrder> specification);
@Override
@EntityGraph(value = "check_order.detail", type = EntityGraph.EntityGraphType.FETCH)
Optional<CheckOrder> findOne(Specification<CheckOrder> specification);
@Transactional
@Modifying
@Query("update CheckOrder check set check.state = ?2, check.modifiedUser = ?3, check.modifiedTime = current_timestamp where check.id = ?1")
void overById(Long id, CheckOrder.State state, User modifiedUser);
@Transactional
@Modifying
@Query("update CheckOrder check set check.state = ?2, check.modifiedUser = ?3, check.modifiedTime = current_timestamp where check.id = ?1")
void overById(Long id, CheckOrder.State state, User modifiedUser);
}

View File

@@ -16,17 +16,17 @@ import org.springframework.stereotype.Repository;
@SuppressWarnings("NullableProblems")
@Repository
public interface ConfirmationRepository extends SimpleRepository<Confirmation, Long> {
@Override
@EntityGraph(value = "confirmation.list", type = EntityGraph.EntityGraphType.FETCH)
List<Confirmation> findAll(Specification<Confirmation> specification);
@Override
@EntityGraph(value = "confirmation.list", type = EntityGraph.EntityGraphType.FETCH)
List<Confirmation> findAll(Specification<Confirmation> specification);
@Override
@EntityGraph(value = "confirmation.list", type = EntityGraph.EntityGraphType.FETCH)
List<Confirmation> findAll(Specification<Confirmation> specification, Sort sort);
@Override
@EntityGraph(value = "confirmation.list", type = EntityGraph.EntityGraphType.FETCH)
List<Confirmation> findAll(Specification<Confirmation> specification, Sort sort);
@Override
@EntityGraph(value = "confirmation.detail", type = EntityGraph.EntityGraphType.FETCH)
Optional<Confirmation> findOne(Specification<Confirmation> specification);
@Override
@EntityGraph(value = "confirmation.detail", type = EntityGraph.EntityGraphType.FETCH)
Optional<Confirmation> findOne(Specification<Confirmation> specification);
Boolean existsByTarget_Id(Long id);
Boolean existsByTarget_Id(Long id);
}

View File

@@ -12,18 +12,18 @@ import org.springframework.stereotype.Repository;
@SuppressWarnings("NullableProblems")
@Repository
public interface DataResourceRepository extends SimpleRepository<DataResource, Long> {
@Override
@EntityGraph(value = "data_resource.list", type = EntityGraph.EntityGraphType.FETCH)
List<DataResource> findAll(Specification<DataResource> specification);
@Override
@EntityGraph(value = "data_resource.list", type = EntityGraph.EntityGraphType.FETCH)
List<DataResource> findAll(Specification<DataResource> specification);
@Override
@EntityGraph(value = "data_resource.list", type = EntityGraph.EntityGraphType.FETCH)
List<DataResource> findAll(Specification<DataResource> specification, Sort sort);
@Override
@EntityGraph(value = "data_resource.list", type = EntityGraph.EntityGraphType.FETCH)
List<DataResource> findAll(Specification<DataResource> specification, Sort sort);
@EntityGraph(value = "data_resource.list", type = EntityGraph.EntityGraphType.FETCH)
List<DataResource> findAllByConfirmationIsNull();
@EntityGraph(value = "data_resource.list", type = EntityGraph.EntityGraphType.FETCH)
List<DataResource> findAllByConfirmationIsNull();
@Override
@EntityGraph(value = "data_resource.detail", type = EntityGraph.EntityGraphType.FETCH)
Optional<DataResource> findOne(Specification<DataResource> specification);
@Override
@EntityGraph(value = "data_resource.detail", type = EntityGraph.EntityGraphType.FETCH)
Optional<DataResource> findOne(Specification<DataResource> specification);
}

View File

@@ -16,12 +16,12 @@ import org.springframework.stereotype.Repository;
@SuppressWarnings("NullableProblems")
@Repository
public interface UserRepository extends SimpleRepository<User, Long> {
@Override
@EntityGraph(value = "user.list", type = EntityGraph.EntityGraphType.FETCH)
List<User> findAll();
@Override
@EntityGraph(value = "user.list", type = EntityGraph.EntityGraphType.FETCH)
List<User> findAll();
Boolean existsByUsername(String username);
Boolean existsByUsername(String username);
@EntityGraph(value = "user.detail", type = EntityGraph.EntityGraphType.FETCH)
Optional<User> findByUsername(String username);
@EntityGraph(value = "user.detail", type = EntityGraph.EntityGraphType.FETCH)
Optional<User> findByUsername(String username);
}

View File

@@ -12,15 +12,15 @@ import org.springframework.stereotype.Repository;
@SuppressWarnings("NullableProblems")
@Repository
public interface WareRepository extends SimpleRepository<Ware, Long> {
@Override
@EntityGraph(value = "ware.list", type = EntityGraph.EntityGraphType.FETCH)
List<Ware> findAll(Specification<Ware> specification);
@Override
@EntityGraph(value = "ware.list", type = EntityGraph.EntityGraphType.FETCH)
List<Ware> findAll(Specification<Ware> specification);
@Override
@EntityGraph(value = "ware.list", type = EntityGraph.EntityGraphType.FETCH)
List<Ware> findAll(Specification<Ware> specification, Sort sort);
@Override
@EntityGraph(value = "ware.list", type = EntityGraph.EntityGraphType.FETCH)
List<Ware> findAll(Specification<Ware> specification, Sort sort);
@Override
@EntityGraph(value = "ware.detail", type = EntityGraph.EntityGraphType.FETCH)
Optional<Ware> findOne(Specification<Ware> specification);
@Override
@EntityGraph(value = "ware.detail", type = EntityGraph.EntityGraphType.FETCH)
Optional<Ware> findOne(Specification<Ware> specification);
}

View File

@@ -1,30 +1,11 @@
package com.eshore.gringotts.web.domain.service;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.eshore.gringotts.web.domain.base.entity.CheckingNeededEntity;
import com.eshore.gringotts.web.domain.base.service.CheckingService;
import com.eshore.gringotts.web.domain.base.service.LogicDeleteService;
import com.eshore.gringotts.web.domain.entity.Authentication;
import com.eshore.gringotts.web.domain.entity.Authentication_;
import com.eshore.gringotts.web.domain.entity.CheckOrder;
import com.eshore.gringotts.web.domain.entity.CheckOrder_;
import com.eshore.gringotts.web.domain.entity.User;
import com.eshore.gringotts.web.domain.repository.AuthenticationRepository;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.collections.api.factory.Lists;
import org.eclipse.collections.api.factory.Maps;
import org.eclipse.collections.api.list.ImmutableList;
import org.eclipse.collections.api.map.ImmutableMap;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.stereotype.Service;
/**
@@ -32,122 +13,37 @@ import org.springframework.stereotype.Service;
* @date 2024-12-02
*/
@Slf4j
@Service("com.eshore.gringotts.web.domain.service.AuthenticationService")
public class AuthenticationService extends LogicDeleteService<Authentication> implements CheckingService {
private final AuthenticationRepository authenticationRepository;
private final UserService userService;
private final CheckOrderService checkOrderService;
private final ObjectMapper mapper;
@Service
public class AuthenticationService extends LogicDeleteService<Authentication> {
private final AuthenticationRepository authenticationRepository;
private final UserService userService;
public AuthenticationService(AuthenticationRepository repository, UserService userService, EntityManager manager, CheckOrderService checkOrderService, Jackson2ObjectMapperBuilder builder) {
super(repository, userService, manager);
this.authenticationRepository = repository;
this.userService = userService;
this.checkOrderService = checkOrderService;
this.mapper = builder.build();
}
public AuthenticationService(AuthenticationRepository repository, UserService userService, EntityManager manager) {
super(repository, userService, manager);
this.authenticationRepository = repository;
this.userService = userService;
}
@Override
protected ImmutableList<Predicate> listPredicate(Root<Authentication> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
User loginUser = userService.currentLoginUser();
if (User.isAdministrator(loginUser)) {
return Lists.immutable.empty();
@Override
public Long save(Authentication entity) {
if (ObjectUtil.isNull(entity.getId()) && authenticationRepository.findOne(
(root, query, criteriaBuilder) -> {
// TODO 同一个资源的授权时间是否重合
// 查询是否存在createdUser为当前登陆用户并且绑定的数据资源是同一个的授权申请
return criteriaBuilder.and(
criteriaBuilder.equal(root.get("createdUser"), userService.currentLoginUser()),
criteriaBuilder.equal(root.get("target"), entity.getTarget())
);
}
return Lists.immutable.of(builder.or(
builder.equal(root.get(Authentication_.createdUser), loginUser),
builder.and(
builder.equal(root.get(Authentication_.order).get(CheckOrder_.target), CheckOrder.Target.ROLE),
builder.equal(root.get(Authentication_.order).get(CheckOrder_.targetRole), loginUser.getRole())
),
builder.and(
builder.equal(root.get(Authentication_.order).get(CheckOrder_.target), CheckOrder.Target.USER),
builder.equal(root.get(Authentication_.order).get(CheckOrder_.targetUser), loginUser)
)
));
).isPresent()) {
throw new AuthenticationDuplicatedException();
}
return super.save(entity);
}
@Override
public Long save(Authentication entity) {
if (ObjectUtil.isNull(entity.getId()) && authenticationRepository.findOne(
(root, query, criteriaBuilder) -> {
// TODO 同一个资源的授权时间是否重合
// 查询是否存在createdUser为当前登陆用户并且绑定的数据资源是同一个的授权申请
return criteriaBuilder.and(
criteriaBuilder.equal(root.get("createdUser"), userService.currentLoginUser()),
criteriaBuilder.equal(root.get("target"), entity.getTarget())
);
}
).isPresent()) {
throw new AuthenticationDuplicatedException();
}
return super.save(entity);
}
@Transactional(rollbackOn = Throwable.class)
public void submit(Long id) throws JsonProcessingException {
Authentication authentication = detailOrThrow(id);
authentication.setState(CheckingNeededEntity.State.OWNER_CHECKING);
Long orderId = checkOrderService.save(new CheckOrder(
"authentication_owner_check",
StrUtil.format("数据资源「{}」的授权申请", authentication.getTarget().getName()),
CheckOrder.Type.AUTHENTICATION,
mapper.writeValueAsString(Maps.immutable.of("authenticationId", authentication.getId())),
"com.eshore.gringotts.web.domain.service.AuthenticationService",
authentication.getCreatedUser()
));
CheckOrder order = checkOrderService.detailOrThrow(orderId);
authentication.setOrder(order);
save(authentication);
}
@Transactional(rollbackOn = Throwable.class)
public void retract(Long id) {
Authentication authentication = detailOrThrow(id);
authentication.setState(Authentication.State.DRAFT);
save(authentication);
CheckOrder order = authentication.getOrder();
order.setState(CheckOrder.State.RETRACT);
checkOrderService.save(order);
}
@Override
@Transactional(rollbackOn = Throwable.class)
public void onChecked(CheckOrder order, CheckOrder.Operation operation, ImmutableMap<String, Object> parameters) {
Long id = (Long) parameters.get("authenticationId");
Authentication authentication = detailOrThrow(id);
if (StrUtil.equals(order.getKeyword(), "authentication_owner_check")) {
switch (operation) {
case APPLY:
authentication.setState(Authentication.State.CHECKING);
order.setKeyword("authentication_checker_check");
order.setTarget(CheckOrder.Target.ROLE);
order.setTargetRole(User.Role.CHECKER);
break;
case REJECT:
authentication.setState(Authentication.State.DRAFT);
order.setState(CheckOrder.State.OVER);
break;
}
} else if (StrUtil.equals(order.getKeyword(), "authentication_checker_check")) {
switch (operation) {
case APPLY:
authentication.setState(Authentication.State.NORMAL);
order.setState(CheckOrder.State.OVER);
break;
case REJECT:
authentication.setState(Authentication.State.DRAFT);
order.setState(CheckOrder.State.OVER);
break;
}
}
save(authentication);
checkOrderService.save(order);
}
public static final class AuthenticationDuplicatedException extends RuntimeException {
public AuthenticationDuplicatedException() {
super("数据资源已绑定该账号的授权申请,无法再次申请");
}
public static final class AuthenticationDuplicatedException extends RuntimeException {
public AuthenticationDuplicatedException() {
super("数据资源已绑定该账号的授权申请,无法再次申请");
}
}
}

View File

@@ -1,26 +1,12 @@
package com.eshore.gringotts.web.domain.service;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.eshore.gringotts.web.domain.base.service.CheckingService;
import com.eshore.gringotts.web.domain.base.service.SimpleServiceSupport;
import com.eshore.gringotts.web.domain.entity.CheckOrder;
import com.eshore.gringotts.web.domain.entity.CheckOrder_;
import com.eshore.gringotts.web.domain.entity.User;
import com.eshore.gringotts.web.domain.entity.order.CheckOrder;
import com.eshore.gringotts.web.domain.flowable.FlowDatabaseRepository;
import com.eshore.gringotts.web.domain.repository.CheckOrderRepository;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import com.lanyuanxiaoyao.flowable.service.FlowService;
import javax.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.collections.api.factory.Lists;
import org.eclipse.collections.api.list.ImmutableList;
import org.eclipse.collections.api.map.ImmutableMap;
import org.springframework.context.ApplicationContext;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.stereotype.Service;
/**
@@ -30,53 +16,30 @@ import org.springframework.stereotype.Service;
@Slf4j
@Service
public class CheckOrderService extends SimpleServiceSupport<CheckOrder> {
private final ApplicationContext applicationContext;
private final ObjectMapper mapper;
private final CheckOrderRepository checkOrderRepository;
private final UserService userService;
private final FlowService flowService;
public CheckOrderService(CheckOrderRepository repository, UserService userService, ApplicationContext applicationContext, Jackson2ObjectMapperBuilder builder) {
super(repository, userService);
this.applicationContext = applicationContext;
this.mapper = builder.build();
this.checkOrderRepository = repository;
this.userService = userService;
}
public CheckOrderService(CheckOrderRepository repository, UserService userService, FlowDatabaseRepository flowDatabaseRepository) {
super(repository, userService);
this.flowService = new FlowService(flowDatabaseRepository);
}
@Override
protected ImmutableList<Predicate> listPredicate(Root<CheckOrder> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
User user = userService.currentLoginUser();
if (User.isAdministrator(user)) {
return Lists.immutable.empty();
}
return Lists.immutable.of(builder.or(
builder.equal(root.get(CheckOrder_.createdUser), user),
builder.and(
builder.equal(root.get(CheckOrder_.target), CheckOrder.Target.USER),
builder.equal(root.get(CheckOrder_.targetUser), user)
),
builder.and(
builder.equal(root.get(CheckOrder_.target), CheckOrder.Target.ROLE),
builder.equal(root.get(CheckOrder_.targetRole), user.getRole())
)
));
}
@Transactional(rollbackOn = Throwable.class)
public void startFlow(CheckOrder order) {
startFlow(order.getId());
}
public void operation(Long id, CheckOrder.Operation operation) throws JsonProcessingException {
CheckOrder order = detailOrThrow(id);
CheckingService service = applicationContext.getBean(order.getTargetClass(), CheckingService.class);
if (ObjectUtil.isNull(service)) {
throw new RuntimeException(StrUtil.format("名为「{}」的服务未找到", order.getTargetClass()));
}
ImmutableMap<String, Object> parameters = mapper.readValue(order.getParameters(), new TypeReference<>() {});
service.onChecked(order, operation, parameters);
}
@Transactional(rollbackOn = Throwable.class)
public void startFlow(Long id) {
flowService.startFlow(id.toString());
}
public void retract(Long id) {
checkOrderRepository.overById(id, CheckOrder.State.RETRACT, userService.currentLoginUser());
}
@Transactional(rollbackOn = Throwable.class)
public void approve(Long id) {
flowService.approve(id.toString());
}
public void over(Long id) {
checkOrderRepository.overById(id, CheckOrder.State.OVER, userService.currentLoginUser());
}
@Transactional(rollbackOn = Throwable.class)
public void reject(Long id) {
flowService.reject(id.toString());
}
}

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