1
0

20 Commits

Author SHA1 Message Date
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
100 changed files with 5045 additions and 4740 deletions

7
.gitignore vendored
View File

@@ -1,6 +1,3 @@
### Custom
*.db
### Maven template ### Maven template
target/ target/
pom.xml.tag pom.xml.tag
@@ -255,3 +252,7 @@ Network Trash Folder
Temporary Items Temporary Items
.apdisk .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> </jdbc-additional-properties>
<working-dir>$ProjectFileDir$</working-dir> <working-dir>$ProjectFileDir$</working-dir>
</data-source> </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> <driver-ref>mysql.8</driver-ref>
<synchronize>true</synchronize> <synchronize>true</synchronize>
<jdbc-driver>com.mysql.cj.jdbc.Driver</jdbc-driver> <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> <jdbc-additional-properties>
<property name="com.intellij.clouds.kubernetes.db.host.port" /> <property name="com.intellij.clouds.kubernetes.db.host.port" />
<property name="com.intellij.clouds.kubernetes.db.enabled" value="false" /> <property name="com.intellij.clouds.kubernetes.db.enabled" value="false" />

View File

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

View File

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

View File

@@ -1,49 +1,49 @@
export function emailFormItem(name) { export function emailFormItem(name) {
return { return {
type: 'input-email', type: 'input-email',
name: name, name: name,
label: '邮箱', label: '邮箱',
placeholder: '请输入邮箱', placeholder: '请输入邮箱',
required: true, required: true,
clearable: true, clearable: true,
clearValueOnEmpty: true, clearValueOnEmpty: true,
validateApi: '${base}/user/exists_username/${username}', validateApi: '${base}/user/exists_username/${username}',
} }
} }
export function passwordFormItem(name, label = '密码') { export function passwordFormItem(name, label = '密码') {
return { return {
type: 'input-password', type: 'input-password',
name: name, name: name,
label: label, label: label,
placeholder: `请输入${label}`, placeholder: `请输入${label}`,
required: true, required: true,
clearable: true, clearable: true,
clearValueOnEmpty: true, clearValueOnEmpty: true,
validations: { validations: {
matchRegexp: 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}$/, /^(?=.*\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: { validationErrors: {
matchRegexp: matchRegexp:
`${label}至少包含字母、数字、特殊字符8-16位并且不能连续出现3个大小连续或相同的数字`, `${label}至少包含字母、数字、特殊字符8-16位并且不能连续出现3个大小连续或相同的数字`,
}, },
} }
} }
export function confirmPasswordFormItem(name, target, label = '密码') { export function confirmPasswordFormItem(name, target, label = '密码') {
return { return {
type: 'input-password', type: 'input-password',
name: name, name: name,
label: `确认${label}`, label: `确认${label}`,
placeholder: `请再次输入${label}`, placeholder: `请再次输入${label}`,
required: true, required: true,
clearable: true, clearable: true,
validations: { validations: {
equalsField: target, equalsField: target,
}, },
validationErrors: { validationErrors: {
equalsField: `两次输入${label}不一致`, equalsField: `两次输入${label}不一致`,
}, },
} }
} }

View File

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

View File

@@ -4,188 +4,198 @@ import {resourceList} from '../../pages/index/tab-data.js'
import {resourceDetailDialog} from '../resource/dialog-resource.js' import {resourceDetailDialog} from '../resource/dialog-resource.js'
function detailForm() { function detailForm() {
return { return {
id: 'ware-form', id: 'ware-form',
debug: information.debug, debug: information.debug,
type: 'form', type: 'form',
...horizontalFormOptions(), ...horizontalFormOptions(),
horizontal: { horizontal: {
left: 2, 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: [ staticSchema: {
{ type: 'tpl',
type: 'hidden', tpl: "<span class='text-primary' style='cursor: pointer'>${resourceName}</span>",
name: 'id', onEvent: {
}, click: {
{ actions: [
visibleOn: '${!detail}', {
type: 'input-image', actionType: 'dialog',
name: 'icon', ...resourceDetailDialog('resourceId'),
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,
} }
]
} }
] }
} }
},
{
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() { export function wareAddDialog() {
return { return {
actionType: 'dialog', actionType: 'dialog',
dialog: { dialog: {
title: '上架数据产品', title: '上架数据产品',
size: 'md', size: 'md',
actions: [ actions: [
{ {
type: 'reset', type: 'reset',
label: '重置', label: '重置',
}, },
{ {
type: 'submit', type: 'submit',
label: '确定', label: '确定',
level: 'primary', level: 'primary',
}
],
body: {
...detailForm(),
api: apiPost(`\${base}/ware/save`),
data: {
add: true,
}
}
} }
],
body: {
...detailForm(),
api: apiPost(`\${base}/ware/save`),
data: {
add: true,
}
}
} }
}
} }
export function wareDetailDialog(field = 'id', actions = []) { export function wareDetailDialog(field = 'id', actions = []) {
return { return {
actionType: 'dialog', actionType: 'dialog',
dialog: { dialog: {
title: '数据产品详情', title: '数据产品详情',
size: 'md', size: 'md',
actions: actions, actions: actions,
body: { body: {
...detailForm(), ...detailForm(),
initApi: apiGet(`\${base}/ware/detail/\${${field}}`), initApi: apiGet(`\${base}/ware/detail/\${${field}}`),
static: true, static: true,
data: { data: {
detail: true, detail: true,
}
}
} }
}
} }
}
} }
export function wareEditeDialog() { export function wareEditeDialog() {
return { return {
actionType: 'dialog', actionType: 'dialog',
dialog: { dialog: {
title: '数据产品详情', title: '数据产品详情',
size: 'md', size: 'md',
actions: [ actions: [
{ {
type: 'reset', type: 'reset',
label: '重置', label: '重置',
}, },
{ {
type: 'submit', type: 'submit',
label: '确定', label: '确定',
level: 'primary', level: 'primary',
}
],
body: {
...detailForm(),
api: apiPost(`\${base}/ware/save`),
initApi: apiGet(`\${base}/ware/detail/\${id}`),
data: {
edit: true
}
},
} }
],
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"> <html lang="zh">
<head> <head>
<meta charset="UTF-8"/> <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> <title></title>
<link href="/assets/sdk/antd.css" rel="stylesheet"/> <link href="/assets/sdk/antd.css" rel="stylesheet"/>
<link href="/assets/sdk/helper.css" rel="stylesheet"/> <link href="/assets/sdk/helper.css" rel="stylesheet"/>
@@ -20,6 +20,6 @@
<body> <body>
<div id="app"></div> <div id="app"></div>
<script src="/assets/sdk/sdk.js"></script> <script src="/assets/sdk/sdk.js"></script>
<script type="module" src="./main.js"></script> <script src="./main.js" type="module"></script>
</body> </body>
</html> </html>

View File

@@ -1,73 +1,200 @@
import {apiGet, useAmis} from '../../components/constants.js' import './style.css'
import {userChangePasswordDialog} from "../../components/user/dialog-user-change-password.js"; import {administratorOnly, apiGet, checkerOnly, useAmis, userOnly} from '../../components/constants.js'
import {tabUser} from "./tab-user.js"; import {userChangePasswordDialog} from '../../components/user/dialog-user-change-password.js'
import {tabData} from "./tab-data.js"; import {tabUser} from './tab-user.js'
import {tabSettings} from "./tab-settings.js"; import {tabData} from './tab-data.js'
import {tabCheck} from "./tab-check.js"; import {tabSettings} from './tab-settings.js'
import {tabPermissions} from "./tab-permissions.js"; import {tabCheck} from './tab-check.js'
import {tabMarket} from "./tab-market.js"; import {tabPermissions} from './tab-permissions.js'
import {tabMarket} from './tab-market.js'
useAmis(information => { useAmis((information) => {
return { return {
id: 'header-service', id: 'header-service',
className: 'h-full', className: 'h-full',
type: 'service', type: 'service',
api: apiGet('${base}/user/state'), api: apiGet('${base}/user/state'),
onEvent: { onEvent: {
fetchInited: { fetchInited: {
actions: [ actions: [
{ {
expression: '${!event.data.responseData.token}', expression: '${!event.data.responseData.token}',
actionType: 'url', actionType: 'url',
args: { args: {
url: '/pages/login/index.html', url: '/pages/login/index.html',
blank: false, 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: [ body: [
{ {
type: 'page', visibleOn: "${activePage === 'market'}",
title: information.title, type: 'wrapper',
subTitle: '提供合法合规的数据要素可信供给工具', body: tabMarket(),
toolbar: [ },
{ {
type: 'dropdown-button', visibleOn: "${activePage === 'tab'}",
label: '${username}', className: 'h-full border-0',
align: 'right', type: 'tabs',
trigger: 'hover', tabsMode: 'vertical',
buttons: [ activeKey: '${tabActiveKey}',
{ tabs: [
label: '修改密码', // tabOverview(),
...userChangePasswordDialog(), {
}, hash: 'data',
{ visibleOn: userOnly,
label: '退出登陆', title: '数据资源',
actionType: 'ajax', icon: 'fa fa-database',
api: apiGet('${base}/user/logout'), reload: true,
reload: 'header-service', body: tabData()
} },
] {
} hash: 'permission',
], visibleOn: userOnly,
bodyClassName: 'p-0', title: '权属管理',
body: { icon: 'fa fa-key',
className: 'h-full border-0', reload: true,
type: 'tabs', body: tabPermissions(),
tabsMode: 'vertical', },
tabs: [ {
// tabOverview(), hash: 'check',
tabMarket(), visibleOn: checkerOnly,
tabPermissions(), title: '审核审查',
tabCheck(), icon: 'fa fa-shield-halved',
tabData(), reload: true,
tabUser(), body: tabCheck(),
tabSettings(), },
] {
}, 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 { import {
apiGet, apiGet,
checkerOnly, checkOverMapping,
checkOverMapping, checkTypeMapping,
checkTypeMapping, crudCommonOptions,
crudCommonOptions, mappingField,
mappingField, operationField,
operationField, stringField,
stringField, timeField,
timeField,
} from "../../components/constants.js"; } from "../../components/constants.js";
import {authenticationDetailDialog, confirmationDetailDialog} from "../../components/permission/dialog-permission.js"; import {authenticationDetailDialog, confirmationDetailDialog} from "../../components/permission/dialog-permission.js";
import {wareDetailDialog} from "../../components/ware/dialog-ware.js"; import {wareDetailDialog} from "../../components/ware/dialog-ware.js";
export function tabCheck() { export function tabCheck() {
return { return [
visibleOn: checkerOnly, {
title: '审核审查', name: 'check_order_list',
icon: 'fa fa-shield-halved', type: 'crud',
reload: true, api: apiGet('${base}/check_order/list'),
body: [ ...crudCommonOptions(),
{ headerToolbar: [
name: 'check_order_list', 'reload',
type: 'crud', ],
api: apiGet('${base}/check_order/list'), columns: [
...crudCommonOptions(), stringField('description', '描述'),
headerToolbar: [ mappingField('type', '类型', checkTypeMapping),
'reload', mappingField('state', '状态', checkOverMapping),
], timeField('createdTime', '创建时间'),
columns: [ stringField('createdUsername', '创建人', 100),
stringField('description', '描述'), timeField('modifiedTime', '最后修改时间'),
mappingField('type', '类型', checkTypeMapping), stringField('modifiedUsername', '最后操作人', 100),
mappingField('state', '状态', checkOverMapping), operationField('操作', undefined, [
timeField('createdTime', '创建时间'), {
stringField('createdUsername', '创建人', 100), visibleOn: "${type === 'CONFIRMATION' && state === 'CHECKING'}",
timeField('modifiedTime', '最后修改时间'), type: 'action',
stringField('modifiedUsername', '最后操作人', 100), label: '处理',
operationField('操作', undefined, [ level: 'link',
{ ...confirmationDetailDialog(
visibleOn: `\${type === 'CONFIRMATION' && state === 'CHECKING'}`, 'parameters.confirmationId',
type: 'action', [
label: '处理', {
level: 'link', type: 'action',
...confirmationDetailDialog( label: '同意',
'parameters.confirmationId', actionType: 'ajax',
[ close: true,
{ api: apiGet('${base}/check_order/operation/${checkOrderId}/APPLY'),
type: 'action', reload: 'check_order_list',
label: '同意', },
actionType: 'ajax', {
close: true, type: 'action',
api: apiGet('${base}/check_order/operation/${checkOrderId}/APPLY'), label: '拒绝',
reload: 'check_order_list', actionType: 'ajax',
}, close: true,
{ api: apiGet('${base}/check_order/operation/${checkOrderId}/REJECT'),
type: 'action', reload: 'check_order_list',
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 === 'CONFIRMATION' && state !== NORMAL}`, },
type: 'action', {
label: '查看', visibleOn: "${type === 'AUTHENTICATION' && state === 'CHECKING'}",
level: 'link', type: 'action',
...confirmationDetailDialog('parameters.confirmationId'), label: '处理',
}, level: 'link',
{ ...authenticationDetailDialog(
visibleOn: `\${type === 'AUTHENTICATION' && state === 'CHECKING'}`, 'parameters.authenticationId',
type: 'action', [
label: '处理', {
level: 'link', type: 'action',
...authenticationDetailDialog( label: '同意',
'parameters.authenticationId', actionType: 'ajax',
[ close: true,
{ api: apiGet('${base}/check_order/operation/${checkOrderId}/APPLY'),
type: 'action', reload: 'check_order_list',
label: '同意', },
actionType: 'ajax', {
close: true, type: 'action',
api: apiGet('${base}/check_order/operation/${checkOrderId}/APPLY'), label: '拒绝',
reload: 'check_order_list', actionType: 'ajax',
}, close: true,
{ api: apiGet('${base}/check_order/operation/${checkOrderId}/REJECT'),
type: 'action', reload: 'check_order_list',
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 === 'AUTHENTICATION' && state !== NORMAL}`, },
type: 'action', {
label: '查看', visibleOn: "${type === 'MARKET' && state === 'CHECKING'}",
level: 'link', type: 'action',
...authenticationDetailDialog('parameters.authenticationId'), label: '处理',
}, level: 'link',
{ ...wareDetailDialog(
visibleOn: `\${type === 'MARKET' && state === 'CHECKING'}`, 'parameters.wareId',
type: 'action', [
label: '处理', {
level: 'link', type: 'action',
...wareDetailDialog( label: '同意',
'parameters.wareId', actionType: 'ajax',
[ close: true,
{ api: apiGet('${base}/check_order/operation/${checkOrderId}/APPLY'),
type: 'action', reload: 'check_order_list',
label: '同意', },
actionType: 'ajax', {
close: true, type: 'action',
api: apiGet('${base}/check_order/operation/${checkOrderId}/APPLY'), label: '拒绝',
reload: 'check_order_list', actionType: 'ajax',
}, close: true,
{ api: apiGet('${base}/check_order/operation/${checkOrderId}/REJECT'),
type: 'action', reload: 'check_order_list',
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'),
visibleOn: `\${type === 'MARKET' && state !== NORMAL}`, },
type: 'action', ]),
label: '查看', ],
level: 'link', },
...wareDetailDialog('parameters.wareId'), ]
},
]),
],
},
],
}
} }

View File

@@ -1,94 +1,181 @@
import { import {
resourceAddDialog, resourceAddDialog,
resourceDetailDialog, resourceDetailDialog,
resourceEditeDialog resourceEditeDialog
} from "../../components/resource/dialog-resource.js"; } from "../../components/resource/dialog-resource.js";
import { import {
apiGet, apiGet,
arrayInCheck, arrayOutCheck,
arrayOutCheck, checkState,
checkState, crudCommonOptions,
crudCommonOptions, mappingField,
mappingField, operationField,
operationField, permissionStateMapping,
permissionStateMapping, timeField
timeField,
userOnly
} from "../../components/constants.js"; } from "../../components/constants.js";
import {wareAddDialog, wareDetailDialog, wareEditeDialog} from "../../components/ware/dialog-ware.js";
export function resourceList() { export function resourceList(showMode = false) {
return { return {
type: 'crud', type: 'crud',
api: apiGet('${base}/data_resource/list'), api: apiGet('${base}/data_resource/list'),
...crudCommonOptions(), ...crudCommonOptions(),
headerToolbar: [ headerToolbar: [
'reload', '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', disabledOn: arrayOutCheck([checkState.none, checkState.draft], 'confirmationState'),
label: '', disabledTip: '审查或确权成功后无法编辑',
icon: 'fa fa-plus', tooltipPlacement: 'top',
...resourceAddDialog() type: 'action',
}, label: '编辑',
], level: 'link',
columns: [ ...resourceEditeDialog(),
{
label: '名称',
name: 'name',
width: 150,
}, },
{ {
label: '描述', disabledOn: arrayOutCheck([checkState.none, checkState.draft], 'confirmationState'),
name: 'description', 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() { export function tabData() {
return { return {
visibleOn: userOnly, type: 'tabs',
title: '数据资源', tabs: [
icon: 'fa fa-database', {
reload: true, title: '资源定义',
body: resourceList(), 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} from "../../components/constants.js";
import {
apiGet,
crudCommonOptions,
mappingField,
operationField,
permissionStateMapping,
timeField
} from "../../components/constants.js";
import {authenticationAddDialog} from "../../components/permission/dialog-permission.js"; import {authenticationAddDialog} from "../../components/permission/dialog-permission.js";
export function tabMarket() { export function tabMarket() {
return { return {
title: '数据市场', type: 'crud',
icon: 'fa fa-store', api: {
reload: true, ...apiGet('${base}/ware/list_public'),
body: [ adaptor: (payload, response, api, context) => {
{ payload.data = payload.data.map(i => {
type: 'tabs', return {
tabs: [ ...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: '公开数据', label: '名称',
body: { content: '${name}',
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(),
}
]
},
}
}, },
{ {
title: '我的数据', label: '归属',
body: { content: '${createdUsername}',
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: '${createdTime}',
},
{
span: 3,
label: '描述',
content: '${description}',
},
]
},
{
type: 'tpl',
tpl: '${content|raw}'
}
]
} }
] }
},
{
type: 'action',
label: '申请授权',
...authenticationAddDialog(),
}
]
} }
}
} }

View File

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

View File

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

View File

@@ -1,83 +1,76 @@
import { import {
administratorOnly, apiGet,
apiGet, copyField,
copyField, crudCommonOptions,
crudCommonOptions, mappingField,
mappingField, operationField,
operationField, timeField,
timeField, userRoleMapping,
userRoleMapping, userStateMapping
userStateMapping
} from '../../components/constants.js' } from '../../components/constants.js'
import {userCheckDialog, userDetailDialog} from "../../components/user/dialog-user-check.js"; import {userCheckDialog, userDetailDialog} from "../../components/user/dialog-user-check.js";
import {userAdministratorRegisterDialog} from "../../components/user/dialog-user-register.js"; import {userAdministratorRegisterDialog} from "../../components/user/dialog-user-register.js";
export function tabUser() { export function tabUser() {
return { return [
visibleOn: administratorOnly, {
title: '用户管理', type: 'crud',
icon: 'fa fa-user', api: apiGet('${base}/user_management/list'),
reload: true, ...crudCommonOptions(),
body: [ headerToolbar: [
{ 'reload',
type: 'crud', {
api: apiGet('${base}/user_management/list'), type: 'action',
...crudCommonOptions(), icon: 'fa fa-plus',
headerToolbar: [ tooltip: '新增账号',
'reload', ...userAdministratorRegisterDialog(),
{ },
type: 'action', ],
icon: 'fa fa-plus', columns: [
tooltip: '新增账号', copyField(
...userAdministratorRegisterDialog(), 'username',
}, '邮箱',
], undefined,
columns: [ undefined,
copyField( userDetailDialog(),
'username', ),
'邮箱', mappingField('role', '角色', userRoleMapping, 120),
undefined, mappingField('state', '账号状态', userStateMapping),
undefined, timeField('createdTime', '创建时间'),
userDetailDialog(), timeField('lastLoginTime', '上次登陆时间'),
), operationField('操作', undefined, [
mappingField('role', '角色', userRoleMapping, 120), {
mappingField('state', '账号状态', userStateMapping), visibleOn: "${state === 'CHECKING'}",
timeField('createdTime', '创建时间'), label: '审核',
timeField('lastLoginTime', '上次登陆时间'), icon: 'fa fa-fingerprint',
operationField('操作', undefined, [ level: 'primary',
{ size: 'xs',
visibleOn: "${state === 'CHECKING'}", ...userCheckDialog(),
label: '审核', },
icon: 'fa fa-fingerprint', {
level: 'primary', visibleOn: "${state === 'NORMAL' && role !== 'ADMINISTRATOR'}",
size: 'xs', label: '禁用',
...userCheckDialog(), icon: 'fa fa-ban',
}, level: 'danger',
{ size: 'xs',
visibleOn: "${state === 'NORMAL' && role !== 'ADMINISTRATOR'}", confirmText: '确认禁用账号${username}',
label: '禁用', confirmTitle: '禁用账号',
icon: 'fa fa-ban', actionType: 'ajax',
level: 'danger', api: apiGet('${base}/user_management/disable/${username}'),
size: 'xs', },
confirmText: '确认禁用账号${username}', {
confirmTitle: '禁用账号', visibleOn: "${state === 'DISABLED' && role !== 'ADMINISTRATOR'}",
actionType: 'ajax', label: '启用',
api: apiGet('${base}/user_management/disable/${username}'), icon: 'fa fa-check',
}, level: 'success',
{ size: 'xs',
visibleOn: "${state === 'DISABLED' && role !== 'ADMINISTRATOR'}", confirmText: '确认启用账号${username}',
label: '启用', confirmTitle: '启用账号',
icon: 'fa fa-check', actionType: 'ajax',
level: 'success', api: apiGet('${base}/user_management/enable/${username}'),
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 => { useAmis(information => {
return { return {
type: 'page', type: 'page',
title: information.title, className: 'h-screen bg-gray-900',
subTitle: '统一登陆入口', bodyClassName: 'h-full flex items-start mt-20',
body: [ body: [
{ {
type: 'grid', type: 'wrapper',
columns: [ className: 'relative w-full max-w-md mx-auto',
body: [
{ {
xs: 0, type: 'flex',
sm: 0, justify: 'center',
md: 4, className: 'mb-8',
body: [], 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, type: 'form',
sm: 12, className: 'bg-white rounded-xl p-10 shadow-2xl',
md: 4, api: '${base}/user/login',
redirect: '/pages/index/index.html?token=${token}',
mode: 'normal',
wrapWithPanel: false,
body: [ body: [
{ {
type: 'form', type: 'input-email',
title: '用户登陆', name: 'username',
api: '${base}/user/login', label: false,
redirect: '/pages/index/index.html?token=${token}', placeholder: '请输入邮箱',
mode: 'horizontal', required: true,
horizontal: { clearable: true,
left: 2, className: 'mb-4',
}, inputClassName: 'rounded-lg',
actions: [ },
{
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', type: 'button',
label: '注册', label: '注册账号',
className: 'text-blue-600 hover:text-blue-700',
level: 'link',
...userRegisterDialog(), ...userRegisterDialog(),
}, },
{ {
type: 'action', type: 'button',
actionType: 'submit', label: '忘记密码?',
label: '登陆', level: 'link',
level: 'primary', className: 'text-gray-600 hover:text-gray-700'
}, }
], ]
body: [
{
type: 'input-email',
name: 'username',
label: '邮箱',
placeholder: '请输入邮箱',
required: true,
clearable: true,
clearValueOnEmpty: true,
},
{
type: 'input-password',
name: 'password',
label: '密码',
placeholder: '请再次输入密码',
required: true,
},
],
}, },
], {
}, type: 'submit',
{ label: '登录',
xs: 0, level: 'primary',
sm: 0, className: 'w-full rounded-lg',
md: 4, size: 'lg'
body: [], }
}, ]
], }
}, ]
], }
]
} }
}) })

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

@@ -34,6 +34,10 @@
<version>${hibernate.version}</version> <version>${hibernate.version}</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency> <dependency>
<groupId>com.h2database</groupId> <groupId>com.h2database</groupId>
<artifactId>h2</artifactId> <artifactId>h2</artifactId>

View File

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

View File

@@ -16,12 +16,12 @@ import org.springframework.web.bind.annotation.RestControllerAdvice;
*/ */
@RestControllerAdvice @RestControllerAdvice
public class ErrorController { 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) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Throwable.class) @ExceptionHandler(Throwable.class)
public AmisResponse<Object> errorHandler(Throwable throwable) { public AmisResponse<Object> errorHandler(Throwable throwable) {
logger.error("Error", throwable); logger.error("Error", throwable);
return AmisResponse.responseError(throwable.getMessage()); return AmisResponse.responseError(throwable.getMessage());
} }
} }

View File

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

View File

@@ -14,80 +14,80 @@ import org.slf4j.LoggerFactory;
* @date 2024-11-14 * @date 2024-11-14
*/ */
public class SnowflakeIdGenerator implements IdentifierGenerator { public class SnowflakeIdGenerator implements IdentifierGenerator {
private static final Logger logger = LoggerFactory.getLogger(SnowflakeIdGenerator.class); private static final Logger logger = LoggerFactory.getLogger(SnowflakeIdGenerator.class);
@Override @Override
public Serializable generate(SharedSessionContractImplementor session, Object object) { public Serializable generate(SharedSessionContractImplementor session, Object object) {
try { try {
return Snowflake.next(); return Snowflake.next();
} catch (Exception e) { } catch (Exception e) {
logger.error("Generate snowflake id failed", e); logger.error("Generate snowflake id failed", e);
throw new RuntimeException(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 static long nextTimestamp() {
/** long milli = nowTimestamp();
* 起始的时间戳 while (milli <= lastTimestamp) {
*/ milli = nowTimestamp();
private final static long START_TIMESTAMP = 1; }
return milli;
/**
* 序列号占用的位数
*/
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 nowTimestamp() {
return Instant.now().toEpochMilli();
}
}
} }

View File

@@ -14,5 +14,5 @@ import org.springframework.context.annotation.Configuration;
@ConfigurationProperties(prefix = "gringotts.upload") @ConfigurationProperties(prefix = "gringotts.upload")
@Configuration @Configuration
public class UploadConfiguration { 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 * @date 2023-07-06
*/ */
public class AmisItemResponse extends AmisMapResponse { public class AmisItemResponse extends AmisMapResponse {
public void setDetail(Object detail) { public void setDetail(Object detail) {
getData().put("item", detail); getData().put("item", detail);
} }
} }

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,34 @@
package com.eshore.gringotts.web.domain.base.controller;
import com.eshore.gringotts.web.configuration.amis.AmisResponse;
import com.eshore.gringotts.web.domain.base.entity.CheckingNeededEntity;
import com.eshore.gringotts.web.domain.base.service.CheckingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
/**
* @author wn
* @version 20241224
*/
@Slf4j
public abstract class CheckingController<ENTITY extends CheckingNeededEntity, SAVE_ITEM, LIST_ITEM, DETAIL_ITEM> extends SimpleControllerSupport<ENTITY, SAVE_ITEM, LIST_ITEM, DETAIL_ITEM> {
private final CheckingService<ENTITY> checkingService;
public CheckingController(CheckingService<ENTITY> service) {
super(service);
this.checkingService = service;
}
@GetMapping("/submit/{id}")
public AmisResponse<Object> submit(@PathVariable Long id) throws Exception {
checkingService.submit(id);
return AmisResponse.responseSuccess();
}
@GetMapping("/retract/{id}")
public AmisResponse<Object> retract(@PathVariable Long id) throws Exception {
checkingService.retract(id);
return AmisResponse.responseSuccess();
}
}

View File

@@ -7,5 +7,5 @@ import com.eshore.gringotts.web.configuration.amis.AmisResponse;
* @date 2024-11-28 * @date 2024-11-28
*/ */
public interface DetailController<DETAIL_ITEM> { 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 * @date 2024-11-28
*/ */
public interface ListController<LIST_ITEM> { 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 * @date 2024-11-28
*/ */
public interface RemoveController { 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 * @date 2024-11-28
*/ */
public interface SaveController<SAVE_ITEM> { 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 @Slf4j
public abstract class SimpleControllerSupport<ENTITY extends SimpleEntity, SAVE_ITEM, LIST_ITEM, DETAIL_ITEM> implements SimpleController<SAVE_ITEM, LIST_ITEM, DETAIL_ITEM> { 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 SAVE = "/save";
protected static final String LIST = "/list"; protected static final String LIST = "/list";
protected static final String DETAIL = "/detail/{id}"; protected static final String DETAIL = "/detail/{id}";
protected static final String REMOVE = "/remove/{id}"; protected static final String REMOVE = "/remove/{id}";
private final SimpleServiceSupport<ENTITY> service; protected final SimpleServiceSupport<ENTITY> service;
public SimpleControllerSupport(SimpleServiceSupport<ENTITY> service) { public SimpleControllerSupport(SimpleServiceSupport<ENTITY> service) {
this.service = 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) @GetMapping(DETAIL)
@Override @Override
public AmisResponse<Long> save(@RequestBody SAVE_ITEM item) throws Exception { public AmisResponse<DETAIL_ITEM> detail(@PathVariable Long id) throws Exception {
return AmisResponse.responseSuccess(service.save(fromSaveItem(item))); return AmisResponse.responseSuccess(toDetailItem(service.detailOrThrow(id)));
} }
@GetMapping(LIST) @GetMapping(REMOVE)
@Override @Override
public AmisResponse<ImmutableList<LIST_ITEM>> list() throws Exception { public AmisResponse<Object> remove(@PathVariable Long id) {
return AmisResponse.responseSuccess(service.list().collect(entity -> { service.remove(id);
try { return AmisResponse.responseSuccess();
return toListItem(entity); }
} catch (Exception e) {
throw new RuntimeException(e);
}
}));
}
@PostMapping(LIST) protected abstract ENTITY fromSaveItem(SAVE_ITEM item) throws Exception;
@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);
}
}));
}
@GetMapping(DETAIL) protected abstract LIST_ITEM toListItem(ENTITY entity) throws Exception;
@Override
public AmisResponse<DETAIL_ITEM> detail(@PathVariable Long id) throws Exception {
return AmisResponse.responseSuccess(toDetailItem(service.detailOrThrow(id)));
}
@GetMapping(REMOVE) protected abstract DETAIL_ITEM toDetailItem(ENTITY entity) throws Exception;
@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;
} }

View File

@@ -12,50 +12,50 @@ import org.eclipse.collections.api.map.ImmutableMap;
*/ */
@Data @Data
public class Query { public class Query {
private Queryable query; private Queryable query;
private ImmutableList<Sortable> sort; private ImmutableList<Sortable> sort;
private Pageable page; 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 @Data
public static class Queryable { public static class Between {
private ImmutableList<String> nullEqual; private String start;
private ImmutableList<String> notNullEqual; private String end;
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;
}
} }
}
@Data @Data
public static class Sortable { public static class Sortable {
private String column; private String column;
private Direction direction; private Direction direction;
public enum Direction { public enum Direction {
ASC, ASC,
DESC, DESC,
}
} }
}
@Data @Data
public static class Pageable { public static class Pageable {
private Integer page; private Integer page;
private Integer size; private Integer size;
} }
} }

View File

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

View File

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

View File

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

View File

@@ -20,8 +20,8 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@MappedSuperclass @MappedSuperclass
@EntityListeners(AuditingEntityListener.class) @EntityListeners(AuditingEntityListener.class)
public class LogicDeleteEntity extends SimpleEntity { 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) @Column(nullable = false)
private Boolean deleted = false; private Boolean deleted = false;
} }

View File

@@ -20,8 +20,8 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@MappedSuperclass @MappedSuperclass
@EntityListeners(AuditingEntityListener.class) @EntityListeners(AuditingEntityListener.class)
public class LogicDeleteIdOnlyEntity extends IdOnlyEntity { 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) @Column(nullable = false)
private Boolean deleted = false; private Boolean deleted = false;
} }

View File

@@ -10,5 +10,5 @@ import lombok.Data;
*/ */
@Data @Data
public abstract class SimpleDetailItem<ENTITY> { 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 @MappedSuperclass
@EntityListeners(AuditingEntityListener.class) @EntityListeners(AuditingEntityListener.class)
public class SimpleEntity extends IdOnlyEntity { public class SimpleEntity extends IdOnlyEntity {
@CreatedDate @CreatedDate
private LocalDateTime createdTime; private LocalDateTime createdTime;
@OneToOne(fetch = FetchType.LAZY) @OneToOne(fetch = FetchType.LAZY)
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) @JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
@ToString.Exclude @ToString.Exclude
@CreatedBy @CreatedBy
private User createdUser; private User createdUser;
@LastModifiedDate @LastModifiedDate
private LocalDateTime modifiedTime; private LocalDateTime modifiedTime;
@OneToOne(fetch = FetchType.LAZY) @OneToOne(fetch = FetchType.LAZY)
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) @JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
@ToString.Exclude @ToString.Exclude
@LastModifiedBy @LastModifiedBy
private User modifiedUser; private User modifiedUser;
} }

View File

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

View File

@@ -10,5 +10,5 @@ import lombok.Data;
*/ */
@Data @Data
public abstract class SimpleSaveItem<ENTITY> { 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; package com.eshore.gringotts.web.domain.base.service;
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.CheckOrder; import com.eshore.gringotts.web.domain.entity.CheckOrder;
import com.eshore.gringotts.web.domain.service.UserService;
import javax.persistence.EntityManager;
import org.eclipse.collections.api.map.ImmutableMap; import org.eclipse.collections.api.map.ImmutableMap;
/** /**
@@ -9,6 +13,16 @@ import org.eclipse.collections.api.map.ImmutableMap;
* @author lanyuanxiaoyao * @author lanyuanxiaoyao
* @date 2024-11-28 * @date 2024-11-28
*/ */
public interface CheckingService { public abstract class CheckingService<ENTITY extends LogicDeleteEntity> extends LogicDeleteService<ENTITY> {
void onChecked(CheckOrder order, CheckOrder.Operation operation, ImmutableMap<String, Object> parameters); 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 com.eshore.gringotts.web.domain.service.UserService;
import javax.persistence.EntityManager; import javax.persistence.EntityManager;
import javax.persistence.Query; 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 javax.transaction.Transactional;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.eclipse.collections.api.list.ImmutableList;
/** /**
* @author lanyuanxiaoyao * @author lanyuanxiaoyao
@@ -21,24 +16,19 @@ import org.eclipse.collections.api.list.ImmutableList;
*/ */
@Slf4j @Slf4j
public abstract class LogicDeleteService<ENTITY extends LogicDeleteEntity> extends SimpleServiceSupport<ENTITY> { 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) { public LogicDeleteService(SimpleRepository<ENTITY, Long> repository, UserService userService, EntityManager manager) {
super(repository, userService); super(repository, userService);
this.manager = manager; this.manager = manager;
} }
@Override @Transactional(rollbackOn = Throwable.class)
protected ImmutableList<Predicate> listPredicate(Root<ENTITY> root, CriteriaQuery<?> query, CriteriaBuilder builder) { @Override
return super.listPredicate(root, query, builder).newWith(builder.equal(root.get("deleted"), false)); 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));
@Transactional(rollbackOn = Throwable.class) query.setParameter(1, id);
@Override query.executeUpdate();
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();
}
} }

View File

@@ -11,21 +11,23 @@ import org.eclipse.collections.api.set.ImmutableSet;
* @date 2024-11-28 * @date 2024-11-28
*/ */
public interface SimpleService<ENTITY extends SimpleEntity> { 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 @Slf4j
public abstract class SimpleServiceSupport<ENTITY extends SimpleEntity> implements SimpleService<ENTITY> { public abstract class SimpleServiceSupport<ENTITY extends SimpleEntity> implements SimpleService<ENTITY> {
protected final SimpleRepository<ENTITY, Long> repository; protected final SimpleRepository<ENTITY, Long> repository;
protected final UserService userService; protected final UserService userService;
public SimpleServiceSupport(SimpleRepository<ENTITY, Long> repository, UserService userService) { public SimpleServiceSupport(SimpleRepository<ENTITY, Long> repository, UserService userService) {
this.repository = repository; this.repository = repository;
this.userService = userService; 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) public IdNotFoundException(Long id) {
@Override super(StrUtil.format("ID为{}的资源不存在", id));
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));
}
} }
}
} }

View File

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

View File

@@ -32,58 +32,58 @@ import org.springframework.web.bind.annotation.RestController;
@RestController @RestController
@RequestMapping("check_order") @RequestMapping("check_order")
public class CheckOrderController implements ListController<CheckOrderController.ListItem> { public class CheckOrderController implements ListController<CheckOrderController.ListItem> {
private final CheckOrderService checkOrderService; private final CheckOrderService checkOrderService;
private final ObjectMapper mapper; private final ObjectMapper mapper;
public CheckOrderController(CheckOrderService checkOrderService, Jackson2ObjectMapperBuilder builder) { public CheckOrderController(CheckOrderService checkOrderService, Jackson2ObjectMapperBuilder builder) {
this.checkOrderService = checkOrderService; this.checkOrderService = checkOrderService;
this.mapper = builder.build(); this.mapper = builder.build();
} }
@GetMapping("/list") @GetMapping("/list")
@Override @Override
public AmisResponse<ImmutableList<CheckOrderController.ListItem>> list() throws Exception { public AmisResponse<ImmutableList<CheckOrderController.ListItem>> list() throws Exception {
return AmisResponse.responseSuccess(checkOrderService.list().collect(this::toListItem)); return AmisResponse.responseSuccess(checkOrderService.list().collect(this::toListItem));
} }
@PostMapping("/list") @PostMapping("/list")
@Override @Override
public AmisResponse<ImmutableList<ListItem>> list(@RequestBody Query query) throws Exception { public AmisResponse<ImmutableList<ListItem>> list(@RequestBody Query query) throws Exception {
return AmisResponse.responseSuccess(checkOrderService.list().collect(this::toListItem)); return AmisResponse.responseSuccess(checkOrderService.list().collect(this::toListItem));
} }
@SneakyThrows @SneakyThrows
private ListItem toListItem(CheckOrder order) { private ListItem toListItem(CheckOrder order) {
ListItem item = new ListItem(); ListItem item = new ListItem();
item.setCheckOrderId(order.getId()); item.setCheckOrderId(order.getId());
item.setDescription(order.getDescription()); item.setDescription(order.getDescription());
item.setType(order.getType()); item.setType(order.getType());
item.setParameters(mapper.readValue(order.getParameters(), new TypeReference<>() {})); item.setParameters(mapper.readValue(order.getParameters(), new TypeReference<>() {}));
item.setState(order.getState()); item.setState(order.getState());
item.setCreatedUsername(order.getCreatedUser().getUsername()); item.setCreatedUsername(order.getCreatedUser().getUsername());
item.setCreatedTime(order.getCreatedTime()); item.setCreatedTime(order.getCreatedTime());
item.setModifiedUsername(order.getModifiedUser().getUsername()); item.setModifiedUsername(order.getModifiedUser().getUsername());
item.setModifiedTime(order.getModifiedTime()); item.setModifiedTime(order.getModifiedTime());
return item; return item;
} }
@GetMapping("/operation/{id}/{operation}") @GetMapping("/operation/{id}/{operation}")
public AmisResponse<Object> operation(@PathVariable Long id, @PathVariable CheckOrder.Operation operation) throws JsonProcessingException { public AmisResponse<Object> operation(@PathVariable Long id, @PathVariable CheckOrder.Operation operation) throws JsonProcessingException {
log.info("id:{}, operation:{}", id, operation); log.info("id:{}, operation:{}", id, operation);
checkOrderService.operation(id, operation); checkOrderService.operation(id, operation);
return AmisResponse.responseSuccess(); return AmisResponse.responseSuccess();
} }
@Data @Data
public static final class ListItem { public static final class ListItem {
private Long checkOrderId; private Long checkOrderId;
private String description; private String description;
private CheckOrder.Type type; private CheckOrder.Type type;
private ImmutableMap<String, Object> parameters; private ImmutableMap<String, Object> parameters;
private CheckOrder.State state; private CheckOrder.State state;
private LocalDateTime createdTime; private LocalDateTime createdTime;
private String createdUsername; private String createdUsername;
private LocalDateTime modifiedTime; private LocalDateTime modifiedTime;
private String modifiedUsername; private String modifiedUsername;
} }
} }

View File

@@ -1,7 +1,6 @@
package com.eshore.gringotts.web.domain.controller; package com.eshore.gringotts.web.domain.controller;
import com.eshore.gringotts.web.configuration.amis.AmisResponse; import com.eshore.gringotts.web.domain.base.controller.CheckingController;
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.FileInfo;
import com.eshore.gringotts.web.domain.base.entity.SimpleListItem; import com.eshore.gringotts.web.domain.base.entity.SimpleListItem;
import com.eshore.gringotts.web.domain.base.entity.SimpleSaveItem; import com.eshore.gringotts.web.domain.base.entity.SimpleSaveItem;
@@ -9,15 +8,12 @@ import com.eshore.gringotts.web.domain.entity.Confirmation;
import com.eshore.gringotts.web.domain.service.ConfirmationService; import com.eshore.gringotts.web.domain.service.ConfirmationService;
import com.eshore.gringotts.web.domain.service.DataFileService; import com.eshore.gringotts.web.domain.service.DataFileService;
import com.eshore.gringotts.web.domain.service.DataResourceService; import com.eshore.gringotts.web.domain.service.DataResourceService;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.eclipse.collections.api.factory.Sets; import org.eclipse.collections.api.factory.Sets;
import org.eclipse.collections.api.set.ImmutableSet; 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.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@@ -28,94 +24,80 @@ import org.springframework.web.bind.annotation.RestController;
@Slf4j @Slf4j
@RestController @RestController
@RequestMapping("confirmation") @RequestMapping("confirmation")
public class ConfirmationController extends SimpleControllerSupport<Confirmation, ConfirmationController.SaveItem, ConfirmationController.ListItem, ConfirmationController.DetailItem> { public class ConfirmationController extends CheckingController<Confirmation, ConfirmationController.SaveItem, ConfirmationController.ListItem, ConfirmationController.DetailItem> {
private final ConfirmationService confirmationService; private final DataResourceService dataResourceService;
private final DataResourceService dataResourceService; private final DataFileService dataFileService;
private final DataFileService dataFileService;
public ConfirmationController(ConfirmationService service, ConfirmationService confirmationService, DataResourceService dataResourceService, DataFileService dataFileService) { public ConfirmationController(ConfirmationService service, DataResourceService dataResourceService, DataFileService dataFileService) {
super(service); super(service);
this.confirmationService = confirmationService; this.dataResourceService = dataResourceService;
this.dataResourceService = dataResourceService; this.dataFileService = dataFileService;
this.dataFileService = dataFileService; }
@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}") @Data
public AmisResponse<Object> submit(@PathVariable Long id) throws JsonProcessingException { @EqualsAndHashCode(callSuper = true)
confirmationService.submit(id); public static final class DetailItem extends SaveItem {
return AmisResponse.responseSuccess(); private String targetName;
} private LocalDateTime createdTime;
private String createdUsername;
@GetMapping("/retract/{id}") private LocalDateTime modifiedTime;
public AmisResponse<Object> retract(@PathVariable Long id) { private String modifiedUsername;
confirmationService.retract(id);
return AmisResponse.responseSuccess(); public DetailItem(Confirmation confirmation) {
} this.setId(confirmation.getId());
this.setTargetId(confirmation.getTarget().getId());
@Override this.setTargetName(confirmation.getTarget().getName());
protected Confirmation fromSaveItem(SaveItem item) throws Exception { this.setDescription(confirmation.getDescription());
Confirmation confirmation = new Confirmation(); this.setEvidenceFiles(Sets.immutable.ofAll(confirmation.getEvidences()).collect(FileInfo::new));
confirmation.setId(item.getId()); this.setCreatedTime(confirmation.getCreatedTime());
confirmation.setDescription(item.getDescription()); this.setCreatedUsername(confirmation.getCreatedUser().getUsername());
confirmation.setTarget(dataResourceService.detailOrThrow(item.getTargetId())); this.setModifiedTime(confirmation.getModifiedTime());
confirmation.setEvidences(dataFileService.list(item.getEvidenceFiles().collect(FileInfo::getValue)).toSet()); this.setModifiedUsername(confirmation.getModifiedUser().getUsername());
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());
}
} }
}
} }

View File

@@ -41,179 +41,179 @@ import org.springframework.web.multipart.MultipartFile;
@RestController @RestController
@RequestMapping("/upload") @RequestMapping("/upload")
public class DataFileController { public class DataFileController {
private final HostConfiguration hostConfiguration; private final HostConfiguration hostConfiguration;
private final DataFileService dataFileService; private final DataFileService dataFileService;
private final String uploadFolderPath; private final String uploadFolderPath;
private final String cacheFolderPath; private final String cacheFolderPath;
private final String sliceFolderPath; private final String sliceFolderPath;
public DataFileController(HostConfiguration hostConfiguration, UploadConfiguration uploadConfiguration, DataFileService dataFileService) { public DataFileController(HostConfiguration hostConfiguration, UploadConfiguration uploadConfiguration, DataFileService dataFileService) {
this.hostConfiguration = hostConfiguration; this.hostConfiguration = hostConfiguration;
this.dataFileService = dataFileService; this.dataFileService = dataFileService;
this.uploadFolderPath = uploadConfiguration.getUploadPath(); this.uploadFolderPath = uploadConfiguration.getUploadPath();
this.cacheFolderPath = StrUtil.format("{}/cache", uploadFolderPath); this.cacheFolderPath = StrUtil.format("{}/cache", uploadFolderPath);
this.sliceFolderPath = StrUtil.format("{}/slice", 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));
} }
File cacheFile = new File(StrUtil.format("{}/{}", cacheFolderPath, id));
@PostMapping("") cacheFile = FileUtil.writeBytes(bytes, cacheFile);
public AmisResponse<FinishResponse> upload(@RequestParam("file") MultipartFile file) throws IOException { String targetMd5 = SecureUtil.md5(cacheFile);
String filename = file.getOriginalFilename(); if (!StrUtil.equals(originMd5, targetMd5)) {
Long id = dataFileService.initialDataFile(filename); throw new RuntimeException("文件上传失败,校验不匹配");
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));
} }
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}") @GetMapping("/download/{id}")
public void download(@PathVariable Long id, HttpServletResponse response) throws IOException { public void download(@PathVariable Long id, HttpServletResponse response) throws IOException {
DataFile dataFile = dataFileService.downloadFile(id); DataFile dataFile = dataFileService.downloadFile(id);
File targetFile = new File(dataFile.getPath()); File targetFile = new File(dataFile.getPath());
response.setHeader("Access-Control-Expose-Headers", "Content-Type"); response.setHeader("Access-Control-Expose-Headers", "Content-Type");
response.setHeader("Content-Type", dataFile.getType()); response.setHeader("Content-Type", dataFile.getType());
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition"); response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setHeader("Content-Disposition", StrUtil.format("attachment; filename={}", dataFile.getFilename())); response.setHeader("Content-Disposition", StrUtil.format("attachment; filename={}", dataFile.getFilename()));
IoUtil.copy(new FileInputStream(targetFile), response.getOutputStream()); 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("文件校验失败,请重新上传");
} }
try {
@PostMapping("/start") File cacheFile = new File(StrUtil.format("{}/{}", cacheFolderPath, request.uploadId));
public AmisResponse<StartResponse> start(@RequestBody StartRequest request) { FileUtil.mkParentDirs(cacheFile);
log.info("Request: {}", request); if (cacheFile.createNewFile()) {
Long id = dataFileService.initialDataFile(request.filename); try (FileOutputStream fos = new FileOutputStream(cacheFile)) {
return AmisResponse.responseSuccess(new StartResponse(id.toString())); try (FileChannel fosChannel = fos.getChannel()) {
} for (FinishRequest.Part part : request.partList) {
File sliceFile = new File(sliceFilePath(request.uploadId, part.eTag));
@PostMapping("/slice") try (FileInputStream fis = new FileInputStream(sliceFile)) {
public AmisResponse<SliceResponse> slice( try (FileChannel fisChannel = fis.getChannel()) {
@RequestParam("uploadId") fisChannel.transferTo(0, fisChannel.size(), fosChannel);
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);
}
}
}
}
} }
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));
} }
} String md5 = SecureUtil.md5(cacheFile);
File targetFile = new File(StrUtil.format("{}/{}", uploadFolderPath, md5));
@Data if (!targetFile.exists()) {
public static final class StartRequest { FileUtil.move(cacheFile, targetFile, true);
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 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 @Data
@NoArgsConstructor public static final class Part {
@AllArgsConstructor private Integer partNumber;
public static final class FinishResponse { @JsonProperty("eTag")
private Long id; private String eTag;
private String filename;
private String value;
private String url;
} }
}
@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 @RestController
@RequestMapping("/data_resource") @RequestMapping("/data_resource")
public class DataResourceController extends SimpleControllerSupport<DataResource, DataResourceController.SaveItem, DataResourceController.ListItem, DataResourceController.DetailItem> { public class DataResourceController extends SimpleControllerSupport<DataResource, DataResourceController.SaveItem, DataResourceController.ListItem, DataResourceController.DetailItem> {
private final ObjectMapper mapper; private final ObjectMapper mapper;
private final DataResourceService dataResourceService; private final DataResourceService dataResourceService;
private final DataFileService dataFileService; private final DataFileService dataFileService;
public DataResourceController(DataResourceService dataResourceService, DataFileService dataFileService, Jackson2ObjectMapperBuilder builder) { public DataResourceController(DataResourceService dataResourceService, DataFileService dataFileService, Jackson2ObjectMapperBuilder builder) {
super(dataResourceService); super(dataResourceService);
this.dataResourceService = dataResourceService; this.dataResourceService = dataResourceService;
this.dataFileService = dataFileService; this.dataFileService = dataFileService;
this.mapper = builder.build(); this.mapper = builder.build();
} }
@GetMapping(LIST + "_no_confirmation") @GetMapping(LIST + "_no_confirmation")
public AmisResponse<ImmutableList<ListItem>> listNoConfirmation() { public AmisResponse<ImmutableList<ListItem>> listNoConfirmation() {
return AmisResponse.responseSuccess(dataResourceService.listNoConfirmation().collect(entity -> { return AmisResponse.responseSuccess(dataResourceService.listNoConfirmation().collect(entity -> {
try { try {
return toListItem(entity); return toListItem(entity);
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
})); }));
} }
@GetMapping(LIST + "_no_authentication") @GetMapping(LIST + "_no_authentication")
public AmisResponse<ImmutableList<ListItem>> listNoAuthentication() { public AmisResponse<ImmutableList<ListItem>> listNoAuthentication() {
return AmisResponse.responseSuccess(dataResourceService.listNoAuthentication().collect(entity -> { return AmisResponse.responseSuccess(dataResourceService.listNoAuthentication().collect(entity -> {
try { try {
return toListItem(entity); return toListItem(entity);
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
})); }));
} }
@GetMapping(LIST + "_no_ware") @GetMapping(LIST + "_no_ware")
public AmisResponse<ImmutableList<ListItem>> listNoWare() { public AmisResponse<ImmutableList<ListItem>> listNoWare() {
return AmisResponse.responseSuccess(dataResourceService.listNoWare().collect(entity -> { return AmisResponse.responseSuccess(dataResourceService.listNoWare().collect(entity -> {
try { try {
return toListItem(entity); return toListItem(entity);
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
})); }));
} }
@Override @Override
protected DataResource fromSaveItem(SaveItem item) throws JsonProcessingException { protected DataResource fromSaveItem(SaveItem item) throws JsonProcessingException {
ResourceType type = generateResourceType(item); ResourceType type = generateResourceType(item);
ResourceFormat format = generateResourceFormat(item); ResourceFormat format = generateResourceFormat(item);
DataResource dataResource = new DataResource(); DataResource dataResource = new DataResource();
dataResource.setId(item.getId()); dataResource.setId(item.getId());
dataResource.setName(item.getName()); dataResource.setName(item.getName());
dataResource.setDescription(item.getDescription()); dataResource.setDescription(item.getDescription());
dataResource.setType(type); dataResource.setType(type);
dataResource.setFormat(format); dataResource.setFormat(format);
if (ObjectUtil.isNotNull(item.getExampleFile())) { if (ObjectUtil.isNotNull(item.getExampleFile())) {
dataResource.setExample(dataFileService.detail(item.getExampleFile().getValue())); dataResource.setExample(dataFileService.detail(item.getExampleFile().getValue()));
}
return dataResource;
} }
return dataResource;
}
@Override @Override
protected ListItem toListItem(DataResource dataResource) { protected ListItem toListItem(DataResource dataResource) {
ListItem item = new ListItem(); ListItem item = new ListItem();
item.setId(dataResource.getId()); item.setId(dataResource.getId());
item.setName(dataResource.getName()); item.setName(dataResource.getName());
item.setDescription(dataResource.getDescription()); item.setDescription(dataResource.getDescription());
item.setType(dataResource.getType().getResourceType().name()); item.setType(dataResource.getType().getResourceType().name());
item.setFormat(dataResource.getFormat().getFormatType().name()); item.setFormat(dataResource.getFormat().getFormatType().name());
if (ObjectUtil.isNotNull(dataResource.getConfirmation())) { if (ObjectUtil.isNotNull(dataResource.getConfirmation())) {
item.setConfirmationId(dataResource.getConfirmation().getId()); item.setConfirmationId(dataResource.getConfirmation().getId());
item.setConfirmationState(dataResource.getConfirmation().getState()); item.setConfirmationState(dataResource.getConfirmation().getState());
} else { } else {
item.setConfirmationState(Confirmation.State.NONE); item.setConfirmationState(Confirmation.State.NONE);
}
item.setCreatedUser(dataResource.getCreatedUser().getUsername());
item.setCreatedTime(dataResource.getCreatedTime());
return item;
} }
item.setCreatedUser(dataResource.getCreatedUser().getUsername());
item.setCreatedTime(dataResource.getCreatedTime());
return item;
}
@Override @Override
protected DetailItem toDetailItem(DataResource dataResource) throws Exception { protected DetailItem toDetailItem(DataResource dataResource) throws Exception {
DetailItem item = new DetailItem(); DetailItem item = new DetailItem();
item.setId(dataResource.getId()); item.setId(dataResource.getId());
item.setResourceTypeId(dataResource.getType().getId()); item.setResourceTypeId(dataResource.getType().getId());
item.setResourceFormatId(dataResource.getFormat().getId()); item.setResourceFormatId(dataResource.getFormat().getId());
item.setName(dataResource.getName()); item.setName(dataResource.getName());
item.setDescription(dataResource.getDescription()); item.setDescription(dataResource.getDescription());
item.setResourceType(dataResource.getType().getResourceType()); item.setResourceType(dataResource.getType().getResourceType());
switch (dataResource.getType().getResourceType()) { switch (dataResource.getType().getResourceType()) {
case API: case API:
ApiResourceType apiType = (ApiResourceType) dataResource.getType(); ApiResourceType apiType = (ApiResourceType) dataResource.getType();
item.setApiUrl(apiType.getUrl()); item.setApiUrl(apiType.getUrl());
item.setApiUsername(apiType.getUsername()); item.setApiUsername(apiType.getUsername());
item.setApiPassword(apiType.getPassword()); item.setApiPassword(apiType.getPassword());
break; break;
case FILE: case FILE:
FileResourceType fileType = (FileResourceType) dataResource.getType(); FileResourceType fileType = (FileResourceType) dataResource.getType();
item.setFile(new FileInfo(fileType.getFile())); item.setFile(new FileInfo(fileType.getFile()));
break; break;
case DATABASE: case DATABASE:
DatabaseResourceType databaseType = (DatabaseResourceType) dataResource.getType(); DatabaseResourceType databaseType = (DatabaseResourceType) dataResource.getType();
item.setDatabaseType(databaseType.getDatabaseType().name()); item.setDatabaseType(databaseType.getDatabaseType().name());
item.setDatabaseJdbc(databaseType.getJdbc()); item.setDatabaseJdbc(databaseType.getJdbc());
item.setDatabaseUsername(databaseType.getUsername()); item.setDatabaseUsername(databaseType.getUsername());
item.setDatabasePassword(databaseType.getPassword()); item.setDatabasePassword(databaseType.getPassword());
break; break;
case HDFS: case HDFS:
HDFSResourceType hdfsType = (HDFSResourceType) dataResource.getType(); HDFSResourceType hdfsType = (HDFSResourceType) dataResource.getType();
item.setCoreSiteFile(new FileInfo(hdfsType.getCoreSite())); item.setCoreSiteFile(new FileInfo(hdfsType.getCoreSite()));
item.setHdfsSiteFile(new FileInfo(hdfsType.getHdfsSite())); item.setHdfsSiteFile(new FileInfo(hdfsType.getHdfsSite()));
break; break;
case FTP: case FTP:
FtpResourceType ftpType = (FtpResourceType) dataResource.getType(); FtpResourceType ftpType = (FtpResourceType) dataResource.getType();
item.setFtpUrl(ftpType.getUrl()); item.setFtpUrl(ftpType.getUrl());
item.setFtpUsername(ftpType.getUsername()); item.setFtpUsername(ftpType.getUsername());
item.setFtpPassword(ftpType.getPassword()); item.setFtpPassword(ftpType.getPassword());
item.setFtpPath(ftpType.getPath()); item.setFtpPath(ftpType.getPath());
item.setFtpRegexFilter(ftpType.getRegexFilter()); item.setFtpRegexFilter(ftpType.getRegexFilter());
break; 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;
} }
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) { private ResourceType generateResourceType(SaveItem item) {
ResourceType type = null; ResourceType type = null;
switch (item.getResourceType()) { switch (item.getResourceType()) {
case API: case API:
type = new ApiResourceType(item.getApiUrl(), item.getApiUsername(), item.getApiPassword()); type = new ApiResourceType(item.getApiUrl(), item.getApiUsername(), item.getApiPassword());
break; break;
case FILE: case FILE:
DataFile dataFile = dataFileService.detail(item.getFile().getValue()); DataFile dataFile = dataFileService.detail(item.getFile().getValue());
type = new FileResourceType(dataFile); type = new FileResourceType(dataFile);
break; break;
case DATABASE: case DATABASE:
type = new DatabaseResourceType( type = new DatabaseResourceType(
item.getDatabaseJdbc(), item.getDatabaseJdbc(),
item.getDatabaseUsername(), item.getDatabaseUsername(),
item.getDatabasePassword(), item.getDatabasePassword(),
EnumUtil.fromString(DatabaseResourceType.DatabaseType.class, item.getDatabaseType()) EnumUtil.fromString(DatabaseResourceType.DatabaseType.class, item.getDatabaseType())
); );
break; break;
case HDFS: case HDFS:
type = new HDFSResourceType(dataFileService.detail(item.getCoreSiteFile().getValue()), dataFileService.detail(item.getHdfsSiteFile().getValue())); type = new HDFSResourceType(dataFileService.detail(item.getCoreSiteFile().getValue()), dataFileService.detail(item.getHdfsSiteFile().getValue()));
break; break;
case FTP: case FTP:
type = new FtpResourceType(item.getFtpUrl(), item.getFtpUsername(), item.getFtpPassword(), item.getFtpPath(), item.getFtpRegexFilter()); type = new FtpResourceType(item.getFtpUrl(), item.getFtpUsername(), item.getFtpPassword(), item.getFtpPath(), item.getFtpRegexFilter());
break; break;
}
type.setId(item.getResourceTypeId());
return type;
} }
type.setId(item.getResourceTypeId());
return type;
}
private ResourceFormat generateResourceFormat(SaveItem item) throws JsonProcessingException { private ResourceFormat generateResourceFormat(SaveItem item) throws JsonProcessingException {
ResourceFormat format = null; ResourceFormat format = null;
switch (item.getFormatType()) { switch (item.getFormatType()) {
case NONE: case NONE:
format = new NoneResourceFormat(); format = new NoneResourceFormat();
break; break;
case LINE: case LINE:
format = new LineResourceFormat(); format = new LineResourceFormat();
break; break;
case JSON: case JSON:
format = new JsonResourceFormat(mapper.writeValueAsString(item.getJsonSchema())); format = new JsonResourceFormat(mapper.writeValueAsString(item.getJsonSchema()));
break; break;
case JSON_LINE: case JSON_LINE:
format = new JsonLineResourceFormat(mapper.writeValueAsString(item.getJsonLineSchema())); format = new JsonLineResourceFormat(mapper.writeValueAsString(item.getJsonLineSchema()));
break; break;
case CSV: case CSV:
format = new CsvResourceFormat(mapper.writeValueAsString(item.getCsvSchema())); format = new CsvResourceFormat(mapper.writeValueAsString(item.getCsvSchema()));
break; break;
}
format.setId(item.getResourceFormatId());
return format;
} }
format.setId(item.getResourceFormatId());
return format;
}
@Data @Data
@EqualsAndHashCode(callSuper = true) @EqualsAndHashCode(callSuper = true)
public static class SaveItem extends SimpleSaveItem<DataResource> { public static class SaveItem extends SimpleSaveItem<DataResource> {
private String name; private String name;
private String description; private String description;
private Long resourceTypeId; private Long resourceTypeId;
private ResourceType.Type resourceType; private ResourceType.Type resourceType;
private String apiUrl; private String apiUrl;
private String apiUsername; private String apiUsername;
private String apiPassword; private String apiPassword;
private FileInfo file; private FileInfo file;
private String databaseType; private String databaseType;
private String databaseJdbc; private String databaseJdbc;
private String databaseUsername; private String databaseUsername;
private String databasePassword; private String databasePassword;
private FileInfo coreSiteFile; private FileInfo coreSiteFile;
private FileInfo hdfsSiteFile; private FileInfo hdfsSiteFile;
private String ftpUrl; private String ftpUrl;
private String ftpUsername; private String ftpUsername;
private String ftpPassword; private String ftpPassword;
private String ftpPath; private String ftpPath;
private String ftpRegexFilter; private String ftpRegexFilter;
private Long resourceFormatId; private Long resourceFormatId;
private ResourceFormat.Type formatType; private ResourceFormat.Type formatType;
private Map<?, ?> jsonSchema; private Map<?, ?> jsonSchema;
private String jsonSchemaText; private String jsonSchemaText;
private Map<?, ?> jsonLineSchema; private Map<?, ?> jsonLineSchema;
private String jsonLineSchemaText; private String jsonLineSchemaText;
private Map<?, ?> csvSchema; private Map<?, ?> csvSchema;
private String csvSchemaText; private String csvSchemaText;
private FileInfo exampleFile; private FileInfo exampleFile;
} }
@Data @Data
@EqualsAndHashCode(callSuper = true) @EqualsAndHashCode(callSuper = true)
public static final class ListItem extends SimpleListItem<DataResource> { public static final class ListItem extends SimpleListItem<DataResource> {
private Long id; private Long id;
private String name; private String name;
private String description; private String description;
private String type; private String type;
private String format; private String format;
private Long confirmationId; private Long confirmationId;
private Confirmation.State confirmationState; private Confirmation.State confirmationState;
private String createdUser; private String createdUser;
private LocalDateTime createdTime; private LocalDateTime createdTime;
} }
@Data @Data
@EqualsAndHashCode(callSuper = true) @EqualsAndHashCode(callSuper = true)
public static final class DetailItem extends SaveItem { public static final class DetailItem extends SaveItem {
private LocalDateTime createdTime; private LocalDateTime createdTime;
private String createdUsername; private String createdUsername;
private LocalDateTime modifiedTime; private LocalDateTime modifiedTime;
private String modifiedUsername; private String modifiedUsername;
} }
} }

View File

@@ -23,54 +23,54 @@ import org.springframework.web.bind.annotation.RestController;
@RestController @RestController
@RequestMapping("/user") @RequestMapping("/user")
public class UserController { 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) { public UserController(UserService userService) {
this.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") @Data
public AmisResponse<UserService.UserInformation> state() { public static final class LoginRequest {
return AmisResponse.responseSuccess(userService.state()); private String username;
} private String password;
private String checkCode;
}
@PostMapping("/register") @Data
public void register(@RequestBody RegisterRequest request) { public static final class RegisterRequest {
logger.info("Register request: {}", request); private String username;
userService.register(request.username, request.password, request.role); private String password;
} private User.Role 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;
}
} }

View File

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

View File

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

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

View File

@@ -34,97 +34,97 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@EntityListeners(AuditingEntityListener.class) @EntityListeners(AuditingEntityListener.class)
@Table(name = Constants.TABLE_PREFIX + "check_order") @Table(name = Constants.TABLE_PREFIX + "check_order")
@NamedEntityGraph(name = "check_order.list", attributeNodes = { @NamedEntityGraph(name = "check_order.list", attributeNodes = {
@NamedAttributeNode(value = "createdUser"), @NamedAttributeNode(value = "createdUser"),
@NamedAttributeNode(value = "modifiedUser"), @NamedAttributeNode(value = "modifiedUser"),
}) })
@NamedEntityGraph(name = "check_order.detail", attributeNodes = { @NamedEntityGraph(name = "check_order.detail", attributeNodes = {
@NamedAttributeNode(value = "createdUser"), @NamedAttributeNode(value = "createdUser"),
@NamedAttributeNode(value = "modifiedUser"), @NamedAttributeNode(value = "modifiedUser"),
}) })
@NoArgsConstructor @NoArgsConstructor
public class CheckOrder extends SimpleEntity { public class CheckOrder extends SimpleEntity {
@Column(nullable = false) @Column(nullable = false)
private String keyword; private String keyword;
@Column(nullable = false) @Column(nullable = false)
private String description; private String description;
@Column(nullable = false) @Column(nullable = false)
@Enumerated(EnumType.STRING) @Enumerated(EnumType.STRING)
private Type type; private Type type;
/** /**
* JSON 结构 Map<String, Object> * JSON 结构 Map<String, Object>
*/ */
@Column(nullable = false) @Column(nullable = false)
private String parameters; private String parameters;
@Column(nullable = false) @Column(nullable = false)
@Enumerated(EnumType.STRING) @Enumerated(EnumType.STRING)
private Target target; private Target target;
@Column(nullable = false) @Column(nullable = false)
private String targetClass; private String targetClass;
@OneToOne(fetch = FetchType.LAZY) @OneToOne(fetch = FetchType.LAZY)
@JoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) @JoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
@ToString.Exclude @ToString.Exclude
private User targetUser; private User targetUser;
@Enumerated(EnumType.STRING) @Enumerated(EnumType.STRING)
private User.Role targetRole; private User.Role targetRole;
@Column(nullable = false) @Column(nullable = false)
@Enumerated(EnumType.STRING) @Enumerated(EnumType.STRING)
private State state = State.CHECKING; private State state = State.CHECKING;
public CheckOrder( public CheckOrder(
String keyword, String keyword,
String description, String description,
Type type, Type type,
String parameters, String parameters,
String targetClass, String targetClass,
User targetUser User targetUser
) { ) {
this.keyword = keyword; this.keyword = keyword;
this.description = description; this.description = description;
this.type = type; this.type = type;
this.parameters = parameters; this.parameters = parameters;
this.target = Target.USER; this.target = Target.USER;
this.targetClass = targetClass; this.targetClass = targetClass;
this.targetUser = targetUser; this.targetUser = targetUser;
} }
public CheckOrder( public CheckOrder(
String keyword, String keyword,
String description, String description,
Type type, Type type,
String parameters, String parameters,
String targetClass, String targetClass,
User.Role targetRole User.Role targetRole
) { ) {
this.keyword = keyword; this.keyword = keyword;
this.description = description; this.description = description;
this.type = type; this.type = type;
this.parameters = parameters; this.parameters = parameters;
this.target = Target.ROLE; this.target = Target.ROLE;
this.targetClass = targetClass; this.targetClass = targetClass;
this.targetRole = targetRole; this.targetRole = targetRole;
} }
public enum Operation { public enum Operation {
APPLY, APPLY,
REJECT, REJECT,
} }
public enum Type { public enum Type {
CONFIRMATION, CONFIRMATION,
AUTHENTICATION, AUTHENTICATION,
MARKET, MARKET,
} }
public enum Target { public enum Target {
USER, USER,
ROLE, ROLE,
} }
public enum State { public enum State {
CHECKING, CHECKING,
RETRACT, RETRACT,
OVER, 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.CheckingNeededEntity;
import com.eshore.gringotts.web.domain.base.entity.LogicDeleteEntity; import com.eshore.gringotts.web.domain.base.entity.LogicDeleteEntity;
import java.util.Set; import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.ConstraintMode; import javax.persistence.ConstraintMode;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.EntityListeners; import javax.persistence.EntityListeners;
@@ -21,7 +20,6 @@ import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
import org.hibernate.annotations.DynamicUpdate; import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where; import org.hibernate.annotations.Where;
import org.springframework.data.jpa.domain.support.AuditingEntityListener; import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@@ -39,23 +37,22 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@EntityListeners(AuditingEntityListener.class) @EntityListeners(AuditingEntityListener.class)
@Table(name = Constants.TABLE_PREFIX + "confirmation") @Table(name = Constants.TABLE_PREFIX + "confirmation")
@NamedEntityGraph(name = "confirmation.list", attributeNodes = { @NamedEntityGraph(name = "confirmation.list", attributeNodes = {
@NamedAttributeNode(value = "target"), @NamedAttributeNode(value = "target"),
@NamedAttributeNode(value = "createdUser"), @NamedAttributeNode(value = "createdUser"),
}) })
@NamedEntityGraph(name = "confirmation.detail", attributeNodes = { @NamedEntityGraph(name = "confirmation.detail", attributeNodes = {
@NamedAttributeNode(value = "target"), @NamedAttributeNode(value = "target"),
@NamedAttributeNode(value = "evidences"), @NamedAttributeNode(value = "evidences"),
@NamedAttributeNode(value = "createdUser"), @NamedAttributeNode(value = "createdUser"),
@NamedAttributeNode(value = "modifiedUser"), @NamedAttributeNode(value = "modifiedUser"),
}) })
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "confirmation" + " set deleted = true where id = ?")
@Where(clause = LogicDeleteEntity.LOGIC_DELETE_CLAUSE) @Where(clause = LogicDeleteEntity.LOGIC_DELETE_CLAUSE)
public class Confirmation extends CheckingNeededEntity { public class Confirmation extends CheckingNeededEntity {
@OneToOne(fetch = FetchType.EAGER) @OneToOne(fetch = FetchType.EAGER)
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) @JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
private DataResource target; private DataResource target;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @OneToMany(fetch = FetchType.LAZY)
@JoinTable(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT), inverseForeignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) @JoinTable(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT), inverseForeignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
@ToString.Exclude @ToString.Exclude
private Set<DataFile> evidences; private Set<DataFile> evidences;
} }

View File

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

View File

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

View File

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

View File

@@ -1,7 +1,5 @@
package com.eshore.gringotts.web.domain.entity.format; 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.DiscriminatorValue;
import javax.persistence.Entity; import javax.persistence.Entity;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
@@ -9,8 +7,6 @@ import lombok.Getter;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
/** /**
* CSV格式 * CSV格式
@@ -25,13 +21,11 @@ import org.hibernate.annotations.Where;
@NoArgsConstructor @NoArgsConstructor
@Entity @Entity
@DiscriminatorValue("CSV") @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 { public class CsvResourceFormat extends ResourceFormat {
private String schema; private String csvSchema;
@Override @Override
public Type getFormatType() { public Type getFormatType() {
return Type.CSV; return Type.CSV;
} }
} }

View File

@@ -1,7 +1,5 @@
package com.eshore.gringotts.web.domain.entity.format; 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.DiscriminatorValue;
import javax.persistence.Entity; import javax.persistence.Entity;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
@@ -9,8 +7,6 @@ import lombok.Getter;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
/** /**
* JSON line格式 * JSON line格式
@@ -25,13 +21,11 @@ import org.hibernate.annotations.Where;
@NoArgsConstructor @NoArgsConstructor
@Entity @Entity
@DiscriminatorValue("JSON_LINE") @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 { public class JsonLineResourceFormat extends ResourceFormat {
private String schema; private String jsonSchema;
@Override @Override
public Type getFormatType() { public Type getFormatType() {
return Type.JSON_LINE; return Type.JSON_LINE;
} }
} }

View File

@@ -1,7 +1,5 @@
package com.eshore.gringotts.web.domain.entity.format; 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.DiscriminatorValue;
import javax.persistence.Entity; import javax.persistence.Entity;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
@@ -9,8 +7,6 @@ import lombok.Getter;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
/** /**
* 一个文件就是一个JSON * 一个文件就是一个JSON
@@ -25,13 +21,11 @@ import org.hibernate.annotations.Where;
@NoArgsConstructor @NoArgsConstructor
@Entity @Entity
@DiscriminatorValue("JSON") @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 { public class JsonResourceFormat extends ResourceFormat {
private String schema; private String jsonSchema;
@Override @Override
public Type getFormatType() { public Type getFormatType() {
return Type.JSON; return Type.JSON;
} }
} }

View File

@@ -1,14 +1,10 @@
package com.eshore.gringotts.web.domain.entity.format; 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.DiscriminatorValue;
import javax.persistence.Entity; import javax.persistence.Entity;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
/** /**
* 无格式,文件每行就是一份数据 * 无格式,文件每行就是一份数据
@@ -21,11 +17,9 @@ import org.hibernate.annotations.Where;
@ToString @ToString
@Entity @Entity
@DiscriminatorValue("LINE") @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 { public class LineResourceFormat extends ResourceFormat {
@Override @Override
public Type getFormatType() { public Type getFormatType() {
return Type.LINE; return Type.LINE;
} }
} }

View File

@@ -1,14 +1,10 @@
package com.eshore.gringotts.web.domain.entity.format; 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.DiscriminatorValue;
import javax.persistence.Entity; import javax.persistence.Entity;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
/** /**
* 无格式,整个文件就是一份数据 * 无格式,整个文件就是一份数据
@@ -21,11 +17,9 @@ import org.hibernate.annotations.Where;
@ToString @ToString
@Entity @Entity
@DiscriminatorValue("NONE") @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 { public class NoneResourceFormat extends ResourceFormat {
@Override @Override
public Type getFormatType() { public Type getFormatType() {
return Type.NONE; return Type.NONE;
} }
} }

View File

@@ -9,8 +9,6 @@ import javax.persistence.Table;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
/** /**
* 资源格式 * 资源格式
@@ -24,16 +22,14 @@ import org.hibernate.annotations.Where;
@Entity @Entity
@Table(name = Constants.TABLE_PREFIX + "resource_format") @Table(name = Constants.TABLE_PREFIX + "resource_format")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE) @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 class ResourceFormat extends LogicDeleteIdOnlyEntity {
public abstract Type getFormatType(); public abstract Type getFormatType();
public enum Type { public enum Type {
NONE, NONE,
LINE, LINE,
JSON, JSON,
JSON_LINE, JSON_LINE,
CSV, CSV,
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -9,8 +9,6 @@ import javax.persistence.Table;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
/** /**
* 资源类型 * 资源类型
@@ -24,16 +22,14 @@ import org.hibernate.annotations.Where;
@Entity @Entity
@Table(name = Constants.TABLE_PREFIX + "resource_type") @Table(name = Constants.TABLE_PREFIX + "resource_type")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) @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 class ResourceType extends LogicDeleteIdOnlyEntity {
public abstract Type getResourceType(); public abstract Type getResourceType();
public enum Type { public enum Type {
API, API,
DATABASE, DATABASE,
FILE, FILE,
FTP, FTP,
HDFS, HDFS,
} }
} }

View File

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

View File

@@ -20,20 +20,20 @@ import org.springframework.stereotype.Repository;
@SuppressWarnings("NullableProblems") @SuppressWarnings("NullableProblems")
@Repository @Repository
public interface CheckOrderRepository extends SimpleRepository<CheckOrder, Long> { public interface CheckOrderRepository extends SimpleRepository<CheckOrder, Long> {
@Override @Override
@EntityGraph(value = "check_order.list", type = EntityGraph.EntityGraphType.FETCH) @EntityGraph(value = "check_order.list", type = EntityGraph.EntityGraphType.FETCH)
List<CheckOrder> findAll(Specification<CheckOrder> specification); List<CheckOrder> findAll(Specification<CheckOrder> specification);
@Override @Override
@EntityGraph(value = "check_order.list", type = EntityGraph.EntityGraphType.FETCH) @EntityGraph(value = "check_order.list", type = EntityGraph.EntityGraphType.FETCH)
List<CheckOrder> findAll(Specification<CheckOrder> specification, Sort sort); List<CheckOrder> findAll(Specification<CheckOrder> specification, Sort sort);
@Override @Override
@EntityGraph(value = "check_order.detail", type = EntityGraph.EntityGraphType.FETCH) @EntityGraph(value = "check_order.detail", type = EntityGraph.EntityGraphType.FETCH)
Optional<CheckOrder> findOne(Specification<CheckOrder> specification); Optional<CheckOrder> findOne(Specification<CheckOrder> specification);
@Transactional @Transactional
@Modifying @Modifying
@Query("update CheckOrder check set check.state = ?2, check.modifiedUser = ?3, check.modifiedTime = current_timestamp where check.id = ?1") @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); void overById(Long id, CheckOrder.State state, User modifiedUser);
} }

View File

@@ -16,17 +16,17 @@ import org.springframework.stereotype.Repository;
@SuppressWarnings("NullableProblems") @SuppressWarnings("NullableProblems")
@Repository @Repository
public interface ConfirmationRepository extends SimpleRepository<Confirmation, Long> { public interface ConfirmationRepository extends SimpleRepository<Confirmation, Long> {
@Override @Override
@EntityGraph(value = "confirmation.list", type = EntityGraph.EntityGraphType.FETCH) @EntityGraph(value = "confirmation.list", type = EntityGraph.EntityGraphType.FETCH)
List<Confirmation> findAll(Specification<Confirmation> specification); List<Confirmation> findAll(Specification<Confirmation> specification);
@Override @Override
@EntityGraph(value = "confirmation.list", type = EntityGraph.EntityGraphType.FETCH) @EntityGraph(value = "confirmation.list", type = EntityGraph.EntityGraphType.FETCH)
List<Confirmation> findAll(Specification<Confirmation> specification, Sort sort); List<Confirmation> findAll(Specification<Confirmation> specification, Sort sort);
@Override @Override
@EntityGraph(value = "confirmation.detail", type = EntityGraph.EntityGraphType.FETCH) @EntityGraph(value = "confirmation.detail", type = EntityGraph.EntityGraphType.FETCH)
Optional<Confirmation> findOne(Specification<Confirmation> specification); 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") @SuppressWarnings("NullableProblems")
@Repository @Repository
public interface DataResourceRepository extends SimpleRepository<DataResource, Long> { public interface DataResourceRepository extends SimpleRepository<DataResource, Long> {
@Override @Override
@EntityGraph(value = "data_resource.list", type = EntityGraph.EntityGraphType.FETCH) @EntityGraph(value = "data_resource.list", type = EntityGraph.EntityGraphType.FETCH)
List<DataResource> findAll(Specification<DataResource> specification); List<DataResource> findAll(Specification<DataResource> specification);
@Override @Override
@EntityGraph(value = "data_resource.list", type = EntityGraph.EntityGraphType.FETCH) @EntityGraph(value = "data_resource.list", type = EntityGraph.EntityGraphType.FETCH)
List<DataResource> findAll(Specification<DataResource> specification, Sort sort); List<DataResource> findAll(Specification<DataResource> specification, Sort sort);
@EntityGraph(value = "data_resource.list", type = EntityGraph.EntityGraphType.FETCH) @EntityGraph(value = "data_resource.list", type = EntityGraph.EntityGraphType.FETCH)
List<DataResource> findAllByConfirmationIsNull(); List<DataResource> findAllByConfirmationIsNull();
@Override @Override
@EntityGraph(value = "data_resource.detail", type = EntityGraph.EntityGraphType.FETCH) @EntityGraph(value = "data_resource.detail", type = EntityGraph.EntityGraphType.FETCH)
Optional<DataResource> findOne(Specification<DataResource> specification); Optional<DataResource> findOne(Specification<DataResource> specification);
} }

View File

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

View File

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

View File

@@ -4,7 +4,6 @@ import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import com.eshore.gringotts.web.domain.base.entity.CheckingNeededEntity; 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.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.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;
@@ -33,121 +32,128 @@ import org.springframework.stereotype.Service;
*/ */
@Slf4j @Slf4j
@Service("com.eshore.gringotts.web.domain.service.AuthenticationService") @Service("com.eshore.gringotts.web.domain.service.AuthenticationService")
public class AuthenticationService extends LogicDeleteService<Authentication> implements CheckingService { public class AuthenticationService extends CheckingService<Authentication> {
private final AuthenticationRepository authenticationRepository; private final AuthenticationRepository authenticationRepository;
private final UserService userService; private final UserService userService;
private final CheckOrderService checkOrderService; private final CheckOrderService checkOrderService;
private final ObjectMapper mapper; private final ObjectMapper mapper;
public AuthenticationService(AuthenticationRepository repository, UserService userService, EntityManager manager, CheckOrderService checkOrderService, Jackson2ObjectMapperBuilder builder) { public AuthenticationService(AuthenticationRepository repository, UserService userService, EntityManager manager, CheckOrderService checkOrderService, Jackson2ObjectMapperBuilder builder) {
super(repository, userService, manager); super(repository, userService, manager);
this.authenticationRepository = repository; this.authenticationRepository = repository;
this.userService = userService; this.userService = userService;
this.checkOrderService = checkOrderService; this.checkOrderService = checkOrderService;
this.mapper = builder.build(); this.mapper = builder.build();
}
@Override
protected ImmutableList<Predicate> listPredicate(Root<Authentication> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
User loginUser = userService.currentLoginUser();
if (User.isAdministrator(loginUser)) {
return Lists.immutable.empty();
} }
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)
)
));
}
@Override @Override
protected ImmutableList<Predicate> listPredicate(Root<Authentication> root, CriteriaQuery<?> query, CriteriaBuilder builder) { public Long save(Authentication entity) {
User loginUser = userService.currentLoginUser(); if (ObjectUtil.isNull(entity.getId()) && authenticationRepository.findOne(
if (User.isAdministrator(loginUser)) { (root, query, criteriaBuilder) -> {
return Lists.immutable.empty(); // 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( ).isPresent()) {
builder.equal(root.get(Authentication_.createdUser), loginUser), throw new AuthenticationDuplicatedException();
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)
)
));
} }
return super.save(entity);
}
@Override @Transactional(rollbackOn = Throwable.class)
public Long save(Authentication entity) { @Override
if (ObjectUtil.isNull(entity.getId()) && authenticationRepository.findOne( public void submit(Long id) throws JsonProcessingException {
(root, query, criteriaBuilder) -> { Authentication authentication = detailOrThrow(id);
// TODO 同一个资源的授权时间是否重合 authentication.setState(CheckingNeededEntity.State.OWNER_CHECKING);
// 查询是否存在createdUser为当前登陆用户并且绑定的数据资源是同一个的授权申请 Long orderId = checkOrderService.save(new CheckOrder(
return criteriaBuilder.and( "authentication_owner_check",
criteriaBuilder.equal(root.get("createdUser"), userService.currentLoginUser()), StrUtil.format("数据资源「{}」的授权申请", authentication.getTarget().getName()),
criteriaBuilder.equal(root.get("target"), entity.getTarget()) CheckOrder.Type.AUTHENTICATION,
); mapper.writeValueAsString(Maps.immutable.of("authenticationId", authentication.getId())),
} "com.eshore.gringotts.web.domain.service.AuthenticationService",
).isPresent()) { authentication.getCreatedUser()
throw new AuthenticationDuplicatedException(); ));
} CheckOrder order = checkOrderService.detailOrThrow(orderId);
return super.save(entity); authentication.setOrder(order);
save(authentication);
}
@Transactional(rollbackOn = Throwable.class)
@Override
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);
}
@Transactional(rollbackOn = Throwable.class) @Override
public void submit(Long id) throws JsonProcessingException { public ImmutableMap<String, Object> archive(Authentication authentication) {
Authentication authentication = detailOrThrow(id); return null;
authentication.setState(CheckingNeededEntity.State.OWNER_CHECKING); }
Long orderId = checkOrderService.save(new CheckOrder(
"authentication_owner_check", public static final class AuthenticationDuplicatedException extends RuntimeException {
StrUtil.format("数据资源「{}」的授权申请", authentication.getTarget().getName()), public AuthenticationDuplicatedException() {
CheckOrder.Type.AUTHENTICATION, super("数据资源已绑定该账号的授权申请,无法再次申请");
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("数据资源已绑定该账号的授权申请,无法再次申请");
}
} }
}
} }

View File

@@ -30,53 +30,53 @@ import org.springframework.stereotype.Service;
@Slf4j @Slf4j
@Service @Service
public class CheckOrderService extends SimpleServiceSupport<CheckOrder> { public class CheckOrderService extends SimpleServiceSupport<CheckOrder> {
private final ApplicationContext applicationContext; private final ApplicationContext applicationContext;
private final ObjectMapper mapper; private final ObjectMapper mapper;
private final CheckOrderRepository checkOrderRepository; private final CheckOrderRepository checkOrderRepository;
private final UserService userService; private final UserService userService;
public CheckOrderService(CheckOrderRepository repository, UserService userService, ApplicationContext applicationContext, Jackson2ObjectMapperBuilder builder) { public CheckOrderService(CheckOrderRepository repository, UserService userService, ApplicationContext applicationContext, Jackson2ObjectMapperBuilder builder) {
super(repository, userService); super(repository, userService);
this.applicationContext = applicationContext; this.applicationContext = applicationContext;
this.mapper = builder.build(); this.mapper = builder.build();
this.checkOrderRepository = repository; this.checkOrderRepository = repository;
this.userService = userService; this.userService = userService;
} }
@Override @Override
protected ImmutableList<Predicate> listPredicate(Root<CheckOrder> root, CriteriaQuery<?> query, CriteriaBuilder builder) { protected ImmutableList<Predicate> listPredicate(Root<CheckOrder> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
User user = userService.currentLoginUser(); User user = userService.currentLoginUser();
if (User.isAdministrator(user)) { if (User.isAdministrator(user)) {
return Lists.immutable.empty(); 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())
)
));
} }
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())
)
));
}
public void operation(Long id, CheckOrder.Operation operation) throws JsonProcessingException { public void operation(Long id, CheckOrder.Operation operation) throws JsonProcessingException {
CheckOrder order = detailOrThrow(id); CheckOrder order = detailOrThrow(id);
CheckingService service = applicationContext.getBean(order.getTargetClass(), CheckingService.class); CheckingService service = applicationContext.getBean(order.getTargetClass(), CheckingService.class);
if (ObjectUtil.isNull(service)) { if (ObjectUtil.isNull(service)) {
throw new RuntimeException(StrUtil.format("名为「{}」的服务未找到", order.getTargetClass())); throw new RuntimeException(StrUtil.format("名为「{}」的服务未找到", order.getTargetClass()));
}
ImmutableMap<String, Object> parameters = mapper.readValue(order.getParameters(), new TypeReference<>() {});
service.onChecked(order, operation, parameters);
} }
ImmutableMap<String, Object> parameters = mapper.readValue(order.getParameters(), new TypeReference<>() {});
service.onChecked(order, operation, parameters);
}
public void retract(Long id) { public void retract(Long id) {
checkOrderRepository.overById(id, CheckOrder.State.RETRACT, userService.currentLoginUser()); checkOrderRepository.overById(id, CheckOrder.State.RETRACT, userService.currentLoginUser());
} }
public void over(Long id) { public void over(Long id) {
checkOrderRepository.overById(id, CheckOrder.State.OVER, userService.currentLoginUser()); checkOrderRepository.overById(id, CheckOrder.State.OVER, userService.currentLoginUser());
} }
} }

View File

@@ -4,7 +4,6 @@ import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import com.eshore.gringotts.web.domain.base.entity.CheckingNeededEntity; 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.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.CheckOrder_; import com.eshore.gringotts.web.domain.entity.CheckOrder_;
import com.eshore.gringotts.web.domain.entity.Confirmation; import com.eshore.gringotts.web.domain.entity.Confirmation;
@@ -13,6 +12,7 @@ import com.eshore.gringotts.web.domain.entity.User;
import com.eshore.gringotts.web.domain.repository.ConfirmationRepository; import com.eshore.gringotts.web.domain.repository.ConfirmationRepository;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join; import javax.persistence.criteria.Join;
@@ -34,103 +34,110 @@ import org.springframework.stereotype.Service;
*/ */
@Slf4j @Slf4j
@Service("com.eshore.gringotts.web.domain.service.ConfirmationService") @Service("com.eshore.gringotts.web.domain.service.ConfirmationService")
public class ConfirmationService extends SimpleServiceSupport<Confirmation> implements CheckingService { public class ConfirmationService extends CheckingService<Confirmation> {
private final ConfirmationRepository confirmationRepository; private final ConfirmationRepository confirmationRepository;
private final CheckOrderService checkOrderService; private final CheckOrderService checkOrderService;
private final ObjectMapper mapper; private final ObjectMapper mapper;
public ConfirmationService(ConfirmationRepository confirmationRepository, UserService userService, CheckOrderService checkOrderService, Jackson2ObjectMapperBuilder builder) { public ConfirmationService(ConfirmationRepository confirmationRepository, UserService userService, EntityManager entityManager, CheckOrderService checkOrderService, Jackson2ObjectMapperBuilder builder) {
super(confirmationRepository, userService); super(confirmationRepository, userService, entityManager);
this.confirmationRepository = confirmationRepository; this.confirmationRepository = confirmationRepository;
this.checkOrderService = checkOrderService; this.checkOrderService = checkOrderService;
this.mapper = builder.build(); this.mapper = builder.build();
}
@Override
protected ImmutableList<Predicate> listPredicate(Root<Confirmation> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
User loginUser = userService.currentLoginUser();
if (User.isAdministrator(loginUser)) {
return Lists.immutable.empty();
} }
Join<Confirmation, CheckOrder> orderJoin = root.join(Confirmation_.order, JoinType.LEFT);
@Override return Lists.immutable.of(builder.or(
protected ImmutableList<Predicate> listPredicate(Root<Confirmation> root, CriteriaQuery<?> query, CriteriaBuilder builder) { builder.equal(root.get(Confirmation_.createdUser), loginUser),
User loginUser = userService.currentLoginUser(); builder.and(
if (User.isAdministrator(loginUser)) { builder.isNotNull(orderJoin),
return Lists.immutable.empty(); builder.or(
}
Join<Confirmation, CheckOrder> orderJoin = root.join(Confirmation_.order, JoinType.LEFT);
return Lists.immutable.of(builder.or(
builder.equal(root.get(Confirmation_.createdUser), loginUser),
builder.and( builder.and(
builder.isNotNull(orderJoin), builder.equal(orderJoin.get(CheckOrder_.target), CheckOrder.Target.ROLE),
builder.or( builder.equal(orderJoin.get(CheckOrder_.targetRole), loginUser.getRole())
builder.and( ),
builder.equal(orderJoin.get(CheckOrder_.target), CheckOrder.Target.ROLE), builder.and(
builder.equal(orderJoin.get(CheckOrder_.targetRole), loginUser.getRole()) builder.equal(orderJoin.get(CheckOrder_.target), CheckOrder.Target.USER),
), builder.equal(orderJoin.get(CheckOrder_.targetUser), loginUser)
builder.and(
builder.equal(orderJoin.get(CheckOrder_.target), CheckOrder.Target.USER),
builder.equal(orderJoin.get(CheckOrder_.targetUser), loginUser)
)
)
) )
)); )
} )
));
}
@Override @Override
public Long save(Confirmation entity) { public Long save(Confirmation entity) {
if (ObjectUtil.isNull(entity.getId()) && confirmationRepository.existsByTarget_Id(entity.getTarget().getId())) { if (ObjectUtil.isNull(entity.getId()) && confirmationRepository.existsByTarget_Id(entity.getTarget().getId())) {
throw new ConfirmationDuplicatedException(); throw new ConfirmationDuplicatedException();
}
return super.save(entity);
} }
return super.save(entity);
}
@Transactional(rollbackOn = Throwable.class) @Transactional(rollbackOn = Throwable.class)
public void submit(Long id) throws JsonProcessingException { @Override
Confirmation confirmation = detailOrThrow(id); public void submit(Long id) throws JsonProcessingException {
confirmation.setState(Confirmation.State.CHECKING); Confirmation confirmation = detailOrThrow(id);
Long orderId = checkOrderService.save(new CheckOrder( confirmation.setState(Confirmation.State.CHECKING);
"confirmation_check", Long orderId = checkOrderService.save(new CheckOrder(
StrUtil.format("数据资源「{}」的确权申请", confirmation.getTarget().getName()), "confirmation_check",
CheckOrder.Type.CONFIRMATION, StrUtil.format("数据资源「{}」的确权申请", confirmation.getTarget().getName()),
mapper.writeValueAsString(Maps.immutable.of("confirmationId", confirmation.getId())), CheckOrder.Type.CONFIRMATION,
"com.eshore.gringotts.web.domain.service.ConfirmationService", mapper.writeValueAsString(Maps.immutable.of("confirmationId", confirmation.getId())),
User.Role.CHECKER "com.eshore.gringotts.web.domain.service.ConfirmationService",
)); User.Role.CHECKER
CheckOrder order = checkOrderService.detailOrThrow(orderId); ));
confirmation.setOrder(order); CheckOrder order = checkOrderService.detailOrThrow(orderId);
save(confirmation); confirmation.setOrder(order);
save(confirmation);
}
@Transactional(rollbackOn = Throwable.class)
@Override
public void retract(Long id) {
Confirmation confirmation = detailOrThrow(id);
confirmation.setState(CheckingNeededEntity.State.DRAFT);
save(confirmation);
CheckOrder order = confirmation.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) {
if (StrUtil.equals(order.getKeyword(), "confirmation_check")) {
Long id = (Long) parameters.get("confirmationId");
Confirmation confirmation = detailOrThrow(id);
switch (operation) {
case APPLY:
confirmation.setState(Confirmation.State.NORMAL);
order.setState(CheckOrder.State.OVER);
break;
case REJECT:
confirmation.setState(Confirmation.State.DRAFT);
order.setState(CheckOrder.State.OVER);
break;
}
save(confirmation);
checkOrderService.save(order);
} }
}
@Transactional(rollbackOn = Throwable.class) @Override
public void retract(Long id) { public ImmutableMap<String, Object> archive(Confirmation confirmation) {
Confirmation confirmation = detailOrThrow(id); return null;
confirmation.setState(CheckingNeededEntity.State.DRAFT); }
save(confirmation);
CheckOrder order = confirmation.getOrder(); public static final class ConfirmationDuplicatedException extends RuntimeException {
order.setState(CheckOrder.State.RETRACT); public ConfirmationDuplicatedException() {
checkOrderService.save(order); super("数据资源已绑定确权申请,无法再次申请");
}
@Override
@Transactional(rollbackOn = Throwable.class)
public void onChecked(CheckOrder order, CheckOrder.Operation operation, ImmutableMap<String, Object> parameters) {
if (StrUtil.equals(order.getKeyword(), "confirmation_check")) {
Long id = (Long) parameters.get("confirmationId");
Confirmation confirmation = detailOrThrow(id);
switch (operation) {
case APPLY:
confirmation.setState(Confirmation.State.NORMAL);
order.setState(CheckOrder.State.OVER);
break;
case REJECT:
confirmation.setState(Confirmation.State.DRAFT);
order.setState(CheckOrder.State.OVER);
break;
}
save(confirmation);
checkOrderService.save(order);
}
}
public static final class ConfirmationDuplicatedException extends RuntimeException {
public ConfirmationDuplicatedException() {
super("数据资源已绑定确权申请,无法再次申请");
}
} }
}
} }

View File

@@ -29,75 +29,75 @@ import org.springframework.stereotype.Service;
@Slf4j @Slf4j
@Service @Service
public class DataFileService extends SimpleServiceSupport<DataFile> { public class DataFileService extends SimpleServiceSupport<DataFile> {
private final DataFileRepository dataFileRepository; private final DataFileRepository dataFileRepository;
private final UserService userService; private final UserService userService;
public DataFileService(DataFileRepository dataFileRepository, UserService userService) { public DataFileService(DataFileRepository dataFileRepository, UserService userService) {
super(dataFileRepository, userService); super(dataFileRepository, userService);
this.dataFileRepository = dataFileRepository; this.dataFileRepository = dataFileRepository;
this.userService = userService; this.userService = userService;
}
@Override
protected ImmutableList<Predicate> listPredicate(Root<DataFile> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
User loginUser = userService.currentLoginUser();
if (User.isAdministrator(loginUser)) {
return Lists.immutable.empty();
} }
@Override Subquery<Confirmation> confirmationSubquery = query.subquery(Confirmation.class);
protected ImmutableList<Predicate> listPredicate(Root<DataFile> root, CriteriaQuery<?> query, CriteriaBuilder builder) { Root<Confirmation> confirmationRoot = confirmationSubquery.from(Confirmation.class);
User loginUser = userService.currentLoginUser(); confirmationSubquery.select(confirmationRoot)
if (User.isAdministrator(loginUser)) { .where(
return Lists.immutable.empty(); builder.isMember(root, confirmationRoot.get(Confirmation_.evidences)),
} EntityHelper.checkNeededEntityPrediction(confirmationRoot, builder, loginUser)
);
Subquery<Confirmation> confirmationSubquery = query.subquery(Confirmation.class); Subquery<Authentication> authenticationSubquery = query.subquery(Authentication.class);
Root<Confirmation> confirmationRoot = confirmationSubquery.from(Confirmation.class); Root<Authentication> authenticationRoot = authenticationSubquery.from(Authentication.class);
confirmationSubquery.select(confirmationRoot) authenticationSubquery.select(authenticationRoot)
.where( .where(
builder.isMember(root, confirmationRoot.get(Confirmation_.evidences)), builder.isMember(root, authenticationRoot.get(Authentication_.evidences)),
EntityHelper.checkNeededEntityPrediction(confirmationRoot, builder, loginUser) EntityHelper.checkNeededEntityPrediction(authenticationRoot, builder, loginUser)
); );
Subquery<Authentication> authenticationSubquery = query.subquery(Authentication.class); return Lists.immutable.of(builder.or(
Root<Authentication> authenticationRoot = authenticationSubquery.from(Authentication.class); builder.equal(root.get(DataFile_.createdUser), loginUser),
authenticationSubquery.select(authenticationRoot) builder.exists(confirmationSubquery),
.where( builder.exists(authenticationSubquery)
builder.isMember(root, authenticationRoot.get(Authentication_.evidences)), ));
EntityHelper.checkNeededEntityPrediction(authenticationRoot, builder, loginUser) }
);
return Lists.immutable.of(builder.or( public DataFile downloadFile(Long id) {
builder.equal(root.get(DataFile_.createdUser), loginUser), return dataFileRepository.findOne((root, query, builder) -> builder.equal(root.get(DataFile_.id), id)).orElseThrow(DataFileNotFoundException::new);
builder.exists(confirmationSubquery), }
builder.exists(authenticationSubquery)
)); public Long initialDataFile(String filename) {
DataFile dataFile = new DataFile();
dataFile.setFilename(filename);
return dataFileRepository.save(dataFile).getId();
}
public void updateDataFile(Long id, String path, Long size, String md5, String type) {
DataFile dataFile = dataFileRepository.findById(id).orElseThrow(UpdateDataFileFailedException::new);
dataFile.setSize(size);
dataFile.setMd5(md5);
dataFile.setPath(path);
dataFile.setType(type);
User loginUser = userService.currentLoginUser();
dataFile.setModifiedUser(loginUser);
dataFileRepository.save(dataFile);
}
public static final class DataFileNotFoundException extends RuntimeException {
public DataFileNotFoundException() {
super("文件未找到,请重新上传");
} }
}
public DataFile downloadFile(Long id) { public static final class UpdateDataFileFailedException extends RuntimeException {
return dataFileRepository.findOne((root, query, builder) -> builder.equal(root.get(DataFile_.id), id)).orElseThrow(DataFileNotFoundException::new); public UpdateDataFileFailedException() {
} super("更新文件信息失败,请重新上传");
public Long initialDataFile(String filename) {
DataFile dataFile = new DataFile();
dataFile.setFilename(filename);
return dataFileRepository.save(dataFile).getId();
}
public void updateDataFile(Long id, String path, Long size, String md5, String type) {
DataFile dataFile = dataFileRepository.findById(id).orElseThrow(UpdateDataFileFailedException::new);
dataFile.setSize(size);
dataFile.setMd5(md5);
dataFile.setPath(path);
dataFile.setType(type);
User loginUser = userService.currentLoginUser();
dataFile.setModifiedUser(loginUser);
dataFileRepository.save(dataFile);
}
public static final class DataFileNotFoundException extends RuntimeException {
public DataFileNotFoundException() {
super("文件未找到,请重新上传");
}
}
public static final class UpdateDataFileFailedException extends RuntimeException {
public UpdateDataFileFailedException() {
super("更新文件信息失败,请重新上传");
}
} }
}
} }

View File

@@ -1,6 +1,6 @@
package com.eshore.gringotts.web.domain.service; package com.eshore.gringotts.web.domain.service;
import com.eshore.gringotts.web.domain.base.service.SimpleServiceSupport; 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.Authentication_; import com.eshore.gringotts.web.domain.entity.Authentication_;
import com.eshore.gringotts.web.domain.entity.Confirmation; import com.eshore.gringotts.web.domain.entity.Confirmation;
@@ -15,6 +15,7 @@ import com.eshore.gringotts.web.domain.repository.DataResourceRepository;
import com.eshore.gringotts.web.domain.repository.ResourceFormatRepository; import com.eshore.gringotts.web.domain.repository.ResourceFormatRepository;
import com.eshore.gringotts.web.domain.repository.ResourceTypeRepository; import com.eshore.gringotts.web.domain.repository.ResourceTypeRepository;
import com.eshore.gringotts.web.helper.EntityHelper; import com.eshore.gringotts.web.helper.EntityHelper;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join; import javax.persistence.criteria.Join;
@@ -34,104 +35,104 @@ import org.springframework.stereotype.Service;
*/ */
@Slf4j @Slf4j
@Service @Service
public class DataResourceService extends SimpleServiceSupport<DataResource> { public class DataResourceService extends LogicDeleteService<DataResource> {
private final DataResourceRepository dataResourceRepository; private final DataResourceRepository dataResourceRepository;
private final ResourceTypeRepository resourceTypeRepository; private final ResourceTypeRepository resourceTypeRepository;
private final ResourceFormatRepository resourceFormatRepository; private final ResourceFormatRepository resourceFormatRepository;
private final UserService userService; private final UserService userService;
public DataResourceService(DataResourceRepository repository, ResourceTypeRepository resourceTypeRepository, ResourceFormatRepository resourceFormatRepository, UserService userService) { public DataResourceService(DataResourceRepository repository, ResourceTypeRepository resourceTypeRepository, ResourceFormatRepository resourceFormatRepository, UserService userService, EntityManager entityManager) {
super(repository, userService); super(repository, userService, entityManager);
this.dataResourceRepository = repository; this.dataResourceRepository = repository;
this.resourceTypeRepository = resourceTypeRepository; this.resourceTypeRepository = resourceTypeRepository;
this.resourceFormatRepository = resourceFormatRepository; this.resourceFormatRepository = resourceFormatRepository;
this.userService = userService; this.userService = userService;
}
@Override
protected ImmutableList<Predicate> listPredicate(Root<DataResource> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
User loginUser = userService.currentLoginUser();
if (User.isAdministrator(loginUser)) {
return Lists.immutable.empty();
} }
@Override Subquery<Confirmation> confirmationSubquery = query.subquery(Confirmation.class);
protected ImmutableList<Predicate> listPredicate(Root<DataResource> root, CriteriaQuery<?> query, CriteriaBuilder builder) { Root<Confirmation> confirmationRoot = confirmationSubquery.from(Confirmation.class);
User loginUser = userService.currentLoginUser(); confirmationSubquery.select(confirmationRoot)
if (User.isAdministrator(loginUser)) { .where(
return Lists.immutable.empty(); builder.equal(confirmationRoot.get(Confirmation_.target), root),
EntityHelper.checkNeededEntityPrediction(confirmationRoot, builder, loginUser)
);
Subquery<Authentication> authenticationSubquery = query.subquery(Authentication.class);
Root<Authentication> authenticationRoot = authenticationSubquery.from(Authentication.class);
authenticationSubquery.select(authenticationRoot)
.where(
builder.equal(authenticationRoot.get(Authentication_.target), root),
EntityHelper.checkNeededEntityPrediction(authenticationRoot, builder, loginUser)
);
return Lists.immutable.of(builder.or(
builder.equal(root.get(DataResource_.createdUser), loginUser),
builder.exists(confirmationSubquery),
builder.exists(authenticationSubquery)
));
}
public ImmutableList<DataResource> listNoConfirmation() {
return Lists.immutable.ofAll(dataResourceRepository.findAll(
(root, query, builder) -> {
Join<DataResource, Confirmation> confirmationJoin = root.join(DataResource_.confirmation, JoinType.LEFT);
return builder.and(
builder.isNull(confirmationJoin.get(Confirmation_.id)),
builder.equal(root.get(DataResource_.createdUser), userService.currentLoginUser())
);
} }
));
}
Subquery<Confirmation> confirmationSubquery = query.subquery(Confirmation.class); public ImmutableList<DataResource> listNoAuthentication() {
Root<Confirmation> confirmationRoot = confirmationSubquery.from(Confirmation.class); return Lists.immutable.ofAll(dataResourceRepository.findAll(
confirmationSubquery.select(confirmationRoot) (root, query, builder) -> {
.where( Join<DataResource, Confirmation> confirmationJoin = root.join(DataResource_.confirmation, JoinType.LEFT);
builder.equal(confirmationRoot.get(Confirmation_.target), root), confirmationJoin.on(builder.equal(confirmationJoin.get(Confirmation_.state), Confirmation.State.NORMAL));
EntityHelper.checkNeededEntityPrediction(confirmationRoot, builder, loginUser)
);
Subquery<Authentication> authenticationSubquery = query.subquery(Authentication.class); Subquery<Authentication> authenticationSubquery = query.subquery(Authentication.class);
Root<Authentication> authenticationRoot = authenticationSubquery.from(Authentication.class); Root<Authentication> authenticationRoot = authenticationSubquery.from(Authentication.class);
authenticationSubquery.select(authenticationRoot) authenticationSubquery.select(authenticationRoot)
.where( .where(
builder.equal(authenticationRoot.get(Authentication_.target), root), builder.equal(authenticationRoot.get(Authentication_.target), root),
EntityHelper.checkNeededEntityPrediction(authenticationRoot, builder, loginUser) builder.equal(authenticationRoot.get(Authentication_.createdUser), userService.currentLoginUser())
); );
return builder.and(
builder.exists(authenticationSubquery).not(),
builder.equal(root.get(DataResource_.createdUser), userService.currentLoginUser())
);
}
));
}
return Lists.immutable.of(builder.or( public ImmutableList<DataResource> listNoWare() {
builder.equal(root.get(DataResource_.createdUser), loginUser), return Lists.immutable.ofAll(dataResourceRepository.findAll(
builder.exists(confirmationSubquery), (root, query, builder) -> {
builder.exists(authenticationSubquery) Join<DataResource, Confirmation> confirmationJoin = root.join(DataResource_.confirmation, JoinType.LEFT);
)); Join<DataResource, Ware> wareJoin = root.join(DataResource_.ware, JoinType.LEFT);
} return builder.and(
builder.isNotNull(confirmationJoin),
builder.equal(confirmationJoin.get(Confirmation_.state), Confirmation.State.NORMAL),
builder.isNull(wareJoin),
builder.equal(root.get(DataResource_.createdUser), userService.currentLoginUser())
);
}
));
}
public ImmutableList<DataResource> listNoConfirmation() { @Override
return Lists.immutable.ofAll(dataResourceRepository.findAll( public Long save(DataResource entity) {
(root, query, builder) -> { ResourceType type = resourceTypeRepository.save(entity.getType());
Join<DataResource, Confirmation> confirmationJoin = root.join(DataResource_.confirmation, JoinType.LEFT); ResourceFormat format = resourceFormatRepository.save(entity.getFormat());
return builder.and( entity.setType(type);
builder.isNull(confirmationJoin.get(Confirmation_.id)), entity.setFormat(format);
builder.equal(root.get(DataResource_.createdUser), userService.currentLoginUser()) return super.save(entity);
); }
}
));
}
public ImmutableList<DataResource> listNoAuthentication() {
return Lists.immutable.ofAll(dataResourceRepository.findAll(
(root, query, builder) -> {
Join<DataResource, Confirmation> confirmationJoin = root.join(DataResource_.confirmation, JoinType.LEFT);
confirmationJoin.on(builder.equal(confirmationJoin.get(Confirmation_.state), Confirmation.State.NORMAL));
Subquery<Authentication> authenticationSubquery = query.subquery(Authentication.class);
Root<Authentication> authenticationRoot = authenticationSubquery.from(Authentication.class);
authenticationSubquery.select(authenticationRoot)
.where(
builder.equal(authenticationRoot.get(Authentication_.target), root),
builder.equal(authenticationRoot.get(Authentication_.createdUser), userService.currentLoginUser())
);
return builder.and(
builder.exists(authenticationSubquery).not(),
builder.equal(root.get(DataResource_.createdUser), userService.currentLoginUser())
);
}
));
}
public ImmutableList<DataResource> listNoWare() {
return Lists.immutable.ofAll(dataResourceRepository.findAll(
(root, query, builder) -> {
Join<DataResource, Confirmation> confirmationJoin = root.join(DataResource_.confirmation, JoinType.LEFT);
Join<DataResource, Ware> wareJoin = root.join(DataResource_.ware, JoinType.LEFT);
return builder.and(
builder.isNotNull(confirmationJoin),
builder.equal(confirmationJoin.get(Confirmation_.state), Confirmation.State.NORMAL),
builder.isNull(wareJoin),
builder.equal(root.get(DataResource_.createdUser), userService.currentLoginUser())
);
}
));
}
@Override
public Long save(DataResource entity) {
ResourceType type = resourceTypeRepository.save(entity.getType());
ResourceFormat format = resourceFormatRepository.save(entity.getFormat());
entity.setType(type);
entity.setFormat(format);
return super.save(entity);
}
} }

View File

@@ -25,252 +25,252 @@ import org.springframework.transaction.annotation.Transactional;
*/ */
@Service @Service
public class UserService { public class UserService {
private static final Logger logger = LoggerFactory.getLogger(UserService.class); private static final Logger logger = LoggerFactory.getLogger(UserService.class);
private final UserRepository userRepository; private final UserRepository userRepository;
public UserService(UserRepository userRepository) { public UserService(UserRepository userRepository) {
this.userRepository = userRepository; this.userRepository = userRepository;
}
private static String encryptPassword(String password) {
String salt = "tY2gNdkt7x%%HcCAFc";
return SecureUtil.sha256(StrUtil.format("{}{}", salt, password));
}
/**
* 当数据库里没有用户的时候,增加一个默认的系统管理员
*/
public void initial() {
if (userRepository.count() == 0) {
User user = new User();
user.setUsername("administrator@eshore.com");
user.setPassword(encryptPassword("bLiN+,qAss,uo'nxoH_:d@HEdD*WdZWAudq$J'a$5Z#aS>K-*dWN5L-i<m:w/U,R"));
user.setRole(User.Role.ADMINISTRATOR);
user.setState(User.State.NORMAL);
user.setCheckedUser(user);
user.setCheckedTime(LocalDateTime.now());
user.setCreatedUser(user);
user.setModifiedUser(user);
userRepository.save(user);
}
}
/**
* 获取当前登陆账号状态
*/
public UserInformation state() {
try {
long id = StpUtil.getLoginIdAsLong();
User user = userRepository.findById(id).orElseThrow(LoginNotFoundException::new);
// User user = userRepository.findByUsername("administrator@eshore.com").orElseThrow(LoginNotFoundException::new);
StpUtil.login(user.getId());
return new UserInformation(user, StpUtil.getTokenInfo());
} catch (NotLoginException e) {
throw new LoginNotFoundException(e);
}
}
public User currentLoginUser() {
return currentLoginUserOptional().orElseThrow(LoginNotFoundException::new);
}
public Optional<User> currentLoginUserOptional() {
try {
return userRepository.findById(StpUtil.getLoginIdAsLong());
} catch (Throwable throwable) {
return Optional.empty();
}
}
private User findUserByUsername(String username) {
return userRepository.findByUsername(username).orElseThrow(UserNotFoundException::new);
}
/**
* 登陆操作
*/
public UserInformation login(String username, String password) {
User user = userRepository.findByUsername(username).orElseThrow(LoginFailureException::new);
if (user.getState() == User.State.CHECKING) {
throw new LoginFailureByCheckingException();
} else if (user.getState() == User.State.DISABLED) {
throw new LoginFailureByDisabledException();
} else if (!StrUtil.equals(encryptPassword(password), user.getPassword())) {
throw new LoginFailureException();
} else {
StpUtil.login(user.getId());
user.setLastLoginTime(LocalDateTime.now());
userRepository.save(user);
return new UserInformation(user, StpUtil.getTokenInfo());
}
}
/**
* 登出操作
*/
public void logout() {
StpUtil.logout();
}
/**
* 注册操作
*/
public void register(String username, String password, User.Role role) {
// 不允许通过这个入口注册管理员
if (User.Role.ADMINISTRATOR.equals(role)) {
throw new RegisterFailureException();
}
User user = new User();
user.setUsername(username);
user.setPassword(encryptPassword(password));
user.setRole(role);
user.setCreatedUser(user);
user.setModifiedUser(user);
userRepository.save(user);
}
/**
* 管理员注册操作
* 直接成功
*/
public void registerFromAdministrator(String username, String password, User.Role role) {
User loginUser = currentLoginUser();
User user = new User();
user.setUsername(username);
user.setPassword(encryptPassword(password));
user.setRole(role);
user.setState(User.State.NORMAL);
user.setCheckedUser(loginUser);
user.setCheckedTime(LocalDateTime.now());
userRepository.save(user);
}
/**
* 是否存在用户名
*/
public boolean exitsUsername(String username) {
return userRepository.existsByUsername(username);
}
/**
* 禁用账号
*/
@Transactional
public void disable(String username) {
User loginUser = currentLoginUser();
User user = findUserByUsername(username);
user.setState(User.State.DISABLED);
user.setModifiedUser(loginUser);
userRepository.save(user);
}
/**
* 启用账号
*/
@Transactional
public void enable(String username) {
User loginUser = currentLoginUser();
User user = findUserByUsername(username);
user.setState(User.State.NORMAL);
user.setModifiedUser(loginUser);
userRepository.save(user);
}
@Transactional
public void check(String username) {
User loginUser = currentLoginUser();
User user = findUserByUsername(username);
user.setState(User.State.NORMAL);
user.setCheckedUser(loginUser);
user.setCheckedTime(LocalDateTime.now());
user.setModifiedUser(loginUser);
userRepository.save(user);
}
public ImmutableList<User> list() {
return Lists.immutable.ofAll(userRepository.findAll());
}
@Transactional
public void changePassword(String oldPassword, String newPassword) {
long id = StpUtil.getLoginIdAsLong();
User user = userRepository.findById(id).orElseThrow(LoginNotFoundException::new);
if (StrUtil.equals(encryptPassword(oldPassword), user.getPassword())) {
user.setPassword(encryptPassword(newPassword));
user.setModifiedUser(user);
userRepository.save(user);
} else {
throw new ChangePasswordFailureException();
}
}
public User detail(String username) {
return userRepository.findByUsername(username).orElseThrow(UserNotFoundException::new);
}
public static class UserNotFoundException extends RuntimeException {
public UserNotFoundException() {
super("账号不存在");
}
}
public static class RegisterFailureException extends RuntimeException {
public RegisterFailureException() {
super("不允许注册的用户类型");
}
}
public static class LoginFailureException extends RuntimeException {
public LoginFailureException() {
super("邮箱或密码错误");
}
}
public static class LoginFailureByCheckingException extends RuntimeException {
public LoginFailureByCheckingException() {
super("账号正在审查中");
}
}
public static class LoginFailureByDisabledException extends RuntimeException {
public LoginFailureByDisabledException() {
super("账号已被禁用");
}
}
public static class LogoutFailureException extends RuntimeException {
public LogoutFailureException() {
super("账号登出失败");
}
}
public static class LoginNotFoundException extends RuntimeException {
public LoginNotFoundException() {
super("账号未登陆");
} }
private static String encryptPassword(String password) { public LoginNotFoundException(Exception exception) {
String salt = "tY2gNdkt7x%%HcCAFc"; super("账号未登陆", exception);
return SecureUtil.sha256(StrUtil.format("{}{}", salt, password));
} }
}
/** public static class ChangePasswordFailureException extends RuntimeException {
* 当数据库里没有用户的时候,增加一个默认的系统管理员 public ChangePasswordFailureException() {
*/ super("原密码不正确");
public void initial() {
if (userRepository.count() == 0) {
User user = new User();
user.setUsername("administrator@eshore.com");
user.setPassword(encryptPassword("administrator"));
user.setRole(User.Role.ADMINISTRATOR);
user.setState(User.State.NORMAL);
user.setCheckedUser(user);
user.setCheckedTime(LocalDateTime.now());
user.setCreatedUser(user);
user.setModifiedUser(user);
userRepository.save(user);
}
} }
}
/** @Data
* 获取当前登陆账号状态 public static class UserInformation {
*/ private String username;
public UserInformation state() { private User.Role role;
try { private String token;
long id = StpUtil.getLoginIdAsLong();
User user = userRepository.findById(id).orElseThrow(LoginNotFoundException::new); public UserInformation(User user, SaTokenInfo token) {
// User user = userRepository.findByUsername("administrator@eshore.com").orElseThrow(LoginNotFoundException::new); this.username = user.getUsername();
StpUtil.login(user.getId()); this.role = user.getRole();
return new UserInformation(user, StpUtil.getTokenInfo()); this.token = token.getTokenValue();
} catch (NotLoginException e) {
throw new LoginNotFoundException(e);
}
}
public User currentLoginUser() {
return currentLoginUserOptional().orElseThrow(LoginNotFoundException::new);
}
public Optional<User> currentLoginUserOptional() {
try {
return userRepository.findById(StpUtil.getLoginIdAsLong());
} catch (Throwable throwable) {
return Optional.empty();
}
}
private User findUserByUsername(String username) {
return userRepository.findByUsername(username).orElseThrow(UserNotFoundException::new);
}
/**
* 登陆操作
*/
public UserInformation login(String username, String password) {
User user = userRepository.findByUsername(username).orElseThrow(LoginFailureException::new);
if (user.getState() == User.State.CHECKING) {
throw new LoginFailureByCheckingException();
} else if (user.getState() == User.State.DISABLED) {
throw new LoginFailureByDisabledException();
} else if (!StrUtil.equals(encryptPassword(password), user.getPassword())) {
throw new LoginFailureException();
} else {
StpUtil.login(user.getId());
user.setLastLoginTime(LocalDateTime.now());
userRepository.save(user);
return new UserInformation(user, StpUtil.getTokenInfo());
}
}
/**
* 登出操作
*/
public void logout() {
StpUtil.logout();
}
/**
* 注册操作
*/
public void register(String username, String password, User.Role role) {
// 不允许通过这个入口注册管理员
if (User.Role.ADMINISTRATOR.equals(role)) {
throw new RegisterFailureException();
}
User user = new User();
user.setUsername(username);
user.setPassword(encryptPassword(password));
user.setRole(role);
user.setCreatedUser(user);
user.setModifiedUser(user);
userRepository.save(user);
}
/**
* 管理员注册操作
* 直接成功
*/
public void registerFromAdministrator(String username, String password, User.Role role) {
User loginUser = currentLoginUser();
User user = new User();
user.setUsername(username);
user.setPassword(encryptPassword(password));
user.setRole(role);
user.setState(User.State.NORMAL);
user.setCheckedUser(loginUser);
user.setCheckedTime(LocalDateTime.now());
userRepository.save(user);
}
/**
* 是否存在用户名
*/
public boolean exitsUsername(String username) {
return userRepository.existsByUsername(username);
}
/**
* 禁用账号
*/
@Transactional
public void disable(String username) {
User loginUser = currentLoginUser();
User user = findUserByUsername(username);
user.setState(User.State.DISABLED);
user.setModifiedUser(loginUser);
userRepository.save(user);
}
/**
* 启用账号
*/
@Transactional
public void enable(String username) {
User loginUser = currentLoginUser();
User user = findUserByUsername(username);
user.setState(User.State.NORMAL);
user.setModifiedUser(loginUser);
userRepository.save(user);
}
@Transactional
public void check(String username) {
User loginUser = currentLoginUser();
User user = findUserByUsername(username);
user.setState(User.State.NORMAL);
user.setCheckedUser(loginUser);
user.setCheckedTime(LocalDateTime.now());
user.setModifiedUser(loginUser);
userRepository.save(user);
}
public ImmutableList<User> list() {
return Lists.immutable.ofAll(userRepository.findAll());
}
@Transactional
public void changePassword(String oldPassword, String newPassword) {
long id = StpUtil.getLoginIdAsLong();
User user = userRepository.findById(id).orElseThrow(LoginNotFoundException::new);
if (StrUtil.equals(encryptPassword(oldPassword), user.getPassword())) {
user.setPassword(encryptPassword(newPassword));
user.setModifiedUser(user);
userRepository.save(user);
} else {
throw new ChangePasswordFailureException();
}
}
public User detail(String username) {
return userRepository.findByUsername(username).orElseThrow(UserNotFoundException::new);
}
public static class UserNotFoundException extends RuntimeException {
public UserNotFoundException() {
super("账号不存在");
}
}
public static class RegisterFailureException extends RuntimeException {
public RegisterFailureException() {
super("不允许注册的用户类型");
}
}
public static class LoginFailureException extends RuntimeException {
public LoginFailureException() {
super("邮箱或密码错误");
}
}
public static class LoginFailureByCheckingException extends RuntimeException {
public LoginFailureByCheckingException() {
super("账号正在审查中");
}
}
public static class LoginFailureByDisabledException extends RuntimeException {
public LoginFailureByDisabledException() {
super("账号已被禁用");
}
}
public static class LogoutFailureException extends RuntimeException {
public LogoutFailureException() {
super("账号登出失败");
}
}
public static class LoginNotFoundException extends RuntimeException {
public LoginNotFoundException() {
super("账号未登陆");
}
public LoginNotFoundException(Exception exception) {
super("账号未登陆", exception);
}
}
public static class ChangePasswordFailureException extends RuntimeException {
public ChangePasswordFailureException() {
super("原密码不正确");
}
}
@Data
public static class UserInformation {
private String username;
private User.Role role;
private String token;
public UserInformation(User user, SaTokenInfo token) {
this.username = user.getUsername();
this.role = user.getRole();
this.token = token.getTokenValue();
}
} }
}
} }

View File

@@ -2,13 +2,13 @@ package com.eshore.gringotts.web.domain.service;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import com.eshore.gringotts.web.domain.base.service.CheckingService; 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.User;
import com.eshore.gringotts.web.domain.entity.Ware; import com.eshore.gringotts.web.domain.entity.Ware;
import com.eshore.gringotts.web.domain.repository.WareRepository; import com.eshore.gringotts.web.domain.repository.WareRepository;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import javax.persistence.EntityManager;
import javax.transaction.Transactional; import javax.transaction.Transactional;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.eclipse.collections.api.factory.Lists; import org.eclipse.collections.api.factory.Lists;
@@ -24,70 +24,77 @@ import org.springframework.stereotype.Service;
*/ */
@Slf4j @Slf4j
@Service("com.eshore.gringotts.web.domain.service.WareService") @Service("com.eshore.gringotts.web.domain.service.WareService")
public class WareService extends SimpleServiceSupport<Ware> implements CheckingService { public class WareService extends CheckingService<Ware> {
private final WareRepository wareRepository; private final WareRepository wareRepository;
private final CheckOrderService checkOrderService; private final CheckOrderService checkOrderService;
private final ObjectMapper mapper; private final ObjectMapper mapper;
public WareService(WareRepository repository, UserService userService, CheckOrderService checkOrderService, Jackson2ObjectMapperBuilder builder) { public WareService(WareRepository repository, UserService userService, EntityManager entityManager, CheckOrderService checkOrderService, Jackson2ObjectMapperBuilder builder) {
super(repository, userService); super(repository, userService, entityManager);
this.wareRepository = repository; this.wareRepository = repository;
this.checkOrderService = checkOrderService; this.checkOrderService = checkOrderService;
this.mapper = builder.build(); this.mapper = builder.build();
}
public ImmutableList<Ware> listPublic() {
return Lists.immutable.ofAll(
wareRepository.findAll((root, query, builder) -> builder.equal(root.get("state"), Ware.State.NORMAL))
);
}
@Transactional(rollbackOn = Throwable.class)
@Override
public void onChecked(CheckOrder order, CheckOrder.Operation operation, ImmutableMap<String, Object> parameters) {
if (StrUtil.equals(order.getKeyword(), "ware_check")) {
Long wareId = (Long) parameters.get("wareId");
Ware ware = detailOrThrow(wareId);
switch (operation) {
case APPLY:
ware.setState(Ware.State.NORMAL);
order.setState(CheckOrder.State.OVER);
break;
case REJECT:
ware.setState(Ware.State.DRAFT);
order.setState(CheckOrder.State.OVER);
break;
}
save(ware);
checkOrderService.save(order);
} }
}
public ImmutableList<Ware> listPublic() { @Override
return Lists.immutable.ofAll( public ImmutableMap<String, Object> archive(Ware ware) {
wareRepository.findAll((root, query, builder) -> builder.equal(root.get("state"), Ware.State.NORMAL)) return null;
); }
}
@Transactional(rollbackOn = Throwable.class) @Transactional(rollbackOn = Throwable.class)
@Override @Override
public void onChecked(CheckOrder order, CheckOrder.Operation operation, ImmutableMap<String, Object> parameters) { public void submit(Long id) throws JsonProcessingException {
if (StrUtil.equals(order.getKeyword(), "ware_check")) { Ware ware = detailOrThrow(id);
Long wareId = (Long) parameters.get("wareId"); ware.setState(Ware.State.CHECKING);
Ware ware = detailOrThrow(wareId); Long orderId = checkOrderService.save(new CheckOrder(
switch (operation) { "ware_check",
case APPLY: StrUtil.format("数据资源「{}」的上架申请", ware.getName()),
ware.setState(Ware.State.NORMAL); CheckOrder.Type.MARKET,
order.setState(CheckOrder.State.OVER); mapper.writeValueAsString(Maps.immutable.of("wareId", ware.getId())),
break; "com.eshore.gringotts.web.domain.service.WareService",
case REJECT: User.Role.CHECKER
ware.setState(Ware.State.DRAFT); ));
order.setState(CheckOrder.State.OVER); CheckOrder order = checkOrderService.detailOrThrow(orderId);
break; ware.setOrder(order);
} save(ware);
save(ware); }
checkOrderService.save(order);
}
}
@Transactional(rollbackOn = Throwable.class) @Transactional(rollbackOn = Throwable.class)
public void submit(Long id) throws JsonProcessingException { @Override
Ware ware = detailOrThrow(id); public void retract(Long id) {
ware.setState(Ware.State.CHECKING); Ware ware = detailOrThrow(id);
Long orderId = checkOrderService.save(new CheckOrder( ware.setState(Ware.State.DRAFT);
"ware_check", save(ware);
StrUtil.format("数据资源「{}」的上架申请", ware.getName()),
CheckOrder.Type.MARKET,
mapper.writeValueAsString(Maps.immutable.of("wareId", ware.getId())),
"com.eshore.gringotts.web.domain.service.WareService",
User.Role.CHECKER
));
CheckOrder order = checkOrderService.detailOrThrow(orderId);
ware.setOrder(order);
save(ware);
}
@Transactional(rollbackOn = Throwable.class) CheckOrder order = ware.getOrder();
public void retract(Long id) { order.setState(CheckOrder.State.RETRACT);
Ware ware = detailOrThrow(id); checkOrderService.save(order);
ware.setState(Ware.State.DRAFT); }
save(ware);
CheckOrder order = ware.getOrder();
order.setState(CheckOrder.State.RETRACT);
checkOrderService.save(order);
}
} }

View File

@@ -19,23 +19,23 @@ import org.springframework.data.jpa.repository.JpaRepository;
* @date 2024-11-25 * @date 2024-11-25
*/ */
public class EntityHelper { public class EntityHelper {
public static <E, ID> void deleteIfUpdateNeeded(JpaRepository<E, ID> repository, Supplier<E> getter, E target) { public static <E, ID> void deleteIfUpdateNeeded(JpaRepository<E, ID> repository, Supplier<E> getter, E target) {
E old = getter.get(); E old = getter.get();
if (ObjectUtil.notEqual(old, target)) { if (ObjectUtil.notEqual(old, target)) {
repository.delete(old); repository.delete(old);
}
} }
}
public static Predicate checkNeededEntityPrediction(Root<? extends CheckingNeededEntity> root, CriteriaBuilder builder, User loginUser) { public static Predicate checkNeededEntityPrediction(Root<? extends CheckingNeededEntity> root, CriteriaBuilder builder, User loginUser) {
return builder.or( return builder.or(
builder.and( builder.and(
builder.equal(root.get(CheckingNeededEntity_.order).get(CheckOrder_.target), CheckOrder.Target.ROLE), builder.equal(root.get(CheckingNeededEntity_.order).get(CheckOrder_.target), CheckOrder.Target.ROLE),
builder.equal(root.get(CheckingNeededEntity_.order).get(CheckOrder_.targetRole), loginUser.getRole()) builder.equal(root.get(CheckingNeededEntity_.order).get(CheckOrder_.targetRole), loginUser.getRole())
), ),
builder.and( builder.and(
builder.equal(root.get(CheckingNeededEntity_.order).get(CheckOrder_.target), CheckOrder.Target.USER), builder.equal(root.get(CheckingNeededEntity_.order).get(CheckOrder_.target), CheckOrder.Target.USER),
builder.equal(root.get(CheckingNeededEntity_.order).get(CheckOrder_.targetUser), loginUser) builder.equal(root.get(CheckingNeededEntity_.order).get(CheckOrder_.targetUser), loginUser)
) )
); );
} }
} }

View File

@@ -6,10 +6,10 @@ spring:
profiles: profiles:
include: common,metrics,encrypt include: common,metrics,encrypt
datasource: datasource:
url: jdbc:h2:./database;DATABASE_TO_LOWER=TRUE;CASE_INSENSITIVE_IDENTIFIERS=TRUE url: jdbc:mysql://132.122.1.185:31000/gringotts
username: lanyuanxiaoyao username: iap
password: lanyuanxiaoyao password: SLvwP6@SM2J*SbUw_iap
driver-class-name: org.h2.Driver driver-class-name: com.mysql.cj.jdbc.Driver
jpa: jpa:
generate-ddl: true generate-ddl: true
show-sql: true show-sql: true
@@ -39,7 +39,31 @@ logging:
spring: spring:
config: config:
activate: activate:
on-profile: macOS on-profile: dev
datasource:
url: jdbc:h2:./database;DATABASE_TO_LOWER=TRUE;CASE_INSENSITIVE_IDENTIFIERS=TRUE
username: lanyuanxiaoyao
password: lanyuanxiaoyao
driver-class-name: org.h2.Driver
---
spring:
config:
activate:
on-profile: build
datasource:
url: jdbc:mysql://132.122.1.185:31000/gringotts
username: iap
password: SLvwP6@SM2J*SbUw_iap
driver-class-name: com.mysql.cj.jdbc.Driver
gringotts:
upload:
upload-path: /home/iap/gringotts/upload
---
spring:
config:
activate:
on-profile: macos
gringotts: gringotts:
upload: upload:
upload-path: /Users/lanyuanxiaoyao/Project/IdeaProjects/gringotts/gringotts-web/target/upload upload-path: /Users/lanyuanxiaoyao/Project/IdeaProjects/gringotts/gringotts-web/target/upload

View File

@@ -11,58 +11,58 @@ import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
* @date 2024-12-03 * @date 2024-12-03
*/ */
public class TestQueryParse { public class TestQueryParse {
public static void main(String[] args) throws JsonProcessingException { public static void main(String[] args) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new EclipseCollectionsModule()); mapper.registerModule(new EclipseCollectionsModule());
mapper.registerModule(new JavaTimeModule()); mapper.registerModule(new JavaTimeModule());
// language=JSON // language=JSON
System.out.println(mapper.readValue("{}", Query.class)); System.out.println(mapper.readValue("{}", Query.class));
// language=JSON // language=JSON
System.out.println(mapper.readValue("{\n" + System.out.println(mapper.readValue("{\n" +
" \"query\": {\n" + " \"query\": {\n" +
" \"equal\": {\n" + " \"equal\": {\n" +
" \"name\": \"lanyuanxiaoyao\"\n" + " \"name\": \"lanyuanxiaoyao\"\n" +
" }\n" + " }\n" +
" }\n" + " }\n" +
"}", Query.class)); "}", Query.class));
// language=JSON // language=JSON
System.out.println(mapper.readValue("{\n" + System.out.println(mapper.readValue("{\n" +
" \"query\": {\n" + " \"query\": {\n" +
" \"equal\": {\n" + " \"equal\": {\n" +
" \"name\": \"lanyuanxiaoyao\"\n" + " \"name\": \"lanyuanxiaoyao\"\n" +
" },\n" + " },\n" +
" \"notEqual\": {\n" + " \"notEqual\": {\n" +
" \"username\": \"lanyuanxiaoyao@qq.com\",\n" + " \"username\": \"lanyuanxiaoyao@qq.com\",\n" +
" \"password\": \"mingland87\"\n" + " \"password\": \"mingland87\"\n" +
" },\n" + " },\n" +
" \"great\": {\n" + " \"great\": {\n" +
" \"age\": 12,\n" + " \"age\": 12,\n" +
" \"createTime\": \"2020-10-12 00:00:00\"\n" + " \"createTime\": \"2020-10-12 00:00:00\"\n" +
" },\n" + " },\n" +
" \"in\": {\n" + " \"in\": {\n" +
" \"age\": [\n" + " \"age\": [\n" +
" 15,\n" + " 15,\n" +
" 18,\n" + " 18,\n" +
" 20\n" + " 20\n" +
" ]\n" + " ]\n" +
" },\n" + " },\n" +
" \"between\": {\n" + " \"between\": {\n" +
" \"createTime\": {\n" + " \"createTime\": {\n" +
" \"start\": \"2024-12-03 00:00:00\",\n" + " \"start\": \"2024-12-03 00:00:00\",\n" +
" \"end\": \"2024-12-03 00:00:00\"\n" + " \"end\": \"2024-12-03 00:00:00\"\n" +
" }\n" + " }\n" +
" }\n" + " }\n" +
" },\n" + " },\n" +
" \"sort\": [\n" + " \"sort\": [\n" +
" {\n" + " {\n" +
" \"column\": \"createTime\",\n" + " \"column\": \"createTime\",\n" +
" \"direction\": \"ASC\"\n" + " \"direction\": \"ASC\"\n" +
" }\n" + " }\n" +
" ],\n" + " ],\n" +
" \"page\": {\n" + " \"page\": {\n" +
" \"size\": 10,\n" + " \"size\": 10,\n" +
" \"page\": 1\n" + " \"page\": 1\n" +
" }\n" + " }\n" +
"}", Query.class)); "}", Query.class));
} }
} }