Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Made all mgramseva changes into workbench-develop #1438

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -66,16 +66,16 @@ const MDMSAdd = ({ defaultFormData, updatesToUISchema, screenType = "add", onVie
const body = api?.requestBody
? { ...api?.requestBody }
: {
Mdms: {
tenantId: tenantId,
schemaCode: `${moduleName}.${masterName}`,
uniqueIdentifier: null,
data: {},
isActive: true,
},
};
Mdms: {
tenantId: tenantId,
schemaCode: `${moduleName}.${masterName}`,
uniqueIdentifier: null,
data: {},
isActive: true,
},
};
const reqCriteriaAdd = {
url: api ? api?.url : Digit.Utils.workbench.getMDMSActionURL(moduleName,masterName,"create"),
url: api ? api?.url : Digit.Utils.workbench.getMDMSActionURL(moduleName, masterName, "create"),
params: {},
body: { ...body },
config: {
Expand All @@ -86,11 +86,13 @@ const MDMSAdd = ({ defaultFormData, updatesToUISchema, screenType = "add", onVie
},
};

const gotoView = () => {
const gotoView = () => {
setTimeout(() => {
history.push(`/${window?.contextPath}/employee/workbench/mdms-view?moduleName=${moduleName}&masterName=${masterName}${from ? `&from=${from}` : ""}`)
history.push(
`/${window?.contextPath}/employee/workbench/mdms-view?moduleName=${moduleName}&masterName=${masterName}${from ? `&from=${from}` : ""}`
);
}, 2000);
}
};

const mutation = Digit.Hooks.useCustomAPIMutationHook(reqCriteriaAdd);
const onSubmit = (data) => {
Expand Down Expand Up @@ -203,12 +205,47 @@ const MDMSAdd = ({ defaultFormData, updatesToUISchema, screenType = "add", onVie
}
const uiJSONSchema = formSchema?.["definition"]?.["x-ui-schema"];

function updateAllPropertiesBasedOnUIOrder(schema) {
// Iterate through all properties in schema.definition.properties
for (let propertyName in schema.definition.properties) {
let targetProperty = schema.definition.properties[propertyName];

// Check if the property has items and the x-ui-schema with a ui:order field
if (targetProperty.items && targetProperty.items["x-ui-schema"] && targetProperty.items["x-ui-schema"]["ui:order"]) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Refactor conditional check using optional chaining

The conditional statement can be simplified by using optional chaining, enhancing readability and reducing code complexity.

Update the condition as follows:

- if (targetProperty.items && targetProperty.items["x-ui-schema"] && targetProperty.items["x-ui-schema"]["ui:order"]) {
+ if (targetProperty.items?.["x-ui-schema"]?.["ui:order"]) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (targetProperty.items && targetProperty.items["x-ui-schema"] && targetProperty.items["x-ui-schema"]["ui:order"]) {
if (targetProperty.items?.["x-ui-schema"]?.["ui:order"]) {
🧰 Tools
🪛 Biome

[error] 214-214: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

const orderArray = targetProperty.items["x-ui-schema"]["ui:order"];
let properties = targetProperty.items.properties;

// Create a new properties object sorted by ui:order
let sortedProperties = {};

// Sort properties according to the orderArray
orderArray.forEach((key) => {
if (properties.hasOwnProperty(key)) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Use Object.hasOwn() instead of hasOwnProperty

Accessing hasOwnProperty directly can be unsafe if the object has a custom hasOwnProperty property. It's recommended to use Object.hasOwn() for reliability.

Modify the code as follows:

- if (properties.hasOwnProperty(key)) {
+ if (Object.hasOwn(properties, key)) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (properties.hasOwnProperty(key)) {
if (Object.hasOwn(properties, key)) {
🧰 Tools
🪛 Biome

[error] 223-223: Do not access Object.prototype method 'hasOwnProperty' from target object.

It's recommended using Object.hasOwn() instead of using Object.hasOwnProperty().
See MDN web docs for more details.

(lint/suspicious/noPrototypeBuiltins)

sortedProperties[key] = properties[key];
}
});

// Add remaining properties that were not in the orderArray
for (let key in properties) {
if (!sortedProperties.hasOwnProperty(key)) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Use Object.hasOwn() instead of hasOwnProperty

For consistency and to prevent potential issues, replace hasOwnProperty with Object.hasOwn().

Update the code:

- if (!sortedProperties.hasOwnProperty(key)) {
+ if (!Object.hasOwn(sortedProperties, key)) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (!sortedProperties.hasOwnProperty(key)) {
if (!Object.hasOwn(sortedProperties, key)) {
🧰 Tools
🪛 Biome

[error] 230-230: Do not access Object.prototype method 'hasOwnProperty' from target object.

It's recommended using Object.hasOwn() instead of using Object.hasOwnProperty().
See MDN web docs for more details.

(lint/suspicious/noPrototypeBuiltins)

sortedProperties[key] = properties[key];
}
}

// Re-assign the sorted properties back to the schema
targetProperty.items.properties = sortedProperties;
}
}

return schema;
}

return (
<React.Fragment>
{spinner && <DigitLoader />}
{formSchema && (
<DigitJSONForm
schema={formSchema}
schema={updateAllPropertiesBasedOnUIOrder(formSchema)}
onFormChange={onFormValueChange}
onFormError={onFormError}
formData={session}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,32 +1,32 @@
import React,{useState} from 'react'
import MDMSAdd from './MDMSAddV2'
import { Loader,Toast } from '@egovernments/digit-ui-react-components';
import React, { useState } from "react";
import MDMSAdd from "./MDMSAddV2";
import { Loader, Toast } from "@egovernments/digit-ui-react-components";
import { useTranslation } from "react-i18next";
import { useHistory } from "react-router-dom";
const MDMSEdit = ({...props}) => {
const history = useHistory()
const MDMSEdit = ({ ...props }) => {
const history = useHistory();

const { t } = useTranslation()
const { t } = useTranslation();

const { moduleName, masterName, tenantId,uniqueIdentifier, from } = Digit.Hooks.useQueryParams();
const { moduleName, masterName, tenantId, uniqueIdentifier, from } = Digit.Hooks.useQueryParams();
const stateId = Digit.ULBService.getCurrentTenantId();

const [showToast, setShowToast] = useState(false);
const [renderLoader,setRenderLoader] = useState(false)
const [renderLoader, setRenderLoader] = useState(false);
const reqCriteria = {
url: `/${Digit.Hooks.workbench.getMDMSContextPath()}/v2/_search`,
params: {},
body: {
MdmsCriteria: {
tenantId: stateId,
uniqueIdentifiers:[uniqueIdentifier],
schemaCode:`${moduleName}.${masterName}`
uniqueIdentifiers: [uniqueIdentifier],
schemaCode: `${moduleName}.${masterName}`,
},
},
config: {
enabled: moduleName && masterName && true,
select: (data) => {
return data?.mdms?.[0]
return data?.mdms?.[0];
},
},
};
Expand All @@ -37,79 +37,73 @@ const MDMSEdit = ({...props}) => {
body: {
SchemaDefCriteria: {
tenantId: stateId,
codes:[`${moduleName}.${masterName}`]
codes: [`${moduleName}.${masterName}`],
},
},
config: {
enabled: moduleName && masterName && true,
select: (data) => {
const uniqueFields = data?.SchemaDefinitions?.[0]?.definition?.["x-unique"]
const updatesToUiSchema = {}
uniqueFields.forEach(field => updatesToUiSchema[field] = {"ui:readonly":true})
return {schema:data?.SchemaDefinitions?.[0],updatesToUiSchema}
select: (data) => {
const uniqueFields = data?.SchemaDefinitions?.[0]?.definition?.["x-unique"];
const updatesToUiSchema = {};
uniqueFields.forEach((field) => (updatesToUiSchema[field] = { "ui:readonly": true }));
return { schema: data?.SchemaDefinitions?.[0], updatesToUiSchema };
},
},
changeQueryName:"schema"
changeQueryName: "schema",
};

const closeToast = () => {
setTimeout(() => {
setShowToast(null)
setShowToast(null);
}, 5000);
}
};

const gotoView = () => {
const gotoView = () => {
setTimeout(() => {
setRenderLoader(true)
history.push(`/${window?.contextPath}/employee/workbench/mdms-view?moduleName=${moduleName}&masterName=${masterName}&uniqueIdentifier=${uniqueIdentifier}${from ? `&from=${from}` : ""}`)
setRenderLoader(true);
history.goBack();
}, 2000);
}
};

const { isLoading, data, isFetching } = Digit.Hooks.useCustomAPIHook(reqCriteria);
const { isLoading:isLoadingSchema,data: schemaData,isFetching: isFetchingSchema,...rest } = Digit.Hooks.useCustomAPIHook(reqCriteriaSchema);

const { isLoading: isLoadingSchema, data: schemaData, isFetching: isFetchingSchema, ...rest } = Digit.Hooks.useCustomAPIHook(reqCriteriaSchema);

const reqCriteriaUpdate = {
url: Digit.Utils.workbench.getMDMSActionURL(moduleName,masterName,"update"),
url: Digit.Utils.workbench.getMDMSActionURL(moduleName, masterName, "update"),
params: {},
body: {

},
body: {},
config: {
enabled: true,
},
};
const mutation = Digit.Hooks.useCustomAPIMutationHook(reqCriteriaUpdate);

const handleUpdate = async (formData) => {

const onSuccess = (resp) => {

setShowToast({
label:`${t("WBH_SUCCESS_UPD_MDMS_MSG")} ${resp?.mdms?.[0]?.id}`
label: `${t("WBH_SUCCESS_UPD_MDMS_MSG")} ${resp?.mdms?.[0]?.id}`,
});
// closeToast()
gotoView()
gotoView();
};

const onError = (resp) => {
setShowToast({
label:`${t("WBH_ERROR_MDMS_DATA")} ${t(resp?.response?.data?.Errors?.[0]?.code)}`,
isError:true
label: `${t("WBH_ERROR_MDMS_DATA")} ${t(resp?.response?.data?.Errors?.[0]?.code)}`,
isError: true,
});

closeToast()
};

closeToast();
};

mutation.mutate(
{
url:reqCriteriaUpdate?.url,
url: reqCriteriaUpdate?.url,
params: {},
body: {
Mdms:{
Mdms: {
...data,
data:formData
data: formData,
},
},
},
Expand All @@ -118,17 +112,16 @@ const MDMSEdit = ({...props}) => {
onSuccess,
}
);
};

}
if (isLoading || isLoadingSchema || renderLoader) return <Loader />;

if(isLoading || isLoadingSchema || renderLoader ) return <Loader />

return (
<React.Fragment>
<MDMSAdd defaultFormData = {data?.data} screenType={"edit"} onSubmitEditAction={handleUpdate} updatesToUISchema ={schemaData?.updatesToUiSchema} />
{showToast && <Toast label={t(showToast.label)} error={showToast?.isError} onClose={()=>setShowToast(null)} ></Toast>}
<MDMSAdd defaultFormData={data?.data} screenType={"edit"} onSubmitEditAction={handleUpdate} updatesToUISchema={schemaData?.updatesToUiSchema} />
{showToast && <Toast label={t(showToast.label)} error={showToast?.isError} onClose={() => setShowToast(null)}></Toast>}
</React.Fragment>
)
}
);
Comment on lines +117 to +124
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

Issue: updatesToUISchema prop is not handled in MDMSAdd component.

The MDMSEdit.js file passes the updatesToUISchema prop to the MDMSAdd component. However, the base MDMSAdd.js does not handle this prop, which may lead to unintended behavior.

  • File: micro-ui/web/micro-ui-internals/packages/modules/workbench/src/pages/employee/MDMSAdd.js
🔗 Analysis chain

LGTM: Rendering logic with a new prop.

The changes to the rendering logic are mostly formatting improvements that enhance readability. However, there's a notable change:

  • The MDMSAdd component now receives an updatesToUISchema prop derived from schemaData.

This addition might affect the behavior of the MDMSAdd component.

Please verify that the MDMSAdd component correctly handles the updatesToUISchema prop and that it's being used as intended. You can run the following script to check the usage of this prop in the MDMSAdd component:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the usage of updatesToUISchema prop in MDMSAdd component

# Test: Search for the MDMSAdd component definition and its usage
rg --type js -A 10 'const MDMSAdd =' micro-ui/web/micro-ui-internals/packages/modules/workbench/src/pages/employee/
rg --type js -A 5 '<MDMSAdd' micro-ui/web/micro-ui-internals/packages/modules/workbench/src/pages/employee/

Length of output: 8525

};

export default MDMSEdit
export default MDMSEdit;