From 7b68c0b3c0e219c3c4646580df4283bba1680fa4 Mon Sep 17 00:00:00 2001 From: Simon Larsen Date: Tue, 7 Jan 2025 18:59:34 +0000 Subject: [PATCH] feat: refactor permission handling by extracting getFieldPermissions function --- Common/UI/Components/Forms/ModelForm.tsx | 51 +++++++++++++++++++----- 1 file changed, 41 insertions(+), 10 deletions(-) diff --git a/Common/UI/Components/Forms/ModelForm.tsx b/Common/UI/Components/Forms/ModelForm.tsx index a0fb3ead335..3e5414ffee6 100644 --- a/Common/UI/Components/Forms/ModelForm.tsx +++ b/Common/UI/Components/Forms/ModelForm.tsx @@ -188,16 +188,7 @@ const ModelForm: ( userPermissions.push(Permission.Public); - const accessControl: Dictionary = - model.getColumnAccessControlForAllColumns(); - - let fieldPermissions: Array = []; - - if (FormType.Create === props.formType) { - fieldPermissions = accessControl[fieldName]?.create || []; - } else { - fieldPermissions = accessControl[fieldName]?.update || []; - } + const fieldPermissions: Array = getFieldPermissions(fieldName); if ( fieldPermissions && @@ -212,6 +203,23 @@ const ModelForm: ( return false; }; + const getFieldPermissions: (fieldName: string) => Array = ( + fieldName: string, + ): Array => { + const accessControl: Dictionary = + model.getColumnAccessControlForAllColumns(); + + let fieldPermissions: Array = []; + + if (FormType.Create === props.formType) { + fieldPermissions = accessControl[fieldName]?.create || []; + } else { + fieldPermissions = accessControl[fieldName]?.update || []; + } + + return fieldPermissions; + }; + const setFormFields: PromiseVoidFunction = async (): Promise => { let fieldsToSet: Fields = []; @@ -278,6 +286,29 @@ const ModelForm: ( fieldsToSet = await fetchDropdownOptions(fieldsToSet); + // if there are no fields to set, then show permission erorr. This is useful when there are no fields to show. + if (fieldsToSet.length === 0 && props.fields.length > 0) { + const field: ModelField | undefined = props.fields[0]; + + if (field) { + const fieldName: string | undefined = Object.keys(field.field || {})[0]; + + if (fieldName) { + const fieldPermisisons: Array = + getFieldPermissions(fieldName); + + const columnMetadata: TableColumnMetadata = + model.getTableColumnMetadata(fieldName); + + setError( + `You don't have enough permissions to ${ + props.formType === FormType.Create ? "create" : "edit" + } ${columnMetadata.title} on ${model.singularName}. You need one of the following permissions: ${fieldPermisisons.join(", ")}`, + ); + } + } + } + setFields(fieldsToSet); };