diff --git a/frontend/micro-ui/web/micro-ui-internals/example/src/UICustomizations.js b/frontend/micro-ui/web/micro-ui-internals/example/src/UICustomizations.js index 981a9b5e1..9c69ef687 100644 --- a/frontend/micro-ui/web/micro-ui-internals/example/src/UICustomizations.js +++ b/frontend/micro-ui/web/micro-ui-internals/example/src/UICustomizations.js @@ -1,12 +1,12 @@ import { Link } from "react-router-dom"; import _ from "lodash"; +import { useTranslation } from "react-i18next"; //create functions here based on module name set in mdms(eg->SearchProjectConfig) //how to call these -> Digit?.Customizations?.[masterName]?.[moduleName] // these functions will act as middlewares var Digit = window.Digit || {}; - function anonymizeHalfString(input) { // Initialize an empty string to store the anonymized output let anonymized = ""; @@ -26,8 +26,7 @@ function anonymizeHalfString(input) { } const businessServiceMap = { - - "muster roll": "MR" + "muster roll": "MR", }; const inboxModuleNameMap = { @@ -37,7 +36,6 @@ const inboxModuleNameMap = { export const UICustomizations = { businessServiceMap, updatePayload: (applicationDetails, data, action, businessService) => { - if (businessService === businessServiceMap.estimate) { const workflow = { comment: data.comments, @@ -88,6 +86,7 @@ export const UICustomizations = { workflow, }; } + if (businessService === businessServiceMap?.["muster roll"]) { const workflow = { comment: data?.comments, @@ -113,7 +112,7 @@ export const UICustomizations = { workflow, }; } - if(businessService === businessServiceMap?.["works.purchase"]){ + if (businessService === businessServiceMap?.["works.purchase"]) { const workflow = { comment: data.comments, documents: data?.documents?.map((document) => { @@ -134,21 +133,21 @@ export const UICustomizations = { }); const additionalFieldsToSet = { - projectId:applicationDetails.additionalDetails.projectId, - invoiceDate:applicationDetails.billDate, - invoiceNumber:applicationDetails.referenceId.split('_')?.[1], - contractNumber:applicationDetails.referenceId.split('_')?.[0], - documents:applicationDetails.additionalDetails.documents - } + projectId: applicationDetails.additionalDetails.projectId, + invoiceDate: applicationDetails.billDate, + invoiceNumber: applicationDetails.referenceId.split("_")?.[1], + contractNumber: applicationDetails.referenceId.split("_")?.[0], + documents: applicationDetails.additionalDetails.documents, + }; return { - bill: {...applicationDetails,...additionalFieldsToSet}, + bill: { ...applicationDetails, ...additionalFieldsToSet }, workflow, }; } }, - enableModalSubmit:(businessService,action,setModalSubmit,data)=>{ - if(businessService === businessServiceMap?.["muster roll"] && action.action==="APPROVE"){ - setModalSubmit(data?.acceptTerms) + enableModalSubmit: (businessService, action, setModalSubmit, data) => { + if (businessService === businessServiceMap?.["muster roll"] && action.action === "APPROVE") { + setModalSubmit(data?.acceptTerms); } }, enableHrmsSearch: (businessService, action) => { @@ -158,11 +157,11 @@ export const UICustomizations = { if (businessService === businessServiceMap.contract) { return action.action.includes("VERIFY_AND_FORWARD"); } - if (businessService === businessServiceMap?.["muster roll"]) { + if (businessService === businessServiceMap?.["muster roll"]) { return action.action.includes("VERIFY"); } - if(businessService === businessServiceMap?.["works.purchase"]){ - return action.action.includes("VERIFY_AND_FORWARD") + if (businessService === businessServiceMap?.["works.purchase"]) { + return action.action.includes("VERIFY_AND_FORWARD"); } return false; }, @@ -173,17 +172,13 @@ export const UICustomizations = { return businessServiceMap?.contract; } else if (moduleCode?.includes("muster roll")) { return businessServiceMap?.["muster roll"]; - } - else if (moduleCode?.includes("works.purchase")) { + } else if (moduleCode?.includes("works.purchase")) { return businessServiceMap?.["works.purchase"]; - } - else if (moduleCode?.includes("works.wages")) { + } else if (moduleCode?.includes("works.wages")) { return businessServiceMap?.["works.wages"]; - } - else if (moduleCode?.includes("works.supervision")) { + } else if (moduleCode?.includes("works.supervision")) { return businessServiceMap?.["works.supervision"]; - } - else { + } else { return businessServiceMap; } }, @@ -201,16 +196,15 @@ export const UICustomizations = { AttendanceInboxConfig: { preProcess: (data) => { - //set tenantId data.body.inbox.tenantId = Digit.ULBService.getCurrentTenantId(); data.body.inbox.processSearchCriteria.tenantId = Digit.ULBService.getCurrentTenantId(); const musterRollNumber = data?.body?.inbox?.moduleSearchCriteria?.musterRollNumber?.trim(); - if(musterRollNumber) data.body.inbox.moduleSearchCriteria.musterRollNumber = musterRollNumber + if (musterRollNumber) data.body.inbox.moduleSearchCriteria.musterRollNumber = musterRollNumber; const attendanceRegisterName = data?.body?.inbox?.moduleSearchCriteria?.attendanceRegisterName?.trim(); - if(attendanceRegisterName) data.body.inbox.moduleSearchCriteria.attendanceRegisterName = attendanceRegisterName + if (attendanceRegisterName) data.body.inbox.moduleSearchCriteria.attendanceRegisterName = attendanceRegisterName; // deleting them for now(assignee-> need clarity from pintu,ward-> static for now,not implemented BE side) const assignee = _.clone(data.body.inbox.moduleSearchCriteria.assignee); @@ -221,11 +215,11 @@ export const UICustomizations = { //cloning locality and workflow states to format them // let locality = _.clone(data.body.inbox.moduleSearchCriteria.locality ? data.body.inbox.moduleSearchCriteria.locality : []); - - let selectedOrg = _.clone(data.body.inbox.moduleSearchCriteria.orgId ? data.body.inbox.moduleSearchCriteria.orgId : null); + + let selectedOrg = _.clone(data.body.inbox.moduleSearchCriteria.orgId ? data.body.inbox.moduleSearchCriteria.orgId : null); delete data.body.inbox.moduleSearchCriteria.orgId; - if(selectedOrg) { - data.body.inbox.moduleSearchCriteria.orgId = selectedOrg?.[0]?.applicationNumber; + if (selectedOrg) { + data.body.inbox.moduleSearchCriteria.orgId = selectedOrg?.[0]?.applicationNumber; } // let selectedWard = _.clone(data.body.inbox.moduleSearchCriteria.ward ? data.body.inbox.moduleSearchCriteria.ward : null); @@ -243,11 +237,10 @@ export const UICustomizations = { // locality = locality?.map((row) => row?.code); states = Object.keys(states)?.filter((key) => states[key]); ward = ward?.map((row) => row?.code); - - + // //adding formatted data to these keys // if (locality.length > 0) data.body.inbox.moduleSearchCriteria.locality = locality; - if (states.length > 0) data.body.inbox.moduleSearchCriteria.status = states; + if (states.length > 0) data.body.inbox.moduleSearchCriteria.status = states; if (ward.length > 0) data.body.inbox.moduleSearchCriteria.ward = ward; const projectType = _.clone(data.body.inbox.moduleSearchCriteria.projectType ? data.body.inbox.moduleSearchCriteria.projectType : {}); if (projectType?.code) data.body.inbox.moduleSearchCriteria.projectType = projectType.code; @@ -255,10 +248,10 @@ export const UICustomizations = { //adding tenantId to moduleSearchCriteria data.body.inbox.moduleSearchCriteria.tenantId = Digit.ULBService.getCurrentTenantId(); - //setting limit and offset becoz somehow they are not getting set in muster inbox - data.body.inbox .limit = data.state.tableForm.limit - data.body.inbox.offset = data.state.tableForm.offset - delete data.state + //setting limit and offset becoz somehow they are not getting set in muster inbox + data.body.inbox.limit = data.state.tableForm.limit; + data.body.inbox.offset = data.state.tableForm.offset; + delete data.state; return data; }, postProcess: (responseArray, uiConfig) => { @@ -277,7 +270,9 @@ export const UICustomizations = { return ( {String(value ? (column.translate ? t(column.prefix ? `${column.prefix}${value}` : value) : value) : t("ES_COMMON_NA"))} @@ -294,7 +289,7 @@ export const UICustomizations = { if (key === "ATM_NO_OF_INDIVIDUALS") { return
{value?.length}
; } - if(key === "ATM_AMOUNT_IN_RS"){ + if (key === "ATM_AMOUNT_IN_RS") { return {value ? Digit.Utils.dss.formatterWithoutRound(value, "number") : t("ES_COMMON_NA")}; } if (key === "ATM_SLA") { @@ -305,10 +300,10 @@ export const UICustomizations = { ); } if (key === "COMMON_WORKFLOW_STATES") { - return {t(`WF_MUSTOR_${value}`)} + return {t(`WF_MUSTOR_${value}`)}; } //added this in case we change the key and not updated here , it'll throw that nothing was returned from cell error if that case is not handled here. To prevent that error putting this default - return {t(`CASE_NOT_HANDLED`)} + return {t(`CASE_NOT_HANDLED`)}; }, MobileDetailsOnClick: (row, tenantId) => { let link; @@ -326,9 +321,9 @@ export const UICustomizations = { body: { SearchCriteria: { tenantId: tenantId, - functions : { - type : "CBO" - } + functions: { + type: "CBO", + }, }, }, config: { @@ -340,7 +335,7 @@ export const UICustomizations = { }; }, }, - SearchWageSeekerConfig: { + SearchWageSeekerConfig: { customValidationCheck: (data) => { //checking both to and from date are present const { createdFrom, createdTo } = data; @@ -364,7 +359,7 @@ export const UICustomizations = { wardCode: "wardCode[0].code", socialCategory: "socialCategory.code", }; - const textConfig = ["name", "individualId"] + const textConfig = ["name", "individualId"]; let Individual = Object.keys(requestBody) .map((key) => { if (selectConfig[key]) { @@ -372,7 +367,7 @@ export const UICustomizations = { } else if (typeof requestBody[key] == "object") { requestBody[key] = requestBody[key]?.code; } else if (textConfig?.includes(key)) { - requestBody[key] = requestBody[key]?.trim() + requestBody[key] = requestBody[key]?.trim(); } return key; }) @@ -400,7 +395,7 @@ export const UICustomizations = { return ( - {String(value ? (column.translate ? t(column.prefix ? `${column.prefix}${value}` : value) : value) : t("ES_COMMON_NA"))} + {String(value ? (column.translate ? t(column.prefix ? `${column.prefix}${value}` : value) : value) : t("ES_COMMON_NA"))} ); @@ -440,30 +435,29 @@ export const UICustomizations = { if (type === "date") { return data[keys.start] && data[keys.end] ? () => new Date(data[keys.start]).getTime() <= new Date(data[keys.end]).getTime() : true; } - } + }, }, - OpenPaymentSearch:{ + OpenPaymentSearch: { preProcess: (data, additionalDetails) => { - //we need to get three things -> consumerCode,businessService,tenantId // businessService and tenantId can be either in queryParams or in form - let {consumerCode,businessService,tenantId} = data?.state?.searchForm || {}; - businessService = businessService?.code - tenantId = tenantId?.[0]?.code - if(!businessService){ - businessService = additionalDetails?.queryParams?.businessService + let { consumerCode, businessService, tenantId } = data?.state?.searchForm || {}; + businessService = businessService?.code; + tenantId = tenantId?.[0]?.code; + if (!businessService) { + businessService = additionalDetails?.queryParams?.businessService; } - if(!tenantId){ - tenantId = additionalDetails?.queryParams?.tenantId + if (!tenantId) { + tenantId = additionalDetails?.queryParams?.tenantId; } const finalParams = { // consumerCode, tenantId, businessService, - connectionNumber:consumerCode, - isOpenPaymentSearch:true - } - data.params = finalParams + connectionNumber: consumerCode, + isOpenPaymentSearch: true, + }; + data.params = finalParams; // data.params.textSearch = finalParams.consumerCode // const tenantId = Digit.ULBService.getCurrentTenantId(); // data.body = { RequestInfo: data.body.RequestInfo }; @@ -489,78 +483,67 @@ export const UICustomizations = { delete data.body.custom; delete data.body.pagination; data.options = { - userService:false, - auth:false - } + userService: false, + auth: false, + }; // delete data.body.inbox; // delete data.params; return data; }, additionalCustomizations: (row, key, column, value, t, searchResult) => { - switch (key) { case "OP_CONS_CODE": - return - - {String(value ? (column.translate ? t(column.prefix ? `${column.prefix}${value}` : value) : value) : t("ES_COMMON_NA"))} - - - + return ( + + + {String(value ? (column.translate ? t(column.prefix ? `${column.prefix}${value}` : value) : value) : t("ES_COMMON_NA"))} + + + ); + case "OP_APPLICATION_TYPE": - return
- { value ? t(Digit.Utils.locale.getTransformedLocale(`OP_APPLICATION_TYPE_${value}`)) : t("ES_COMMON_NA")} -
- + return
{value ? t(Digit.Utils.locale.getTransformedLocale(`OP_APPLICATION_TYPE_${value}`)) : t("ES_COMMON_NA")}
; + case "OP_APPLICATION_STATUS": - return
- { value ? t(Digit.Utils.locale.getTransformedLocale(`OP_APPLICATION_STATUS_${value}`)) : t("ES_COMMON_NA")} -
+ return
{value ? t(Digit.Utils.locale.getTransformedLocale(`OP_APPLICATION_STATUS_${value}`)) : t("ES_COMMON_NA")}
; case "OP_CONNECTION_TYPE": - return
- { value ? t(Digit.Utils.locale.getTransformedLocale(`OP_CONNECTION_TYPE_${value}`)) : t("ES_COMMON_NA")} -
+ return
{value ? t(Digit.Utils.locale.getTransformedLocale(`OP_CONNECTION_TYPE_${value}`)) : t("ES_COMMON_NA")}
; case "OP_METER_INSTALLATION_DATE": - return
- {value ? Digit.DateUtils.ConvertEpochToDate(value) : t("ES_COMMON_NA")} -
+ return
{value ? Digit.DateUtils.ConvertEpochToDate(value) : t("ES_COMMON_NA")}
; case "OP_METER_READING_DATE": - return
- {value ? Digit.DateUtils.ConvertEpochToDate(value) : t("ES_COMMON_NA")} -
+ return
{value ? Digit.DateUtils.ConvertEpochToDate(value) : t("ES_COMMON_NA")}
; case "OP_PROPERTY_TYPE": - return
- { value ? t(Digit.Utils.locale.getTransformedLocale(`OP_PROPERTY_TYPE_${value}`)) : t("ES_COMMON_NA")} -
+ return
{value ? t(Digit.Utils.locale.getTransformedLocale(`OP_PROPERTY_TYPE_${value}`)) : t("ES_COMMON_NA")}
; case "OP_PAYER_NAME": - return
- {value ? anonymizeHalfString(value) : t("ES_COMMON_NA")} -
- - + return
{value ? anonymizeHalfString(value) : t("ES_COMMON_NA")}
; + default: - return {t("ES_COMMON_DEFAULT_NA")} + return {t("ES_COMMON_DEFAULT_NA")}; } if (key === "OP_BILL_DATE") { return Digit.DateUtils.ConvertEpochToDate(value); } - if(key === "OP_BILL_TOTAL_AMT"){ - return {`₹ ${value}`} + if (key === "OP_BILL_TOTAL_AMT") { + return {`₹ ${value}`}; } - if(key === "OP_CONS_CODE") { - return + if (key === "OP_CONS_CODE") { + return ( + {String(value ? (column.translate ? t(column.prefix ? `${column.prefix}${value}` : value) : value) : t("ES_COMMON_NA"))} - + + ); } }, populateReqCriteria: () => { + const { t } = useTranslation(); const tenantId = Digit.ULBService.getCurrentTenantId(); return { url: "/mdms-v2/v1/_search", @@ -583,29 +566,28 @@ export const UICustomizations = { config: { enabled: true, select: (data) => { - const result = data?.MdmsRes?.tenant?.tenants?.filter( - (row) => row?.divisionCode && row?.divisionName - )?.map((row) => ({ - ...row, - updatedCode: `${row.divisionName} - ${row?.name}`, - })); + const result = data?.MdmsRes?.tenant?.tenants + ?.filter((row) => row?.divisionCode && row?.divisionName) + ?.map((row) => ({ + ...row, + updatedCode: `${row?.divisionName} - ${t(row?.code)}`, + })); return result; }, }, }; }, customValidationCheck: (data) => { - //checking both to and from date are present const { consumerCode } = data; - if(!consumerCode) return false; - if(consumerCode.length < 10 || consumerCode.length > 25){ + if (!consumerCode) return false; + if (consumerCode.length < 10 || consumerCode.length > 25) { return { warning: true, label: "ES_COMMON_ENTER_VALID_CONSUMER_CODE" }; } // if ((createdFrom === "" && createdTo !== "") || (createdFrom !== "" && createdTo === "")) // return { warning: true, label: "ES_COMMON_ENTER_DATE_RANGE" }; return false; - } - } + }, + }, }; diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hrms/src/components/SearchUserForm.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hrms/src/components/SearchUserForm.js index 7f47e97f1..2eca8baf4 100644 --- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hrms/src/components/SearchUserForm.js +++ b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hrms/src/components/SearchUserForm.js @@ -82,7 +82,7 @@ function buildTree(data, hierarchy) { return tree; } -const SearchUserForm = ({ uniqueTenants, setUniqueTenants, roles, setUniqueRoles, employeeData }) => { +const SearchUserForm = React.memo(({ uniqueTenants, setUniqueTenants, roles, setUniqueRoles, employeeData }) => { const { t } = useTranslation(); const [showToast, setShowToast] = useState(null); const [hierarchy, setHierarchy] = useState([ @@ -92,12 +92,20 @@ const SearchUserForm = ({ uniqueTenants, setUniqueTenants, roles, setUniqueRoles { level: "subDivisionCode", value: 4, optionsKey: "subDivisionName", isMandatory: false }, { level: "sectionCode", value: 5, optionsKey: "sectionName", isMandatory: false }, // { "level": "schemeCode", "value": 6,"optionsKey":"schemeName" }, + { level: "code", value: 7, optionsKey: "code", isMandatory: false }, + ]); + + const [divisionHierarchy, setDivisionHierarchy] = useState([ + { level: "subDivisionCode", value: 4, optionsKey: "subDivisionName", isMandatory: false }, + { level: "sectionCode", value: 5, optionsKey: "sectionName", isMandatory: false }, { level: "code", value: 7, optionsKey: "name", isMandatory: false }, ]); const [tree, setTree] = useState(null); const [rolesOptions, setRolesOptions] = useState(null); const [isShowAllClicked, setIsShowAllClicked] = useState(false); + const divisionAdmin = Digit.UserService.hasAccess(["DIV_ADMIN"]); + // const [zones,setZones] = useState([]) // const [circles,setCircles] = useState([]) // const [divisions,setDivisions] = useState([]) @@ -106,6 +114,60 @@ const SearchUserForm = ({ uniqueTenants, setUniqueTenants, roles, setUniqueRoles // const [schemes,setSchemes] = useState([]) // const [codes,setCodes] = useState([]) + const { + register, + handleSubmit, + setValue, + getValues, + reset, + watch, + trigger, + control, + formState, + errors, + setError, + clearErrors, + unregister, + } = useForm({ + defaultValues: { + zoneCode: "", + circleCode: "", + divisionCode: "", + subDivisionCode: "", + sectionCode: "", + code: "", + roles: [], + }, + }); + + const formData = watch(); + + const clearSearch = () => { + reset({ + zoneCode: "", + circleCode: "", + divisionCode: "", + subDivisionCode: "", + sectionCode: "", + code: "", + roles: [], + }); + setUniqueRoles(null); + setUniqueTenants(null); + + // dispatch({ + // type: uiConfig?.type === "filter"?"clearFilterForm" :"clearSearchForm", + // state: { ...uiConfig?.defaultValues } + // //need to pass form with empty strings + // }) + //here reset tableForm as well + // dispatch({ + // type: "tableForm", + // state: { limit:10,offset:0 } + // //need to pass form with empty strings + // }) + }; + const requestCriteria = { url: "/mdms-v2/v1/_search", params: { tenantId: Digit.ULBService.getStateId() }, @@ -155,112 +217,83 @@ const SearchUserForm = ({ uniqueTenants, setUniqueTenants, roles, setUniqueRoles const filteredResult = filterKeys(result, requiredKeys); const resultInTree = buildTree(filteredResult, hierarchy); const excludeCodes = ["HRMS_ADMIN", "LOC_ADMIN", "MDMS_ADMIN", "EMPLOYEE", "SYSTEM"]; - const DIV_ADMIN = Digit.UserService.hasAccess(["DIV_ADMIN"]); - setRolesOptions( - data?.MdmsRes?.["ws-services-masters"]?.["WSServiceRoles"]?.filter( + const roles = data?.MdmsRes?.["ws-services-masters"]?.["WSServiceRoles"] + ?.filter( (row) => !excludeCodes.includes(row?.code) && - (row?.name === "Secretary" || row?.name === "Sarpanch" || row?.name === "Revenue Collector" || !DIV_ADMIN && row?.name === "DIVISION ADMIN") + (row?.name === "Secretary" || row?.name === "Sarpanch" || row?.name === "Revenue Collector" || row?.name === "DIVISION ADMIN") ) - ); - //updating to state roles as requested - // setRolesOptions([ - // // { - // // code: "", - // // name: "Select All", - // // description: "", - // // }, - // { - // code: "EMPLOYEE", - // name: "EMPLOYEE", - // labelKey: "ACCESSCONTROL_ROLES_ROLES_EMPLOYEE", - // }, - // { - // code: "DIV_ADMIN", - // name: "DIVISION ADMIN", - // labelKey: "ACCESSCONTROL_ROLES_ROLES_DIV_ADMIN", - // }, - // { - // code: "HRMS_ADMIN", - // name: "HRMS_ADMIN", - // labelKey: "ACCESSCONTROL_ROLES_ROLES_HRMS_ADMIN", - // }, - // { - // code: "MDMS_ADMIN", - // name: "MDMS Admin", - // description: "Mdms admin", - // }, - - // ]) + ?.map((role) => ({ + ...role, + i18text: "ACCESSCONTROL_ROLES_ROLES_" + role?.code, + })); + setRolesOptions(roles); setTree(resultInTree); return result; }, }, }; - const { isLoading, data, revalidate, isFetching, error } = Digit.Hooks.useCustomAPIHook(requestCriteria); - - const { - register, - handleSubmit, - setValue, - getValues, - reset, - watch, - trigger, - control, - formState, - errors, - setError, - clearErrors, - unregister, - } = useForm({ - defaultValues: { - zoneCode: "", - circleCode: "", - divisionCode: "", - subDivisionCode: "", - sectionCode: "", - code: "", - roles: [], + const requestCriteria2 = { + url: "/mdms-v2/v1/_search", + params: { tenantId: Digit.ULBService.getStateId() }, + body: { + MdmsCriteria: { + tenantId: Digit.ULBService.getStateId(), + moduleDetails: [ + { + moduleName: "tenant", + masterDetails: [ + { + name: "tenants", + filter: `[?(@.code == '${Digit.ULBService.getCurrentTenantId()}')]`, + }, + ], + }, + ], + }, }, - }); - - const formData = watch(); - - const clearSearch = () => { - reset({ - zoneCode: "", - circleCode: "", - divisionCode: "", - subDivisionCode: "", - sectionCode: "", - code: "", - roles: [], - }); - setUniqueRoles(null); - setUniqueTenants(null); + changeQueryName: "userData", + config: { + cacheTime: Infinity, + select: (data) => { + const requiredKeys = [ + "code", + "name", + "zoneCode", + "zoneName", + "circleCode", + "circleName", + "divisionCode", + "divisionName", + "subDivisionCode", + "subDivisionName", + "sectionCode", + "sectionName", + "schemeCode", + "schemeName", + ]; + const result = data?.MdmsRes?.tenant?.tenants; + formData.zoneCode = result[0]; + formData.circleCode = result[0]; + formData.divisionCode = result[0]; - // dispatch({ - // type: uiConfig?.type === "filter"?"clearFilterForm" :"clearSearchForm", - // state: { ...uiConfig?.defaultValues } - // //need to pass form with empty strings - // }) - //here reset tableForm as well - // dispatch({ - // type: "tableForm", - // state: { limit:10,offset:0 } - // //need to pass form with empty strings - // }) + const filteredResult = filterKeys(result, requiredKeys); + return result; + }, + }, }; + const { isLoading, data, revalidate, isFetching, error } = Digit.Hooks.useCustomAPIHook(requestCriteria); + const { data: userData } = Digit.Hooks.useCustomAPIHook(requestCriteria2); + useEffect(() => { if (isShowAllClicked && employeeData) { jsonToExcel(employeeData, "employees.xlsx"); setIsShowAllClicked(false); } - }, [employeeData]); + }, [employeeData, uniqueTenants]); function jsonToExcel(employeeData, fileName) { const employees = employeeData.map((employee) => ({ @@ -286,16 +319,41 @@ const SearchUserForm = ({ uniqueTenants, setUniqueTenants, roles, setUniqueRoles } const showAllData = () => { - clearSearch(); + // clearSearch(); + if (divisionAdmin) setRequiredOptions(formData); setIsShowAllClicked(true); - const listOfUniqueTenants = getUniqueLeafCodes(tree); + //here apply a logic to compute the subtree based on the hierarchy selected + const levels = hierarchy.map(({ level }) => level); + + //compute current level + let maxSelectedLevel = levels[0]; + + levels.forEach((level) => { + if (formData[level]) { + maxSelectedLevel = level; + } else { + return; + } + }); + + const levelIndex = levels.indexOf(maxSelectedLevel); + let currentLevel = tree; + + for (let i = 0; i <= levelIndex; i++) { + const code = formData?.[levels[i]]?.[levels[i]]; + if (!code || !currentLevel[code]) break; + currentLevel = currentLevel[code]; + } + //this is the list of tenants under the current subtree + const listOfUniqueTenants = getUniqueLeafCodes(currentLevel); setUniqueTenants(() => listOfUniqueTenants); setUniqueRoles(() => rolesOptions?.filter((row) => row.code)?.map((role) => role.code)); }; + const onSubmit = (data) => { //assuming atleast one hierarchy is entered - + if (divisionAdmin) setRequiredOptions(data); if (Object.keys(data).length === 0 || Object.values(data).every((value) => !value)) { //toast message setShowToast({ warning: true, label: t("ES_COMMON_MIN_SEARCH_CRITERIA_MSG") }); @@ -320,6 +378,7 @@ const SearchUserForm = ({ uniqueTenants, setUniqueTenants, roles, setUniqueRoles //checking roles if (data?.roles?.length === 0 || !data?.roles) { + setShowToast({ warning: true, label: t("ES_COMMON_MIN_SEARCH_CRITERIA_MSG") }); setTimeout(closeToast, 5000); return; @@ -327,6 +386,7 @@ const SearchUserForm = ({ uniqueTenants, setUniqueTenants, roles, setUniqueRoles //here apply a logic to compute the subtree based on the hierarchy selected const levels = hierarchy.map(({ level }) => level); + //compute current level let maxSelectedLevel = levels[0]; levels.forEach((level) => { @@ -338,8 +398,8 @@ const SearchUserForm = ({ uniqueTenants, setUniqueTenants, roles, setUniqueRoles }); const levelIndex = levels.indexOf(maxSelectedLevel); - let currentLevel = tree; + for (let i = 0; i <= levelIndex; i++) { const code = data?.[levels[i]]?.[levels[i]]; if (!code || !currentLevel[code]) return []; @@ -351,23 +411,41 @@ const SearchUserForm = ({ uniqueTenants, setUniqueTenants, roles, setUniqueRoles setUniqueTenants(() => listOfUniqueTenants); setUniqueRoles(() => data?.roles?.filter((row) => row.code)?.map((role) => role.code)); }; + const [divisionTree, setDivisionTree] = useState(null); + + useEffect(() => { + if (userData) { + const zoneC = userData[0].zoneCode; + const circleC = userData[0].circleCode; + const divisionC = userData[0].divisionCode; + + if (tree && tree[zoneC] && tree[zoneC][circleC]) { + setDivisionTree(tree[zoneC][circleC][divisionC]); + } + } + }, [userData, tree]); + + const setRequiredOptions = (formData) => { + formData.zoneCode = userData[0]; + formData.circleCode = userData[0]; + formData.divisionCode = userData[0]; + }; const optionsForHierarchy = (level, value) => { if (!tree) return []; + if (divisionAdmin && !divisionTree) return []; - const levels = hierarchy.map(({ level }) => level); + const levels = divisionAdmin ? divisionHierarchy.map(({ level }) => level) : hierarchy.map(({ level }) => level); const levelIndex = levels.indexOf(level); - - //zoneCode(1st level(highest parent)) - if (levelIndex === -1 || levelIndex === 0) return tree.options; - - let currentLevel = tree; + if (levelIndex === -1 || levelIndex === 0) return divisionAdmin ? divisionTree.options : tree.options; + let currentLevel = divisionAdmin ? divisionTree : tree; for (let i = 0; i < levelIndex; i++) { const code = formData[levels[i]]?.[levels[i]]; if (!code || !currentLevel[code]) return []; currentLevel = currentLevel[code]; } - return currentLevel.options || []; + if (divisionAdmin) setRequiredOptions(formData); + return currentLevel?.options || []; }; const closeToast = () => { @@ -375,7 +453,7 @@ const SearchUserForm = ({ uniqueTenants, setUniqueTenants, roles, setUniqueRoles }; const renderHierarchyFields = useMemo(() => { - return hierarchy.map(({ level, optionsKey, isMandatory, ...rest }, idx) => ( + return (divisionAdmin ? divisionHierarchy : hierarchy).map(({ level, optionsKey, isMandatory, ...rest }, idx) => ( {`${t(Digit.Utils.locale.getTransformedLocale(`HR_SU_${level}`))} ${ isMandatory ? "*" : "" @@ -391,7 +469,11 @@ const SearchUserForm = ({ uniqueTenants, setUniqueTenants, roles, setUniqueRoles select={(e) => { props.onChange(e); //clear all child levels - const childLevels = hierarchy.slice(hierarchy.findIndex((h) => h.level === level) + 1); + // const childLevels = hierarchy.slice(hierarchy.findIndex((h) => h.level === level) + 1); + // childLevels.forEach((child) => setValue(child.level, "")); + const childLevels = (divisionAdmin ? divisionHierarchy : hierarchy).slice( + (divisionAdmin ? divisionHierarchy : hierarchy).findIndex((h) => h.level === level) + 1 + ); childLevels.forEach((child) => setValue(child.level, "")); }} selected={props.value} @@ -413,12 +495,6 @@ const SearchUserForm = ({ uniqueTenants, setUniqueTenants, roles, setUniqueRoles )); }, [formData]); - useEffect(() => { - rolesOptions?.forEach((option) => { - option.i18text = "ACCESSCONTROL_ROLES_ROLES_" + option?.code; - }); - }, [rolesOptions]); - if (isLoading || !setTree) { return ; } @@ -503,6 +579,6 @@ const SearchUserForm = ({ uniqueTenants, setUniqueTenants, roles, setUniqueRoles )} ); -}; +}); export default SearchUserForm;