feat: improve code

This commit is contained in:
chenos 2021-08-11 11:18:10 +08:00
parent c1dfc8b2f5
commit 66549dc4bf
7 changed files with 108 additions and 74 deletions

View File

@ -17,7 +17,7 @@ import { middlewares } from '@nocobase/server';
useStaticServer: !(process.env.APP_USE_STATIC_SERVER === 'false' || !process.env.APP_USE_STATIC_SERVER), useStaticServer: !(process.env.APP_USE_STATIC_SERVER === 'false' || !process.env.APP_USE_STATIC_SERVER),
})); }));
await api.database.getModel('collections').load({ skipExisting: true }); await api.database.getModel('collections').load();
api.listen(process.env.API_PORT, () => { api.listen(process.env.API_PORT, () => {
console.log(`http://localhost:${process.env.API_PORT}/`); console.log(`http://localhost:${process.env.API_PORT}/`);

View File

@ -21,7 +21,8 @@ import * as uiSchema from './ui-schema';
const Collection = database.getModel('collections'); const Collection = database.getModel('collections');
const collection = await Collection.create(config); const collection = await Collection.create(config);
await collection.updateAssociations({ await collection.updateAssociations({
generalFields: config.fields, generalFields: config.fields.filter(field => field.state !== 0),
systemFields: config.fields.filter(field => field.state === 0),
}); });
await collection.migrate(); await collection.migrate();

View File

@ -31,12 +31,13 @@ const useActionDataSource = () => {
const field = useField<Formily.Core.Models.ArrayField>(); const field = useField<Formily.Core.Models.ArrayField>();
const dataSource = []; const dataSource = [];
for (const [actionName, value] of actionTypeMap) { for (const [actionName, value] of actionTypeMap) {
const index = field?.value?.findIndex((item) => { const item = field?.value?.find((item) => {
return item.actionName === actionName; return item.actionName === actionName;
}); });
dataSource.push({ dataSource.push({
actionName, actionName,
enable: index > -1, ...item,
enable: !!item,
}); });
} }
return dataSource; return dataSource;
@ -52,7 +53,9 @@ const useFieldPermissions = () => {
return item.actionName === actionName; return item.actionName === actionName;
}); });
return ( return (
item?.fieldPermissions?.map((permission) => permission.field_key) || [] item?.fields?.map((field) => {
return typeof field === 'string' ? field : field.key;
}) || []
); );
}; };
const service = useRequest( const service = useRequest(
@ -86,7 +89,7 @@ const useFieldPermissions = () => {
update: findFieldKeys('update'), update: findFieldKeys('update'),
destroy: findFieldKeys('destroy'), destroy: findFieldKeys('destroy'),
create: findFieldKeys('create'), create: findFieldKeys('create'),
} };
const renderCell = (actionName, value, record) => { const renderCell = (actionName, value, record) => {
return ( return (
<Checkbox <Checkbox
@ -95,67 +98,83 @@ const useFieldPermissions = () => {
let fieldIndex = field?.value?.findIndex((item) => { let fieldIndex = field?.value?.findIndex((item) => {
return item.actionName === actionName; return item.actionName === actionName;
}); });
console.log('fieldIndex', fieldIndex)
if (e.target.checked) { if (e.target.checked) {
if (fieldIndex === -1) { if (fieldIndex === -1) {
field.push({ field.push({
actionName, actionName,
collection_name: ctx.record.name, collection_name: ctx.record.name,
role_name: role.name, role_name: role.name,
fieldPermissions: [{ fields: [record.field.key],
field_key: record.field.key,
}],
}); });
} else { } else {
const permissions = field.value[fieldIndex].fieldPermissions || []; const fields = field.value[fieldIndex].fields || [];
permissions.push({ fields.push(record.field.key);
field_key: record.field.key, field.value[fieldIndex].fields = fields;
}
} else if (fieldIndex > -1) {
const fields: any[] = field.value[fieldIndex].fields || [];
const index = fields?.findIndex((field) => {
let fieldKey = field;
if (typeof fieldKey === 'object') {
fieldKey = fieldKey.key;
}
return fieldKey === record?.field?.key;
}); });
field.value[fieldIndex].fieldPermissions = permissions; if (index > -1) {
console.log('fieldIndex', permissions); fields.splice(index, 1);
field.value[fieldIndex].fields = [...fields];
} }
} }
// fieldIndex = field.value.length - 1;
// const permissions: any[] =
// field.value[fieldIndex].fieldPermissions || [];
// const index = permissions?.findIndex(
// (permission) => permission.field_key === record?.field?.key,
// );
// if (e.target.checked) {
// permissions.push({
// field_key: record.field.key,
// });
// } else {
// permissions.splice(index, 1);
// }
// console.log({ permissions });
// field.value[fieldIndex].fieldPermissions = permissions;
}} }}
/> />
); );
}; };
const columns = [ const ColumnTitle = ({ actionName }) => {
{ const checked =
dataSource?.length > 0 && keys[actionName]?.length === dataSource?.length;
return (
<div>
<Checkbox
checked={checked}
onChange={(e) => {
let fieldIndex = field?.value?.findIndex((item) => {
return item.actionName === actionName;
});
if (e.target.checked) {
if (fieldIndex === -1) {
field.push({
actionName,
collection_name: ctx.record.name,
role_name: role.name,
fields: dataSource?.map((item) => {
return item?.field?.key;
}),
});
} else {
field.value[fieldIndex].fields = dataSource?.map((item) => {
return item?.field?.key;
});
}
} else {
if (fieldIndex > -1) {
field.value[fieldIndex].fields = [];
}
}
}}
/>{' '}
{actionTypeMap.get(actionName)}
</div>
);
};
const columns: any[] = ['create', 'get', 'update'].map((actionName) => ({
title: <ColumnTitle actionName={actionName} />,
dataIndex: actionName,
render: (value, record) => renderCell(actionName, value, record),
}));
columns.unshift({
title: '字段名称', title: '字段名称',
dataIndex: ['field', 'uiSchema', 'title'], dataIndex: ['field', 'uiSchema', 'title'],
}, });
{
title: <div> <Checkbox /></div>,
dataIndex: 'create',
render: (value, record) => renderCell('create', value, record),
},
{
title: '查看',
dataIndex: 'get',
render: (value, record) => renderCell('get', value, record),
},
{
title: '编辑',
dataIndex: 'update',
render: (value, record) => renderCell('update', value, record),
},
];
return { columns, dataSource, service }; return { columns, dataSource, service };
}; };
@ -165,7 +184,7 @@ export const ActionPermissionField = observer((props) => {
const field = useField<Formily.Core.Models.ArrayField>(); const field = useField<Formily.Core.Models.ArrayField>();
const actionDataSource = useActionDataSource(); const actionDataSource = useActionDataSource();
const { columns, dataSource, service } = useFieldPermissions(); const { columns, dataSource, service } = useFieldPermissions();
console.log('field?.value', field?.value); console.log('actionPermissions', field?.value);
return ( return (
<div> <div>
<Table <Table
@ -209,7 +228,7 @@ export const ActionPermissionField = observer((props) => {
collection_name: ctx.record.name, collection_name: ctx.record.name,
role_name: role.name, role_name: role.name,
actionName: record.actionName, actionName: record.actionName,
fieldPermissions: [], fields: [],
}); });
} }
} else { } else {

View File

@ -6,12 +6,12 @@ import { useCollectionsContext } from '../../../constate/Collections';
import { Button } from 'antd'; import { Button } from 'antd';
import { LockOutlined } from '@ant-design/icons'; import { LockOutlined } from '@ant-design/icons';
import cls from 'classnames'; import cls from 'classnames';
import { uid } from '@formily/shared'; import { uid, isValid } from '@formily/shared';
import { Resource } from '../../../resource'; import { Resource } from '../../../resource';
import { TableRowContext, useTable } from '../../../schemas/table'; import { TableRowContext, useTable } from '../../../schemas/table';
import { useRequest } from 'ahooks'; import { useRequest } from 'ahooks';
import { VisibleContext } from '../../../context'; import { VisibleContext } from '../../../context';
import { connect, ISchema, observer } from '@formily/react'; import { connect, ISchema, observer, useForm } from '@formily/react';
import { DescriptionsContext } from '../../../schemas/form'; import { DescriptionsContext } from '../../../schemas/form';
import { createContext } from 'react'; import { createContext } from 'react';
import { ActionPermissionField } from './ActionPermissionField'; import { ActionPermissionField } from './ActionPermissionField';
@ -51,9 +51,16 @@ class ActionPermissionResource extends Resource {
} }
const useActionPermissionSubmit = () => { const useActionPermissionSubmit = () => {
const form = useForm();
const role = useContext(RoleContext);
const resource = Resource.make({
resourceName: 'roles',
resourceKey: role.name,
});
return { return {
async run() { async run() {
console.log('useActionPermissionSubmit'); await resource.save(form.values);
console.log('useActionPermissionSubmit', form.values?.actionPermissions);
}, },
}; };
}; };
@ -74,14 +81,25 @@ const useActionPermissionResource = ({ onSuccess }) => {
role_name: role.name, role_name: role.name,
collection_name: ctx.record.name, collection_name: ctx.record.name,
}, },
appends: ['fieldPermissions'], appends: ['fields'],
}); });
}, },
{ {
formatResult: (result) => result?.data, formatResult: (result) => result?.data,
onSuccess(data) { onSuccess(data) {
console.log('actionPermissions', data);
onSuccess({ onSuccess({
permissions: data, actionPermissions: data.map((permission) => {
const item: any = {}
Object.keys(permission).forEach(key => {
if (isValid(permission[key])) {
item[key] = permission[key];
}
});
item.fields =
permission?.fields.map((field) => field.key) || [];
return item;
}),
}); });
}, },
manual: true, manual: true,
@ -185,7 +203,7 @@ const collectionSchema: ISchema = {
useOkAction: useActionPermissionSubmit, useOkAction: useActionPermissionSubmit,
}, },
properties: { properties: {
permissions: { actionPermissions: {
type: 'array', type: 'array',
'x-component': 'ActionPermissionField', 'x-component': 'ActionPermissionField',
}, },
@ -366,7 +384,6 @@ const schema: ISchema = {
displayName: 'destroy', displayName: 'destroy',
}, },
'x-component': 'Action', 'x-component': 'Action',
'x-designable-bar': 'Table.Action.DesignableBar',
'x-component-props': { 'x-component-props': {
useAction: '{{ Table.useTableDestroyAction }}', useAction: '{{ Table.useTableDestroyAction }}',
}, },

View File

@ -62,7 +62,7 @@ const FormMain = (props: any) => {
const { resource, run, service } = useResource({ const { resource, run, service } = useResource({
onSuccess: (initialValues: any) => { onSuccess: (initialValues: any) => {
console.log('onSuccess', { initialValues }); console.log('onSuccess', { initialValues });
form.setInitialValues(initialValues); // form.setInitialValues(initialValues);
form.setValues(initialValues); form.setValues(initialValues);
}, },
}); });

View File

@ -8,12 +8,17 @@ export default {
type: 'uid', type: 'uid',
name: 'name', name: 'name',
primaryKey: true, primaryKey: true,
prefix: 't_', prefix: 'r_',
}, },
{ {
type: 'string', type: 'string',
name: 'title', name: 'title',
}, },
{
type: 'hasMany',
name: 'actionPermissions',
target: 'action_permissions',
},
{ {
type: 'belongsToMany', type: 'belongsToMany',
name: 'users', name: 'users',

View File

@ -50,11 +50,7 @@ export default {
unique: true, unique: true,
hidden: true, hidden: true,
privilege: 'undelete', privilege: 'undelete',
uiSchema: { state: 0,
type: 'string',
title: 'Token',
'x-component': 'Password',
},
}, },
{ {
interface: 'password', interface: 'password',
@ -63,11 +59,7 @@ export default {
unique: true, unique: true,
hidden: true, hidden: true,
privilege: 'undelete', privilege: 'undelete',
uiSchema: { state: 0,
type: 'string',
title: 'Reset Token',
'x-component': 'Password',
},
}, },
], ],
} as TableOptions; } as TableOptions;