Browse Source

feat(permissions): 完善权限分组与定义.

pull/1060/head
colin 1 year ago
parent
commit
0fbac2c577
  1. 1
      apps/vben5/apps/app-antd/package.json
  2. 1
      apps/vben5/apps/app-antd/src/adapter/request/index.ts
  3. 5
      apps/vben5/apps/app-antd/src/locales/langs/en-US/abp.json
  4. 120
      apps/vben5/apps/app-antd/src/locales/langs/en-US/component.json
  5. 5
      apps/vben5/apps/app-antd/src/locales/langs/zh-CN/abp.json
  6. 120
      apps/vben5/apps/app-antd/src/locales/langs/zh-CN/component.json
  7. 29
      apps/vben5/apps/app-antd/src/router/routes/modules/abp.ts
  8. 15
      apps/vben5/apps/app-antd/src/views/permissions/definitions/index.vue
  9. 15
      apps/vben5/apps/app-antd/src/views/permissions/groups/index.vue
  10. 42
      apps/vben5/packages/@abp/core/src/hooks/SimpleStateChecking/useRequireAuthenticatedSimpleStateChecker.ts
  11. 59
      apps/vben5/packages/@abp/core/src/hooks/SimpleStateChecking/useRequireFeaturesSimpleStateChecker.ts
  12. 62
      apps/vben5/packages/@abp/core/src/hooks/SimpleStateChecking/useRequireGlobalFeaturesSimpleStateChecker.ts
  13. 123
      apps/vben5/packages/@abp/core/src/hooks/SimpleStateChecking/useRequirePermissionsSimpleStateChecker.ts
  14. 5
      apps/vben5/packages/@abp/core/src/hooks/index.ts
  15. 36
      apps/vben5/packages/@abp/core/src/hooks/useAuthorization.ts
  16. 56
      apps/vben5/packages/@abp/core/src/hooks/useFeatures.ts
  17. 49
      apps/vben5/packages/@abp/core/src/hooks/useGlobalFeatures.ts
  18. 49
      apps/vben5/packages/@abp/core/src/hooks/useLocalization.ts
  19. 109
      apps/vben5/packages/@abp/core/src/hooks/useLocalizationSerializer.ts
  20. 135
      apps/vben5/packages/@abp/core/src/hooks/useSimpleStateCheck.ts
  21. 5
      apps/vben5/packages/@abp/core/src/store/abp.ts
  22. 27
      apps/vben5/packages/@abp/core/src/types/features.ts
  23. 26
      apps/vben5/packages/@abp/core/src/types/global.ts
  24. 2
      apps/vben5/packages/@abp/core/src/types/index.ts
  25. 6
      apps/vben5/packages/@abp/core/src/types/permissions.ts
  26. 19
      apps/vben5/packages/@abp/core/src/utils/is.ts
  27. 7
      apps/vben5/packages/@abp/permission/package.json
  28. 75
      apps/vben5/packages/@abp/permission/src/api/definitions.ts
  29. 77
      apps/vben5/packages/@abp/permission/src/api/groups.ts
  30. 142
      apps/vben5/packages/@abp/permission/src/components/definitions/groups/PermissionGroupDefinitionModal.vue
  31. 270
      apps/vben5/packages/@abp/permission/src/components/definitions/groups/PermissionGroupDefinitionTable.vue
  32. 282
      apps/vben5/packages/@abp/permission/src/components/definitions/permissions/PermissionDefinitionModal.vue
  33. 333
      apps/vben5/packages/@abp/permission/src/components/definitions/permissions/PermissionDefinitionTable.vue
  34. 53
      apps/vben5/packages/@abp/permission/src/components/definitions/permissions/types.ts
  35. 1
      apps/vben5/packages/@abp/permission/src/constants/index.ts
  36. 20
      apps/vben5/packages/@abp/permission/src/constants/permissions.ts
  37. 46
      apps/vben5/packages/@abp/permission/src/types/definitions.ts
  38. 27
      apps/vben5/packages/@abp/permission/src/types/groups.ts
  39. 1
      apps/vben5/packages/@abp/ui/package.json
  40. 2
      apps/vben5/packages/@abp/ui/src/adapter/vxe-table.ts
  41. 4
      apps/vben5/packages/@abp/ui/src/components/codeeditor/index.vue
  42. 5
      apps/vben5/packages/@abp/ui/src/components/index.ts
  43. 177
      apps/vben5/packages/@abp/ui/src/components/localizable-input/LocalizableInput.vue
  44. 66
      apps/vben5/packages/@abp/ui/src/components/properties/PropertyModal.vue
  45. 133
      apps/vben5/packages/@abp/ui/src/components/properties/PropertyTable.vue
  46. 14
      apps/vben5/packages/@abp/ui/src/components/properties/types.ts

1
apps/vben5/apps/app-antd/package.json

@ -31,6 +31,7 @@
"@abp/core": "workspace:*", "@abp/core": "workspace:*",
"@abp/identity": "workspace:*", "@abp/identity": "workspace:*",
"@abp/openiddict": "workspace:*", "@abp/openiddict": "workspace:*",
"@abp/permission": "workspace:*",
"@abp/request": "workspace:*", "@abp/request": "workspace:*",
"@abp/ui": "workspace:*", "@abp/ui": "workspace:*",
"@vben/access": "workspace:*", "@vben/access": "workspace:*",

1
apps/vben5/apps/app-antd/src/adapter/request/index.ts

@ -47,6 +47,7 @@ export function initRequestClient() {
config.headers.Authorization = `${accessStore.accessToken}`; config.headers.Authorization = `${accessStore.accessToken}`;
} }
config.headers['Accept-Language'] = preferences.app.locale; config.headers['Accept-Language'] = preferences.app.locale;
config.headers['X-Request-From'] = 'vben';
return config; return config;
}, },
}); });

5
apps/vben5/apps/app-antd/src/locales/langs/en-US/abp.json

@ -10,6 +10,11 @@
"securityLogs": "Security Logs", "securityLogs": "Security Logs",
"organizationUnits": "Organization Units", "organizationUnits": "Organization Units",
"auditLogs": "Audit Logs" "auditLogs": "Audit Logs"
},
"permissions": {
"title": "Permissions",
"groups": "Groups",
"definitions": "Definitions"
} }
}, },
"openiddict": { "openiddict": {

120
apps/vben5/apps/app-antd/src/locales/langs/en-US/component.json

@ -0,0 +1,120 @@
{
"localizable_input": {
"placeholder": "Select localized resources",
"resources": {
"fiexed": {
"group": "Define",
"label": "Fiexed",
"placeholder": "Please enter custom content"
},
"localization": {
"group": "Localization",
"placeholder": "Please select a name"
}
}
},
"extra_property_dictionary": {
"title": "Extra properties",
"key": "Key",
"value": "Value",
"actions": {
"title": "Actions",
"create": "Add",
"update": "Edit",
"delete": "Delete",
"clean": "Clean"
},
"itemWillBeDeleted": "{key} will be deleted!",
"validator": {
"duplicateKey": "A key of the same name has been added"
}
},
"value_type_nput": {
"type": {
"name": "Type",
"FREE_TEXT": {
"name": "Free Text"
},
"TOGGLE": {
"name": "Toggle"
},
"SELECTION": {
"name": "Selection",
"displayText": "Display Text",
"displayTextNotBeEmpty": "Display text cannot be empty",
"value": "value",
"duplicateKeyOrValue": "The name or value of the selection is not allowed to be repeated",
"itemsNotBeEmpty": "Selectable items cannot be empty",
"itemsNotFound": "The selection is not included in the optional list",
"actions": {
"title": "Actions",
"create": "Add",
"update": "Edit",
"delete": "Delete",
"clean": "Clean"
},
"modal": {
"title": "Selection"
}
}
},
"validator": {
"name": "Validator",
"isInvalidValue": "The value failed to pass {0}; check the validator options.",
"NULL": {
"name": "None"
},
"BOOLEAN": {
"name": "Boolean"
},
"NUMERIC": {
"name": "Numeric",
"minValue": "Min Value",
"maxValue": "Max Value"
},
"STRING": {
"name": "String",
"allowNull": "Allow Null",
"minLength": "Min Length",
"maxLength": "Max Length",
"regularExpression": "Regular Expression"
}
}
},
"simple_state_checking": {
"title": "State checking",
"actions": {
"create": "Add",
"update": "Edit",
"delete": "Delete",
"clean": "Clean"
},
"table": {
"name": "Name",
"properties": "Properties",
"actions": "Actions"
},
"form": {
"name": "State checking"
},
"requireAuthenticated": {
"title": "Require Authenticated"
},
"requireFeatures": {
"title": "Require Features",
"requiresAll": "Requires All",
"requiresAllDesc": "If checked, all selected features need to be enabled.",
"featureNames": "Required features"
},
"requireGlobalFeatures": {
"title": "Require Global Features",
"featureNames": "Required Global Features"
},
"requirePermissions": {
"title": "Require Permissions",
"requiresAll": "Requires All",
"requiresAllDesc": "If checked, you need to have all the selected permissions.",
"permissions": "Required Permissions"
}
}
}

5
apps/vben5/apps/app-antd/src/locales/langs/zh-CN/abp.json

@ -10,6 +10,11 @@
"securityLogs": "安全日志", "securityLogs": "安全日志",
"organizationUnits": "组织机构", "organizationUnits": "组织机构",
"auditLogs": "审计日志" "auditLogs": "审计日志"
},
"permissions": {
"title": "权限管理",
"groups": "权限分组",
"definitions": "权限定义"
} }
}, },
"openiddict": { "openiddict": {

120
apps/vben5/apps/app-antd/src/locales/langs/zh-CN/component.json

@ -0,0 +1,120 @@
{
"localizable_input": {
"placeholder": "请选择本地化资源",
"resources": {
"fiexed": {
"group": "自定义",
"label": "固定内容",
"placeholder": "请输入自定义内容"
},
"localization": {
"group": "本地化",
"placeholder": "请选择名称"
}
}
},
"extra_property_dictionary": {
"title": "扩展属性",
"key": "名称",
"value": "键值",
"actions": {
"title": "操作",
"create": "新增",
"update": "编辑",
"delete": "删除",
"clean": "清除"
},
"validator": {
"duplicateKey": "已经添加了一个相同名称的键"
},
"itemWillBeDeleted": "{key} 将被删除!"
},
"value_type_nput": {
"type": {
"name": "类型",
"FREE_TEXT": {
"name": "自由文本"
},
"TOGGLE": {
"name": "切换"
},
"SELECTION": {
"name": "选择",
"displayText": "显示名称",
"displayTextNotBeEmpty": "显示名称不可为空",
"value": "选择项",
"duplicateKeyOrValue": "选择项的名称或值不允许重复",
"itemsNotBeEmpty": "可选择项列表不能为空",
"itemsNotFound": "选择项不包含在可选列表中",
"actions": {
"title": "操作",
"create": "新增",
"update": "编辑",
"delete": "删除",
"clean": "清除"
},
"modal": {
"title": "选择项"
}
}
},
"validator": {
"name": "验证器",
"isInvalidValue": "值未能通过 {0} 校验, 请检查验证器选项.",
"NULL": {
"name": "未定义"
},
"BOOLEAN": {
"name": "布尔类型"
},
"NUMERIC": {
"name": "数值类型",
"minValue": "最小值",
"maxValue": "最大值"
},
"STRING": {
"name": "字符类型",
"allowNull": "允许空值",
"minLength": "最小长度",
"maxLength": "最大长度",
"regularExpression": "正则表达式"
}
}
},
"simple_state_checking": {
"title": "状态检查",
"actions": {
"create": "新增",
"update": "编辑",
"delete": "删除",
"clean": "清除"
},
"table": {
"name": "名称",
"properties": "属性",
"actions": "操作"
},
"form": {
"name": "状态检查器"
},
"requireAuthenticated": {
"title": "需要用户认证"
},
"requireFeatures": {
"title": "检查所需功能",
"requiresAll": "要求所有",
"requiresAllDesc": "如果勾选,则需要启用所有选择的功能.",
"featureNames": "需要的功能"
},
"requireGlobalFeatures": {
"title": "检查全局功能",
"featureNames": "需要的全局功能"
},
"requirePermissions": {
"title": "检查所需权限",
"requiresAll": "要求所有",
"requiresAllDesc": "如果勾选,则需要拥有所有选择的权限.",
"permissions": "需要的权限"
}
}
}

29
apps/vben5/apps/app-antd/src/router/routes/modules/abp.ts

@ -81,6 +81,35 @@ const routes: RouteRecordRaw[] = [
}, },
], ],
}, },
{
meta: {
title: $t('abp.manage.permissions.title'),
icon: 'arcticons:permissionsmanager',
},
name: 'PermissionManagement',
path: '/manage/permissions',
children: [
{
meta: {
title: $t('abp.manage.permissions.groups'),
icon: 'lucide:group',
},
name: 'PermissionGroupDefinitions',
path: '/manage/permissions/groups',
component: () => import('#/views/permissions/groups/index.vue'),
},
{
meta: {
title: $t('abp.manage.permissions.definitions'),
icon: 'icon-park-outline:permissions',
},
name: 'PermissionDefinitions',
path: '/manage/permissions/definitions',
component: () =>
import('#/views/permissions/definitions/index.vue'),
},
],
},
{ {
meta: { meta: {
title: $t('abp.manage.identity.auditLogs'), title: $t('abp.manage.identity.auditLogs'),

15
apps/vben5/apps/app-antd/src/views/permissions/definitions/index.vue

@ -0,0 +1,15 @@
<script lang="ts" setup>
import { Page } from '@vben/common-ui';
import { PermissionDefinitionTable } from '@abp/permission';
defineOptions({
name: 'PermissionDefinitions',
});
</script>
<template>
<Page>
<PermissionDefinitionTable />
</Page>
</template>

15
apps/vben5/apps/app-antd/src/views/permissions/groups/index.vue

@ -0,0 +1,15 @@
<script lang="ts" setup>
import { Page } from '@vben/common-ui';
import { PermissionGroupDefinitionTable } from '@abp/permission';
defineOptions({
name: 'PermissionGroupDefinitions',
});
</script>
<template>
<Page>
<PermissionGroupDefinitionTable />
</Page>
</template>

42
apps/vben5/packages/@abp/core/src/hooks/SimpleStateChecking/useRequireAuthenticatedSimpleStateChecker.ts

@ -0,0 +1,42 @@
import type {
CurrentUser,
IHasSimpleStateCheckers,
ISimpleStateChecker,
SimpleStateCheckerContext,
} from '../../types/global';
import { useAbpStore } from '../../store/abp';
export interface RequireAuthenticatedStateChecker {
name: string;
}
export class RequireAuthenticatedSimpleStateChecker<
TState extends IHasSimpleStateCheckers<TState>,
>
implements RequireAuthenticatedStateChecker, ISimpleStateChecker<TState>
{
_currentUser?: CurrentUser;
name = 'A';
constructor(currentUser?: CurrentUser) {
this._currentUser = currentUser;
}
isEnabled(_context: SimpleStateCheckerContext<TState>): boolean {
return this._currentUser?.isAuthenticated ?? false;
}
serialize(): string {
return JSON.stringify({
T: this.name,
});
}
}
export function useRequireAuthenticatedSimpleStateChecker<
TState extends IHasSimpleStateCheckers<TState>,
>(): ISimpleStateChecker<TState> {
const abpStore = useAbpStore();
return new RequireAuthenticatedSimpleStateChecker<TState>(
abpStore.application?.currentUser,
);
}

59
apps/vben5/packages/@abp/core/src/hooks/SimpleStateChecking/useRequireFeaturesSimpleStateChecker.ts

@ -0,0 +1,59 @@
import type { IFeatureChecker } from '../../types/features';
import type {
IHasSimpleStateCheckers,
ISimpleStateChecker,
SimpleStateCheckerContext,
} from '../../types/global';
import { useFeatures } from '../useFeatures';
export interface RequireFeaturesStateChecker {
featureNames: string[];
name: string;
requiresAll: boolean;
}
export class RequireFeaturesSimpleStateChecker<
TState extends IHasSimpleStateCheckers<TState>,
>
implements RequireFeaturesStateChecker, ISimpleStateChecker<TState>
{
_featureChecker: IFeatureChecker;
featureNames: string[];
name: string = 'F';
requiresAll: boolean;
constructor(
featureChecker: IFeatureChecker,
featureNames: string[],
requiresAll: boolean = false,
) {
this._featureChecker = featureChecker;
this.featureNames = featureNames;
this.requiresAll = requiresAll;
}
isEnabled(_context: SimpleStateCheckerContext<TState>): boolean {
return this._featureChecker.isEnabled(this.featureNames, this.requiresAll);
}
serialize(): string {
return JSON.stringify({
A: this.requiresAll,
N: this.featureNames,
T: this.name,
});
}
}
export function useRequireFeaturesSimpleStateChecker<
TState extends IHasSimpleStateCheckers<TState>,
>(
featureNames: string[],
requiresAll: boolean = false,
): ISimpleStateChecker<TState> {
const { featureChecker } = useFeatures();
return new RequireFeaturesSimpleStateChecker(
featureChecker,
featureNames,
requiresAll,
);
}

62
apps/vben5/packages/@abp/core/src/hooks/SimpleStateChecking/useRequireGlobalFeaturesSimpleStateChecker.ts

@ -0,0 +1,62 @@
import type { IGlobalFeatureChecker } from '../../types/features';
import type {
IHasSimpleStateCheckers,
ISimpleStateChecker,
SimpleStateCheckerContext,
} from '../../types/global';
import { useGlobalFeatures } from '../useGlobalFeatures';
export interface RequireGlobalFeaturesStateChecker {
featureNames: string[];
name: string;
requiresAll: boolean;
}
export class RequireGlobalFeaturesSimpleStateChecker<
TState extends IHasSimpleStateCheckers<TState>,
>
implements RequireGlobalFeaturesStateChecker, ISimpleStateChecker<TState>
{
_globalFeatureChecker: IGlobalFeatureChecker;
featureNames: string[];
name: string = 'G';
requiresAll: boolean;
constructor(
globalFeatureChecker: IGlobalFeatureChecker,
featureNames: string[],
requiresAll: boolean = false,
) {
this._globalFeatureChecker = globalFeatureChecker;
this.featureNames = featureNames;
this.requiresAll = requiresAll;
}
isEnabled(_context: SimpleStateCheckerContext<TState>): boolean {
return this._globalFeatureChecker.isEnabled(
this.featureNames,
this.requiresAll,
);
}
serialize(): string {
return JSON.stringify({
A: this.requiresAll,
N: this.featureNames,
T: this.name,
});
}
}
export function useRequireGlobalFeaturesSimpleStateChecker<
TState extends IHasSimpleStateCheckers<TState>,
>(
featureNames: string[],
requiresAll: boolean = false,
): ISimpleStateChecker<TState> {
const globalFeatureChecker = useGlobalFeatures();
return new RequireGlobalFeaturesSimpleStateChecker(
globalFeatureChecker,
featureNames,
requiresAll,
);
}

123
apps/vben5/packages/@abp/core/src/hooks/SimpleStateChecking/useRequirePermissionsSimpleStateChecker.ts

@ -0,0 +1,123 @@
import type {
IHasSimpleStateCheckers,
ISimpleBatchStateChecker,
ISimpleStateChecker,
SimpleBatchStateCheckerContext,
SimpleStateCheckerContext,
SimpleStateCheckerResult,
} from '../../types/global';
import type { IPermissionChecker } from '../../types/permissions';
import { useAuthorization } from '../useAuthorization';
export class RequirePermissionsSimpleBatchStateCheckerModel<
TState extends IHasSimpleStateCheckers<TState>,
> {
permissions: string[];
requiresAll: boolean;
state: TState;
constructor(
state: TState,
permissions: string[],
requiresAll: boolean = true,
) {
this.state = state;
this.permissions = permissions;
this.requiresAll = requiresAll;
}
}
export interface RequirePermissionsStateChecker<
TState extends IHasSimpleStateCheckers<TState>,
> {
model: RequirePermissionsSimpleBatchStateCheckerModel<TState>;
name: string;
}
export class RequirePermissionsSimpleStateChecker<
TState extends IHasSimpleStateCheckers<TState>,
>
implements RequirePermissionsStateChecker<TState>, ISimpleStateChecker<TState>
{
_permissionChecker: IPermissionChecker;
model: RequirePermissionsSimpleBatchStateCheckerModel<TState>;
name: string = 'P';
constructor(
permissionChecker: IPermissionChecker,
model: RequirePermissionsSimpleBatchStateCheckerModel<TState>,
) {
this.model = model;
this._permissionChecker = permissionChecker;
}
isEnabled(_context: SimpleStateCheckerContext<TState>): boolean {
return this._permissionChecker.isGranted(
this.model.permissions,
this.model.requiresAll,
);
}
serialize(): string {
return JSON.stringify({
A: this.model.requiresAll,
N: this.model.permissions,
T: this.name,
});
}
}
export class RequirePermissionsSimpleBatchStateChecker<
TState extends IHasSimpleStateCheckers<TState>,
> implements ISimpleBatchStateChecker<TState>
{
_permissionChecker: IPermissionChecker;
models: RequirePermissionsSimpleBatchStateCheckerModel<TState>[];
name: string = 'P';
constructor(
permissionChecker: IPermissionChecker,
models: RequirePermissionsSimpleBatchStateCheckerModel<TState>[],
) {
this.models = models;
this._permissionChecker = permissionChecker;
}
isEnabled(context: SimpleBatchStateCheckerContext<TState>) {
const result = {} as SimpleStateCheckerResult<TState>;
context.states.forEach((state) => {
const model = this.models.find((x) => x.state === state);
if (model) {
result[model.state] = this._permissionChecker.isGranted(
model.permissions,
model.requiresAll,
);
}
});
return result;
}
serialize(): string | undefined {
return undefined;
}
}
export function useRequirePermissionsSimpleStateChecker<
TState extends IHasSimpleStateCheckers<TState>,
>(
model: RequirePermissionsSimpleBatchStateCheckerModel<TState>,
): ISimpleStateChecker<TState> {
const permissionChecker = useAuthorization();
return new RequirePermissionsSimpleStateChecker<TState>(
permissionChecker,
model,
);
}
export function useRequirePermissionsSimpleBatchStateChecker<
TState extends IHasSimpleStateCheckers<TState>,
>(
models: RequirePermissionsSimpleBatchStateCheckerModel<TState>[],
): ISimpleBatchStateChecker<TState> {
const permissionChecker = useAuthorization();
return new RequirePermissionsSimpleBatchStateChecker<TState>(
permissionChecker,
models,
);
}

5
apps/vben5/packages/@abp/core/src/hooks/index.ts

@ -1,4 +1,9 @@
export * from './useAuthorization';
export * from './useFeatures';
export * from './useGlobalFeatures';
export * from './useLocalization'; export * from './useLocalization';
export * from './useLocalizationSerializer';
export * from './useSettings'; export * from './useSettings';
export * from './useSimpleStateCheck';
export * from './useValidation'; export * from './useValidation';
export * from './useWindowSizeFn'; export * from './useWindowSizeFn';

36
apps/vben5/packages/@abp/core/src/hooks/useAuthorization.ts

@ -0,0 +1,36 @@
import type { IPermissionChecker } from '../types/permissions';
import { computed } from 'vue';
import { useAbpStore } from '../store/abp';
export function useAuthorization(): IPermissionChecker {
const abpStore = useAbpStore();
const getGrantedPolicies = computed(() => {
return abpStore.application?.auth.grantedPolicies ?? {};
});
function isGranted(name: string | string[], requiresAll?: boolean): boolean {
const grantedPolicies = getGrantedPolicies.value;
if (Array.isArray(name)) {
if (requiresAll === undefined || requiresAll === true) {
return name.every((name) => grantedPolicies[name]);
}
return name.some((name) => grantedPolicies[name]);
}
return grantedPolicies[name] ?? false;
}
function authorize(name: string | string[]): void {
if (!isGranted(name)) {
throw new Error(
`Authorization failed! Given policy has not granted: ${name}`,
);
}
}
return {
authorize,
isGranted,
};
}

56
apps/vben5/packages/@abp/core/src/hooks/useFeatures.ts

@ -0,0 +1,56 @@
import type { FeatureValue, IFeatureChecker } from '../types/features';
import { computed } from 'vue';
import { useAbpStore } from '../store/abp';
export function useFeatures() {
const abpStore = useAbpStore();
const getFeatures = computed(() => {
const fetures = abpStore.application?.features.values ?? {};
const fetureValues = Object.keys(fetures).map((key): FeatureValue => {
return {
name: key,
value: fetures[key] ?? '',
};
});
return fetureValues;
});
function get(name: string): FeatureValue | undefined {
return getFeatures.value.find((feature) => name === feature.name);
}
function _isEnabled(name: string): boolean {
const setting = get(name);
return setting?.value.toLowerCase() === 'true';
}
const featureChecker: IFeatureChecker = {
getOrEmpty(name: string) {
return get(name)?.value ?? '';
},
isEnabled(featureNames: string | string[], requiresAll?: boolean) {
if (Array.isArray(featureNames)) {
if (featureNames.length === 0) return true;
if (requiresAll === undefined || requiresAll === true) {
for (const featureName of featureNames) {
if (!_isEnabled(featureName)) return false;
}
return true;
}
for (const featureName of featureNames) {
if (_isEnabled(featureName)) return true;
}
} else {
return _isEnabled(featureNames);
}
return false;
},
};
return { featureChecker };
}

49
apps/vben5/packages/@abp/core/src/hooks/useGlobalFeatures.ts

@ -0,0 +1,49 @@
import { computed } from 'vue';
import { useAbpStore } from '../store/abp';
import { isNullOrWhiteSpace } from '../utils/string';
export function useGlobalFeatures() {
const getGlobalFeatures = computed(() => {
const abpStore = useAbpStore();
const enabledFeatures =
abpStore.application?.globalFeatures.enabledFeatures ?? [];
return enabledFeatures;
});
function get(name: string): string | undefined {
return getGlobalFeatures.value.find((feature) => name === feature);
}
function _isEnabled(name: string): boolean {
const feature = get(name);
return !isNullOrWhiteSpace(feature);
}
function isEnabled(
featureNames: string | string[],
requiresAll?: boolean,
): boolean {
if (Array.isArray(featureNames)) {
if (featureNames.length === 0) return true;
if (requiresAll === undefined || requiresAll === true) {
for (const featureName of featureNames) {
if (!_isEnabled(featureName)) return false;
}
return true;
}
for (const featureName of featureNames) {
if (_isEnabled(featureName)) return true;
}
} else {
return _isEnabled(featureNames);
}
return false;
}
return {
isEnabled,
};
}

49
apps/vben5/packages/@abp/core/src/hooks/useLocalization.ts

@ -1,6 +1,6 @@
import type { Dictionary, StringLocalizer } from '../types'; import type { Dictionary, StringLocalizer } from '../types';
import { computed } from 'vue'; import { computed, ref, watch } from 'vue';
import merge from 'lodash.merge'; import merge from 'lodash.merge';
@ -9,24 +9,47 @@ import { format } from '../utils/string';
export function useLocalization(resourceNames?: string | string[]) { export function useLocalization(resourceNames?: string | string[]) {
const abpStore = useAbpStore(); const abpStore = useAbpStore();
const getResource = computed(() => {
if (!abpStore.application) {
return {};
}
const { values } = abpStore.application.localization;
const localizations = ref<Dictionary<string, Dictionary<string, string>>>({});
watch(
() => abpStore.localization,
(localization) => {
if (!localization?.resources) {
localizations.value = {};
return;
}
const localizationResource: Dictionary<
string,
Dictionary<string, string>
> = {};
Object.keys(localization.resources).forEach((resourceName) => {
if (localization.resources[resourceName]) {
localizationResource[resourceName] =
localization.resources[resourceName].texts;
}
});
localizations.value = localizationResource;
},
{
deep: true,
immediate: true,
},
);
const getResource = computed(() => {
let resource: { [key: string]: string } = {}; let resource: { [key: string]: string } = {};
if (resourceNames) { if (resourceNames) {
if (Array.isArray(resourceNames)) { if (Array.isArray(resourceNames)) {
resourceNames.forEach((name) => { resourceNames.forEach((name) => {
resource = merge(resource, values[name]); resource = merge(resource, localizations.value[name]);
}); });
} else { } else {
resource = merge(resource, values[resourceNames]); resource = merge(resource, localizations.value[resourceNames]);
} }
} else { } else {
Object.keys(values).forEach((rs) => { Object.keys(localizations.value).forEach((rs) => {
resource = merge(resource, values[rs]); resource = merge(resource, localizations.value[rs]);
}); });
} }
@ -34,11 +57,7 @@ export function useLocalization(resourceNames?: string | string[]) {
}); });
const getResourceByName = computed(() => { const getResourceByName = computed(() => {
return (resource: string): Dictionary<string, string> => { return (resource: string): Dictionary<string, string> => {
if (!abpStore.application) { return localizations.value[resource] ?? {};
return {};
}
const { values } = abpStore.application.localization;
return values[resource] ?? {};
}; };
}); });

109
apps/vben5/packages/@abp/core/src/hooks/useLocalizationSerializer.ts

@ -0,0 +1,109 @@
import type { LocalizableStringInfo } from '../types';
import { isNullOrWhiteSpace } from '../utils/string';
interface ValidateOptions {
required?: boolean;
}
interface ILocalizableStringSerializer {
deserialize(value?: string): LocalizableStringInfo;
serialize(value?: LocalizableStringInfo): string;
validate(value?: string, opt?: ValidateOptions): boolean;
}
export function useLocalizationSerializer(): ILocalizableStringSerializer {
function Validate(value?: string, opt?: ValidateOptions): boolean {
if (!value || isNullOrWhiteSpace(value)) {
if (!opt || opt.required === undefined || opt.required === true) {
return false;
}
return true;
}
if (value.length < 3 || value[1] !== ':') {
return false;
}
const type = value[0];
switch (type) {
case 'F': {
return !isNullOrWhiteSpace(value.slice(2).trim());
}
case 'L': {
const commaPosition = value.indexOf(',', 2);
if (commaPosition === -1) {
return false;
}
const name = value.slice(Math.max(0, commaPosition + 1));
if (isNullOrWhiteSpace(name)) {
return false;
}
return true;
}
default: {
return false;
}
}
}
function Serialize(value?: LocalizableStringInfo): string {
if (!value) return '';
return `L:${value.resourceName},${value.name}`;
}
function Deserialize(value?: string): LocalizableStringInfo {
if (!value || isNullOrWhiteSpace(value)) {
return {
name: '',
resourceName: '',
};
}
if (value.length < 2 || value[1] !== ':') {
return {
name: value,
resourceName: '',
};
}
const type = value[0];
switch (type) {
case 'F': {
return {
name: value.slice(2),
resourceName: 'Fixed',
};
}
case 'L': {
const commaPosition = value.indexOf(',', 2);
if (commaPosition === -1) {
return {
name: value,
resourceName: 'Default',
};
}
const resourceName = value.slice(2, commaPosition);
const name = value.slice(Math.max(0, commaPosition + 1));
if (isNullOrWhiteSpace(resourceName)) {
return {
name: value,
resourceName: 'Default',
};
}
return {
name,
resourceName,
};
}
default: {
return {
name: value,
resourceName: 'Default',
};
}
}
}
return {
deserialize: Deserialize,
serialize: Serialize,
validate: Validate,
};
}

135
apps/vben5/packages/@abp/core/src/hooks/useSimpleStateCheck.ts

@ -0,0 +1,135 @@
import type {
IHasSimpleStateCheckers,
ISimpleStateChecker,
ISimpleStateCheckerSerializer,
} from '../types/global';
import { isNullOrUnDef } from '../utils/is';
import { isNullOrWhiteSpace } from '../utils/string';
import { useRequireAuthenticatedSimpleStateChecker } from './SimpleStateChecking/useRequireAuthenticatedSimpleStateChecker';
import { useRequireFeaturesSimpleStateChecker } from './SimpleStateChecking/useRequireFeaturesSimpleStateChecker';
import { useRequireGlobalFeaturesSimpleStateChecker } from './SimpleStateChecking/useRequireGlobalFeaturesSimpleStateChecker';
import { useRequirePermissionsSimpleStateChecker } from './SimpleStateChecking/useRequirePermissionsSimpleStateChecker';
class SimpleStateCheckerSerializer implements ISimpleStateCheckerSerializer {
deserialize<TState extends IHasSimpleStateCheckers<TState>>(
jsonObject: any,
state: TState,
): ISimpleStateChecker<TState> | undefined {
if (isNullOrUnDef(jsonObject) || !Reflect.has(jsonObject, 'T')) {
return undefined;
}
switch (String(jsonObject.T)) {
case 'A': {
return useRequireAuthenticatedSimpleStateChecker();
}
case 'F': {
const features = jsonObject.N as string[];
if (features === undefined) {
throw new Error(
`'N' is not an array in the serialized state checker! JsonObject: ${
jsonObject
}`,
);
}
return useRequireFeaturesSimpleStateChecker(
features,
jsonObject.A === true,
);
}
case 'G': {
const globalFeatures = jsonObject.N as string[];
if (globalFeatures === undefined) {
throw new Error(
`'N' is not an array in the serialized state checker! JsonObject: ${
jsonObject
}`,
);
}
return useRequireGlobalFeaturesSimpleStateChecker(
globalFeatures,
jsonObject.A === true,
);
}
case 'P': {
const permissions = jsonObject.N as string[];
if (permissions === undefined) {
throw new Error(
`'N' is not an array in the serialized state checker! JsonObject: ${
jsonObject
}`,
);
}
return useRequirePermissionsSimpleStateChecker({
permissions,
requiresAll: jsonObject.A === true,
state,
});
}
default: {
return undefined;
}
}
}
deserializeArray<TState extends IHasSimpleStateCheckers<TState>>(
value: string,
state: TState,
): ISimpleStateChecker<TState>[] {
if (isNullOrWhiteSpace(value)) return [];
const jsonObject = JSON.parse(value);
if (isNullOrUnDef(jsonObject)) return [];
if (Array.isArray(jsonObject)) {
if (jsonObject.length === 0) return [];
return jsonObject
.map((json) => this.deserialize(json, state))
.filter((checker) => !isNullOrUnDef(checker))
.map((checker) => checker);
}
const stateChecker = this.deserialize(jsonObject, state);
if (!stateChecker) return [];
return [stateChecker];
}
serialize<TState extends IHasSimpleStateCheckers<TState>>(
checker: ISimpleStateChecker<TState>,
): string | undefined {
return checker.serialize();
}
serializeArray<TState extends IHasSimpleStateCheckers<TState>>(
stateCheckers: ISimpleStateChecker<TState>[],
): string | undefined {
if (stateCheckers.length === 0) return undefined;
if (stateCheckers.length === 1) {
const stateChecker = stateCheckers[0];
const single = stateChecker?.serialize();
if (isNullOrUnDef(single)) return undefined;
return `[${single}]`;
}
let serializedCheckers: string = '';
stateCheckers.forEach((checker) => {
const serializedChecker = checker.serialize();
if (!isNullOrUnDef(serializedChecker)) {
serializedCheckers += `${serializedChecker},`;
}
});
if (serializedCheckers.endsWith(',')) {
serializedCheckers = serializedCheckers.slice(
0,
Math.max(0, serializedCheckers.length - 1),
);
}
return serializedCheckers.length > 0
? `[${serializedCheckers}]`
: undefined;
}
}
export function useSimpleStateCheck<
TState extends IHasSimpleStateCheckers<TState>,
>() {
return {
serializer: new SimpleStateCheckerSerializer(),
};
}

5
apps/vben5/packages/@abp/core/src/store/abp.ts

@ -52,7 +52,12 @@ export const useAbpStore = defineStore(
localization.value = val; localization.value = val;
} }
function $reset() {
application.value = undefined;
}
return { return {
$reset,
application, application,
getI18nLocales, getI18nLocales,
localization, localization,

27
apps/vben5/packages/@abp/core/src/types/features.ts

@ -0,0 +1,27 @@
import type { NameValue } from './global';
type FeatureValue = NameValue<string>;
/**
*
*/
interface IFeatureChecker {
/**
*
* @param name
* @returns ,
*/
getOrEmpty(name: string): string;
/**
*
* @param featureNames
* @param requiresAll
*/
isEnabled(featureNames: string | string[], requiresAll?: boolean): boolean;
}
interface IGlobalFeatureChecker {
isEnabled(featureNames: string | string[], requiresAll?: boolean): boolean;
}
export type { FeatureValue, IFeatureChecker, IGlobalFeatureChecker };

26
apps/vben5/packages/@abp/core/src/types/global.ts

@ -206,31 +206,35 @@ interface CurrentUser {
userName: string; userName: string;
} }
// eslint-disable-next-line no-use-before-define interface IHasSimpleStateCheckers<
TState extends IHasSimpleStateCheckers<TState>,
> {
// eslint-disable-next-line no-use-before-define
stateCheckers: ISimpleStateChecker<TState>[];
}
type SimpleStateRecord<
TState extends IHasSimpleStateCheckers<TState>,
TValue,
> = {
[P in TState]: TValue;
};
type SimpleStateCheckerResult<TState extends IHasSimpleStateCheckers<TState>> = type SimpleStateCheckerResult<TState extends IHasSimpleStateCheckers<TState>> =
Map<TState, boolean>; SimpleStateRecord<TState, boolean>;
interface SimpleStateCheckerContext< interface SimpleStateCheckerContext<
// eslint-disable-next-line no-use-before-define
TState extends IHasSimpleStateCheckers<TState>, TState extends IHasSimpleStateCheckers<TState>,
> { > {
state: TState; state: TState;
} }
interface SimpleBatchStateCheckerContext< interface SimpleBatchStateCheckerContext<
// eslint-disable-next-line no-use-before-define
TState extends IHasSimpleStateCheckers<TState>, TState extends IHasSimpleStateCheckers<TState>,
> { > {
states: TState[]; states: TState[];
} }
interface IHasSimpleStateCheckers<
TState extends IHasSimpleStateCheckers<TState>,
> {
// eslint-disable-next-line no-use-before-define
stateCheckers: ISimpleStateChecker<TState>[];
}
interface ISimpleStateChecker<TState extends IHasSimpleStateCheckers<TState>> { interface ISimpleStateChecker<TState extends IHasSimpleStateCheckers<TState>> {
isEnabled(context: SimpleStateCheckerContext<TState>): boolean; isEnabled(context: SimpleStateCheckerContext<TState>): boolean;
serialize(): string | undefined; serialize(): string | undefined;

2
apps/vben5/packages/@abp/core/src/types/index.ts

@ -1,7 +1,9 @@
export * from './dto'; export * from './dto';
export * from './features';
export * from './global'; export * from './global';
export * from './localization'; export * from './localization';
export * from './openid'; export * from './openid';
export * from './permissions';
export * from './rules'; export * from './rules';
export * from './settings'; export * from './settings';
export * from './table'; export * from './table';

6
apps/vben5/packages/@abp/core/src/types/permissions.ts

@ -0,0 +1,6 @@
interface IPermissionChecker {
authorize(name: string | string[]): void;
isGranted(name: string | string[], requiresAll?: boolean): boolean;
}
export type { IPermissionChecker };

19
apps/vben5/packages/@abp/core/src/utils/is.ts

@ -0,0 +1,19 @@
export function isNullAndUnDef(val: unknown): val is null | undefined {
return isUnDef(val) && isNull(val);
}
export function isNullOrUnDef(val: unknown): val is null | undefined {
return isUnDef(val) || isNull(val);
}
export function isDef<T = unknown>(val?: T): val is T {
return val !== undefined;
}
export function isUnDef<T = unknown>(val?: T): val is T {
return !isDef(val);
}
export function isNull(value: any): value is null {
return value === null;
}

7
apps/vben5/packages/@abp/permission/package.json

@ -31,6 +31,11 @@
"@vben/layouts": "workspace:*", "@vben/layouts": "workspace:*",
"@vben/locales": "workspace:*", "@vben/locales": "workspace:*",
"ant-design-vue": "catalog:", "ant-design-vue": "catalog:",
"vue": "catalog:*" "lodash.clonedeep": "catalog:",
"vue": "catalog:*",
"vxe-table": "catalog:"
},
"devDependencies": {
"@types/lodash.clonedeep": "catalog:"
} }
} }

75
apps/vben5/packages/@abp/permission/src/api/definitions.ts

@ -0,0 +1,75 @@
import type { ListResultDto } from '@abp/core';
import type {
PermissionDefinitionCreateDto,
PermissionDefinitionDto,
PermissionDefinitionGetListInput,
PermissionDefinitionUpdateDto,
} from '../types/definitions';
import { requestClient } from '@abp/request';
/**
*
* @param name
*/
export function deleteApi(name: string): Promise<void> {
return requestClient.delete(`/api/permission-management/definitions/${name}`);
}
/**
*
* @param name
* @returns
*/
export function getApi(name: string): Promise<PermissionDefinitionDto> {
return requestClient.get<PermissionDefinitionDto>(
`/api/permission-management/definitions/${name}`,
);
}
/**
*
* @param input
* @returns
*/
export function getListApi(
input?: PermissionDefinitionGetListInput,
): Promise<ListResultDto<PermissionDefinitionDto>> {
return requestClient.get<ListResultDto<PermissionDefinitionDto>>(
`/api/permission-management/definitions`,
{
params: input,
},
);
}
/**
*
* @param input
* @returns
*/
export function createApi(
input: PermissionDefinitionCreateDto,
): Promise<PermissionDefinitionDto> {
return requestClient.post<PermissionDefinitionDto>(
'/api/permission-management/definitions',
input,
);
}
/**
*
* @param name
* @param input
* @returns
*/
export function updateApi(
name: string,
input: PermissionDefinitionUpdateDto,
): Promise<PermissionDefinitionDto> {
return requestClient.put<PermissionDefinitionDto>(
`/api/permission-management/definitions/${name}`,
input,
);
}

77
apps/vben5/packages/@abp/permission/src/api/groups.ts

@ -0,0 +1,77 @@
import type { ListResultDto } from '@abp/core';
import type {
PermissionGroupDefinitionCreateDto,
PermissionGroupDefinitionDto,
PermissionGroupDefinitionGetListInput,
PermissionGroupDefinitionUpdateDto,
} from '../types/groups';
import { requestClient } from '@abp/request';
/**
*
* @param name
*/
export function deleteApi(name: string): Promise<void> {
return requestClient.delete(
`/api/permission-management/definitions/groups/${name}`,
);
}
/**
*
* @param name
* @returns
*/
export function getApi(name: string): Promise<PermissionGroupDefinitionDto> {
return requestClient.get<PermissionGroupDefinitionDto>(
`/api/permission-management/definitions/groups/${name}`,
);
}
/**
*
* @param input
* @returns
*/
export function getListApi(
input?: PermissionGroupDefinitionGetListInput,
): Promise<ListResultDto<PermissionGroupDefinitionDto>> {
return requestClient.get<ListResultDto<PermissionGroupDefinitionDto>>(
`/api/permission-management/definitions/groups`,
{
params: input,
},
);
}
/**
*
* @param input
* @returns
*/
export function createApi(
input: PermissionGroupDefinitionCreateDto,
): Promise<PermissionGroupDefinitionDto> {
return requestClient.post<PermissionGroupDefinitionDto>(
'/api/permission-management/definitions/groups',
input,
);
}
/**
*
* @param name
* @param input
* @returns
*/
export function updateApi(
name: string,
input: PermissionGroupDefinitionUpdateDto,
): Promise<PermissionGroupDefinitionDto> {
return requestClient.put<PermissionGroupDefinitionDto>(
`/api/permission-management/definitions/groups/${name}`,
input,
);
}

142
apps/vben5/packages/@abp/permission/src/components/definitions/groups/PermissionGroupDefinitionModal.vue

@ -1,7 +1,145 @@
<script setup lang="ts"></script> <script setup lang="ts">
import type { PropertyInfo } from '@abp/ui';
import type { FormInstance } from 'ant-design-vue';
import type { PermissionGroupDefinitionDto } from '../../../types/groups';
import { defineEmits, defineOptions, ref, toValue, useTemplateRef } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { LocalizableInput, PropertyTable } from '@abp/ui';
import { Form, Input, message, Tabs } from 'ant-design-vue';
import { createApi, getApi, updateApi } from '../../../api/groups';
defineOptions({
name: 'PermissionGroupDefinitionModal',
});
const emits = defineEmits<{
(event: 'change', data: PermissionGroupDefinitionDto): void;
}>();
const FormItem = Form.Item;
const TabPane = Tabs.TabPane;
type TabKeys = 'basic' | 'props';
const defaultModel = {} as PermissionGroupDefinitionDto;
const isEditModel = ref(false);
const activeTab = ref<TabKeys>('basic');
const form = useTemplateRef<FormInstance>('form');
const formModel = ref<PermissionGroupDefinitionDto>({ ...defaultModel });
const [Modal, modalApi] = useVbenModal({
class: 'w-1/2',
draggable: true,
fullscreenButton: false,
onCancel() {
modalApi.close();
},
onConfirm: async () => {
await form.value?.validate();
const api = isEditModel.value
? updateApi(formModel.value.name, toValue(formModel))
: createApi(toValue(formModel));
modalApi.setState({ confirmLoading: true, loading: true });
api
.then((res) => {
message.success($t('AbpUi.SavedSuccessfully'));
emits('change', res);
modalApi.close();
})
.finally(() => {
modalApi.setState({ confirmLoading: false, loading: false });
});
},
onOpenChange: async (isOpen: boolean) => {
if (isOpen) {
isEditModel.value = false;
activeTab.value = 'basic';
formModel.value = { ...defaultModel };
modalApi.setState({
showConfirmButton: true,
title: $t('AbpPermissionManagement.GroupDefinitions:AddNew'),
});
try {
modalApi.setState({ loading: true });
const { name } = modalApi.getData<PermissionGroupDefinitionDto>();
name && (await onGet(name));
} finally {
modalApi.setState({ loading: false });
}
}
},
title: $t('AbpPermissionManagement.GroupDefinitions:AddNew'),
});
async function onGet(name: string) {
isEditModel.value = true;
const dto = await getApi(name);
formModel.value = dto;
modalApi.setState({
showConfirmButton: !dto.isStatic,
title: `${$t('AbpPermissionManagement.GroupDefinitions')} - ${dto.name}`,
});
}
function onPropChange(prop: PropertyInfo) {
formModel.value.extraProperties ??= {};
formModel.value.extraProperties[prop.key] = prop.value;
}
function onPropDelete(prop: PropertyInfo) {
formModel.value.extraProperties ??= {};
delete formModel.value.extraProperties[prop.key];
}
</script>
<template> <template>
<div></div> <Modal>
<Form
ref="form"
:label-col="{ span: 6 }"
:model="formModel"
:wrapper-col="{ span: 18 }"
>
<Tabs v-model:active-key="activeTab">
<!-- 基本信息 -->
<TabPane key="basic" :tab="$t('AbpPermissionManagement.BasicInfo')">
<FormItem
:label="$t('AbpPermissionManagement.DisplayName:Name')"
name="name"
required
>
<Input
v-model:value="formModel.name"
:disabled="formModel.isStatic"
autocomplete="off"
/>
</FormItem>
<FormItem
:label="$t('AbpPermissionManagement.DisplayName:DisplayName')"
name="displayName"
required
>
<LocalizableInput
v-model:value="formModel.displayName"
:disabled="formModel.isStatic"
/>
</FormItem>
</TabPane>
<!-- 属性 -->
<TabPane key="props" :tab="$t('AbpPermissionManagement.Properties')">
<PropertyTable
:data="formModel.extraProperties"
:disabled="formModel.isStatic"
@change="onPropChange"
@delete="onPropDelete"
/>
</TabPane>
</Tabs>
</Form>
</Modal>
</template> </template>
<style scoped></style> <style scoped></style>

270
apps/vben5/packages/@abp/permission/src/components/definitions/groups/PermissionGroupDefinitionTable.vue

@ -1,7 +1,273 @@
<script setup lang="ts"></script> <script setup lang="ts">
import type { VbenFormProps, VxeGridListeners, VxeGridProps } from '@abp/ui';
import type { MenuInfo } from 'ant-design-vue/es/menu/src/interface';
import type { PermissionGroupDefinitionDto } from '../../../types/groups';
import { defineAsyncComponent, h, onMounted, reactive, ref } from 'vue';
import { useAccess } from '@vben/access';
import { useVbenModal } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import { $t } from '@vben/locales';
import { useLocalization, useLocalizationSerializer } from '@abp/core';
import { useVbenVxeGrid } from '@abp/ui';
import {
DeleteOutlined,
EditOutlined,
EllipsisOutlined,
PlusOutlined,
} from '@ant-design/icons-vue';
import { Button, Dropdown, Menu, message, Modal } from 'ant-design-vue';
import { deleteApi, getListApi } from '../../../api/groups';
import {
GroupDefinitionsPermissions,
PermissionDefinitionsPermissions,
} from '../../../constants/permissions';
defineOptions({
name: 'PermissionGroupDefinitionTable',
});
const MenuItem = Menu.Item;
const PermissionsOutlined = createIconifyIcon('icon-park-outline:permissions');
const permissionGroups = ref<PermissionGroupDefinitionDto[]>([]);
const pageState = reactive({
current: 1,
size: 10,
total: 0,
});
const { Lr } = useLocalization();
const { hasAccessByCodes } = useAccess();
const { deserialize } = useLocalizationSerializer();
const formOptions: VbenFormProps = {
//
collapsed: false,
handleReset: onReset,
async handleSubmit(params) {
pageState.current = 1;
await onGet(params);
},
schema: [
{
component: 'Input',
fieldName: 'filter',
formItemClass: 'col-span-2 items-baseline',
label: $t('AbpUi.Search'),
},
],
//
showCollapseButton: true,
//
submitOnEnter: true,
};
const gridOptions: VxeGridProps<PermissionGroupDefinitionDto> = {
columns: [
{
align: 'left',
field: 'name',
minWidth: 150,
title: $t('AbpPermissionManagement.DisplayName:Name'),
},
{
align: 'left',
field: 'displayName',
minWidth: 150,
title: $t('AbpPermissionManagement.DisplayName:DisplayName'),
},
{
field: 'action',
fixed: 'right',
slots: { default: 'action' },
title: $t('AbpUi.Actions'),
width: 220,
},
],
exportConfig: {},
keepSource: true,
toolbarConfig: {
custom: true,
export: true,
refresh: false,
zoom: true,
},
};
const gridEvents: VxeGridListeners<PermissionGroupDefinitionDto> = {
pageChange(params) {
pageState.current = params.currentPage;
pageState.size = params.pageSize;
onPageChange();
},
};
const [Grid, gridApi] = useVbenVxeGrid({
formOptions,
gridEvents,
gridOptions,
});
const [PermissionGroupDefinitionModal, groupModalApi] = useVbenModal({
connectedComponent: defineAsyncComponent(
() => import('./PermissionGroupDefinitionModal.vue'),
),
});
const [PermissionDefinitionModal, permissionModalApi] = useVbenModal({
connectedComponent: defineAsyncComponent(
() => import('../permissions/PermissionDefinitionModal.vue'),
),
});
async function onGet(input?: Record<string, string>) {
try {
gridApi.setLoading(true);
const { items } = await getListApi(input);
pageState.total = items.length;
permissionGroups.value = items.map((item) => {
const localizableString = deserialize(item.displayName);
return {
...item,
displayName: Lr(localizableString.resourceName, localizableString.name),
};
});
onPageChange();
} finally {
gridApi.setLoading(false);
}
}
async function onReset() {
await gridApi.formApi.resetForm();
const input = await gridApi.formApi.getValues();
await onGet(input);
}
function onPageChange() {
const items = permissionGroups.value.slice(
(pageState.current - 1) * pageState.size,
pageState.current * pageState.size,
);
gridApi.setGridOptions({
data: items,
pagerConfig: {
currentPage: pageState.current,
pageSize: pageState.size,
total: pageState.total,
},
});
}
function onCreate() {
groupModalApi.setData({});
groupModalApi.open();
}
function onUpdate(row: PermissionGroupDefinitionDto) {
groupModalApi.setData(row);
groupModalApi.open();
}
function onMenuClick(row: PermissionGroupDefinitionDto, info: MenuInfo) {
switch (info.key) {
case 'permissions': {
permissionModalApi.setData({
groupName: row.name,
});
permissionModalApi.open();
break;
}
}
}
function onDelete(row: PermissionGroupDefinitionDto) {
Modal.confirm({
centered: true,
content: `${$t('AbpUi.ItemWillBeDeletedMessageWithFormat', [row.name])}`,
onOk: async () => {
await deleteApi(row.name);
message.success($t('AbpUi.SuccessfullyDeleted'));
onGet();
},
title: $t('AbpUi.AreYouSure'),
});
}
onMounted(onGet);
</script>
<template> <template>
<div></div> <Grid :table-title="$t('AbpPermissionManagement.GroupDefinitions')">
<template #toolbar-tools>
<Button
:icon="h(PlusOutlined)"
type="primary"
v-access:code="[GroupDefinitionsPermissions.Create]"
@click="onCreate"
>
{{ $t('AbpPermissionManagement.GroupDefinitions:AddNew') }}
</Button>
</template>
<template #action="{ row }">
<div class="flex flex-row">
<div :class="`${row.isStatic ? 'w-full' : 'basis-1/3'}`">
<Button
:icon="h(EditOutlined)"
block
type="link"
v-access:code="[GroupDefinitionsPermissions.Update]"
@click="onUpdate(row)"
>
{{ $t('AbpUi.Edit') }}
</Button>
</div>
<template v-if="!row.isStatic">
<div class="basis-1/3">
<Button
:icon="h(DeleteOutlined)"
block
danger
type="link"
v-access:code="[GroupDefinitionsPermissions.Delete]"
@click="onDelete(row)"
>
{{ $t('AbpUi.Delete') }}
</Button>
</div>
<div class="basis-1/3">
<Dropdown>
<template #overlay>
<Menu @click="(info) => onMenuClick(row, info)">
<MenuItem
v-if="
hasAccessByCodes([
PermissionDefinitionsPermissions.Create,
])
"
key="permissions"
:icon="h(PermissionsOutlined)"
>
{{
$t('AbpPermissionManagement.PermissionDefinitions:AddNew')
}}
</MenuItem>
</Menu>
</template>
<Button :icon="h(EllipsisOutlined)" type="link" />
</Dropdown>
</div>
</template>
</div>
</template>
</Grid>
<PermissionGroupDefinitionModal @change="() => onGet()" />
<PermissionDefinitionModal />
</template> </template>
<style scoped></style> <style scoped></style>

282
apps/vben5/packages/@abp/permission/src/components/definitions/permissions/PermissionDefinitionModal.vue

@ -1,7 +1,285 @@
<script setup lang="ts"></script> <script setup lang="ts">
import type { PropertyInfo } from '@abp/ui';
import type { FormInstance } from 'ant-design-vue';
import type { PermissionDefinitionDto } from '../../../types/definitions';
import type { PermissionGroupDefinitionDto } from '../../../types/groups';
import { defineEmits, defineOptions, ref, toValue, useTemplateRef } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import {
listToTree,
useLocalization,
useLocalizationSerializer,
} from '@abp/core';
import { LocalizableInput, PropertyTable } from '@abp/ui';
import {
Checkbox,
Form,
Input,
message,
Select,
Tabs,
TreeSelect,
} from 'ant-design-vue';
import {
createApi,
getApi,
getListApi as getPermissionsApi,
updateApi,
} from '../../../api/definitions';
import { getListApi as getGroupsApi } from '../../../api/groups';
import { useTypesMap } from './types';
defineOptions({
name: 'PermissionDefinitionModal',
});
const emits = defineEmits<{
(event: 'change', data: PermissionDefinitionDto): void;
}>();
const FormItem = Form.Item;
const TabPane = Tabs.TabPane;
interface PermissionTreeVo {
children: PermissionTreeVo[];
displayName: string;
groupName: string;
name: string;
}
type TabKeys = 'basic' | 'props';
const defaultModel = {
isEnabled: true,
} as PermissionDefinitionDto;
const isEditModel = ref(false);
const activeTab = ref<TabKeys>('basic');
const form = useTemplateRef<FormInstance>('form');
const formModel = ref<PermissionDefinitionDto>({ ...defaultModel });
const { multiTenancySideOptions, providerOptions } = useTypesMap();
const availableGroups = ref<PermissionGroupDefinitionDto[]>([]);
const availablePermissions = ref<PermissionTreeVo[]>([]);
const { Lr } = useLocalization();
const { deserialize } = useLocalizationSerializer();
const [Modal, modalApi] = useVbenModal({
class: 'w-1/2',
draggable: true,
fullscreenButton: false,
onCancel() {
modalApi.close();
},
onConfirm: async () => {
await form.value?.validate();
const api = isEditModel.value
? updateApi(formModel.value.name, toValue(formModel))
: createApi(toValue(formModel));
modalApi.setState({ confirmLoading: true, loading: true });
api
.then((res) => {
message.success($t('AbpUi.SavedSuccessfully'));
emits('change', res);
modalApi.close();
})
.finally(() => {
modalApi.setState({ confirmLoading: false, loading: false });
});
},
onOpenChange: async (isOpen: boolean) => {
if (isOpen) {
isEditModel.value = false;
activeTab.value = 'basic';
formModel.value = { ...defaultModel };
availablePermissions.value = [];
availableGroups.value = [];
modalApi.setState({
showConfirmButton: true,
title: $t('AbpPermissionManagement.PermissionDefinitions:AddNew'),
});
try {
modalApi.setState({ loading: true });
const { groupName, name } = modalApi.getData<PermissionDefinitionDto>();
name && (await onGet(name));
await onInitGroups(groupName);
} finally {
modalApi.setState({ loading: false });
}
}
},
title: $t('AbpPermissionManagement.PermissionDefinitions:AddNew'),
});
async function onInitGroups(name?: string) {
const { items } = await getGroupsApi({ filter: name });
availableGroups.value = items.map((group) => {
const localizableGroup = deserialize(group.displayName);
return {
...group,
displayName: Lr(localizableGroup.resourceName, localizableGroup.name),
};
});
if (name) {
formModel.value.groupName = name;
await onGroupChange(name);
}
}
async function onGet(name: string) {
isEditModel.value = true;
const dto = await getApi(name);
formModel.value = dto;
modalApi.setState({
showConfirmButton: !dto.isStatic,
title: `${$t('AbpPermissionManagement.PermissionDefinitions')} - ${dto.name}`,
});
}
async function onGroupChange(name?: string) {
const { items } = await getPermissionsApi({
groupName: name,
});
const permissions = items.map((permission) => {
const localizablePermission = deserialize(permission.displayName);
return {
...permission,
disabled: permission.name === formModel.value.name,
displayName: Lr(
localizablePermission.resourceName,
localizablePermission.name,
),
};
});
availablePermissions.value = listToTree(permissions, {
id: 'name',
pid: 'parentName',
});
}
function onPropChange(prop: PropertyInfo) {
formModel.value.extraProperties ??= {};
formModel.value.extraProperties[prop.key] = prop.value;
}
function onPropDelete(prop: PropertyInfo) {
formModel.value.extraProperties ??= {};
delete formModel.value.extraProperties[prop.key];
}
</script>
<template> <template>
<div></div> <Modal>
<Form
ref="form"
:label-col="{ span: 6 }"
:model="formModel"
:wrapper-col="{ span: 18 }"
>
<Tabs v-model:active-key="activeTab">
<!-- 基本信息 -->
<TabPane key="basic" :tab="$t('AbpPermissionManagement.BasicInfo')">
<FormItem
:label="$t('AbpPermissionManagement.DisplayName:IsEnabled')"
name="isEnabled"
>
<Checkbox
v-model:checked="formModel.isEnabled"
:disabled="formModel.isStatic"
>
{{ $t('AbpPermissionManagement.DisplayName:IsEnabled') }}
</Checkbox>
</FormItem>
<FormItem
:label="$t('AbpPermissionManagement.DisplayName:GroupName')"
name="groupName"
required
>
<Select
v-model:value="formModel.groupName"
:allow-clear="true"
:disabled="formModel.isStatic"
:field-names="{
label: 'displayName',
value: 'name',
}"
:options="availableGroups"
@change="(e) => onGroupChange(e?.toString())"
/>
</FormItem>
<FormItem
v-if="availablePermissions.length > 0"
:label="$t('AbpPermissionManagement.DisplayName:ParentName')"
name="parentName"
>
<TreeSelect
v-model:value="formModel.parentName"
:allow-clear="true"
:disabled="formModel.isStatic"
:field-names="{
label: 'displayName',
value: 'name',
children: 'children',
}"
:tree-data="availablePermissions"
/>
</FormItem>
<FormItem
:label="$t('AbpPermissionManagement.DisplayName:Name')"
name="name"
required
>
<Input
v-model:value="formModel.name"
:disabled="formModel.isStatic"
autocomplete="off"
/>
</FormItem>
<FormItem
:label="$t('AbpPermissionManagement.DisplayName:DisplayName')"
name="displayName"
required
>
<LocalizableInput
v-model:value="formModel.displayName"
:disabled="formModel.isStatic"
/>
</FormItem>
<FormItem
:label="$t('AbpPermissionManagement.DisplayName:MultiTenancySide')"
name="multiTenancySide"
>
<Select
v-model:value="formModel.multiTenancySide"
:disabled="formModel.isStatic"
:options="multiTenancySideOptions"
/>
</FormItem>
<FormItem
:label="$t('AbpPermissionManagement.DisplayName:Providers')"
name="providers"
>
<Select
v-model:value="formModel.providers"
:allow-clear="true"
:disabled="formModel.isStatic"
:options="providerOptions"
mode="multiple"
/>
</FormItem>
</TabPane>
<!-- 属性 -->
<TabPane key="props" :tab="$t('AbpPermissionManagement.Properties')">
<PropertyTable
:data="formModel.extraProperties"
:disabled="formModel.isStatic"
@change="onPropChange"
@delete="onPropDelete"
/>
</TabPane>
</Tabs>
</Form>
</Modal>
</template> </template>
<style scoped></style> <style scoped></style>
import { useLocalization, useLocalizationSerializer } from '@abp/core';

333
apps/vben5/packages/@abp/permission/src/components/definitions/permissions/PermissionDefinitionTable.vue

@ -1,7 +1,336 @@
<script setup lang="ts"></script> <script setup lang="ts">
import type { VbenFormProps, VxeGridListeners, VxeGridProps } from '@abp/ui';
import type { PermissionGroupDefinitionDto } from '../../../types/groups';
import { defineAsyncComponent, h, onMounted, reactive, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import {
listToTree,
useLocalization,
useLocalizationSerializer,
} from '@abp/core';
import { useVbenVxeGrid } from '@abp/ui';
import {
DeleteOutlined,
EditOutlined,
PlusOutlined,
} from '@ant-design/icons-vue';
import { Button, message, Modal, Tag } from 'ant-design-vue';
import { VxeGrid } from 'vxe-table';
import {
deleteApi,
getListApi as getPermissionsApi,
} from '../../../api/definitions';
import { getListApi as getGroupsApi } from '../../../api/groups';
import { GroupDefinitionsPermissions } from '../../../constants/permissions';
import { type PermissionDefinitionDto } from '../../../types/definitions';
import { useTypesMap } from './types';
defineOptions({
name: 'PermissionDefinitionTable',
});
interface PermissionVo {
children: PermissionVo[];
displayName: string;
groupName: string;
isEnabled: boolean;
isStatic: boolean;
name: string;
parentName?: string;
providers: string[];
stateCheckers: string[];
}
interface PermissionGroupVo {
displayName: string;
name: string;
permissions: PermissionVo[];
}
const permissionGroups = ref<PermissionGroupVo[]>([]);
const pageState = reactive({
current: 1,
size: 10,
total: 0,
});
const { Lr } = useLocalization();
const { deserialize } = useLocalizationSerializer();
const { multiTenancySidesMap, providersMap } = useTypesMap();
const formOptions: VbenFormProps = {
//
collapsed: false,
handleReset: onReset,
async handleSubmit(params) {
pageState.current = 1;
await onGet(params);
},
schema: [
{
component: 'Input',
fieldName: 'filter',
formItemClass: 'col-span-2 items-baseline',
label: $t('AbpUi.Search'),
},
],
//
showCollapseButton: true,
//
submitOnEnter: true,
};
const gridOptions: VxeGridProps<PermissionGroupDefinitionDto> = {
columns: [
{
align: 'center',
type: 'seq',
width: 50,
},
{
align: 'left',
field: 'group',
slots: { content: 'group' },
type: 'expand',
width: 50,
},
{
align: 'left',
field: 'name',
minWidth: 150,
title: $t('AbpPermissionManagement.DisplayName:Name'),
},
{
align: 'left',
field: 'displayName',
minWidth: 150,
title: $t('AbpPermissionManagement.DisplayName:DisplayName'),
},
],
expandConfig: {
padding: true,
trigger: 'row',
},
exportConfig: {},
keepSource: true,
toolbarConfig: {
custom: true,
export: true,
refresh: false,
zoom: true,
},
};
const subGridColumns: VxeGridProps<PermissionDefinitionDto>['columns'] = [
{
align: 'center',
type: 'seq',
width: 50,
},
{
align: 'left',
field: 'name',
minWidth: 150,
title: $t('AbpPermissionManagement.DisplayName:Name'),
treeNode: true,
},
{
align: 'left',
field: 'displayName',
minWidth: 120,
title: $t('AbpPermissionManagement.DisplayName:DisplayName'),
},
{
align: 'center',
field: 'multiTenancySide',
minWidth: 100,
slots: { default: 'tenant' },
title: $t('AbpPermissionManagement.DisplayName:MultiTenancySide'),
},
{
align: 'center',
field: 'providers',
minWidth: 100,
slots: { default: 'providers' },
title: $t('AbpPermissionManagement.DisplayName:Providers'),
},
{
field: 'action',
fixed: 'right',
slots: { default: 'action' },
title: $t('AbpUi.Actions'),
width: 180,
},
];
const gridEvents: VxeGridListeners<PermissionGroupDefinitionDto> = {
pageChange(params) {
pageState.current = params.currentPage;
pageState.size = params.pageSize;
onPageChange();
},
};
const [GroupGrid, gridApi] = useVbenVxeGrid({
formOptions,
gridEvents,
gridOptions,
});
const [PermissionDefinitionModal, modalApi] = useVbenModal({
connectedComponent: defineAsyncComponent(
() => import('./PermissionDefinitionModal.vue'),
),
});
async function onGet(input?: Record<string, string>) {
try {
gridApi.setLoading(true);
const groupRes = await getGroupsApi(input);
const permissionRes = await getPermissionsApi(input);
pageState.total = groupRes.items.length;
permissionGroups.value = groupRes.items.map((group) => {
const localizableGroup = deserialize(group.displayName);
const permissions = permissionRes.items
.filter((permission) => permission.groupName === group.name)
.map((permission) => {
const localizablePermission = deserialize(permission.displayName);
return {
...permission,
displayName: Lr(
localizablePermission.resourceName,
localizablePermission.name,
),
};
});
return {
...group,
displayName: Lr(localizableGroup.resourceName, localizableGroup.name),
permissions: listToTree(permissions, {
id: 'name',
pid: 'parentName',
}),
};
});
onPageChange();
} finally {
gridApi.setLoading(false);
}
}
async function onReset() {
await gridApi.formApi.resetForm();
const input = await gridApi.formApi.getValues();
await onGet(input);
}
function onPageChange() {
const items = permissionGroups.value.slice(
(pageState.current - 1) * pageState.size,
pageState.current * pageState.size,
);
gridApi.setGridOptions({
data: items,
pagerConfig: {
currentPage: pageState.current,
pageSize: pageState.size,
total: pageState.total,
},
});
}
function onCreate() {
modalApi.setData({});
modalApi.open();
}
function onUpdate(row: PermissionDefinitionDto) {
modalApi.setData(row);
modalApi.open();
}
function onDelete(row: PermissionDefinitionDto) {
Modal.confirm({
centered: true,
content: `${$t('AbpUi.ItemWillBeDeletedMessageWithFormat', [row.name])}`,
onOk: async () => {
await deleteApi(row.name);
message.success($t('AbpUi.SuccessfullyDeleted'));
onGet();
},
title: $t('AbpUi.AreYouSure'),
});
}
onMounted(onGet);
</script>
<template> <template>
<div></div> <GroupGrid :table-title="$t('AbpPermissionManagement.PermissionDefinitions')">
<template #toolbar-tools>
<Button
:icon="h(PlusOutlined)"
type="primary"
v-access:code="[GroupDefinitionsPermissions.Create]"
@click="onCreate"
>
{{ $t('AbpPermissionManagement.PermissionDefinitions:AddNew') }}
</Button>
</template>
<template #group="{ row: group }">
<VxeGrid
:columns="subGridColumns"
:data="group.permissions"
:tree-config="{
trigger: 'row',
rowField: 'name',
childrenField: 'children',
}"
>
<template #tenant="{ row: permission }">
<Tag color="blue">
{{ multiTenancySidesMap[permission.multiTenancySide] }}
</Tag>
</template>
<template #providers="{ row: permission }">
<template v-for="provider in permission.providers" :key="provider">
<Tag color="blue" style="margin: 5px">
{{ providersMap[provider] }}
</Tag>
</template>
</template>
<template #action="{ row: permission }">
<div class="flex flex-row">
<Button
:icon="h(EditOutlined)"
block
type="link"
v-access:code="[GroupDefinitionsPermissions.Update]"
@click="onUpdate(permission)"
>
{{ $t('AbpUi.Edit') }}
</Button>
<Button
v-if="!permission.isStatic"
:icon="h(DeleteOutlined)"
block
danger
type="link"
v-access:code="[GroupDefinitionsPermissions.Delete]"
@click="onDelete(permission)"
>
{{ $t('AbpUi.Delete') }}
</Button>
</div>
</template>
</VxeGrid>
</template>
</GroupGrid>
<PermissionDefinitionModal @change="() => onGet()" />
</template> </template>
<style scoped></style> <style scoped></style>

53
apps/vben5/packages/@abp/permission/src/components/definitions/permissions/types.ts

@ -0,0 +1,53 @@
import { $t } from '@vben/locales';
import { MultiTenancySides } from '../../../types/definitions';
export function useTypesMap() {
const multiTenancySidesMap: { [key: number]: string } = {
[MultiTenancySides.Both]: $t(
'AbpPermissionManagement.MultiTenancySides:Both',
),
[MultiTenancySides.Host]: $t(
'AbpPermissionManagement.MultiTenancySides:Host',
),
[MultiTenancySides.Tenant]: $t(
'AbpPermissionManagement.MultiTenancySides:Tenant',
),
};
const multiTenancySideOptions = [
{
label: multiTenancySidesMap[MultiTenancySides.Tenant],
value: MultiTenancySides.Tenant,
},
{
label: multiTenancySidesMap[MultiTenancySides.Host],
value: MultiTenancySides.Host,
},
{
label: multiTenancySidesMap[MultiTenancySides.Both],
value: MultiTenancySides.Both,
},
];
const providersMap: { [key: string]: string } = {
C: $t('AbpPermissionManagement.Providers:Client'),
O: $t('AbpPermissionManagement.Providers:OrganizationUnit'),
R: $t('AbpPermissionManagement.Providers:Role'),
U: $t('AbpPermissionManagement.Providers:User'),
};
const providerOptions = [
{ label: providersMap.R, value: 'R' },
{ label: providersMap.U, value: 'U' },
{ label: providersMap.O, value: 'O' },
{ label: providersMap.C, value: 'C' },
];
return {
multiTenancySideOptions,
multiTenancySidesMap,
providerOptions,
providersMap,
};
}

1
apps/vben5/packages/@abp/permission/src/constants/index.ts

@ -0,0 +1 @@
export * from './permissions';

20
apps/vben5/packages/@abp/permission/src/constants/permissions.ts

@ -0,0 +1,20 @@
/** 分组权限 */
export const GroupDefinitionsPermissions = {
/** 新增 */
Create: 'PermissionManagement.GroupDefinitions.Create',
Default: 'PermissionManagement.GroupDefinitions',
/** 删除 */
Delete: 'PermissionManagement.GroupDefinitions.Delete',
/** 更新 */
Update: 'PermissionManagement.GroupDefinitions.Update',
};
/** 权限定义权限 */
export const PermissionDefinitionsPermissions = {
/** 新增 */
Create: 'PermissionManagement.Definitions.Create',
Default: 'PermissionManagement.Definitions',
/** 删除 */
Delete: 'PermissionManagement.Definitions.Delete',
/** 更新 */
Update: 'PermissionManagement.Definitions.Update',
};

46
apps/vben5/packages/@abp/permission/src/types/definitions.ts

@ -0,0 +1,46 @@
import type { IHasExtraProperties } from '@abp/core';
export enum MultiTenancySides {
Both = 0x3,
Host = 0x2,
Tenant = 0x1,
}
interface PermissionDefinitionCreateOrUpdateDto extends IHasExtraProperties {
displayName: string;
isEnabled: boolean;
parentName?: string;
providers: string[];
stateCheckers: string;
}
interface PermissionDefinitionCreateDto
extends PermissionDefinitionCreateOrUpdateDto {
groupName: string;
name: string;
}
interface PermissionDefinitionDto extends IHasExtraProperties {
displayName: string;
groupName: string;
isEnabled: boolean;
isStatic: boolean;
multiTenancySide: MultiTenancySides;
name: string;
parentName?: string;
providers: string[];
stateCheckers: string;
}
interface PermissionDefinitionGetListInput {
filter?: string;
groupName?: string;
}
type PermissionDefinitionUpdateDto = PermissionDefinitionCreateOrUpdateDto;
export type {
PermissionDefinitionCreateDto,
PermissionDefinitionDto,
PermissionDefinitionGetListInput,
PermissionDefinitionUpdateDto,
};

27
apps/vben5/packages/@abp/permission/src/types/groups.ts

@ -0,0 +1,27 @@
import type { IHasExtraProperties } from '@abp/core';
interface PermissionGroupDefinitionCreateOrUpdateDto
extends IHasExtraProperties {
displayName: string;
}
interface PermissionGroupDefinitionCreateDto
extends PermissionGroupDefinitionCreateOrUpdateDto {
name: string;
}
interface PermissionGroupDefinitionDto extends IHasExtraProperties {
displayName: string;
isStatic: boolean;
name: string;
}
interface PermissionGroupDefinitionGetListInput {
filter?: string;
}
type PermissionGroupDefinitionUpdateDto =
PermissionGroupDefinitionCreateOrUpdateDto;
export type {
PermissionGroupDefinitionCreateDto,
PermissionGroupDefinitionDto,
PermissionGroupDefinitionGetListInput,
PermissionGroupDefinitionUpdateDto,
};

1
apps/vben5/packages/@abp/ui/package.json

@ -40,6 +40,7 @@
"@vben-core/shared": "workspace:*", "@vben-core/shared": "workspace:*",
"@vben-core/typings": "workspace:*", "@vben-core/typings": "workspace:*",
"@vben/common-ui": "workspace:*", "@vben/common-ui": "workspace:*",
"@vben/icons": "workspace:*",
"@vben/locales": "workspace:*", "@vben/locales": "workspace:*",
"@vben/plugins": "workspace:*", "@vben/plugins": "workspace:*",
"@vueuse/core": "catalog:", "@vueuse/core": "catalog:",

2
apps/vben5/packages/@abp/ui/src/adapter/vxe-table.ts

@ -22,7 +22,7 @@ setupVbenVxeTable({
minHeight: 180, minHeight: 180,
pagerConfig: { pagerConfig: {
pageSize: 10, pageSize: 10,
pageSizes: [10, 15, 25, 50, 100], pageSizes: [10, 25, 50, 100],
}, },
proxyConfig: { proxyConfig: {
autoLoad: true, autoLoad: true,

4
apps/vben5/packages/@abp/ui/src/components/CodeEditor.vue → apps/vben5/packages/@abp/ui/src/components/codeeditor/index.vue

@ -4,8 +4,8 @@ import { computed } from 'vue';
import { isString } from '@vben-core/shared/utils'; import { isString } from '@vben-core/shared/utils';
import CodeMirror from './codemirror/CodeMirror.vue'; import CodeMirror from '../codemirror/CodeMirror.vue';
import { MODE } from './codemirror/types'; import { MODE } from '../codemirror/types';
const props = defineProps({ const props = defineProps({
autoFormat: { default: true, type: Boolean }, autoFormat: { default: true, type: Boolean },

5
apps/vben5/packages/@abp/ui/src/components/index.ts

@ -1,2 +1,5 @@
export { default as CodeEditor } from './CodeEditor.vue'; export { default as CodeEditor } from './codeeditor/index.vue';
export * from './codemirror'; export * from './codemirror';
export { default as LocalizableInput } from './localizable-input/LocalizableInput.vue';
export { default as PropertyTable } from './properties/PropertyTable.vue';
export * from './properties/types';

177
apps/vben5/packages/@abp/ui/src/components/localizable-input/LocalizableInput.vue

@ -0,0 +1,177 @@
<script setup lang="ts">
import type { DefaultOptionType } from 'ant-design-vue/lib/select';
import { computed, shallowReactive, watch } from 'vue';
import { $t } from '@vben/locales';
import {
isNullOrWhiteSpace,
type LocalizableStringInfo,
useAbpStore,
useLocalizationSerializer,
} from '@abp/core';
import { Form, Input, Select } from 'ant-design-vue';
const props = defineProps<{
allowClear?: boolean;
disabled?: boolean;
value?: string;
}>();
const emits = defineEmits(['update:value', 'change']);
const ItemReset = Form.ItemRest;
const InputGroup = Input.Group;
interface State {
displayName?: string;
displayNames: DefaultOptionType[];
resourceName?: string;
}
const abpStore = useAbpStore();
const formItemContext = Form.useInjectFormItemContext();
const { deserialize, serialize } = useLocalizationSerializer();
const state = shallowReactive<State>({
displayNames: [] as any[],
});
const getIsFixed = computed(() => {
return state.resourceName === 'Fixed';
});
const getResources = computed(() => {
if (!abpStore.localization) {
return [];
}
const sources = Object.keys(abpStore.localization.resources).map((key) => {
return {
label: key,
value: key,
};
});
return [
{
label: $t('component.localizable_input.resources.fiexed.group'),
options: [
{
label: $t('component.localizable_input.resources.fiexed.label'),
value: 'Fixed',
},
],
value: 'F',
},
{
label: $t('component.localizable_input.resources.localization.group'),
options: sources,
value: 'R',
},
];
});
watch(
() => props.value,
(value) => {
const info = deserialize(value);
if (state.resourceName !== info.resourceName) {
state.resourceName = isNullOrWhiteSpace(info.resourceName)
? undefined
: info.resourceName;
handleResourceChange(state.resourceName, false);
}
if (state.displayName !== info.name) {
state.displayName = isNullOrWhiteSpace(info.name) ? undefined : info.name;
}
},
{
immediate: true,
},
);
function handleResourceChange(value?: string, triggerChanged?: boolean) {
state.displayNames = [];
const resources = abpStore.localization!.resources;
if (value && resources[value]) {
state.displayNames = Object.keys(resources[value].texts).map((key) => {
const labelText = resources[value]?.texts[key];
return {
label: labelText ?? key,
value: key,
};
});
}
state.displayName = undefined;
if (triggerChanged === true) {
triggerDisplayNameChange(state.displayName);
}
}
function handleDisplayNameChange(value?: string) {
triggerDisplayNameChange(value);
}
function triggerDisplayNameChange(value?: string) {
if (!value) {
return;
}
let updateValue = '';
if (getIsFixed.value) {
updateValue = `F:${value}`;
} else if (!isNullOrWhiteSpace(state.resourceName)) {
const info: LocalizableStringInfo = {
name: value,
resourceName: state.resourceName ?? '',
};
updateValue = serialize(info);
}
emits('change', updateValue);
emits('update:value', updateValue);
formItemContext.onFieldChange();
}
</script>
<template>
<div class="w-full">
<ItemReset>
<InputGroup>
<div class="flex flex-row gap-4">
<div class="basis-2/5">
<Select
v-model:value="state.resourceName"
:allow-clear="props.allowClear"
:disabled="props.disabled"
:options="getResources"
:placeholder="$t('component.localizable_input.placeholder')"
class="w-full"
@change="(value) => handleResourceChange(value?.toString(), true)"
/>
</div>
<div class="basis-3/5">
<Input
v-if="getIsFixed"
:allow-clear="props.allowClear"
:disabled="props.disabled"
:placeholder="
$t('component.localizable_input.resources.fiexed.placeholder')
"
:value="state.displayName"
autocomplete="off"
class="w-full"
@change="
(e) => handleDisplayNameChange(e.target.value?.toString())
"
/>
<Select
v-else
:allow-clear="props.allowClear"
:disabled="props.disabled"
:options="state.displayNames"
:placeholder="
$t(
'component.localizable_input.resources.localization.placeholder',
)
"
:value="state.displayName"
class="w-full"
@change="(e) => handleDisplayNameChange(e?.toString())"
/>
</div>
</div>
</InputGroup>
</ItemReset>
</div>
</template>

66
apps/vben5/packages/@abp/ui/src/components/properties/PropertyModal.vue

@ -0,0 +1,66 @@
<script setup lang="ts">
import type { PropertyInfo } from './types';
import { useVbenForm, useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
defineOptions({
name: 'PropertyModal',
});
const emits = defineEmits<{
(event: 'change', data: PropertyInfo): void;
}>();
const [Form, formApi] = useVbenForm({
handleSubmit: onSubmit,
schema: [
{
component: 'Input',
componentProps: {
autocomplete: 'off',
},
fieldName: 'key',
label: $t('component.extra_property_dictionary.key'),
rules: 'required',
},
{
component: 'Input',
componentProps: {
autocomplete: 'off',
},
fieldName: 'value',
label: $t('component.extra_property_dictionary.value'),
rules: 'required',
},
],
showDefaultActions: false,
});
const [Modal, modalApi] = useVbenModal({
class: 'w-1/2',
draggable: true,
fullscreenButton: false,
onCancel() {
modalApi.close();
},
onConfirm: async () => {
await formApi.validateAndSubmitForm();
},
title: $t('component.extra_property_dictionary.title'),
});
function onSubmit(input: Record<string, any>) {
emits('change', {
key: input.key,
value: input.value,
});
modalApi.close();
}
</script>
<template>
<Modal>
<Form />
</Modal>
</template>
<style scoped></style>

133
apps/vben5/packages/@abp/ui/src/components/properties/PropertyTable.vue

@ -0,0 +1,133 @@
<script setup lang="ts">
import type { TableColumnsType } from 'ant-design-vue';
import type { PropertyInfo, PropertyProps } from './types';
import { computed, defineAsyncComponent } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import { $t } from '@vben/locales';
import { Button, Popconfirm, Table } from 'ant-design-vue';
defineOptions({
name: 'PropertyTable',
});
const props = withDefaults(defineProps<PropertyProps>(), {
allowDelete: true,
allowEdit: true,
disabled: false,
});
const emits = defineEmits<{
(event: 'change', data: PropertyInfo): void;
(event: 'delete', data: PropertyInfo): void;
}>();
const DeleteOutlined = createIconifyIcon('ant-design:delete-outlined');
const PlusOutlined = createIconifyIcon('ant-design:plus-outlined');
const getDataResource = computed((): PropertyInfo[] => {
if (!props.data) return [];
return Object.keys(props.data).map((item) => {
return {
key: item,
value: props.data![item]!,
};
});
});
const [PropertyModal, modalApi] = useVbenModal({
connectedComponent: defineAsyncComponent(() => import('./PropertyModal.vue')),
});
const getTableColumns = computed(() => {
const columns: TableColumnsType<PropertyInfo> = [
{
align: 'left',
dataIndex: 'key',
fixed: 'left',
minWidth: 100,
title: $t('component.extra_property_dictionary.key'),
},
{
align: 'left',
dataIndex: 'value',
fixed: 'left',
title: $t('component.extra_property_dictionary.value'),
},
];
return [
...columns,
...(props.disabled
? []
: [
{
align: 'center',
dataIndex: 'action',
fixed: 'right',
key: 'action',
title: $t('component.extra_property_dictionary.actions.title'),
width: 150,
},
]),
];
});
function onCreate() {
modalApi.open();
}
function onDelete(prop: Record<string, string>) {
emits('delete', {
key: prop.key!,
value: prop.value!,
});
}
function onChange(prop: Record<string, string>) {
emits('change', {
key: prop.key!,
value: prop.value!,
});
}
</script>
<template>
<div class="flex flex-col gap-4">
<div class="flex flex-row justify-end">
<Button
v-if="!props.disabled && props.allowEdit"
class="flex items-center gap-2"
type="primary"
@click="onCreate"
>
<template #icon>
<PlusOutlined class="inline" />
</template>
{{ $t('component.extra_property_dictionary.actions.create') }}
</Button>
</div>
<div class="justify-center">
<Table :columns="getTableColumns" :data-source="getDataResource">
<template #bodyCell="{ record, column }">
<template v-if="column.dataIndex === 'action'">
<Popconfirm
v-if="props.allowDelete"
:title="`${$t('component.extra_property_dictionary.itemWillBeDeleted', [record.key])}`"
@confirm="onDelete(record)"
>
<Button block class="flex items-center gap-2" danger type="link">
<template #icon>
<DeleteOutlined class="inline" />
</template>
{{ $t('component.extra_property_dictionary.actions.delete') }}
</Button>
</Popconfirm>
</template>
</template>
</Table>
</div>
<PropertyModal @change="onChange" />
</div>
</template>
<style scoped></style>

14
apps/vben5/packages/@abp/ui/src/components/properties/types.ts

@ -0,0 +1,14 @@
import type { Dictionary } from '@abp/core';
interface PropertyInfo {
key: string;
value: string;
}
interface PropertyProps {
allowDelete?: boolean;
allowEdit?: boolean;
data?: Dictionary<string, string>;
disabled?: boolean;
}
export type { PropertyInfo, PropertyProps };
Loading…
Cancel
Save