",
- "license": "MIT",
- "keywords": [
- "digit",
- "egov",
- "dpg",
- "digit-ui",
- "workbench",
- "campaign",
- "Campaign"
- ]
-}
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/Module.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/Module.js
deleted file mode 100644
index cc2f33443d4..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/Module.js
+++ /dev/null
@@ -1,141 +0,0 @@
-import { Loader, TourProvider } from "@egovernments/digit-ui-react-components";
-import React from "react";
-import { useRouteMatch } from "react-router-dom";
-import EmployeeApp from "./pages/employee";
-import { CustomisedHooks } from "./hooks";
-import { UICustomizations } from "./configs/UICustomizations";
-import CampaignCard from "./components/CampaignCard";
-import CycleConfiguration from "./pages/employee/CycleConfiguration";
-import DeliverySetup from "./pages/employee/deliveryRule";
-import TimelineCampaign from "./components/TimelineCampaign";
-import CampaignDates from "./components/CampaignDates";
-import CampaignType from "./components/CampaignType";
-import CampaignName from "./components/CampaignName";
-import MyCampaign from "./pages/employee/MyCampaign";
-import CampaignSummary from "./components/CampaignSummary";
-import CycleDetaisPreview from "./components/CycleDetaisPreview";
-import Response from "./pages/employee/Response";
-import SelectingBoundaries from "./components/SelectingBoundaries";
-import UploadData from "./components/UploadData";
-import CampaignSelection from "./components/CampaignType";
-import CampaignDocumentsPreview from "./components/CampaignDocumentsPreview";
-import AddProduct from "./pages/employee/AddProduct";
-import AddProductField from "./components/AddProductField";
-import CycleDataPreview from "./components/CycleDataPreview";
-import { ErrorBoundary } from "@egovernments/digit-ui-components";
-import CampaignResourceDocuments from "./components/CampaignResourceDocuments";
-
-/**
- * The CampaignModule function fetches store data based on state code, module code, and language, and
- * renders the EmployeeApp component within a TourProvider component if the data is not loading.
- * @returns The CampaignModule component returns either a Loader component if data is still loading, or
- * a TourProvider component wrapping an EmployeeApp component with specific props passed to it.
- */
-const CampaignModule = ({ stateCode, userType, tenants }) => {
- const tenantId = Digit.ULBService.getCurrentTenantId();
- const { data: BOUNDARY_HIERARCHY_TYPE } = Digit.Hooks.useCustomMDMS(tenantId, "HCM-ADMIN-CONSOLE", [{ name: "hierarchyConfig" }], {
- select: (data) => {
- return data?.["HCM-ADMIN-CONSOLE"]?.hierarchyConfig?.[0]?.hierarchy;
- },
- });
-
- const moduleCode = ["campaignmanager", "workbench", "mdms", "schema", "hcm-admin-schemas", `boundary-${BOUNDARY_HIERARCHY_TYPE}`];
- const { path, url } = useRouteMatch();
- const language = Digit.StoreData.getCurrentLanguage();
- const { isLoading, data: store } = Digit.Services.useStore({
- stateCode,
- moduleCode,
- language,
- });
-
- if (isLoading) {
- return ;
- }
-
- return (
-
-
-
-
-
- );
-};
-
-const componentsToRegister = {
- CampaignModule: CampaignModule,
- CampaignCard: CampaignCard,
- UploadData,
- DeliveryRule: DeliverySetup,
- CycleConfiguration: CycleConfiguration,
- TimelineCampaign,
- CampaignDates,
- CampaignType,
- CampaignName,
- MyCampaign,
- CampaignSummary,
- CycleDetaisPreview,
- Response,
- SelectingBoundaries,
- CampaignSelection,
- CampaignDocumentsPreview: CampaignDocumentsPreview,
- AddProduct,
- AddProductField,
- CycleDataPreview,
- CampaignResourceDocuments,
-};
-
-const overrideHooks = () => {
- Object.keys(CustomisedHooks).map((ele) => {
- if (ele === "Hooks") {
- Object.keys(CustomisedHooks[ele]).map((hook) => {
- Object.keys(CustomisedHooks[ele][hook]).map((method) => {
- setupHooks(hook, method, CustomisedHooks[ele][hook][method]);
- });
- });
- } else if (ele === "Utils") {
- Object.keys(CustomisedHooks[ele]).map((hook) => {
- Object.keys(CustomisedHooks[ele][hook]).map((method) => {
- setupHooks(hook, method, CustomisedHooks[ele][hook][method], false);
- });
- });
- } else {
- Object.keys(CustomisedHooks[ele]).map((method) => {
- setupLibraries(ele, method, CustomisedHooks[ele][method]);
- });
- }
- });
-};
-
-/* To Overide any existing hook we need to use similar method */
-const setupHooks = (HookName, HookFunction, method, isHook = true) => {
- window.Digit = window.Digit || {};
- window.Digit[isHook ? "Hooks" : "Utils"] = window.Digit[isHook ? "Hooks" : "Utils"] || {};
- window.Digit[isHook ? "Hooks" : "Utils"][HookName] = window.Digit[isHook ? "Hooks" : "Utils"][HookName] || {};
- window.Digit[isHook ? "Hooks" : "Utils"][HookName][HookFunction] = method;
-};
-/* To Overide any existing libraries we need to use similar method */
-const setupLibraries = (Library, service, method) => {
- window.Digit = window.Digit || {};
- window.Digit[Library] = window.Digit[Library] || {};
- window.Digit[Library][service] = method;
-};
-
-/* To Overide any existing config/middlewares we need to use similar method */
-const updateCustomConfigs = () => {
- setupLibraries("Customizations", "commonUiConfig", { ...window?.Digit?.Customizations?.commonUiConfig, ...UICustomizations });
- // setupLibraries("Utils", "parsingUtils", { ...window?.Digit?.Utils?.parsingUtils, ...parsingUtils });
-};
-
-/**
- * The `initCampaignComponents` function initializes campaign components by overriding hooks, updating
- * custom configurations, and registering components.
- */
-const initCampaignComponents = () => {
- overrideHooks();
- updateCustomConfigs();
- Object.entries(componentsToRegister).forEach(([key, value]) => {
- Digit.ComponentRegistryService.setComponent(key, value);
- });
-};
-
-export { initCampaignComponents };
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/AddProductField.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/AddProductField.js
deleted file mode 100644
index 94a73fd6b24..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/AddProductField.js
+++ /dev/null
@@ -1,144 +0,0 @@
-import React, { useState, useEffect } from "react";
-import { AddIcon, Button, Card, CardText, Header, TextInput, Dropdown } from "@egovernments/digit-ui-react-components";
-import { useTranslation } from "react-i18next";
-import { LabelFieldPair } from "@egovernments/digit-ui-react-components";
-import { DustbinIcon } from "./icons/DustbinIcon";
-// import { productType } from "../configs/productType";
-import { PRIMARY_COLOR } from "../utils";
-
-const AddProductField = ({ onSelect }) => {
- const { t } = useTranslation();
- const tenantId = Digit.ULBService.getCurrentTenantId();
- const { isLoading: productTypeLoading, data: productType } = Digit.Hooks.useCustomMDMS(tenantId, "HCM-ADMIN-CONSOLE", [{ name: "productType" }], {
- select: (data) => {
- return data?.["HCM-ADMIN-CONSOLE"]?.productType;
- },
- });
- const [productFieldData, setProductFieldData] = useState([{ key: 1, name: null, type: null, variant: null }]);
-
- useEffect(() => {
- onSelect("addProduct", productFieldData);
- }, [productFieldData]);
-
- const addMoreField = () => {
- setProductFieldData((prev) => [
- ...prev,
- {
- key: prev.length + 1,
- name: null,
- type: null,
- variant: null,
- },
- ]);
- };
-
- const deleteProductField = (index) => {
- setProductFieldData((prev) => {
- const temp = prev.filter((i) => i.key !== index);
- return temp.map((i, n) => ({ ...i, key: n + 1 }));
- });
- };
-
- const handleUpdateField = (data, target, index) => {
- setProductFieldData((prev) => {
- return prev.map((i) => {
- if (i.key === index) {
- return {
- ...i,
- [target]: data,
- };
- }
- return {
- ...i,
- };
- });
- });
- };
-
- return (
-
- {t(`HCM_CAMPAIGN_ADD_NEW_PRODUCT_HEADER`)}
-
- {t(`HCM_CAMPAIGN_ADD_NEW_PRODUCT_DESCRIPTION_PRE_TEXT`)} {t(`HCM_CAMPAIGN_ADD_NEW_PRODUCT_DESCRIPTION_BOLD_TEXT`)}
- {t(`HCM_CAMPAIGN_ADD_NEW_PRODUCT_DESCRIPTION_POST_TEXT`)}
-
- {productFieldData?.map((field, index) => {
- return (
-
-
-
Product {field?.key}
- {productFieldData?.length > 1 && (
-
deleteProductField(field.key)}
- style={{
- cursor: "pointer",
- fontWeight: "600",
- marginLeft: "1rem",
- fontSize: "1rem",
- color: PRIMARY_COLOR,
- display: "flex",
- gap: "0.5rem",
- alignItems: "center",
- marginTop: "1rem",
- }}
- >
-
- {t(`CAMPAIGN_DELETE_ROW_TEXT`)}
-
- )}
-
-
-
- {`${t("HCM_PRODUCT_NAME")}`}
- *
-
- handleUpdateField(event.target.value, "name", field.key)}
- />
-
-
-
- {`${t("HCM_PRODUCT_TYPE")}`}
- *
-
- {
- handleUpdateField(value, "type", field.key);
- }}
- />
-
-
-
- {`${t("HCM_PRODUCT_VARIANT")}`}
- *
-
- handleUpdateField(event.target.value, "variant", field?.key)}
- />
-
-
- );
- })}
- }
- onButtonClick={addMoreField}
- />
-
- );
-};
-
-export default AddProductField;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/BulkUpload.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/BulkUpload.js
deleted file mode 100644
index 5f854cfac79..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/BulkUpload.js
+++ /dev/null
@@ -1,202 +0,0 @@
-import React, { useState, useMemo, useEffect } from "react";
-import { UploadIcon, FileIcon, DeleteIconv2, Button, DownloadIcon, PopUp, SVG } from "@egovernments/digit-ui-react-components";
-import { FileUploader } from "react-drag-drop-files";
-import { useTranslation } from "react-i18next";
-import XLSX from "xlsx";
-import XlsPreview from "./XlsPreview";
-import { PRIMARY_COLOR } from "../utils";
-import { Toast } from "@egovernments/digit-ui-components";
-
-/**
- * The BulkUpload component in JavaScript allows users to upload, validate, preview, download, and
- * delete files in bulk with support for Excel file validation.
- * @returns The `BulkUpload` component is returning a JSX structure that includes conditional rendering
- * based on the presence of `fileData`. If `fileData` is empty or null, it renders a `FileUploader`
- * component with drag and drop functionality. If `fileData` contains files, it renders file cards for
- * each file with options to download and delete. Additionally, it includes a preview component for
- * Excel files
- */
-const BulkUpload = ({ multiple = true, onSubmit, fileData, onFileDelete, onFileDownload }) => {
- const { t } = useTranslation();
- const [files, setFiles] = useState([]);
- const fileTypes = ["XLS", "XLSX", "csv", "CSV"];
- const tenantId = Digit.ULBService.getCurrentTenantId();
- const [showPreview, setShowPreview] = useState(false);
- const [fileUrl, setFileUrl] = useState(fileData?.[0]);
- const [fileName, setFileName] = useState(null);
- const [showToast, setShowToast] = useState(false);
-
- useEffect(() => {
- const fetch = async () => {
- const { data: { fileStoreIds: fileUrl } = {} } = await Digit.UploadServices.Filefetch([fileData?.[0]?.filestoreId], tenantId);
- const temp = fileData?.map((i) => ({
- ...i,
- url: fileUrl?.[0]?.url,
- }));
- setFileUrl(temp?.[0]);
- };
- fetch();
- }, [fileData]);
-
- const closeToast = () => {
- setTimeout(() => {
- setShowToast(null);
- }, 5000);
- };
-
- const dragDropJSX = (
-
-
-
- {t("WBH_DRAG_DROP")} {t("WBH_BULK_BROWSE_FILES")}
-
-
- );
-
- const handleFileDelete = (file, index) => {
- onFileDelete(file, index);
- };
-
- const validateExcel = (selectedFile) => {
- return new Promise((resolve, reject) => {
- // Check if a file is selected
- if (!selectedFile) {
- reject(t("HCM_FILE_UPLOAD_ERROR"));
- return;
- }
-
- // Read the Excel file
- const reader = new FileReader();
- reader.onload = (e) => {
- try {
- const data = new Uint8Array(e.target.result);
- const workbook = XLSX.read(data, { type: "array" });
-
- // Assuming your columns are in the first sheet
- const sheet = workbook.Sheets[workbook.SheetNames[0]];
-
- const columnsToValidate = XLSX.utils.sheet_to_json(sheet, {
- header: 1,
- })[0];
-
- // Check if all columns have non-empty values in every row
- const isValid = XLSX.utils
- .sheet_to_json(sheet)
- .every((row) => columnsToValidate.every((column) => row[column] !== undefined && row[column] !== null && row[column] !== ""));
-
- if (isValid) {
- // All columns in all rows have non-empty values, it is valid
- resolve(true);
- } else {
- // const label = "HCM_FILE_VALIDATION_ERROR";
- // setShowToast({ isError: true, label });
- reject(t("HCM_FILE_VALIDATION_ERROR"));
- }
- } catch (error) {
- reject("HCM_FILE_UNAVAILABLE");
- }
- };
-
- reader.readAsArrayBuffer(selectedFile);
- });
- };
-
- const handleFileDownload = async (e, file) => {
- if (e?.stopPropagation) {
- e.stopPropagation();
- }
- onFileDownload(file);
- };
-
- const handleChange = async (newFiles) => {
- try {
- // await validateExcel(newFiles[0]);
- onSubmit([...newFiles]);
- } catch (error) {
- // Handle the validation error, you can display a message or take appropriate actions.
- setShowToast({ key: "error", label: error });
- closeToast();
- }
- };
-
- const fileTypeError = (err) => {
- setShowToast({ key: "error", label: t("HCM_ERROR_INVALID_FILE_TYPE") });
- };
-
- const renderFileCards = useMemo(() => {
- return fileData?.map((file, index) => (
- {
- e.stopPropagation();
- setShowPreview(true);
- }}
- >
-
{
- // setShowPreview(true);
- // }}
- >
-
-
{file.filename}
-
-
- }
- type="button"
- className="workbench-download-template-btn hover"
- onButtonClick={(e) => {
- e.stopPropagation();
- handleFileDownload(e, fileUrl);
- }}
- />
- }
- type="button"
- className="workbench-download-template-btn hover"
- onButtonClick={(e) => {
- e.stopPropagation();
- handleFileDelete(file, index);
- setShowPreview(false);
- }}
- />
-
-
- ));
- }, [fileData, fileUrl]);
-
- return (
-
- {(!fileData || fileData?.length === 0) && (
-
- )}
- {fileData?.length > 0 && renderFileCards}
- {showPreview && handleFileDownload(null, fileUrl)} onBack={() => setShowPreview(false)} />}
- {showToast && (
- setShowToast(null)}
- >
- )}
-
- );
-};
-
-export default BulkUpload;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignCard.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignCard.js
deleted file mode 100644
index e5b5b7419b7..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignCard.js
+++ /dev/null
@@ -1,71 +0,0 @@
-import { EmployeeModuleCard, SVG } from "@egovernments/digit-ui-react-components";
-import React from "react";
-import { useTranslation } from "react-i18next";
-
-const ROLES = {
- CAMPAIGN_MANAGER:["CAMPAIGN_MANAGER"]
-};
-
-/**
- * The CampaignCard component renders a card with links related to campaign management, filtering out
- * links based on employee roles.
- * @returns The CampaignCard component is being returned. It contains a list of links related to
- * campaign actions, such as setting up a campaign and viewing personal campaigns. The links are
- * filtered based on employee roles before being displayed in the EmployeeModuleCard component.
- */
-const CampaignCard = () => {
- if (!Digit.Utils.didEmployeeHasAtleastOneRole(Object.values(ROLES).flatMap((e) => e))) {
- return null;
- }
-
- const { t } = useTranslation();
- const tenantId = Digit.ULBService.getCurrentTenantId();
- // const reqCriteria = {
- // url: "/project-factory/v1/project-type/search",
- // params: {},
- // body: { CampaignDetails:{
- // tenantId,
- // createdBy: Digit.UserService.getUser().info.uuid,
- // pagination: {
- // "sortBy": "createdTime",
- // "sortOrder": "desc",
- // "limit": 1,
- // "offset": 0
- // }
- // } },
- // config: {
- // select: (data) => {
- // return data?.totalCount;
- // },
- // },
- // };
- // const { isLoading, data } = Digit.Hooks.useCustomAPIHook(
- // reqCriteria
- // );
- let links = [
-
- {
- label: t("ACTION_TEST_SETUP_CAMPAIGN"),
- link: `/${window?.contextPath}/employee/campaign/setup-campaign`,
- roles: ROLES.CAMPAIGN_MANAGER
- },
- {
- label: t("ACTION_TEST_MY_CAMPAIGN"),
- link: `/${window?.contextPath}/employee/campaign/my-campaign`,
- roles: ROLES.CAMPAIGN_MANAGER,
- // count: isLoading?"-":data
- },
- ];
-
- links = links.filter((link) => (link?.roles && link?.roles?.length > 0 ? Digit.Utils.didEmployeeHasAtleastOneRole(link?.roles) : true));
-
- const propsForModuleCard = {
- Icon: ,
- moduleName: t("ACTION_TEST_CAMPAIGN"),
- kpis: [],
- links: links,
- };
- return ;
-};
-
-export default CampaignCard;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignDates.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignDates.js
deleted file mode 100644
index 71bcfa4e447..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignDates.js
+++ /dev/null
@@ -1,122 +0,0 @@
-import React, { useState, useEffect } from "react";
-import { DatePicker, LabelFieldPair, Header } from "@egovernments/digit-ui-react-components";
-import { useTranslation } from "react-i18next";
-import { ErrorMessage, FieldV1, TextInput } from "@egovernments/digit-ui-components";
-
-const CampaignDates = ({ onSelect, formData, ...props }) => {
- const { t } = useTranslation();
- const ONE_DAY_IN_MS = 24 * 60 * 60 * 1000;
- const today = Digit.Utils.date.getDate(Date.now() + ONE_DAY_IN_MS);
- const [dates, setDates] = useState({
- startDate: props?.props?.sessionData?.HCM_CAMPAIGN_DATE?.campaignDates?.startDate || today,
- endDate: props?.props?.sessionData?.HCM_CAMPAIGN_DATE?.campaignDates?.endDate || today,
- });
- const [startDate, setStartDate] = useState(props?.props?.sessionData?.HCM_CAMPAIGN_DATE?.campaignDates?.startDate); // Set default start date to today
- const [endDate, setEndDate] = useState(props?.props?.sessionData?.HCM_CAMPAIGN_DATE?.campaignDates?.endDate); // Default end date
- const [executionCount, setExecutionCount] = useState(0);
- const [error, setError] = useState(null);
- const [startValidation, setStartValidation] = useState(null);
-
- useEffect(() => {
- setDates({
- startDate: props?.props?.sessionData?.HCM_CAMPAIGN_DATE?.campaignDates?.startDate,
- endDate: props?.props?.sessionData?.HCM_CAMPAIGN_DATE?.campaignDates?.endDate,
- });
- setStartDate(props?.props?.sessionData?.HCM_CAMPAIGN_DATE?.campaignDates?.startDate);
- setEndDate(props?.props?.sessionData?.HCM_CAMPAIGN_DATE?.campaignDates?.endDate);
- }, [props?.props?.sessionData?.HCM_CAMPAIGN_DATE?.campaignDates]);
-
- useEffect(() => {
- if (props?.props?.isSubmitting && !endDate && !startDate) {
- setError({ startDate: "CAMPAIGN_FIELD_MANDATORY", endDate: "CAMPAIGN_FIELD_MANDATORY" });
- } else if (props?.props?.isSubmitting && !startDate) {
- setError({ startDate: "CAMPAIGN_FIELD_MANDATORY" });
- } else if (props?.props?.isSubmitting && !endDate) {
- setError({ endDate: "CAMPAIGN_FIELD_MANDATORY" });
- } else if (!props?.props?.isSubmitting) {
- setError(null);
- }
- }, [props?.props?.isSubmitting]);
- useEffect(() => {
- if (!startDate && startValidation) {
- setError({ startDate: "CAMPAIGN_START_DATE_ERROR" });
- } else if (!endDate && startValidation) {
- setError({ endDate: "CAMPAIGN_END_DATE_ERROR" });
- } else if (new Date(endDate).getTime() < new Date(startDate).getTime() && startValidation) {
- setError({ endDate: "CAMPAIGN_END_DATE_BEFORE_ERROR" });
- onSelect("campaignDates", { startDate: startDate, endDate: endDate });
- } else if (startValidation && new Date(endDate).getTime() === new Date(startDate).getTime()) {
- setError({ endDate: "CAMPAIGN_END_DATE_SAME_ERROR" });
- onSelect("campaignDates", { startDate: startDate, endDate: endDate });
- } else if (startDate || endDate) {
- setError(null);
- onSelect("campaignDates", { startDate: startDate, endDate: endDate });
- }
- }, [startDate, endDate]);
-
- useEffect(() => {
- if (executionCount < 5) {
- onSelect("campaignDates", { startDate: startDate, endDate: endDate });
- setExecutionCount((prevCount) => prevCount + 1);
- }
- });
-
- function setStart(value) {
- setStartDate(value);
- }
-
- function setEnd(date) {
- setEndDate(date);
- }
-
- return (
-
- {t(`HCM_CAMPAIGN_DATES_HEADER`)}
- {t(`HCM_CAMPAIGN_DATES_DESCRIPTION`)}
-
-
-
{t(`HCM_CAMPAIGN_DATES`)}
-
*
-
-
- {
- // setStartValidation(true);
- setStart(d);
- }}
- />
- {
- setStartValidation(true);
- setEnd(d);
- }}
- />
-
-
-
- );
-};
-
-export default CampaignDates;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignDocumentsPreview.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignDocumentsPreview.js
deleted file mode 100644
index 2c8bbf77eaf..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignDocumentsPreview.js
+++ /dev/null
@@ -1,92 +0,0 @@
-import React, { useState, useEffect, Fragment } from "react";
-import { useTranslation } from "react-i18next";
-import { DocumentIcon } from "./DocumentIcon";
-import XlsPreview from "./XlsPreview";
-import { XlsxFile } from "./icons/XlsxFile";
-import { downloadExcelWithCustomName } from "../utils";
-import { InfoCard } from "@egovernments/digit-ui-components";
-
-function CampaignDocumentsPreview({ documents = [], svgStyles = {}, isUserGenerate = false, cardErrors }) {
- const { t } = useTranslation();
- const tenantId = Digit.ULBService.getCurrentTenantId();
- const [filesArray, setFilesArray] = useState(null);
- const [pdfFiles, setPdfFiles] = useState({});
- const [showPreview, setShowPreview] = useState(false);
-
- useEffect(() => {
- let acc = documents?.map((i) => (i?.id ? i?.id : i?.filestoreId));
- setFilesArray(acc);
- }, [documents]);
-
- useEffect(() => {
- if (filesArray?.length > 0) {
- Digit.UploadServices.Filefetch(filesArray, Digit.ULBService.getCurrentTenantId()).then((res) => {
- setPdfFiles(res?.data);
- });
- }
- }, [filesArray]);
-
- const handleFileDownload = ({ id, name }) => {
- const fileNameWithoutExtension = name?.split(/\.(xlsx|xls)/)?.[0];
- downloadExcelWithCustomName({ fileStoreId: id, customName: fileNameWithoutExtension });
- };
- return (
-
-
- {documents?.length > 0 ? (
- documents?.map(
- (document, index) =>
- (document?.id || document?.filestoreId) && (
-
-
setShowPreview(true)}>
-
-
-
-
- {isUserGenerate
- ? document?.type
- : document?.filename
- ? t(document?.filename)
- : t("CAMPAIGN_DOCUMENT_TITLE", { INDEX: index + 1 })}
-
-
- {showPreview && (
-
- handleFileDownload({
- id: document?.id ? document?.id : document?.filestoreId,
- name: isUserGenerate ? document?.type : document?.filename,
- })
- }
- onBack={() => setShowPreview(false)}
- />
- )}
-
- )
- )
- ) : (
-
-
{t("ES_CAMPAIGN_NO_DOCUMENTS_AVAILABLE")}
- {cardErrors?.map((i) => (
-
]}
- />
- ))}
-
- )}
-
-
- );
-}
-
-export default CampaignDocumentsPreview;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignHeader.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignHeader.js
deleted file mode 100644
index 5a4f7f546f2..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignHeader.js
+++ /dev/null
@@ -1,32 +0,0 @@
-import { BackButton, Tutorial, useTourState, Help } from "@egovernments/digit-ui-react-components";
-import React, { useEffect, useContext, Fragment } from "react";
-import { useTranslation } from "react-i18next";
-import { useLocation } from "react-router-dom";
-import { TourSteps } from "../utils/TourSteps";
-
-const CampaignHeader = () => {
- const { tourState, setTourState } = useTourState();
- // const { tutorial, updateTutorial } = useContext(TutorialContext);
- const { t } = useTranslation();
- //using location.pathname we can update the stepIndex accordingly when help is clicked from any other screen(other than home screen)
- const { pathname } = useLocation();
-
- const startTour = () => {
- setTourState({
- run: TourSteps[pathname]?.length > 0 ? true : false,
- steps: TourSteps[pathname] || [],
- tourActive: TourSteps[pathname]?.length > 0 ? true : false,
- });
- };
-
- return (
- <>
-
-
-
-
- >
- );
-};
-
-export default CampaignHeader;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignName.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignName.js
deleted file mode 100644
index 4540e3f46f4..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignName.js
+++ /dev/null
@@ -1,66 +0,0 @@
-import React, { useState, useEffect ,Fragment} from "react";
-import { Header } from "@egovernments/digit-ui-react-components";
-import { useTranslation } from "react-i18next";
-import { LabelFieldPair } from "@egovernments/digit-ui-react-components";
-import { ErrorMessage, FieldV1 } from "@egovernments/digit-ui-components";
-
-const CampaignName = ({ onSelect, formData, control, formState, ...props }) => {
- const { t } = useTranslation();
- const [name, setName] = useState(props?.props?.sessionData?.HCM_CAMPAIGN_NAME?.campaignName || "");
- const [executionCount, setExecutionCount] = useState(0);
- const [startValidation, setStartValidation] = useState(null);
- const [error, setError] = useState(null);
- useEffect(() => {
- setName(props?.props?.sessionData?.HCM_CAMPAIGN_NAME?.campaignName);
- }, [props?.props?.sessionData?.HCM_CAMPAIGN_NAME]);
-
- useEffect(() => {
- if (props?.props?.isSubmitting && !name) {
- setError({ message: "CAMPAIGN_FIELD_ERROR_MANDATORY" });
- } else {
- setError(null);
- }
- }, [props?.props?.isSubmitting]);
- useEffect(() => {
- if (startValidation && !name) {
- setError({ message: "CAMPAIGN_NAME_FIELD_ERROR" });
- } else if (name) {
- setError(null);
- onSelect("campaignName", name);
- }
- }, [name, props?.props?.sessionData?.HCM_CAMPAIGN_NAME?.campaignName]);
-
- useEffect(() => {
- if (executionCount < 5) {
- onSelect("campaignName", name);
- setExecutionCount((prevCount) => prevCount + 1);
- }
- });
-
- return (
-
- {t(`HCM_CAMPAIGN_NAME_HEADER`)}
- {t(`HCM_CAMPAIGN_NAME_DESCRIPTION`)}
-
-
- {`${t("HCM_CAMPAIGN_NAME")}`}
- *
-
- {
- setStartValidation(true);
- setName(event.target.value);
- }}
- />
-
-
- );
-};
-
-export default CampaignName;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignResourceDocuments.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignResourceDocuments.js
deleted file mode 100644
index 827ff5062eb..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignResourceDocuments.js
+++ /dev/null
@@ -1,50 +0,0 @@
-import React, { useState, useEffect, Fragment } from "react";
-import { useTranslation } from "react-i18next";
-import CampaignDocumentsPreview from "./CampaignDocumentsPreview";
-import { CardText } from "@egovernments/digit-ui-components";
-
-function CampaignResourceDocuments({ resources = [], svgStyles = {}, isUserGenerate = false }) {
- const { t } = useTranslation();
- const tenantId = Digit.ULBService.getCurrentTenantId();
- const [processData, setProcessData] = useState([]);
- const reqCriteriaResource = {
- url: `/project-factory/v1/data/_search`,
- body: {
- SearchCriteria: {
- tenantId: tenantId,
- id: resources,
- },
- },
- config: {
- enabled: true,
- select: (data) => {
- return data?.ResourceDetails;
- },
- },
- };
-
- const { isLoading, data: resourceData, isFetching } = Digit.Hooks.useCustomAPIHook(reqCriteriaResource);
-
- useEffect(() => {
- if (!isLoading) {
- const temp = resourceData.map((i) => {
- return {
- id: i?.processedFilestoreId,
- type: "User Credential",
- };
- });
- setProcessData(temp);
- }
- }, [isLoading, resourceData]);
-
- if (!processData?.[0]?.id) {
- return {t("NO_DOCUMENTS_AVAILABLE")};
- }
- return (
-
-
-
- );
-}
-
-export default CampaignResourceDocuments;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignSummary.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignSummary.js
deleted file mode 100644
index 6f37dfb6ae2..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignSummary.js
+++ /dev/null
@@ -1,484 +0,0 @@
-import React, { Fragment, useEffect, useRef, useState } from "react";
-import { useTranslation } from "react-i18next";
-import { useHistory } from "react-router-dom";
-import { Button, EditIcon, Header, Loader, ViewComposer } from "@egovernments/digit-ui-react-components";
-import { InfoBannerIcon, Toast } from "@egovernments/digit-ui-components";
-import { DownloadIcon } from "@egovernments/digit-ui-react-components";
-import { PRIMARY_COLOR, downloadExcelWithCustomName } from "../utils";
-
-function mergeObjects(item) {
- const arr = item;
- const mergedArr = [];
- const mergedAttributes = new Set();
-
- arr.forEach((obj) => {
- if (!mergedAttributes.has(obj.attribute)) {
- const sameAttrObjs = arr.filter((o) => o.attribute === obj.attribute);
-
- if (sameAttrObjs.length > 1) {
- const fromValue = Math.min(...sameAttrObjs.map((o) => o.value));
- const toValue = Math.max(...sameAttrObjs.map((o) => o.value));
-
- mergedArr.push({
- fromValue,
- toValue,
- value: fromValue > 0 && toValue > 0 ? `${fromValue} to ${toValue}` : null,
- operator: "IN_BETWEEN",
- attribute: obj.attribute,
- });
-
- mergedAttributes.add(obj.attribute);
- } else {
- mergedArr.push(obj);
- }
- }
- });
-
- return mergedArr;
-}
-
-function loopAndReturn(dataa, t) {
- let newArray = [];
- const data = dataa?.map((i) => ({ ...i, operator: i?.operator, attribute: i?.attribute }));
-
- data.forEach((item) => {
- // Check if an object with the same attribute already exists in the newArray
- const existingIndex = newArray.findIndex((element) => element.attribute === item.attribute);
- if (existingIndex !== -1) {
- // If an existing item is found, replace it with the new object
- const existingItem = newArray[existingIndex];
- newArray[existingIndex] = {
- attribute: existingItem.attribute,
- operator: "IN_BETWEEN",
- toValue: existingItem.value && item.value ? Math.min(existingItem.value, item.value) : null,
- fromValue: existingItem.value && item.value ? Math.max(existingItem.value, item.value) : null,
- };
- } else if (item?.operator === "EQUAL_TO") {
- newArray.push({
- ...item,
- value: item?.value ? t(item?.value) : null,
- });
- } else {
- newArray.push(item);
- }
- });
-
- const withKey = newArray.map((i, c) => ({ key: c + 1, ...i }));
- const format = withKey.map((i) => {
- if (i.operator === "IN_BETWEEN") {
- return {
- ...i,
- value: `${i?.toValue ? i?.toValue : "N/A"} to ${i?.fromValue ? i?.fromValue : "N/A"}`,
- };
- }
- return {
- ...i,
- };
- });
- return format;
-}
-
-function reverseDeliveryRemap(data, t) {
- if (!data) return null;
- const reversedData = [];
- let currentCycleIndex = null;
- let currentCycle = null;
-
- data.forEach((item, index) => {
- if (currentCycleIndex !== item.cycleNumber) {
- currentCycleIndex = item.cycleNumber;
- currentCycle = {
- cycleIndex: currentCycleIndex.toString(),
- startDate: item?.startDate ? Digit.Utils.date.convertEpochToDate(item?.startDate) : null,
- endDate: item?.endDate ? Digit.Utils.date.convertEpochToDate(item?.endDate) : null,
- active: index === 0, // Initialize active to false
- deliveries: [],
- };
- reversedData.push(currentCycle);
- }
-
- const deliveryIndex = item.deliveryNumber.toString();
-
- let delivery = currentCycle.deliveries.find((delivery) => delivery.deliveryIndex === deliveryIndex);
-
- if (!delivery) {
- delivery = {
- deliveryIndex: deliveryIndex,
- active: item.deliveryNumber === 1, // Set active to true only for the first delivery
- deliveryRules: [],
- };
- currentCycle.deliveries.push(delivery);
- }
-
- delivery.deliveryRules.push({
- ruleKey: item.deliveryRuleNumber,
- delivery: {},
- attributes: loopAndReturn(item.conditions, t),
- products: [...item.products],
- });
- });
-
- return reversedData;
-}
-
-const fetchResourceFile = async (tenantId, resourceIdArr) => {
- const res = await Digit.CustomService.getResponse({
- url: `/project-factory/v1/data/_search`,
- body: {
- SearchCriteria: {
- tenantId: tenantId,
- id: resourceIdArr,
- },
- },
- });
- return res?.ResourceDetails;
-};
-
-const CampaignSummary = (props) => {
- const { t } = useTranslation();
- const history = useHistory();
- const tenantId = Digit.ULBService.getCurrentTenantId();
- const searchParams = new URLSearchParams(location.search);
- const id = searchParams.get("id");
- const noAction = searchParams.get("action");
- const [showToast, setShowToast] = useState(null);
- const [userCredential, setUserCredential] = useState(null);
- const [deliveryErrors, setDeliveryErrors] = useState(null);
- const [targetErrors, setTargetErrors] = useState(null);
- const [facilityErrors, setFacilityErrors] = useState(null);
- const [userErrors, setUserErrors] = useState(null);
- const [cycleDatesError, setCycleDatesError] = useState(null);
- const [summaryErrors, setSummaryErrors] = useState(null);
- const handleRedirect = (step, activeCycle) => {
- const urlParams = new URLSearchParams(window.location.search);
- const id = urlParams.get("id");
- urlParams.set("key", step);
- urlParams.set("preview", false);
- if (activeCycle) {
- urlParams.set("activeCycle", activeCycle);
- }
- const newUrl = `${window.location.pathname}?${urlParams.toString()}`;
- history.push(newUrl);
- };
-
- useEffect(() => {
- if (props?.props?.summaryErrors) {
- if (props?.props?.summaryErrors?.deliveryErrors) {
- const temp = props?.props?.summaryErrors?.deliveryErrors?.map((i) => {
- return {
- ...i,
- onClick: i?.dateError ? () => handleRedirect(5) : () => handleRedirect(6, i?.cycle),
- };
- });
- setSummaryErrors({ ...props?.props?.summaryErrors, deliveryErrors: temp });
- } else {
- setSummaryErrors(props?.props?.summaryErrors);
- }
- }
- // if (props?.props?.summaryErrors?.deliveryErrors) {
- // const temp = props?.props?.summaryErrors?.deliveryErrors?.map((i) => {
- // return {
- // ...i,
- // onClick: () => handleRedirect(6, i?.cycle),
- // };
- // });
- // setDeliveryErrors(temp);
- // }
- // if (props?.props?.summaryErrors?.targetErrors) {
- // setTargetErrors(props?.props?.summaryErrors?.targetErrors);
- // }
- // if (props?.props?.summaryErrors?.facilityErrors) {
- // setFacilityErrors(props?.props?.summaryErrors?.facilityErrors);
- // }
- // if (props?.props?.summaryErrors?.userErrors) {
- // setUserErrors(props?.props?.summaryErrors?.userErrors);
- // }
- }, [props?.props?.summaryErrors]);
-
- const { isLoading, data, error, refetch } = Digit.Hooks.campaign.useSearchCampaign({
- tenantId: tenantId,
- filter: {
- ids: [id],
- },
- config: {
- select: (data) => {
- const resourceIdArr = [];
- data?.[0]?.resources?.map((i) => {
- if (i?.createResourceId && i?.type === "user") {
- resourceIdArr.push(i?.createResourceId);
- }
- });
- let processid;
-
- const ss = async () => {
- let temp = await fetchResourceFile(tenantId, resourceIdArr);
- processid = temp;
- return;
- };
- ss();
- const target = data?.[0]?.deliveryRules;
- const cycleData = reverseDeliveryRemap(target, t);
- return {
- cards: [
- {
- sections: [
- {
- type: "DATA",
- cardHeader: { value: t("CAMPAIGN_DETAILS"), inlineStyles: { marginTop: 0, fontSize: "1.5rem" } },
- cardSecondaryAction: noAction !== "false" && (
- handleRedirect(1)}>
- {t(`CAMPAIGN_EDIT`)}
-
-
- ),
- values: [
- {
- key: "CAMPAIGN_TYPE",
- value: data?.[0]?.projectType ? t(`CAMPAIGN_PROJECT_${data?.[0]?.projectType?.toUpperCase()}`) : t("CAMPAIGN_SUMMARY_NA"),
- },
- {
- key: "CAMPAIGN_NAME",
- value: data?.[0]?.campaignName || t("CAMPAIGN_SUMMARY_NA"),
- },
- {
- key: "CAMPAIGN_START_DATE",
- value: Digit.Utils.date.convertEpochToDate(data?.[0]?.startDate) || t("CAMPAIGN_SUMMARY_NA"),
- },
- {
- key: "CAMPAIGN_END_DATE",
- value: Digit.Utils.date.convertEpochToDate(data?.[0]?.endDate) || t("CAMPAIGN_SUMMARY_NA"),
- },
- ],
- },
- ],
- },
- // data?.[0]?.resources?.find((i) => i?.type === "boundaryWithTarget") ?
- {
- name: "target",
- errorName: "target",
- sections: [
- {
- name: "target",
- type: "COMPONENT",
- component: "CampaignDocumentsPreview",
- props: {
- documents: data?.[0]?.resources?.filter((i) => i?.type === "boundaryWithTarget"),
- },
- cardHeader: { value: t("TARGET_DETAILS"), inlineStyles: { marginTop: 0, fontSize: "1.5rem" } },
- cardSecondaryAction: noAction !== "false" && (
- handleRedirect(7)}>
- {t(`CAMPAIGN_EDIT`)}
-
-
- ),
- },
- ],
- },
- // : {}
- // data?.[0]?.resources?.find((i) => i?.type === "facility") ?
- {
- name: "facility",
- errorName: "facility",
- sections: [
- {
- name: "facility",
- type: "COMPONENT",
- component: "CampaignDocumentsPreview",
- props: {
- documents: data?.[0]?.resources?.filter((i) => i.type === "facility"),
- },
- cardHeader: { value: t("FACILITY_DETAILS"), inlineStyles: { marginTop: 0, fontSize: "1.5rem" } },
- cardSecondaryAction: noAction !== "false" && (
- handleRedirect(8)}>
- {t(`CAMPAIGN_EDIT`)}
-
-
- ),
- },
- ],
- },
- // : {}
- // data?.[0]?.resources?.find((i) => i?.type === "user") ?
- {
- name: "user",
- errorName: "user",
- sections: [
- {
- name: "user",
- type: "COMPONENT",
- component: "CampaignDocumentsPreview",
- props: {
- documents: data?.[0]?.resources?.filter((i) => i.type === "user"),
- },
- cardHeader: { value: t("USER_DETAILS"), inlineStyles: { marginTop: 0, fontSize: "1.5rem" } },
- cardSecondaryAction: noAction !== "false" && (
- handleRedirect(9)}>
- {t(`CAMPAIGN_EDIT`)}
-
-
- ),
- },
- ],
- },
- // : {}
- resourceIdArr?.length > 0
- ? {
- sections: [
- {
- type: "COMPONENT",
- component: "CampaignResourceDocuments",
- props: {
- isUserGenerate: true,
- // resources: processid,
- resources: resourceIdArr,
- },
- cardHeader: { value: t("USER_GENERATE_DETAILS"), inlineStyles: { marginTop: 0, fontSize: "1.5rem" } },
- },
- ],
- }
- : {},
- {
- sections: [
- {
- type: "DATA",
- cardHeader: { value: t("CAMPAIGN_DELIVERY_DETAILS"), inlineStyles: { marginTop: 0, fontSize: "1.5rem" } },
- cardSecondaryAction: noAction !== "false" && (
- handleRedirect(5)}>
- {t(`CAMPAIGN_EDIT`)}
-
-
- ),
- values: [
- {
- key: "CAMPAIGN_NO_OF_CYCLES",
- value:
- data?.[0]?.deliveryRules && data?.[0]?.deliveryRules.map((item) => item.cycleNumber)?.length > 0
- ? Math.max(...data?.[0]?.deliveryRules.map((item) => item.cycleNumber))
- : t("CAMPAIGN_SUMMARY_NA"),
- },
- {
- key: "CAMPAIGN_NO_OF_DELIVERIES",
- value:
- data?.[0]?.deliveryRules && data?.[0]?.deliveryRules.map((item) => item.deliveryNumber)?.length > 0
- ? Math.max(...data?.[0]?.deliveryRules.map((item) => item.deliveryNumber))
- : t("CAMPAIGN_SUMMARY_NA"),
- },
- ],
- },
- ],
- },
- ...cycleData?.map((item, index) => {
- return {
- name: `CYCLE_${index + 1}`,
- errorName: "deliveryErrors",
- sections: [
- {
- name: `CYCLE_${index + 1}`,
- type: "COMPONENT",
- cardHeader: { value: `${t("CYCLE")} ${item?.cycleIndex}`, inlineStyles: { marginTop: 0, fontSize: "1.5rem" } },
- cardSecondaryAction: noAction !== "false" && (
- handleRedirect(5)}>
- {t(`CAMPAIGN_EDIT`)}
-
-
- ),
- component: "CycleDataPreview",
- props: {
- data: item,
- },
- },
- ],
- };
- }),
- ],
- error: data?.[0]?.additionalDetails?.error,
- data: data?.[0],
- status: data?.[0]?.status,
- userGenerationSuccess: resourceIdArr,
- };
- },
- enabled: id ? true : false,
- staleTime: 0,
- cacheTime: 0,
- },
- });
-
- if (isLoading) {
- return ;
- }
- const closeToast = () => {
- setShowToast(null);
- };
- useEffect(() => {
- if (showToast) {
- setTimeout(closeToast, 5000);
- }
- }, [showToast]);
- useEffect(() => {
- if (data?.status === "failed" && data?.error) {
- setShowToast({ label: data?.error, key: "error" });
- }
- if (data?.status === "creating") {
- setShowToast({ label: "CAMPAIGN_STATUS_CREATING_MESSAGE", key: "info" });
- }
- if (data?.status === "created" && data?.userGenerationSuccess?.length > 0) {
- setShowToast({ label: "CAMPAIGN_USER_GENERATION_SUCCESS", key: "success" });
- }
- }, [data]);
-
- const downloadUserCred = async () => {
- downloadExcelWithCustomName(userCredential);
- };
-
- useEffect(() => {
- if (data?.userGenerationSuccess?.length > 0) {
- const fetchUser = async () => {
- const responseTemp = await Digit.CustomService.getResponse({
- url: `/project-factory/v1/data/_search`,
- body: {
- SearchCriteria: {
- tenantId: tenantId,
- id: data?.userGenerationSuccess,
- },
- },
- });
-
- const response = responseTemp?.ResourceDetails?.map((i) => i?.processedFilestoreId);
-
- if (response?.[0]) {
- setUserCredential({ fileStoreId: response?.[0], customName: "userCredential" });
- }
- };
- fetchUser();
- }
- }, [data]);
- return (
- <>
-
- {t("ES_TQM_SUMMARY_HEADING")}
- {userCredential && (
- }
- type="button"
- className="campaign-download-template-btn hover"
- onButtonClick={downloadUserCred}
- />
- )}
-
-
-
- {showToast && (
-
- )}
-
- >
- );
-};
-
-export default CampaignSummary;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignType.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignType.js
deleted file mode 100644
index a57ceb7008f..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CampaignType.js
+++ /dev/null
@@ -1,143 +0,0 @@
-import React, { useState, useMemo, useRef, useEffect } from "react";
-import { UploadIcon, FileIcon, DeleteIconv2, Toast, Card, Header } from "@egovernments/digit-ui-react-components";
-import { useTranslation } from "react-i18next";
-import { LabelFieldPair } from "@egovernments/digit-ui-react-components";
-import { Button, CardText, Dropdown, ErrorMessage, PopUp } from "@egovernments/digit-ui-components";
-
-const CampaignSelection = ({ onSelect, formData, formState, ...props }) => {
- const { t } = useTranslation();
- const tenantId = Digit.ULBService.getStateId();
- const { isLoading, data: projectType } = Digit.Hooks.useCustomMDMS(tenantId, "HCM-PROJECT-TYPES", [{ name: "projectTypes" }]);
- const [type, setType] = useState(props?.props?.sessionData?.HCM_CAMPAIGN_TYPE?.projectType || {});
- const [beneficiaryType, setBeneficiaryType] = useState(props?.props?.sessionData?.HCM_CAMPAIGN_TYPE?.projectType?.beneficiaryType || "");
- const [showBeneficiary, setShowBeneficiaryType] = useState(Boolean(props?.props?.sessionData?.HCM_CAMPAIGN_TYPE?.projectType?.beneficiaryType));
- const [executionCount, setExecutionCount] = useState(0);
- const [error, setError] = useState(null);
- const [startValidation, setStartValidation] = useState(null);
- const [showPopUp, setShowPopUp] = useState(null);
- const [canUpdate, setCanUpdate] = useState(null);
-
- useEffect(() => {
- if (props?.props?.isSubmitting && !type) {
- setError({ message: "CAMPAIGN_FIELD_MANDATORY" });
- }
- }, [props?.props?.isSubmitting]);
- useEffect(() => {
- setType(props?.props?.sessionData?.HCM_CAMPAIGN_TYPE?.projectType);
- setBeneficiaryType(props?.props?.sessionData?.HCM_CAMPAIGN_TYPE?.projectType?.beneficiaryType);
- setShowBeneficiaryType(Boolean(props?.props?.sessionData?.HCM_CAMPAIGN_TYPE?.projectType?.beneficiaryType));
- }, [props?.props?.sessionData?.HCM_CAMPAIGN_TYPE?.projectType]);
-
- const handleChange = (data) => {
- setType(data);
- setBeneficiaryType(data?.beneficiaryType);
- setShowBeneficiaryType(true);
- };
-
- useEffect(() => {
- if (!type && startValidation) {
- setError({ message: "CAMPAIGN_FIELD_MANDATORY" });
- } else {
- setError(null);
- onSelect("projectType", type);
- }
- }, [type]);
-
- useEffect(() => {
- if (executionCount < 5) {
- onSelect("projectType", type);
- setExecutionCount((prevCount) => prevCount + 1);
- }
- });
- return (
-
- {t(`HCM_CAMPAIGN_TYPE_HEADER`)}
- {t(`HCM_CAMPAIGN_TYPE_DESCRIPTION`)}
-
-
- {`${t("HCM_CAMPAIGN_TYPE")}`}
- *
-
- {
- if (props?.props?.sessionData?.HCM_CAMPAIGN_TYPE?.projectType && !canUpdate) {
- setShowPopUp(true);
- return;
- }
- return;
- }}
- onFocus={(e) => {
- if (props?.props?.sessionData?.HCM_CAMPAIGN_TYPE?.projectType && !canUpdate) {
- setShowPopUp(true);
- return;
- }
- return;
- }}
- >
- {
- setStartValidation(true);
- handleChange(value);
- }}
- />
- {error?.message && }
-
-
- {showBeneficiary && (
-
- {`${t("HCM_BENEFICIARY_TYPE")}`}
- {t(`CAMPAIGN_TYPE_${beneficiaryType}`)}
-
- )}
- {showPopUp && (
-
- {t("ES_CAMPAIGN_UPDATE_TYPE_MODAL_TEXT") + " "}
- ,
- ]}
- onOverlayClick={() => {
- setShowPopUp(false);
- }}
- footerChildren={[
-
- )}
-
- );
-};
-
-export default CampaignSelection;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CycleDataPreview.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CycleDataPreview.js
deleted file mode 100644
index 9faad7c4c2a..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CycleDataPreview.js
+++ /dev/null
@@ -1,186 +0,0 @@
-import { Card, LabelFieldPair, Row } from "@egovernments/digit-ui-react-components";
-import React, { Fragment, useEffect, useState } from "react";
-import { useTranslation } from "react-i18next";
-import DetailsTable from "./DetailsTable";
-import { Button, InfoCard } from "@egovernments/digit-ui-components";
-
-const Tabs = ({ deliveryData, onTabChange }) => {
- // const { campaignData, dispatchCampaignData } = useContext(CycleContext);
- const { t } = useTranslation();
-
- return (
-
- {deliveryData?.map((_, index) => (
- onTabChange(_.deliveryIndex, index)}
- >
- {t(`CAMPAIGN_DELIVERY`)} {index + 1}
-
- ))}
-
- );
-};
-
-const CycleDataPreview = ({ data, items, index, errors, onErrorClick, cardErrors }) => {
- const { t } = useTranslation();
- const [deliveryData, setDeliveryData] = useState(data?.deliveries);
- const [activeTab, setActiveTab] = useState(1);
-
- useEffect(() => {
- setDeliveryData(data?.deliveries);
- }, [data?.deliveries]);
-
- const handleTabChange = (tabIndex, index) => {
- setDeliveryData((prev) => {
- return prev.map((i) => {
- if (i.deliveryIndex == tabIndex) {
- return {
- ...i,
- active: true,
- };
- } else {
- return {
- ...i,
- active: false,
- };
- }
- });
- });
- };
- // return null;
- return (
- <>
- {cardErrors?.map((i) => (
- ]}
- />
- ))}
- {/* {i.error ? i.error : i.message)} */}
-
- {data?.startDate && (
-
- )}
- {data?.endDate && (
-
- )}
-
-
-
-
-
-
- {deliveryData
- .find((i) => i.active === true)
- ?.deliveryRules?.map((rules, ruleIndex) => {
- return (
-
- {rules?.attributes?.length > 0 && (
-
- )}
- {rules?.products?.length > 0 && (
-
- )}
-
- );
- })}
-
- {/*
- {item?.conditions?.length > 0 && (
-
- )}
- {item?.products?.length > 0 && (
-
- )}
- */}
- >
- );
-};
-
-export default CycleDataPreview;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CycleDetaisPreview.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CycleDetaisPreview.js
deleted file mode 100644
index 515b25191d9..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/CycleDetaisPreview.js
+++ /dev/null
@@ -1,143 +0,0 @@
-import { Card, LabelFieldPair, Row } from "@egovernments/digit-ui-react-components";
-import React, { Fragment } from "react";
-import { useTranslation } from "react-i18next";
-import DetailsTable from "./DetailsTable";
-
-function mergeObjects(item) {
- const arr = item?.conditions;
- const mergedArr = [];
- const mergedAttributes = new Set();
-
- arr.forEach((obj) => {
- if (!mergedAttributes.has(obj.attribute)) {
- const sameAttrObjs = arr.filter((o) => o.attribute === obj.attribute);
-
- if (sameAttrObjs.length > 1) {
- const fromValue = Math.min(...sameAttrObjs.map((o) => o.value));
- const toValue = Math.max(...sameAttrObjs.map((o) => o.value));
-
- mergedArr.push({
- fromValue,
- toValue,
- value: fromValue > 0 && toValue > 0 ? `${fromValue} to ${toValue}` : null,
- operator: "IN_BETWEEN",
- attribute: obj.attribute,
- });
-
- mergedAttributes.add(obj.attribute);
- } else {
- mergedArr.push(obj);
- }
- }
- });
-
- return { ...item, conditions: mergedArr };
-}
-
-const CycleDetaisPreview = ({ data, items, index }) => {
- const { t } = useTranslation();
- const item = mergeObjects(items);
-
- return (
- <>
-
-
- {/*
- {`${t("CYCLE_NUMBER")}`}
- {item?.cycleNumber}
-
-
- {`${t("DELIVERY_NUMBER")}`}
- {item?.deliveryNumber}
- */}
- {item?.startDate || item?.endDate ? (
-
-
-
- {t(`CYCLE`)} {item?.cycleNumber}
-
-
- {item?.startDate && (
-
- )}
- {item?.endDate && (
-
- )}
-
- ) : null}
-
-
- {item?.conditions?.length > 0 && (
-
- )}
- {item?.products?.length > 0 && (
-
- )}
-
- >
- );
-};
-
-export default CycleDetaisPreview;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/DetailsTable.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/DetailsTable.js
deleted file mode 100644
index 5c6e01fcc22..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/DetailsTable.js
+++ /dev/null
@@ -1,76 +0,0 @@
-import React, { Fragment } from "react";
-import { useTable } from "react-table";
-import { useTranslation } from "react-i18next";
-import { CardLabel, CardSubHeader } from "@egovernments/digit-ui-react-components";
-
-const DetailsTable = ({ className = "", columnsData, rowsData, summaryRows, cardHeader }) => {
- const { t } = useTranslation();
-
- const columns = React.useMemo(() => columnsData, [t]);
-
- const data = React.useMemo(() => {
- const temp = rowsData.map((i) => ({
- ...i,
- operator: t(i?.operator),
- attribute: i?.attribute ? t(`CAMPAIGN_ATTRIBUTE_${i?.attribute?.toUpperCase()}`) : "",
- }));
- return temp;
- }, [rowsData]);
-
- const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } = useTable({
- columns,
- data,
- });
-
- return (
- <>
- {cardHeader && (
-
- {cardHeader?.value}
-
- )}
-
-
-
- {headerGroups.map((headerGroup) => (
-
- {headerGroup.headers.map((column) => (
-
- {column.render("Header")}
- |
- ))}
-
- ))}
-
-
-
- {rows.map((row) => {
- prepareRow(row);
- return (
-
- {row.cells.map((cell) => (
-
- {cell.render("Cell")}
- |
- ))}
-
- );
- })}
-
- {summaryRows && (
-
- {summaryRows.map((cell, index) => (
-
- {index === 4 ? {cell} : cell}
- |
- ))}
-
- )}
-
-
-
- >
- );
-};
-
-export default DetailsTable;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/DocumentIcon.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/DocumentIcon.js
deleted file mode 100644
index 9b61bf67136..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/DocumentIcon.js
+++ /dev/null
@@ -1,29 +0,0 @@
-import React from "react";
-export const DocumentIcon = ({ styles = {}, className, fill = "#D4351C" }) => (
-
-);
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/PlusMinusInput.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/PlusMinusInput.js
deleted file mode 100644
index 89d7b574032..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/PlusMinusInput.js
+++ /dev/null
@@ -1,47 +0,0 @@
-import React, { useState } from "react";
-
-const PlusMinusInput = (props, customProps) => {
- let count = props?.defaultValues || 1;
-
- function incrementCount() {
- if (count >= 1) {
- count = count + 1;
- props.onSelect(count);
- } else {
- count = 1;
- props.onSelect(count);
- }
- }
- function decrementCount() {
- if (count > 1) {
- count = count - 1;
- props.onSelect(count);
- } else {
- count = 1;
- props.onSelect(count);
- }
- }
-
- return (
-
-
- decrementCount(count)} className="PlusMinusbutton">
- -
-
-
- incrementCount(count)} className="PlusMinusbutton">
- +
-
-
-
- );
-};
-
-export default PlusMinusInput;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/RemovableTagNew.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/RemovableTagNew.js
deleted file mode 100644
index b04159181a6..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/RemovableTagNew.js
+++ /dev/null
@@ -1,16 +0,0 @@
-import React from "react";
-import { Close } from "@egovernments/digit-ui-react-components";
-
-const RemoveableTagNew = ({ text = {}, onClick, extraStyles, disabled = false }) => (
-
- {text?.label && {`${text?.label} :`}}
-
- {text?.value}
-
-
-
-
-
-);
-
-export default RemoveableTagNew;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/SelectingBoundaries.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/SelectingBoundaries.js
deleted file mode 100644
index 239cf948ee0..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/SelectingBoundaries.js
+++ /dev/null
@@ -1,542 +0,0 @@
-import React, { useEffect, useState, Fragment, useMemo } from "react";
-import { CardText, LabelFieldPair, Card, Header, CardLabel, LoaderWithGap } from "@egovernments/digit-ui-react-components";
-import { useTranslation } from "react-i18next";
-import { InfoCard, MultiSelectDropdown, PopUp, Button, Toast } from "@egovernments/digit-ui-components";
-import { mailConfig } from "../configs/mailConfig";
-/**
- * The function `SelectingBoundaries` in JavaScript handles the selection of boundaries based on
- * hierarchy data and allows users to choose specific boundaries within the hierarchy.
- * @returns The `SelectingBoundaries` component is being returned. It consists of JSX elements
- * including Cards, Headers, Dropdowns, MultiSelectDropdowns, and InfoCard. The component allows users
- * to select hierarchy types and boundaries based on the data fetched from API calls. It also handles
- * the selection of boundaries and updates the state accordingly. The component is designed to be
- * interactive and user-friendly for selecting boundaries within
- */
-function SelectingBoundaries({ onSelect, formData, ...props }) {
- const { t } = useTranslation();
- const tenantId = Digit.ULBService.getCurrentTenantId();
- const [params, setParams] = useState(props?.props?.dataParams);
- const [hierarchy, setHierarchy] = useState(params?.hierarchyType);
- const [boundaryType, setBoundaryType] = useState(
- props?.props?.sessionData?.HCM_CAMPAIGN_SELECTING_BOUNDARY_DATA?.boundaryType?.boundaryData ? undefined : null
- );
- const [targetedData, setTargetedData] = useState();
- const [boundaryData, setBoundaryData] = useState(props?.props?.sessionData?.HCM_CAMPAIGN_SELECTING_BOUNDARY_DATA?.boundaryType?.boundaryData || {});
- // const [parentArray, setParentArray] = useState(props?.props?.sessionData?.HCM_CAMPAIGN_SELECTING_BOUNDARY_DATA?.boundaryType?.selectedData.filter(item => item.includeAllChildren).map(item => item.code) || null);
- const [parentArray, setParentArray] = useState(null);
- const [boundaryTypeDataresult, setBoundaryTypeDataresult] = useState(null);
- const [selectedData, setSelectedData] = useState(props?.props?.sessionData?.HCM_CAMPAIGN_SELECTING_BOUNDARY_DATA?.boundaryType?.selectedData || []);
- const [parentBoundaryTypeRoot, setParentBoundaryTypeRoot] = useState(
- (props?.props?.sessionData?.HCM_CAMPAIGN_SELECTING_BOUNDARY_DATA?.boundaryType?.selectedData?.find((item) => item?.isRoot === true) || {})
- ?.boundaryType || null
- );
- const [showToast, setShowToast] = useState(null);
- const [updatedHierarchy, setUpdatedHierarchy] = useState({});
- const [hierarchyTypeDataresult, setHierarchyTypeDataresult] = useState(params?.hierarchy);
- const [executionCount, setExecutionCount] = useState(0);
- // State variable to store the lowest hierarchy level
- // const [lowestHierarchy, setLowestHierarchy] = useState(null);
- const [showPopUp, setShowPopUp] = useState(null);
- const [restrictSelection, setRestrictSelection] = useState(null);
- const [updateBoundary, setUpdateBoundary] = useState(null);
- const [loaderEnabled, setLoaderEnabled] = useState(false);
- const { isLoading, data: hierarchyConfig } = Digit.Hooks.useCustomMDMS(tenantId, "HCM-ADMIN-CONSOLE", [{ name: "hierarchyConfig" }]);
-
- // const lowestHierarchy = hierarchyConfig?.["HCM-ADMIN-CONSOLE"]?.hierarchyConfig?.[0]?.lowestHierarchy;
- const lowestHierarchy = useMemo(() => hierarchyConfig?.["HCM-ADMIN-CONSOLE"]?.hierarchyConfig?.[0]?.lowestHierarchy, [hierarchyConfig]);
- const lowestChild = hierarchyTypeDataresult?.boundaryHierarchy.filter((item) => item.parentBoundaryType === lowestHierarchy)?.[0]?.boundaryType;
- const searchParams = new URLSearchParams(location.search);
- const isDraft = searchParams.get("draft");
-
- useEffect(() => {
- if (!updateBoundary) {
- if (
- props?.props?.sessionData?.HCM_CAMPAIGN_UPLOAD_BOUNDARY_DATA?.uploadBoundary?.uploadedFile?.length > 0 ||
- props?.props?.sessionData?.HCM_CAMPAIGN_UPLOAD_FACILITY_DATA?.uploadFacility?.uploadedFile?.length > 0 ||
- props?.props?.sessionData?.HCM_CAMPAIGN_UPLOAD_USER_DATA?.uploadUser?.uploadedFile?.length > 0
- ) {
- setRestrictSelection(true);
- }
- }
- }, [props?.props?.sessionData, updateBoundary]);
-
- useEffect(() => {
- if (props?.props?.dataParams) {
- setParams(props?.props?.dataParams);
- }
- }, [props?.props?.dataParams]);
-
- useEffect(() => {
- onSelect("boundaryType", { boundaryData: boundaryData, selectedData: selectedData, updateBoundary: updateBoundary });
- }, [boundaryData, selectedData]);
-
- useEffect(() => {
- setHierarchy(params?.hierarchyType);
- }, [params?.hierarchyType]);
-
- useEffect(() => {
- if (params?.hierarchy) {
- const sortHierarchy = (hierarchy) => {
- const boundaryMap = new Map();
- hierarchy.forEach(item => {
- boundaryMap.set(item.boundaryType, item);
- });
-
- const sortedHierarchy = [];
- let currentType = null;
-
- while (sortedHierarchy.length < hierarchy.length) {
- for (let i = 0; i < hierarchy.length; i++) {
- if (hierarchy[i].parentBoundaryType === currentType) {
- sortedHierarchy.push(hierarchy[i]);
- currentType = hierarchy[i].boundaryType;
- break;
- }
- }
- }
-
- return sortedHierarchy;
- };
-
- const sortedHierarchy = sortHierarchy(params.hierarchy.boundaryHierarchy);
- setHierarchyTypeDataresult({
- ...params.hierarchy,
- boundaryHierarchy: sortedHierarchy
- });
- }
- }, [params?.hierarchy]);
-
- useEffect(() => {
- if (executionCount < 5) {
- onSelect("boundaryType", { boundaryData: boundaryData, selectedData: selectedData, updateBoundary: updateBoundary });
- setExecutionCount((prevCount) => prevCount + 1);
- }
- });
-
- useEffect(() => {
- setBoundaryData(
- props?.props?.sessionData?.HCM_CAMPAIGN_SELECTING_BOUNDARY_DATA?.boundaryType?.boundaryData
- ? props?.props?.sessionData?.HCM_CAMPAIGN_SELECTING_BOUNDARY_DATA?.boundaryType?.boundaryData
- : {}
- );
- setSelectedData(
- props?.props?.sessionData?.HCM_CAMPAIGN_SELECTING_BOUNDARY_DATA?.boundaryType?.selectedData
- ? props?.props?.sessionData?.HCM_CAMPAIGN_SELECTING_BOUNDARY_DATA?.boundaryType?.selectedData
- : []
- );
- }, [props?.props?.sessionData?.HCM_CAMPAIGN_SELECTING_BOUNDARY_DATA?.boundaryType]);
-
- const closeToast = () => {
- setShowToast(null);
- };
-
- useEffect(() => {
- if (hierarchyTypeDataresult) {
- const boundaryDataObj = {};
- hierarchyTypeDataresult?.boundaryHierarchy?.forEach((boundary) => {
- boundaryDataObj[boundary?.boundaryType] = [];
- });
- if (!props?.props?.sessionData?.HCM_CAMPAIGN_SELECTING_BOUNDARY_DATA?.boundaryType?.boundaryData || Object.keys(boundaryData).length === 0) {
- setBoundaryData(boundaryDataObj);
- }
- const boundaryWithTypeNullParent = hierarchyTypeDataresult?.boundaryHierarchy?.find((boundary) => boundary?.parentBoundaryType === null);
- // Set the boundary type with null parentBoundaryType
- if (boundaryWithTypeNullParent) {
- if (!props?.props?.sessionData?.HCM_CAMPAIGN_SELECTING_BOUNDARY_DATA?.boundaryType?.boundaryData || Object.keys(boundaryData).length === 0) {
- setBoundaryType(boundaryWithTypeNullParent?.boundaryType);
- }
- setParentBoundaryTypeRoot(boundaryWithTypeNullParent?.boundaryType);
- }
- createHierarchyStructure(hierarchyTypeDataresult);
- }
- }, [hierarchyTypeDataresult]);
-
- function createHierarchyStructure(hierarchyTypeDataresult) {
- const hierarchyStructure = {};
-
- // Recursive function to gather all descendants for a given boundary type
- function gatherDescendants(boundaryType) {
- const descendants = [];
- hierarchyTypeDataresult;
-
- // Find all children for the current boundary type
- const children = hierarchyTypeDataresult?.boundaryHierarchy?.filter((item) => item?.parentBoundaryType === boundaryType);
-
- // Recursively gather descendants for each child
- children.forEach((child) => {
- const childBoundaryType = child?.boundaryType;
- const childDescendants = gatherDescendants(childBoundaryType);
- descendants.push(childBoundaryType, ...childDescendants);
- });
-
- return descendants;
- }
-
- // Iterate through the boundaryHierarchy array to populate hierarchyStructure
- hierarchyTypeDataresult?.boundaryHierarchy?.forEach((item) => {
- const boundaryType = item?.boundaryType;
- const descendants = gatherDescendants(boundaryType);
-
- hierarchyStructure[boundaryType] = descendants;
- });
-
- setUpdatedHierarchy(hierarchyStructure);
- }
-
- const newData = [];
- const fetchBoundaryTypeData = async () => {
- if (boundaryType === undefined || boundaryType === lowestChild) {
- // Do nothing if boundaryType is undefined
- return;
- }
- if (parentArray === null) {
- const reqCriteriaBoundaryTypeSearch = Digit.CustomService.getResponse({
- url: "/boundary-service/boundary-relationships/_search",
- params: {
- tenantId: tenantId,
- hierarchyType: hierarchy,
- boundaryType: boundaryType,
- parent: null,
- },
- body: {},
- });
- // setShowToast({ key: "info", label: t("HCM_PLEASE_WAIT_LOADING_BOUNDARY") });
- const boundaryTypeData = await reqCriteriaBoundaryTypeSearch;
- setBoundaryTypeDataresult([{ parentCode: null, boundaryTypeData: boundaryTypeData }]);
- // closeToast();
- } else {
- // for (const parentCode of parentArray) {
- // const reqCriteriaBoundaryTypeSearch = Digit.CustomService.getResponse({
- // url: "/boundary-service/boundary-relationships/_search",
- // params: {
- // tenantId: tenantId,
- // hierarchyType: hierarchy,
- // boundaryType: boundaryType,
- // parent: parentCode,
- // },
- // body: {},
- // });
- // // setShowToast({ key: "info", label: t("HCM_PLEASE_WAIT_LOADING_BOUNDARY") });
- // setLoaderEnabled(true);
- // const boundaryTypeData = await reqCriteriaBoundaryTypeSearch;
- // newData.push({ parentCode, boundaryTypeData });
- // }
- setLoaderEnabled(true);
- const temp = await Digit.Hooks.campaign.useParallelSearch({
- parentArray: parentArray,
- tenantId: tenantId,
- boundaryType: boundaryType,
- hierarchy: hierarchy,
- targetedData: targetedData,
- });
- const newDataArray = [...newData, ...temp];
- setBoundaryTypeDataresult(newDataArray);
- setTimeout(() => {
- setLoaderEnabled(false);
- }, 100);
- // closeToast();
- }
- };
-
- useEffect(() => {
- fetchBoundaryTypeData();
- }, [boundaryType, parentArray, selectedData]);
-
- useEffect(() => {
- if (boundaryTypeDataresult) {
- if (boundaryType !== undefined) {
- const updatedBoundaryData = {
- ...boundaryData,
- [boundaryType]: boundaryTypeDataresult,
- };
- setBoundaryData(updatedBoundaryData);
- } else {
- const updatedBoundaryData = {
- ...boundaryData,
- [boundaryTypeDataresult?.[0]?.boundaryTypeData?.TenantBoundary?.[0]?.boundary?.[0]?.boundaryType]: boundaryTypeDataresult,
- };
- setBoundaryData(updatedBoundaryData);
- }
- }
- }, [boundaryTypeDataresult]);
-
- const checkDataPresent = ({ action }) => {
- if (action === false) {
- setShowPopUp(false);
- setUpdateBoundary(true);
- setRestrictSelection(false);
- return;
- }
- if (action === true) {
- setShowPopUp(false);
- setUpdateBoundary(false);
- return;
- }
- };
-
- const handleBoundaryChange = (data, boundary) => {
- setTargetedData(boundary?.boundaryType);
- if (
- !updateBoundary &&
- restrictSelection &&
- (props?.props?.sessionData?.HCM_CAMPAIGN_UPLOAD_BOUNDARY_DATA?.uploadBoundary?.uploadedFile?.length > 0 ||
- props?.props?.sessionData?.HCM_CAMPAIGN_UPLOAD_FACILITY_DATA?.uploadFacility?.uploadedFile?.length > 0 ||
- props?.props?.sessionData?.HCM_CAMPAIGN_UPLOAD_USER_DATA?.uploadUser?.uploadedFile?.length > 0)
- ) {
- setShowPopUp(true);
- return;
- }
- if (!data || data.length === 0) {
- const check = updatedHierarchy[boundary?.boundaryType];
-
- if (check) {
- const typesToRemove = [boundary?.boundaryType, ...check];
- const updatedSelectedData = selectedData?.filter((item) => !typesToRemove?.includes(item?.type));
- const updatedBoundaryData = { ...boundaryData };
-
- typesToRemove.forEach((type) => {
- if (type !== boundary?.boundaryType && updatedBoundaryData?.hasOwnProperty(type)) {
- updatedBoundaryData[type] = [];
- }
- });
- if (!_.isEqual(selectedData, updatedSelectedData)) {
- setSelectedData(updatedSelectedData);
- }
- setBoundaryData(updatedBoundaryData);
- }
- return;
- }
-
- let res = [];
- data &&
- data?.map((ob) => {
- res.push(ob?.[1]);
- });
-
- // const transformedRes = res?.map((item) => ({
- // code: item.code,
- // type: item.type || item.boundaryType,
- // isRoot: item.boundaryType === parentBoundaryTypeRoot,
- // includeAllChildren: item.type === lowestHierarchy || item.boundaryType === lowestHierarchy,
- // parent: item?.parent,
- // }));
-
- let transformedRes = [];
- if (!isDraft) {
- transformedRes = res?.map((item) => ({
- code: item.code,
- type: item.type || item.boundaryType,
- isRoot: item.boundaryType === parentBoundaryTypeRoot,
- includeAllChildren: item.type === lowestHierarchy || item.boundaryType === lowestHierarchy,
- parent: item?.parent,
- }));
- } else {
- // transformedRes = selectedData.filter((item) => item?.type === boundary?.boundaryType)
- const filteredData = selectedData.filter((item) => item?.type === boundary?.boundaryType);
- if (filteredData.length === 0) {
- // If no selected data for the particular boundary type, run the transformation logic
- transformedRes = res?.map((item) => ({
- code: item.code,
- type: item.type || item.boundaryType,
- isRoot: item.boundaryType === parentBoundaryTypeRoot,
- includeAllChildren: item.type === lowestHierarchy || item.boundaryType === lowestHierarchy,
- parent: item?.parent,
- }));
- } else {
- transformedRes = filteredData;
- }
- }
-
- const newBoundaryType = transformedRes?.[0]?.type;
- const existingBoundaryType = selectedData?.length > 0 ? selectedData?.[0]?.type : null;
- if (existingBoundaryType === newBoundaryType) {
- // Update only the data for the specific boundaryType
- const flattenedRes = transformedRes.flat();
- const updatedSelectedData = selectedData
- ?.map((item) => {
- if (item.type === newBoundaryType) {
- return transformedRes?.flat();
- } else {
- return item;
- }
- })
- .flat();
- if (!_.isEqual(selectedData, updatedSelectedData)) {
- setSelectedData(updatedSelectedData);
- }
- } else {
- // Update only the data for the new boundaryType
- const mergedData = [...selectedData?.filter((item) => item?.type !== newBoundaryType), ...transformedRes];
-
- // Filter out items with undefined type
- const filteredData = mergedData?.filter(
- (item, index, self) => item?.type !== undefined && index === self?.findIndex((t) => t?.code === item?.code)
- );
-
- // Filter out items whose parent is not present in the array
-
- const updatedSelectedData = [];
- const addChildren = (item) => {
- updatedSelectedData.push(item);
- const children = filteredData.filter((child) => child.parent === item.code);
- children.forEach((child) => addChildren(child));
- };
- filteredData.filter((item) => item.isRoot).forEach((rootItem) => addChildren(rootItem));
- if (!_.isEqual(selectedData, updatedSelectedData)) {
- setSelectedData(updatedSelectedData);
- }
- }
- const parentBoundaryEntry = hierarchyTypeDataresult
- ? hierarchyTypeDataresult?.boundaryHierarchy?.find(
- (e) => e?.parentBoundaryType === res?.[0]?.boundaryType || e?.parentBoundaryType === res?.[0]?.type
- )
- : null;
- setBoundaryType(parentBoundaryEntry?.boundaryType);
- const codes = res?.map((item) => item?.code);
- if (JSON.stringify(codes) !== JSON.stringify(parentArray)) {
- setParentArray(codes);
- }
- };
-
- return (
- <>
- {loaderEnabled && }
-
-
-
{t(`CAMPAIGN_SELECT_BOUNDARY`)}
-
{t(`CAMPAIGN_SELECT_BOUNDARIES_DESCRIPTION`)}
- {hierarchyTypeDataresult?.boundaryHierarchy
- .filter((boundary, index, array) => {
- // Find the index of the lowest hierarchy
- const lowestIndex = array.findIndex((b) => b.boundaryType === lowestHierarchy);
- // Include only those boundaries that are above or equal to the lowest hierarchy
- return index <= lowestIndex;
- })
- .map((boundary, index) =>
- boundary?.parentBoundaryType == null ? (
-
-
- {/* {t(`${hierarchy}_${boundary?.boundaryType}`?.toUpperCase())} */}
- {t((hierarchy + "_" + boundary?.boundaryType).toUpperCase())}
-
- *
-
-
- item?.boundaryTypeData?.TenantBoundary?.[0]?.boundary)?.flat() || []
- }
- optionsKey={"code"}
- selected={selectedData?.filter((item) => item?.type === boundary?.boundaryType) || []}
- onSelect={(value) => {
- handleBoundaryChange(value, boundary);
- }}
- />
-
-
- ) : (
-
-
- {t((hierarchy + "_" + boundary?.boundaryType).toUpperCase())}
- *
-
-
- ({
- code: item?.parentCode,
- options:
- item?.boundaryTypeData?.TenantBoundary?.[0]?.boundary?.map((child) => ({
- code: child?.code,
- type: child?.boundaryType,
- parent: item?.parentCode,
- })) || [],
- })) || []
- }
- optionsKey={"code"}
- onSelect={(value) => {
- handleBoundaryChange(value, boundary);
- }}
- selected={selectedData?.filter((item) => item?.type === boundary?.boundaryType) || []}
- addCategorySelectAllCheck={true}
- addSelectAllCheck={true}
- variant="nestedmultiselect"
- />
-
-
- )
- )}
-
-
-
- {t("HCM_BOUNDARY_INFO ")}
-
- {mailConfig?.mailId}
-
- ,
- ]}
- label={"Info"}
- />
- {showPopUp && (
-
- {t("ES_CAMPAIGN_UPDATE_BOUNDARY_MODAL_TEXT") + " "}
- ,
- ]}
- onOverlayClick={() => {
- setShowPopUp(false);
- }}
- footerChildren={[
- {
- checkDataPresent({ action: false });
- }}
- />,
- {
- checkDataPresent({ action: true });
- }}
- />,
- ]}
- sortFooterChildren={true}
- >
- )}
- {showToast && (
-
- )}
- >
- );
-}
-export default SelectingBoundaries;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/TimelineCampaign.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/TimelineCampaign.js
deleted file mode 100644
index 8e4f6062d86..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/TimelineCampaign.js
+++ /dev/null
@@ -1,46 +0,0 @@
-import React from "react";
-import { useTranslation } from "react-i18next";
-import { TickMark } from "@egovernments/digit-ui-react-components";
-
-let actions = [];
-
-const getAction = (flow) => {
- switch (flow) {
- case "STAKEHOLDER":
- actions = ["BPA_LICENSE_DETAILS_LABEL", "BPA_NEW_ADDRESS_HEADER_DETAILS", "BPA_DOC_DETAILS_SUMMARY", "BPA_STEPPER_SUMMARY_HEADER"];
- break;
- case "OCBPA":
- actions = ["BPA_BASIC_AND_PLOT_DETAILS_LABEL", "BPA_SCRUTINY_DETAILS", "BPA_DOCUMENT_AND_NOC_DETAILS_LABEL", "BPA_STEPPER_SUMMARY_HEADER"];
- break;
- default:
- actions = [
- "HCM_CAMPAIGN_SETUP_DETAILS",
- "HCM_DELIVERY_DETAILS",
- "HCM_BOUNDARY_DETAILS",
- "HCM_TARGETS",
- "HCM_FACILITY_DETAILS",
- "HCM_USER_DETAILS",
- "HCM_REVIEW_DETAILS",
- ];
- }
-};
-const TimelineCampaign = ({ currentStep = 1, flow = "" , onStepClick }) => {
- const { t } = useTranslation();
- const isMobile = window.Digit.Utils.browser.isMobile();
- getAction(flow);
- return (
-
- {actions.map((action, index, arr) => (
-
onStepClick(index)}>
-
- {index < currentStep - 1 ? : index + 1}
- {t(action)}
-
- {index < arr.length - 1 &&
}
-
- ))}
-
- );
-};
-
-export default TimelineCampaign;
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/UploadData.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/UploadData.js
deleted file mode 100644
index 09cb1a0f9c0..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/UploadData.js
+++ /dev/null
@@ -1,1163 +0,0 @@
-import { Header, LoaderWithGap } from "@egovernments/digit-ui-react-components";
-import React, { useRef, useState, useEffect, Fragment } from "react";
-import { useTranslation } from "react-i18next";
-import { Card, Modal, CardText } from "@egovernments/digit-ui-react-components";
-import BulkUpload from "./BulkUpload";
-import Ajv from "ajv";
-import XLSX from "xlsx";
-import { InfoCard, PopUp, Toast, Button, DownloadIcon } from "@egovernments/digit-ui-components";
-import { schemaConfig } from "../configs/schemaConfig";
-import { headerConfig } from "../configs/headerConfig";
-import { PRIMARY_COLOR } from "../utils";
-import { downloadExcelWithCustomName } from "../utils";
-
-/**
- * The `UploadData` function in JavaScript handles the uploading, validation, and management of files
- * for different types of data in a web application.
- * @returns The `UploadData` component is returning a JSX structure that includes a div with class
- * names, a Header component, a Button component for downloading a template, an info-text div, a
- * BulkUpload component for handling file uploads, and an InfoCard component for displaying error
- * messages if any validation errors occur during file upload.
- */
-const UploadData = ({ formData, onSelect, ...props }) => {
- const { t } = useTranslation();
- const tenantId = Digit.ULBService.getCurrentTenantId();
- const [uploadedFile, setUploadedFile] = useState([]);
- const params = Digit.SessionStorage.get("HCM_CAMPAIGN_MANAGER_UPLOAD_ID");
- const [showInfoCard, setShowInfoCard] = useState(false);
- const [errorsType, setErrorsType] = useState({});
- const [schema, setSchema] = useState(null);
- const [showToast, setShowToast] = useState(null);
- const type = props?.props?.type;
- const [executionCount, setExecutionCount] = useState(0);
- const [isError, setIsError] = useState(false);
- const [isSuccess, setIsSuccess] = useState(false);
- const [apiError, setApiError] = useState(null);
- const [isValidation, setIsValidation] = useState(false);
- const [fileName, setFileName] = useState(null);
- const [downloadError, setDownloadError] = useState(false);
- const [resourceId, setResourceId] = useState(null);
- const searchParams = new URLSearchParams(location.search);
- const id = searchParams.get("id");
- // const { isLoading, data: Schemas } = Digit.Hooks.useCustomMDMS(tenantId, "HCM-ADMIN-CONSOLE", [
- // { name: "facilitySchema" },
- // { name: "userSchema" },
- // { name: "Boundary" },
- // ]);
-
- const { data: Schemas, isLoading: isThisLoading } = Digit.Hooks.useCustomMDMS(tenantId, "HCM-ADMIN-CONSOLE", [{ name: "adminSchema" }]);
-
- const { data: readMe } = Digit.Hooks.useCustomMDMS(tenantId, "HCM-ADMIN-CONSOLE", [{ name: "ReadMeConfig" }]);
- const { data: baseTimeOut } = Digit.Hooks.useCustomMDMS(tenantId, "HCM-ADMIN-CONSOLE", [{ name: "baseTimeout" }]);
- const [sheetHeaders, setSheetHeaders] = useState({});
- const [translatedSchema, setTranslatedSchema] = useState({});
- const [readMeInfo, setReadMeInfo] = useState({});
- const [enabled, setEnabled] = useState(false);
- const [showPopUp, setShowPopUp] = useState(true);
- const currentKey = searchParams.get("key");
- const totalData = Digit.SessionStorage.get("HCM_CAMPAIGN_MANAGER_FORM_DATA");
- const [convertedSchema, setConvertedSchema] = useState({});
- const [loader, setLoader] = useState(false);
-
-
- useEffect(() => {
- if (type === "facilityWithBoundary") {
- onSelect("uploadFacility", { uploadedFile, isError, isValidation, apiError, isSuccess });
- } else if (type === "boundary") {
- onSelect("uploadBoundary", { uploadedFile, isError, isValidation, apiError, isSuccess });
- } else {
- onSelect("uploadUser", { uploadedFile, isError, isValidation, apiError, isSuccess });
- }
- }, [uploadedFile, isError, isValidation, apiError, isSuccess]);
-
- useEffect(() => {
- if (resourceId) {
- setUploadedFile((prev) =>
- prev.map((i) => ({
- ...i,
- resourceId: resourceId,
- }))
- );
- }
- }, [resourceId]);
- var translateSchema = (schema) => {
- var newSchema = { ...schema };
- var newProp = {};
-
- // Object.keys(schema?.properties)
- // .map((e) => ({ key: e, value: t(e) }))
- // .map((e) => {
- // newProp[e.value] = schema?.properties[e.key];
- // });
-
- // Translate properties keys and their 'name' fields
- Object.keys(schema?.properties).forEach((key) => {
- const translatedKey = t(key);
- const translatedProperty = { ...schema.properties[key], name: t(schema.properties[key].name) };
- newProp[translatedKey] = translatedProperty;
- });
- const newRequired = schema?.required.map((e) => t(e));
-
- newSchema.properties = newProp;
- newSchema.required = newRequired;
- delete newSchema.unique;
- return { ...newSchema };
- };
-
- var translateReadMeInfo = (schema) => {
- const translatedSchema = schema.map((item) => {
- return {
- header: t(item.header),
- isHeaderBold: item.isHeaderBold,
- inSheet: item.inSheet,
- inUiInfo: item.inUiInfo,
- descriptions: item.descriptions.map((desc) => {
- return {
- text: t(desc.text),
- isStepRequired: desc.isStepRequired,
- };
- }),
- };
- });
- return translatedSchema;
- };
-
- function enrichSchema(data, properties, required, columns) {
- // Sort columns based on orderNumber, using name as tie-breaker if orderNumbers are equal
- columns.sort((a, b) => {
- if (a?.orderNumber === b?.orderNumber) {
- return a.name.localeCompare(b.name);
- }
- return a.orderNumber - b.orderNumber;
- });
-
- // Extract sorted property names
- const sortedPropertyNames = columns.map((column) => column.name);
-
- // Update data with new properties and required fields
- data.properties = properties;
- data.required = required;
- // delete data.campaignType;
- // data.columns = sortedPropertyNames;
- }
-
- function convertIntoSchema(data) {
- var convertData = { ...data };
- var properties = {};
- var required = [];
- var columns = [];
-
- for (const propType of ["enumProperties", "numberProperties", "stringProperties"]) {
- if (convertData?.properties[propType] && Array.isArray(convertData?.properties[propType]) && convertData?.properties[propType]?.length > 0) {
- for (const property of convertData?.properties[propType]) {
- properties[property?.name] = {
- ...property,
- type: propType === "stringProperties" ? "string" : propType === "numberProperties" ? "number" : undefined,
- };
-
- if (property?.isRequired && required.indexOf(property?.name) === -1) {
- required.push(property?.name);
- }
-
- // If orderNumber is missing, default to a very high number
- columns.push({ name: property?.name, orderNumber: property?.orderNumber || 9999999999 });
- }
- }
- }
- enrichSchema(convertData, properties, required, columns);
- const newData = JSON.parse(JSON.stringify(convertData));
- delete newData.campaignType;
- return newData;
- }
-
- useEffect(() => {
- if (uploadedFile.length == 0) {
- setErrorsType({});
- }
- }, [uploadedFile]);
-
- useEffect(async () => {
- if (Schemas?.["HCM-ADMIN-CONSOLE"]?.adminSchema) {
- const facility = await convertIntoSchema(Schemas?.["HCM-ADMIN-CONSOLE"]?.adminSchema?.filter((item) => item.title === "facility")?.[0]);
- const boundary = await convertIntoSchema(
- Schemas?.["HCM-ADMIN-CONSOLE"]?.adminSchema?.filter(
- (item) => item.title === "boundaryWithTarget" && item.campaignType === totalData?.HCM_CAMPAIGN_TYPE?.projectType?.code
- )?.[0]
- );
- const user = await convertIntoSchema(Schemas?.["HCM-ADMIN-CONSOLE"]?.adminSchema?.filter((item) => item.title === "user")?.[0]);
- const schema = {
- boundary: boundary,
- facilityWithBoundary: facility,
- userWithBoundary: user,
- };
-
- setConvertedSchema(schema);
- }
- }, [Schemas?.["HCM-ADMIN-CONSOLE"]?.adminSchema, type]);
-
- useEffect(async () => {
- if (convertedSchema && Object.keys(convertedSchema).length > 0) {
- const newFacilitySchema = await translateSchema(convertedSchema?.facilityWithBoundary);
- const newBoundarySchema = await translateSchema(convertedSchema?.boundary);
- const newUserSchema = await translateSchema(convertedSchema?.userWithBoundary);
- const headers = {
- boundary: Object?.keys(newBoundarySchema?.properties),
- facilityWithBoundary: Object?.keys(newFacilitySchema?.properties),
- userWithBoundary: Object?.keys(newUserSchema?.properties),
- };
-
- const schema = {
- boundary: newBoundarySchema,
- facilityWithBoundary: newFacilitySchema,
- userWithBoundary: newUserSchema,
- };
-
- setSheetHeaders(headers);
- setTranslatedSchema(schema);
- }
- }, [convertedSchema]);
-
- useEffect(async () => {
- if (readMe?.["HCM-ADMIN-CONSOLE"]) {
- const newReadMeFacility = await translateReadMeInfo(
- readMe?.["HCM-ADMIN-CONSOLE"]?.ReadMeConfig?.filter((item) => item.type === type)?.[0]?.texts
- );
- const newReadMeUser = await translateReadMeInfo(readMe?.["HCM-ADMIN-CONSOLE"]?.ReadMeConfig?.filter((item) => item.type === type)?.[0]?.texts);
- const newReadMeboundary = await translateReadMeInfo(
- readMe?.["HCM-ADMIN-CONSOLE"]?.ReadMeConfig?.filter((item) => item.type === type)?.[0]?.texts
- );
-
- const readMeText = {
- boundary: newReadMeboundary,
- facilityWithBoundary: newReadMeFacility,
- userWithBoundary: newReadMeUser,
- };
-
- setReadMeInfo(readMeText);
- }
- }, [readMe?.["HCM-ADMIN-CONSOLE"], type]);
-
- useEffect(() => {
- if (executionCount < 5) {
- let uploadType = "uploadUser";
- if (type === "boundary") {
- uploadType = "uploadBoundary";
- } else if (type === "facilityWithBoundary") {
- uploadType = "uploadFacility";
- }
- onSelect(uploadType, { uploadedFile, isError, isValidation: false, apiError: false, isSuccess: uploadedFile?.length > 0 });
- setExecutionCount((prevCount) => prevCount + 1);
- }
- });
-
- useEffect(() => {
- switch (type) {
- case "boundary":
- setUploadedFile(props?.props?.sessionData?.HCM_CAMPAIGN_UPLOAD_BOUNDARY_DATA?.uploadBoundary?.uploadedFile || []);
- setApiError(null);
- setIsValidation(false);
- setDownloadError(false);
- setIsError(false);
- setIsSuccess(props?.props?.sessionData?.HCM_CAMPAIGN_UPLOAD_BOUNDARY_DATA?.uploadBoundary?.isSuccess || null);
- setShowPopUp(!props?.props?.sessionData?.HCM_CAMPAIGN_UPLOAD_BOUNDARY_DATA?.uploadBoundary?.uploadedFile.length);
- break;
- case "facilityWithBoundary":
- setUploadedFile(props?.props?.sessionData?.HCM_CAMPAIGN_UPLOAD_FACILITY_DATA?.uploadFacility?.uploadedFile || []);
- setApiError(null);
- setIsValidation(false);
- setDownloadError(false);
- setIsError(false);
- setIsSuccess(props?.props?.sessionData?.HCM_CAMPAIGN_UPLOAD_FACILITY_DATA?.uploadFacility?.isSuccess || null);
- setShowPopUp(!props?.props?.sessionData?.HCM_CAMPAIGN_UPLOAD_FACILITY_DATA?.uploadFacility?.uploadedFile.length);
- break;
- default:
- setUploadedFile(props?.props?.sessionData?.HCM_CAMPAIGN_UPLOAD_USER_DATA?.uploadUser?.uploadedFile || []);
- setApiError(null);
- setIsValidation(false);
- setDownloadError(false);
- setIsError(false);
- setIsSuccess(props?.props?.sessionData?.HCM_CAMPAIGN_UPLOAD_USER_DATA?.uploadUser?.isSuccess || null);
- setShowPopUp(!props?.props?.sessionData?.HCM_CAMPAIGN_UPLOAD_USER_DATA?.uploadUser?.uploadedFile.length);
- break;
- }
- }, [type, props?.props?.sessionData]);
-
- useEffect(() => {
- if (errorsType[type]) {
- setShowInfoCard(true);
- } else {
- setShowInfoCard(false);
- }
- }, [type, errorsType]);
-
- const validateData = (data) => {
- const ajv = new Ajv({ strict: false }); // Initialize Ajv
- let validate = ajv.compile(translatedSchema[type]);
- const errors = []; // Array to hold validation errors
-
- data.forEach((item, index) => {
- if (!validate(item)) {
- errors.push({ index: (item?.["!row#number!"] || item?.["__rowNum__"]) + 1, errors: validate.errors });
- }
- });
-
- if (errors.length > 0) {
- const errorMessage = errors
- .map(({ index, errors }) => {
- const formattedErrors = errors
- .map((error) => {
- let instancePath = error.instancePath || ""; // Assign an empty string if dataPath is not available
- if (instancePath.startsWith("/")) {
- instancePath = instancePath.slice(1);
- }
- if (error.keyword === "required") {
- const missingProperty = error.params?.missingProperty || "";
- return `${t("HCM_DATA_AT_ROW")} ${index} ${t("HCM_IN_COLUMN")} '${missingProperty}' ${t("HCM_DATA_SHOULD_NOT_BE_EMPTY")}`;
- }
- if(error.keyword === "type" && error.message === "must be string"){
- return `${t("HCM_DATA_AT_ROW")} ${index} ${t("HCM_IN_COLUMN")} ${instancePath} ${t("HCM_IS_INVALID")}`
- }
- let formattedError = `${t("HCM_IN_COLUMN")} '${instancePath}' ${error.message}`;
- if (error.keyword === "enum" && error.params && error.params.allowedValues) {
- formattedError += `${t("HCM_DATA_ALLOWED_VALUES_ARE")} ${error.params.allowedValues.join("/ ")}`;
- }
- return `${t("HCM_DATA_AT_ROW")} ${index} ${formattedError}`;
- })
- .join(", ");
- return formattedErrors;
- })
- .join(", ");
-
- setErrorsType((prevErrors) => ({
- ...prevErrors,
- [type]: errorMessage,
- }));
- setIsError(true);
- return false;
- } else {
- setErrorsType((prevErrors) => ({
- ...prevErrors,
- [type]: "", // Clear the error message
- }));
- setShowInfoCard(false);
- return true;
- }
- };
-
- const validateTarget = (jsonData, headersToValidate) => {
- const boundaryCodeIndex = headersToValidate.indexOf(t("HCM_ADMIN_CONSOLE_BOUNDARY_CODE"));
- const headersBeforeBoundaryCode = headersToValidate.slice(0, boundaryCodeIndex);
-
- const filteredData = jsonData
- .filter((e) => {
- if (e[headersBeforeBoundaryCode[headersBeforeBoundaryCode.length - 1]]) {
- return true;
- }
- })
- .filter((e) => e[t("HCM_ADMIN_CONSOLE_TARGET_AT_THE_SELECTED_BOUNDARY_LEVEL")]);
-
- if (filteredData.length == 0) {
- const errorMessage = t("HCM_MISSING_TARGET");
- setErrorsType((prevErrors) => ({
- ...prevErrors,
- [type]: errorMessage,
- }));
- setIsError(true);
- return false;
- }
-
- const targetValue = filteredData?.[0][t("HCM_ADMIN_CONSOLE_TARGET_AT_THE_SELECTED_BOUNDARY_LEVEL")];
-
- if (targetValue <= 0 || targetValue >= 100000000) {
- const errorMessage = t("HCM_TARGET_VALIDATION_ERROR");
- setErrorsType((prevErrors) => ({
- ...prevErrors,
- [type]: errorMessage,
- }));
- setIsError(true);
- return false;
- }
- return true;
- };
-
- const validateTargetData = (data, sheetName, targetError) => {
- const ajv = new Ajv({ strict: false }); // Initialize Ajv
- let validate = ajv.compile(translatedSchema[type]);
- const errors = []; // Array to hold validation errors
-
-
- data.forEach((item, index) => {
- if (!validate(item)) {
- errors.push({ index: (item?.["!row#number!"] || item?.["__rowNum__"]) + 1, errors: validate.errors });
- }
- });
-
- // if (errors.length > 0) {
- // const errorMessage = errors
- // .map(({ index, errors }) => {
- // const formattedErrors = errors.map((error) => {
-
- // let formattedError = `${error.instancePath}: ${error.message}`;
- // if (error.keyword === "enum" && error.params && error.params.allowedValues) {
- // formattedError += `. Allowed values are: ${error.params.allowedValues.join("/ ")}`;
- // }
- // return formattedError;
- // })
- // .join(", ");
- // return `Data at row ${index}: ${formattedErrors} at ${sheetName}`;
- // })
- // .join(" , ");
- // setIsError(true);
- // targetError.push(errorMessage);
- // return false;
- // } else {
- // return true;
- // }
-
- if (errors.length > 0) {
- const errorMessage = errors
- .map(({ index, errors }) => {
- const formattedErrors = errors
- .map((error) => {
- let instancePath = error.instancePath || ""; // Assign an empty string if dataPath is not available
- if (instancePath.startsWith("/")) {
- instancePath = instancePath.slice(1);
- }
- if (error.keyword === "required") {
- const missingProperty = error.params?.missingProperty || "";
- return `${t("HCM_DATA_AT_ROW")} ${index} ${t("HCM_IN_COLUMN")} '${missingProperty}' ${t("HCM_DATA_SHOULD_NOT_BE_EMPTY")} at ${sheetName}`;
- }
- if(error.keyword === "type" && error.message === "must be string"){
- return `${t("HCM_DATA_AT_ROW")} ${index} ${t("HCM_IN_COLUMN")} ${instancePath} ${t("HCM_IS_INVALID")} at ${sheetName}`
- }
- let formattedError = `${t("HCM_IN_COLUMN")} '${instancePath}' ${error.message}`;
- if (error.keyword === "enum" && error.params && error.params.allowedValues) {
- formattedError += `${t("HCM_DATA_ALLOWED_VALUES_ARE")} ${error.params.allowedValues.join("/ ")}`;
- }
- return `${t("HCM_DATA_AT_ROW")} ${index} ${formattedError} at ${sheetName}`;
- })
- .join(", ");
- return formattedErrors;
- })
- .join(", ");
-
-
- setIsError(true);
- targetError.push(errorMessage);
- return false;
- }else{
- return true;
- }
- };
- // Function to compare arrays for equality
- const arraysEqual = (arr1, arr2) => {
- if (arr1.length !== arr2.length) return false;
- for (let i = 0; i < arr1.length; i++) {
- if (arr1[i] !== arr2[i]) return false;
- }
- return true;
- };
-
- const validateMultipleTargets = (workbook) => {
- let isValid = true;
- const sheet = workbook.Sheets[workbook.SheetNames[2]];
- const mdmsHeaders = sheetHeaders[type];
- const expectedHeaders = XLSX.utils.sheet_to_json(sheet, {
- header: 1,
- })[0];
-
-
- for (const header of mdmsHeaders) {
- if (!expectedHeaders.includes(t(header))) {
- const errorMessage = t("HCM_MISSING_HEADERS");
- setErrorsType((prevErrors) => ({
- ...prevErrors,
- [type]: errorMessage,
- }));
- setIsError(true);
- isValid = false;
- break;
- }
- }
-
- if (!isValid) return isValid;
-
- for (let i = 2; i < workbook.SheetNames.length; i++) {
- const sheetName = workbook?.SheetNames[i];
-
- const sheet = workbook?.Sheets[sheetName];
-
- // Convert the sheet to JSON to extract headers
- const headersToValidate = XLSX.utils.sheet_to_json(sheet, {
- header: 1,
- })[0];
-
- // Check if headers match the expected headers
- if (!arraysEqual(headersToValidate, expectedHeaders)) {
- const errorMessage = t("HCM_MISSING_HEADERS");
- setErrorsType((prevErrors) => ({
- ...prevErrors,
- [type]: errorMessage,
- }));
- setIsError(true);
- isValid = false;
- break;
- }
- }
-
- if (!isValid) return isValid;
- const targetError = [];
-
- // Iterate over each sheet in the workbook, starting from the second sheet
- for (let i = 2; i < workbook.SheetNames.length; i++) {
- const sheetName = workbook?.SheetNames[i];
-
- const sheet = workbook?.Sheets[sheetName];
-
- // Convert the sheet to JSON to extract headers
- const headersToValidate = XLSX.utils.sheet_to_json(sheet, {
- header: 1,
- })[0];
-
- const jsonData = XLSX.utils.sheet_to_json(sheet, { blankrows: true });
-
- // const boundaryCodeIndex = headersToValidate.indexOf(t("HCM_ADMIN_CONSOLE_BOUNDARY_CODE"));
- // const headersBeforeBoundaryCode = headersToValidate.slice(0, boundaryCodeIndex);
-
- // const columnBeforeBoundaryCode = jsonData.map((row) => row[headersBeforeBoundaryCode[headersBeforeBoundaryCode.length - 1]]);
-
- // // Getting the length of data in the column before the boundary code
- // const lengthOfColumnBeforeBoundaryCode = columnBeforeBoundaryCode.filter((value) => value !== undefined && value !== "").length;
-
- // const filteredData = jsonData
- // .filter((e) => e[headersBeforeBoundaryCode[headersBeforeBoundaryCode?.length - 1]])
- // .filter((e) => e[t("HCM_ADMIN_CONSOLE_TARGET_AT_THE_SELECTED_BOUNDARY_LEVEL")]);
- // if (filteredData?.length == 0 || filteredData?.length != lengthOfColumnBeforeBoundaryCode) {
- // const errorMessage = t("HCM_MISSING_TARGET");
- // setErrorsType((prevErrors) => ({
- // ...prevErrors,
- // [type]: errorMessage,
- // }));
- // setIsError(true);
- // isValid = false;
- // break;
- // }
-
- // const targetValue = filteredData?.[0][t("HCM_ADMIN_CONSOLE_TARGET_AT_THE_SELECTED_BOUNDARY_LEVEL")];
-
- // if (targetValue <= 0 || targetValue >= 100000000) {
- // const errorMessage = t("HCM_TARGET_VALIDATION_ERROR");
- // setErrorsType((prevErrors) => ({
- // ...prevErrors,
- // [type]: errorMessage,
- // }));
- // setIsError(true);
- // isValid = false;
- // break;
- // }
- // }
-
- if (!validateTargetData(jsonData, sheetName, targetError)) {
- // setShowInfoCard(true);
- // isValid = false;
- // break;
- }
- }
- if (targetError.length > 0) {
- const errorMessage = targetError.join(", ");
- setErrorsType((prevErrors) => ({
- ...prevErrors,
- [type]: errorMessage,
- }));
- setShowInfoCard(true);
- isValid = false;
- } else {
- setErrorsType((prevErrors) => ({
- ...prevErrors,
- [type]: "", // Clear the error message
- }));
- setShowInfoCard(false);
- isValid = true;
- }
- return isValid;
- };
-
- const validateExcel = (selectedFile) => {
- return new Promise((resolve, reject) => {
- // Check if a file is selected
- if (!selectedFile) {
- reject(t("HCM_FILE_UPLOAD_ERROR"));
- return;
- }
-
- // Read the Excel file
- const reader = new FileReader();
- reader.onload = (e) => {
- try {
- const data = new Uint8Array(e.target.result);
- const workbook = XLSX.read(data, { type: "array" });
- const sheet = workbook.Sheets[workbook.SheetNames[1]];
- const headersToValidate = XLSX.utils.sheet_to_json(sheet, {
- header: 1,
- })[0];
-
- const SheetNames = workbook.SheetNames[1];
- const expectedHeaders = sheetHeaders[type];
-
- const sheetData = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[1]], { blankrows: true });
- var jsonData = sheetData.map((row, index) => {
- const rowData = {};
- if (Object.keys(row).length > 0) {
- Object.keys(row).forEach((key) => {
- rowData[key] = row[key] === undefined || row[key] === "" ? "" : row[key];
- });
- rowData["!row#number!"] = index + 1; // Adding row number
- return rowData;
- }
- });
-
- jsonData = jsonData.filter((element) => element !== undefined);
- if (type === "boundary") {
- if (SheetNames !== t("HCM_ADMIN_CONSOLE_BOUNDARY_DATA")) {
- const errorMessage = t("HCM_INVALID_BOUNDARY_SHEET");
- setErrorsType((prevErrors) => ({
- ...prevErrors,
- [type]: errorMessage,
- }));
- setIsError(true);
- return;
- }
- } else if (type === "facilityWithBoundary") {
- if (type === "facilityWithBoundary") {
- const activeColumnName = t("HCM_ADMIN_CONSOLE_FACILITY_USAGE");
- const uniqueIdentifierColumnName = t("HCM_ADMIN_CONSOLE_FACILITY_CODE");
- if (activeColumnName && uniqueIdentifierColumnName) {
- jsonData = jsonData.filter((item) => item[activeColumnName] !== "Inactive" || !item[uniqueIdentifierColumnName]);
- }
- if (jsonData.length == 0) {
- const errorMessage = t("HCM_FACILITY_USAGE_VALIDATION");
- setErrorsType((prevErrors) => ({
- ...prevErrors,
- [type]: errorMessage,
- }));
- setIsError(true);
- return;
- }
- }
- if (SheetNames !== t("HCM_ADMIN_CONSOLE_AVAILABLE_FACILITIES")) {
- const errorMessage = t("HCM_INVALID_FACILITY_SHEET");
- setErrorsType((prevErrors) => ({
- ...prevErrors,
- [type]: errorMessage,
- }));
- setIsError(true);
- return;
- }
- } else {
- if (SheetNames !== t("HCM_ADMIN_CONSOLE_USER_LIST")) {
- const errorMessage = t("HCM_INVALID_USER_SHEET");
- setErrorsType((prevErrors) => ({
- ...prevErrors,
- [type]: errorMessage,
- }));
- setIsError(true);
- return;
- }
- }
- if (type === "boundary" && workbook?.SheetNames?.length >= 3) {
- if (!validateMultipleTargets(workbook)) {
- return;
- }
- } else if (type !== "boundary") {
- for (const header of expectedHeaders) {
- if (!headersToValidate.includes(header)) {
- const errorMessage = t("HCM_MISSING_HEADERS");
- setErrorsType((prevErrors) => ({
- ...prevErrors,
- [type]: errorMessage,
- }));
- setIsError(true);
- return;
- }
- }
- }
-
- if (type === "boundary" && workbook?.SheetNames.length == 1) {
- if (!validateTarget(jsonData, headersToValidate)) {
- return;
- }
- }
-
- if (jsonData.length == 0) {
- const errorMessage = t("HCM_EMPTY_SHEET");
- setErrorsType((prevErrors) => ({
- ...prevErrors,
- [type]: errorMessage,
- }));
- setIsError(true);
- return;
- }
- if (type !== "boundary") {
- if (validateData(jsonData, SheetNames)) {
- resolve(true);
- } else {
- setShowInfoCard(true);
- }
- }
- } catch (error) {
- console.log("error", error);
- reject("HCM_FILE_UNAVAILABLE");
- }
- };
-
- reader.readAsArrayBuffer(selectedFile);
- });
- };
-
- const onBulkUploadSubmit = async (file) => {
- if (file.length > 1) {
- setShowToast({ key: "error", label: t("HCM_ERROR_MORE_THAN_ONE_FILE") });
- return;
- }
- setFileName(file?.[0]?.name);
- const module = "HCM-ADMIN-CONSOLE-CLIENT";
- const { data: { files: fileStoreIds } = {} } = await Digit.UploadServices.MultipleFilesStorage(module, file, tenantId);
- const filesArray = [fileStoreIds?.[0]?.fileStoreId];
- const { data: { fileStoreIds: fileUrl } = {} } = await Digit.UploadServices.Filefetch(filesArray, tenantId);
- const fileData = fileUrl
- .map((i) => {
- const urlParts = i?.url?.split("/");
- const fileName = file?.[0]?.name;
- const id = fileUrl?.[0]?.id;
- // const fileType = type === "facilityWithBoundary" ? "facility" : type === "userWithBoundary" ? "user" : type;
- const fileType =
- type === "facilityWithBoundary" ? "facility" : type === "userWithBoundary" ? "user" : type === "boundary" ? "boundaryWithTarget" : type;
- return {
- // ...i,
- filestoreId: id,
- resourceId: resourceId,
- filename: fileName,
- type: fileType,
- };
- })
- .map(({ id, ...rest }) => rest);
- setUploadedFile(fileData);
- const validate = await validateExcel(file[0]);
- };
-
- const onFileDelete = (file, index) => {
- setUploadedFile((prev) => prev.filter((i) => i.id !== file.id));
- setIsError(false);
- setIsSuccess(false);
- setIsValidation(false);
- setApiError(null);
- setErrorsType({});
- setShowToast(null);
- };
-
- const onFileDownload = (file) => {
- if (file && file?.url) {
- // Splitting filename before .xlsx or .xls
- const fileNameWithoutExtension = file?.filename.split(/\.(xlsx|xls)/)[0];
- downloadExcelWithCustomName({ fileStoreId: file?.filestoreId, customName: fileNameWithoutExtension });
- }
- };
- useEffect(() => {
- const fetchData = async () => {
- if (!errorsType[type] && uploadedFile?.length > 0 && !isSuccess) {
- // setShowToast({ key: "info", label: t("HCM_VALIDATION_IN_PROGRESS") });
- setIsValidation(true);
- setIsError(true);
- setLoader(true);
-
- try {
- const temp = await Digit.Hooks.campaign.useResourceData(
- uploadedFile,
- params?.hierarchyType,
- type,
- tenantId,
- id,
- baseTimeOut?.["HCM-ADMIN-CONSOLE"]
- );
- if (temp?.isError) {
- setLoader(false);
- setIsValidation(false);
- const errorMessage = temp?.error.replaceAll(":", "-");
- setShowToast({ key: "error", label: errorMessage, transitionTime: 5000000 });
- setIsError(true);
- setApiError(errorMessage);
-
- return;
- }
- if (temp?.status === "completed") {
- setLoader(false);
- setIsValidation(false);
- if (temp?.additionalDetails?.sheetErrors.length === 0) {
- setShowToast({ key: "success", label: t("HCM_VALIDATION_COMPLETED") });
- if (temp?.id) {
- setResourceId(temp?.id);
- }
- if (!errorsType[type]) {
- setIsError(false);
- setIsSuccess(true);
- return;
- // setIsValidation(false);
- }
- return;
- } else {
- const processedFileStore = temp?.processedFilestoreId;
- if (!processedFileStore) {
- setShowToast({ key: "error", label: t("HCM_VALIDATION_FAILED") });
- // setIsValidation(true);
- return;
- } else {
- const { data: { fileStoreIds: fileUrl } = {} } = await Digit.UploadServices.Filefetch([processedFileStore], tenantId);
- const fileData = fileUrl
- .map((i) => {
- const urlParts = i?.url?.split("/");
- const id = fileUrl?.[0]?.id;
- // const fileName = fileName;
- const fileType =
- type === "facilityWithBoundary"
- ? "facility"
- : type === "userWithBoundary"
- ? "user"
- : type === "boundary"
- ? "boundaryWithTarget"
- : type;
- return {
- ...i,
- filestoreId: id,
- filename: fileName,
- type: fileType,
- resourceId: temp?.id,
- };
- })
- .map(({ id, ...rest }) => rest);
- // onFileDelete(uploadedFile);
- setUploadedFile(fileData);
- setShowToast({ key: "warning", label: t("HCM_CHECK_FILE_AGAIN") });
- setIsError(true);
- }
- }
- } else {
- setLoader(false);
- setIsValidation(false);
- // setShowToast({ key: "error", label: t("HCM_VALIDATION_FAILED"), transitionTime: 5000000 });
- const processedFileStore = temp?.processedFilestoreId;
- if (!processedFileStore) {
- setShowToast({ key: "error", label: t("HCM_VALIDATION_FAILED"), transitionTime: 5000000 });
- return;
- } else {
- setIsError(true);
- const { data: { fileStoreIds: fileUrl } = {} } = await Digit.UploadServices.Filefetch([processedFileStore], tenantId);
- const fileData = fileUrl
- .map((i) => {
- const urlParts = i?.url?.split("/");
- const id = fileUrl?.[0]?.id;
- // const fileName = file?.[0]?.name;
- const fileType =
- type === "facilityWithBoundary"
- ? "facility"
- : type === "userWithBoundary"
- ? "user"
- : type === "boundary"
- ? "boundaryWithTarget"
- : type;
- return {
- ...i,
- filestoreId: id,
- filename: fileName,
- type: fileType,
- };
- })
- .map(({ id, ...rest }) => rest);
- // onFileDelete(uploadedFile);
- setUploadedFile(fileData);
- setShowToast({ key: "warning", label: t("HCM_CHECK_FILE_AGAIN"), transitionTime: 5000000 });
- setIsError(true);
- }
- }
- } catch (error) {}
- }
- };
-
- fetchData();
- }, [errorsType]);
-
- const { data: facilityId, isLoading: isFacilityLoading, refetch: refetchFacility } = Digit.Hooks.campaign.useGenerateIdCampaign({
- type: "facilityWithBoundary",
- hierarchyType: params?.hierarchyType,
- campaignId: id,
- // config: {
- // enabled: setTimeout(fetchUpload || (fetchBoundary && currentKey > 6)),
- // },
- config: {
- enabled: enabled,
- },
- });
-
- const { data: boundaryId, isLoading: isBoundaryLoading, refetch: refetchBoundary } = Digit.Hooks.campaign.useGenerateIdCampaign({
- type: "boundary",
- hierarchyType: params?.hierarchyType,
- campaignId: id,
- // config: {
- // enabled: fetchUpload || (fetchBoundary && currentKey > 6),
- // },
- config: {
- enabled: enabled,
- },
- });
-
- const { data: userId, isLoading: isUserLoading, refetch: refetchUser } = Digit.Hooks.campaign.useGenerateIdCampaign({
- type: "userWithBoundary",
- hierarchyType: params?.hierarchyType,
- campaignId: id,
- // config: {
- // enabled: fetchUpload || (fetchBoundary && currentKey > 6),
- // },
- config: {
- enabled: enabled,
- },
- });
-
- const Template = {
- url: "/project-factory/v1/data/_download",
- params: {
- tenantId: tenantId,
- type: type,
- hierarchyType: params?.hierarchyType,
- id: type === "boundary" ? params?.boundaryId : type === "facilityWithBoundary" ? params?.facilityId : params?.userId,
- },
- };
- const mutation = Digit.Hooks.useCustomAPIMutationHook(Template);
-
- const downloadTemplate = async () => {
- if (type === "boundary" && params?.isBoundaryLoading) {
- setDownloadError(true);
- setShowToast({ key: "info", label: t("HCM_PLEASE_WAIT_TRY_IN_SOME_TIME") });
- return;
- }
- if (type === "facilityWithBoundary" && params?.isFacilityLoading) {
- setDownloadError(true);
- setShowToast({ key: "info", label: t("HCM_PLEASE_WAIT_TRY_IN_SOME_TIME") });
- return;
- }
- if (type === "userWithBoundary" && params?.isUserLoading) {
- setDownloadError(true);
- setShowToast({ key: "info", label: t("HCM_PLEASE_WAIT_TRY_IN_SOME_TIME") });
- return;
- }
- if (!params?.boundaryId || !params?.facilityId || !params?.userId) {
- setEnabled(true);
-
- setDownloadError(true);
- setShowToast({ key: "info", label: t("HCM_PLEASE_WAIT_TRY_IN_SOME_TIME") });
- return;
- }
- await mutation.mutate(
- {
- params: {
- tenantId: tenantId,
- type: type,
- hierarchyType: params?.hierarchyType,
- id: type === "boundary" ? params?.boundaryId : type === "facilityWithBoundary" ? params?.facilityId : params?.userId,
- },
- },
- {
- onSuccess: async (result) => {
- if (result?.GeneratedResource?.[0]?.status === "failed") {
- setDownloadError(true);
- setShowToast({ key: "error", label: t("ERROR_WHILE_DOWNLOADING") });
- return;
- }
- if (!result?.GeneratedResource?.[0]?.fileStoreid || result?.GeneratedResource?.length == 0) {
- setDownloadError(true);
- setShowToast({ key: "info", label: t("HCM_PLEASE_WAIT_TRY_IN_SOME_TIME") });
- return;
- }
- const filesArray = [result?.GeneratedResource?.[0]?.fileStoreid];
- const { data: { fileStoreIds: fileUrl } = {} } = await Digit.UploadServices.Filefetch(filesArray, tenantId);
- const fileData = fileUrl?.map((i) => {
- const urlParts = i?.url?.split("/");
- // const fileName = urlParts[urlParts?.length - 1]?.split("?")?.[0];
- const fileName = type === "boundary" ? "Target Template" : type === "facilityWithBoundary" ? "Facility Template" : "User Template";
- return {
- ...i,
- filename: fileName,
- };
- });
-
- if (fileData && fileData?.[0]?.url) {
- setDownloadError(false);
- if (fileData?.[0]?.id) {
- downloadExcelWithCustomName({ fileStoreId: fileData?.[0]?.id, customName: fileData?.[0]?.filename });
- }
- } else {
- setDownloadError(true);
- setShowToast({ key: "info", label: t("HCM_PLEASE_WAIT") });
- }
- },
- onError: (result) => {
- setDownloadError(true);
- setShowToast({ key: "error", label: t("ERROR_WHILE_DOWNLOADING") });
- },
- }
- );
- };
-
- // useEffect(() => {
- // if (showToast) {
- // setTimeout(closeToast, 5000);
- // }
- // }, [showToast]);
- const closeToast = () => {
- setShowToast(null);
- };
- useEffect(() => {
- if (showToast) {
- const t = setTimeout(closeToast, 50000);
- return () => clearTimeout(t);
- }
- }, [showToast]);
-
- useEffect(() => {
- setShowToast(null);
- }, [currentKey]);
-
- return (
- <>
- {loader && }
-
-
-
- {type === "boundary" ? t("WBH_UPLOAD_TARGET") : type === "facilityWithBoundary" ? t("WBH_UPLOAD_FACILITY") : t("WBH_UPLOAD_USER")}
-
-
-
- {uploadedFile.length === 0 && (
-
- {type === "boundary" ? t("HCM_BOUNDARY_MESSAGE") : type === "facilityWithBoundary" ? t("HCM_FACILITY_MESSAGE") : t("HCM_USER_MESSAGE")}
-
- )}
-
- {showInfoCard && (
-
- {errorsType[type] && (
-
- {errorsType[type].split(",").slice(0,50).map((error, index) => (
-
- {index > 0 &&
}
- {error.trim()}
-
- ))}
-
- )}
- ,
- ]}
- />
- )}
-
- (
-
-
{info?.header}
-
- {info?.descriptions.map((desc, i) => (
- -
-
{i + 1}.
- {desc.text}
-
- ))}
-
-
- ))}
- label={"Info"}
- />
- {showPopUp && (
-
- {type === "boundary"
- ? t("ES_CAMPAIGN_UPLOAD_BOUNDARY_DATA_MODAL_TEXT")
- : type === "facilityWithBoundary"
- ? t("ES_CAMPAIGN_UPLOAD_FACILITY_DATA_MODAL_TEXT")
- : t("ES_CAMPAIGN_UPLOAD_USER_DATA_MODAL_TEXT ")}
- ,
- ]}
- onOverlayClick={() => {
- setShowPopUp(false);
- }}
- footerChildren={[
- {
- setShowPopUp(false);
- }}
- />,
- {
- downloadTemplate(), setShowPopUp(false);
- }}
- />,
- ]}
- sortFooterChildren={true}
- onClose={() => {
- setShowPopUp(false);
- }}
- >
- )}
- {showToast && (uploadedFile?.length > 0 || downloadError) && (
-
- )}
- >
- );
-};
-
-export default UploadData;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/XlsPreview.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/XlsPreview.js
deleted file mode 100644
index a3a10a43830..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/XlsPreview.js
+++ /dev/null
@@ -1,69 +0,0 @@
-import { PopUp, SVG, DownloadIcon, Button } from "@egovernments/digit-ui-react-components";
-import React from "react";
-import DocViewer, { DocViewerRenderers } from "@cyntler/react-doc-viewer";
-import { useTranslation } from "react-i18next";
-import { PRIMARY_COLOR } from "../utils";
-
-const ArrowBack = ({ className = "", height = "15", width = "15", styles = {} }) => {
- return (
-
- );
-};
-function XlsPreview({ file, ...props }) {
- const { t } = useTranslation();
- const documents = file
- ? [
- {
- fileType: "xlsx",
- fileName: file?.filename,
- uri: file?.url,
- },
- ]
- : null;
-
- return (
-
-
- }
- type="button"
- className="workbench-download-template-btn"
- onButtonClick={() => props?.onBack()}
- />
- }
- type="button"
- className="workbench-download-template-btn"
- onButtonClick={() => props?.onDownload()}
- />
-
-
-
-
-
- );
-}
-
-export default XlsPreview;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/icons/DustbinIcon.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/icons/DustbinIcon.js
deleted file mode 100644
index b9191f6db26..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/icons/DustbinIcon.js
+++ /dev/null
@@ -1,10 +0,0 @@
-import React from "react";
-import { PRIMARY_COLOR } from "../../utils";
-export const DustbinIcon = () => (
-
-);
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/icons/XlsxFile.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/icons/XlsxFile.js
deleted file mode 100644
index 82ecfa8f625..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/components/icons/XlsxFile.js
+++ /dev/null
@@ -1,32 +0,0 @@
-import React from "react";
-
-export const XlsxFile = ({ className = "", fill = "none", style = {} }) => (
-
-);
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/CampaignConfig.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/CampaignConfig.js
deleted file mode 100644
index 91195b2376f..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/CampaignConfig.js
+++ /dev/null
@@ -1,267 +0,0 @@
-export const CampaignConfig = (totalFormData, dataParams, isSubmitting, summaryErrors) => {
- return [
- {
- form: [
- {
- stepCount: "1",
- key: "1",
- name: "HCM_CAMPAIGN_TYPE",
- body: [
- {
- isMandatory: false,
- key: "projectType",
- type: "component",
- skipAPICall: true,
- component: "CampaignSelection",
- withoutLabel: true,
- disable: false,
- customProps: {
- module: "HCM",
- sessionData: totalFormData,
- isSubmitting: isSubmitting,
- },
- populators: {
- name: "projectType",
- },
- },
- ],
- },
- {
- stepCount: "1",
- key: "2",
- name: "HCM_CAMPAIGN_NAME",
- body: [
- {
- isMandatory: false,
- key: "campaignName",
- type: "component",
- component: "CampaignName",
- mandatoryOnAPI: true,
- withoutLabel: true,
- withoutLabelFieldPair: true,
- disable: false,
- customProps: {
- module: "HCM",
- sessionData: totalFormData,
- isSubmitting: isSubmitting,
- },
- populators: {
- name: "campaignName",
- required: true,
- },
- },
- ],
- },
- {
- stepCount: "2",
- key: "3",
- name: "HCM_CAMPAIGN_SELECTING_BOUNDARY_DATA",
- body: [
- {
- isMandatory: false,
- key: "boundaryType",
- type: "component",
- component: "SelectingBoundaries",
- withoutLabelFieldPair: true,
- withoutLabel: true,
- disable: false,
- customProps: {
- module: "HCM",
- sessionData: totalFormData,
- dataParams: dataParams,
- },
- populators: {
- name: "boundaryType",
- // optionsKey: "code",
- error: "ES__REQUIRED",
- required: true,
- },
- },
- ],
- },
- {
- stepCount: "3",
- key: "4",
- name: "HCM_CAMPAIGN_DATE",
- body: [
- {
- isMandatory: false,
- key: "campaignDates",
- type: "component",
- component: "CampaignDates",
- withoutLabel: true,
- disable: false,
- customProps: {
- module: "HCM",
- sessionData: totalFormData,
- isSubmitting: isSubmitting,
- },
- populators: {
- name: "campaignDates",
- // optionsKey: "code",
- // error: "ES__REQUIRED",
- required: true,
- },
- },
- ],
- },
- {
- stepCount: "3",
- key: "5",
- name: "HCM_CAMPAIGN_CYCLE_CONFIGURE",
- body: [
- {
- isMandatory: false,
- key: "cycleConfigure",
- type: "component",
- component: "CycleConfiguration",
- withoutLabelFieldPair: true,
- withoutLabel: true,
- disable: false,
- customProps: {
- module: "HCM",
- },
- populators: {
- name: "cycleConfiguration",
- sessionData: totalFormData,
- // optionsKey: "code",
- error: "ES__REQUIRED",
- required: true,
- },
- },
- ],
- },
- {
- stepCount: "3",
- key: "6",
- name: "HCM_CAMPAIGN_DELIVERY_DATA",
- body: [
- {
- isMandatory: false,
- key: "deliveryRule",
- type: "component",
- component: "DeliveryRule",
- withoutLabelFieldPair: true,
- withoutLabel: true,
- disable: false,
- customProps: {
- module: "HCM",
- sessionData: totalFormData,
- },
- populators: {
- name: "deliveryRule",
- // optionsKey: "code",
- error: "ES__REQUIRED",
- required: true,
- },
- },
- ],
- },
- {
- stepCount: "4",
- key: "7",
- name: "HCM_CAMPAIGN_UPLOAD_BOUNDARY_DATA",
- body: [
- {
- isMandatory: false,
- key: "uploadBoundary",
- type: "component",
- component: "UploadData",
- withoutLabel: true,
- withoutLabelFieldPair: true,
- disable: false,
- customProps: {
- module: "HCM",
- sessionData: totalFormData,
- type: "boundary",
- },
- populators: {
- name: "uploadBoundary",
- // optionsKey: "code",
- // error: "ES__REQUIRED",
- required: true,
- },
- },
- ],
- },
- {
- stepCount: "5",
- key: "8",
- name: "HCM_CAMPAIGN_UPLOAD_FACILITY_DATA",
- body: [
- {
- isMandatory: false,
- key: "uploadFacility",
- type: "component",
- component: "UploadData",
- withoutLabel: true,
- withoutLabelFieldPair: true,
- disable: false,
- customProps: {
- module: "HCM",
- sessionData: totalFormData,
- type: "facilityWithBoundary",
- },
- populators: {
- name: "uploadFacility",
- required: true,
- },
- },
- ],
- },
- {
- stepCount: "6",
- key: "9",
- name: "HCM_CAMPAIGN_UPLOAD_USER_DATA",
- body: [
- {
- isMandatory: false,
- key: "uploadUser",
- type: "component",
- component: "UploadData",
- withoutLabel: true,
- withoutLabelFieldPair: true,
- disable: false,
- customProps: {
- module: "HCM",
- sessionData: totalFormData,
- type: "userWithBoundary",
- },
- populators: {
- name: "uploadUser",
- required: true,
- },
- },
- ],
- },
- {
- stepCount: "7",
- key: "10",
- isLast: true,
- body: [
- {
- isMandatory: false,
- key: "summary",
- type: "component",
- component: "CampaignSummary",
- withoutLabel: true,
- withoutLabelFieldPair: true,
- disable: false,
- customProps: {
- module: "HCM",
- sessionData: totalFormData,
- summaryErrors: summaryErrors
- },
- populators: {
- name: "summary",
- // optionsKey: "code",
- // error: "ES__REQUIRED",
- required: true,
- },
- },
- ],
- },
- ],
- },
- ];
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/UICustomizations.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/UICustomizations.js
deleted file mode 100644
index 63954b2a810..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/UICustomizations.js
+++ /dev/null
@@ -1,472 +0,0 @@
-import { Link, useHistory } from "react-router-dom";
-import _ from "lodash";
-import React from "react";
-
-//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 || {};
-
-const businessServiceMap = {};
-
-const inboxModuleNameMap = {};
-
-export const UICustomizations = {
- MyCampaignConfigOngoing: {
- preProcess: (data, additionalDetails) => {
- const tenantId = Digit.ULBService.getCurrentTenantId();
- data.body = { RequestInfo: data.body.RequestInfo };
- const { limit, offset } = data?.state?.tableForm || {};
- const { campaignName, campaignType } = data?.state?.searchForm || {};
- data.body.CampaignDetails = {
- tenantId: tenantId,
- status: ["creating", "created"],
- createdBy: Digit.UserService.getUser().info.uuid,
- campaignsIncludeDates: true,
- startDate: Date.now(),
- endDate: Date.now(),
- pagination: {
- sortBy: "createdTime",
- sortOrder: "desc",
- limit: limit,
- offset: offset,
- },
- };
- if (campaignName) {
- data.body.CampaignDetails.campaignName = campaignName;
- }
- if (campaignType) {
- data.body.CampaignDetails.projectType = campaignType?.[0]?.code;
- }
- delete data.body.custom;
- delete data.body.inbox;
- delete data.params;
- return data;
- },
- populateCampaignTypeReqCriteria: () => {
- const tenantId = Digit.ULBService.getCurrentTenantId();
-
- return {
- url: "/egov-mdms-service/v1/_search",
- params: { tenantId },
- body: {
- MdmsCriteria: {
- tenantId: tenantId,
- moduleDetails: [
- {
- moduleName: "HCM-PROJECT-TYPES",
- masterDetails: [
- {
- name: "projectTypes",
- },
- ],
- },
- ],
- },
- },
- changeQueryName: "setWorkflowStatus",
- config: {
- enabled: true,
- select: (data) => {
- return data?.MdmsRes?.["HCM-PROJECT-TYPES"]?.projectTypes;
- },
- },
- };
- },
- getCustomActionLabel: (obj, row) => {
- return "";
- },
- additionalCustomizations: (row, key, column, value, t, searchResult) => {
- switch (key) {
- case "CAMPAIGN_NAME":
- return (
-
-
- {String(value ? (column.translate ? t(column.prefix ? `${column.prefix}${value}` : value) : value) : t("ES_COMMON_NA"))}
-
-
- );
-
- case "CAMPAIGN_START_DATE":
- return Digit.DateUtils.ConvertEpochToDate(value);
- case "CAMPAIGN_END_DATE":
- return Digit.DateUtils.ConvertEpochToDate(value);
- default:
- return "case_not_found";
- }
- },
- onCardClick: (obj) => {
- return `view-test-results?tenantId=${obj?.apiResponse?.businessObject?.tenantId}&id=${obj?.apiResponse?.businessObject?.testId}&from=TQM_BREAD_INBOX`;
- },
- onCardActionClick: (obj) => {
- return `view-test-results?tenantId=${obj?.apiResponse?.businessObject?.tenantId}&id=${obj?.apiResponse?.businessObject?.testId}&from=TQM_BREAD_INBOX`;
- },
- getCustomActionLabel: (obj, row) => {
- return "TQM_VIEW_TEST_DETAILS";
- },
- },
- MyCampaignConfigCompleted: {
- preProcess: (data, additionalDetails) => {
- const tenantId = Digit.ULBService.getCurrentTenantId();
- data.body = { RequestInfo: data.body.RequestInfo };
- const { limit, offset } = data?.state?.tableForm || {};
- const { campaignName, campaignType } = data?.state?.searchForm || {};
- data.body.CampaignDetails = {
- tenantId: tenantId,
- status: ["creating", "created"],
- endDate: Date.now() - 24 * 60 * 60 * 1000,
- createdBy: Digit.UserService.getUser().info.uuid,
- pagination: {
- sortBy: "createdTime",
- sortOrder: "desc",
- limit: limit,
- offset: offset,
- },
- };
- if (campaignName) {
- data.body.CampaignDetails.campaignName = campaignName;
- }
- if (campaignType) {
- data.body.CampaignDetails.projectType = campaignType?.[0]?.code;
- }
- delete data.body.custom;
- delete data.body.inbox;
- delete data.params;
- return data;
- },
- populateCampaignTypeReqCriteria: () => {
- const tenantId = Digit.ULBService.getCurrentTenantId();
-
- return {
- url: "/egov-mdms-service/v1/_search",
- params: { tenantId },
- body: {
- MdmsCriteria: {
- tenantId: tenantId,
- moduleDetails: [
- {
- moduleName: "HCM-PROJECT-TYPES",
- masterDetails: [
- {
- name: "projectTypes",
- },
- ],
- },
- ],
- },
- },
- changeQueryName: "setWorkflowStatus",
- config: {
- enabled: true,
- select: (data) => {
- return data?.MdmsRes?.["HCM-PROJECT-TYPES"]?.projectTypes;
- },
- },
- };
- },
- getCustomActionLabel: (obj, row) => {
- return "";
- },
- additionalCustomizations: (row, key, column, value, t, searchResult) => {
- switch (key) {
- case "CAMPAIGN_NAME":
- return (
-
-
- {String(value ? (column.translate ? t(column.prefix ? `${column.prefix}${value}` : value) : value) : t("ES_COMMON_NA"))}
-
-
- );
-
- case "CAMPAIGN_START_DATE":
- return Digit.DateUtils.ConvertEpochToDate(value);
- case "CAMPAIGN_END_DATE":
- return Digit.DateUtils.ConvertEpochToDate(value);
- default:
- return "case_not_found";
- }
- },
- onCardClick: (obj) => {
- return `view-test-results?tenantId=${obj?.apiResponse?.businessObject?.tenantId}&id=${obj?.apiResponse?.businessObject?.testId}&from=TQM_BREAD_INBOX`;
- },
- onCardActionClick: (obj) => {
- return `view-test-results?tenantId=${obj?.apiResponse?.businessObject?.tenantId}&id=${obj?.apiResponse?.businessObject?.testId}&from=TQM_BREAD_INBOX`;
- },
- getCustomActionLabel: (obj, row) => {
- return "TQM_VIEW_TEST_DETAILS";
- },
- },
- MyCampaignConfigUpcoming: {
- preProcess: (data, additionalDetails) => {
- const tenantId = Digit.ULBService.getCurrentTenantId();
- data.body = { RequestInfo: data.body.RequestInfo };
- const { limit, offset } = data?.state?.tableForm || {};
- const { campaignName, campaignType } = data?.state?.searchForm || {};
- data.body.CampaignDetails = {
- tenantId: tenantId,
- status: ["creating", "created"],
- createdBy: Digit.UserService.getUser().info.uuid,
- campaignsIncludeDates: false,
- startDate: Date.now() + 24 * 60 * 60 * 1000,
- pagination: {
- sortBy: "createdTime",
- sortOrder: "desc",
- limit: limit,
- offset: offset,
- },
- };
- if (campaignName) {
- data.body.CampaignDetails.campaignName = campaignName;
- }
- if (campaignType) {
- data.body.CampaignDetails.projectType = campaignType?.[0]?.code;
- }
- delete data.body.custom;
- delete data.body.inbox;
- delete data.params;
- return data;
- },
- populateCampaignTypeReqCriteria: () => {
- const tenantId = Digit.ULBService.getCurrentTenantId();
-
- return {
- url: "/egov-mdms-service/v1/_search",
- params: { tenantId },
- body: {
- MdmsCriteria: {
- tenantId: tenantId,
- moduleDetails: [
- {
- moduleName: "HCM-PROJECT-TYPES",
- masterDetails: [
- {
- name: "projectTypes",
- },
- ],
- },
- ],
- },
- },
- changeQueryName: "setWorkflowStatus",
- config: {
- enabled: true,
- select: (data) => {
- return data?.MdmsRes?.["HCM-PROJECT-TYPES"]?.projectTypes;
- },
- },
- };
- },
- getCustomActionLabel: (obj, row) => {
- return "";
- },
- additionalCustomizations: (row, key, column, value, t, searchResult) => {
- switch (key) {
- case "CAMPAIGN_NAME":
- return (
-
-
- {String(value ? (column.translate ? t(column.prefix ? `${column.prefix}${value}` : value) : value) : t("ES_COMMON_NA"))}
-
-
- );
-
- case "CAMPAIGN_START_DATE":
- return Digit.DateUtils.ConvertEpochToDate(value);
- case "CAMPAIGN_END_DATE":
- return Digit.DateUtils.ConvertEpochToDate(value);
- default:
- return "case_not_found";
- }
- },
- onCardClick: (obj) => {
- return `view-test-results?tenantId=${obj?.apiResponse?.businessObject?.tenantId}&id=${obj?.apiResponse?.businessObject?.testId}&from=TQM_BREAD_INBOX`;
- },
- onCardActionClick: (obj) => {
- return `view-test-results?tenantId=${obj?.apiResponse?.businessObject?.tenantId}&id=${obj?.apiResponse?.businessObject?.testId}&from=TQM_BREAD_INBOX`;
- },
- getCustomActionLabel: (obj, row) => {
- return "TQM_VIEW_TEST_DETAILS";
- },
- },
- MyCampaignConfigDrafts: {
- preProcess: (data, additionalDetails) => {
- const tenantId = Digit.ULBService.getCurrentTenantId();
- data.body = { RequestInfo: data.body.RequestInfo };
- const { limit, offset } = data?.state?.tableForm || {};
- const { campaignName, campaignType } = data?.state?.searchForm || {};
- data.body.CampaignDetails = {
- tenantId: tenantId,
- status: ["drafted"],
- createdBy: Digit.UserService.getUser().info.uuid,
- pagination: {
- sortBy: "createdTime",
- sortOrder: "desc",
- limit: limit,
- offset: offset,
- },
- };
- if (campaignName) {
- data.body.CampaignDetails.campaignName = campaignName;
- }
- if (campaignType) {
- data.body.CampaignDetails.projectType = campaignType?.[0]?.code;
- }
- delete data.body.custom;
- delete data.body.custom;
- delete data.body.inbox;
- delete data.params;
- return data;
- },
- populateCampaignTypeReqCriteria: () => {
- const tenantId = Digit.ULBService.getCurrentTenantId();
-
- return {
- url: "/egov-mdms-service/v1/_search",
- params: { tenantId },
- body: {
- MdmsCriteria: {
- tenantId: tenantId,
- moduleDetails: [
- {
- moduleName: "HCM-PROJECT-TYPES",
- masterDetails: [
- {
- name: "projectTypes",
- },
- ],
- },
- ],
- },
- },
- changeQueryName: "setWorkflowStatus",
- config: {
- enabled: true,
- select: (data) => {
- return data?.MdmsRes?.["HCM-PROJECT-TYPES"]?.projectTypes;
- },
- },
- };
- },
- getCustomActionLabel: (obj, row) => {
- return "";
- },
- additionalCustomizations: (row, key, column, value, t, searchResult) => {
- switch (key) {
- case "CAMPAIGN_NAME":
- return (
-
-
- {String(value ? (column.translate ? t(column.prefix ? `${column.prefix}${value}` : value) : value) : t("ES_COMMON_NA"))}
-
-
- );
-
- case "CAMPAIGN_START_DATE":
- return Digit.DateUtils.ConvertEpochToDate(value);
- case "CAMPAIGN_END_DATE":
- return Digit.DateUtils.ConvertEpochToDate(value);
- default:
- return "case_not_found";
- }
- },
- onCardClick: (obj) => {
- return `view-test-results?tenantId=${obj?.apiResponse?.businessObject?.tenantId}&id=${obj?.apiResponse?.businessObject?.testId}&from=TQM_BREAD_INBOX`;
- },
- onCardActionClick: (obj) => {
- return `view-test-results?tenantId=${obj?.apiResponse?.businessObject?.tenantId}&id=${obj?.apiResponse?.businessObject?.testId}&from=TQM_BREAD_INBOX`;
- },
- getCustomActionLabel: (obj, row) => {
- return "TQM_VIEW_TEST_DETAILS";
- },
- },
- MyCampaignConfigFailed: {
- preProcess: (data, additionalDetails) => {
- const tenantId = Digit.ULBService.getCurrentTenantId();
- data.body = { RequestInfo: data.body.RequestInfo };
- const { limit, offset } = data?.state?.tableForm || {};
- const { campaignName, campaignType } = data?.state?.searchForm || {};
- data.body.CampaignDetails = {
- tenantId: tenantId,
- status: ["failed"],
- createdBy: Digit.UserService.getUser().info.uuid,
- pagination: {
- sortBy: "createdTime",
- sortOrder: "desc",
- limit: limit,
- offset: offset,
- },
- };
- if (campaignName) {
- data.body.CampaignDetails.campaignName = campaignName;
- }
- if (campaignType) {
- data.body.CampaignDetails.projectType = campaignType?.[0]?.code;
- }
- delete data.body.custom;
- delete data.body.inbox;
- delete data.params;
- return data;
- },
- populateCampaignTypeReqCriteria: () => {
- const tenantId = Digit.ULBService.getCurrentTenantId();
-
- return {
- url: "/egov-mdms-service/v1/_search",
- params: { tenantId },
- body: {
- MdmsCriteria: {
- tenantId: tenantId,
- moduleDetails: [
- {
- moduleName: "HCM-PROJECT-TYPES",
- masterDetails: [
- {
- name: "projectTypes",
- },
- ],
- },
- ],
- },
- },
- changeQueryName: "setWorkflowStatus",
- config: {
- enabled: true,
- select: (data) => {
- return data?.MdmsRes?.["HCM-PROJECT-TYPES"]?.projectTypes;
- },
- },
- };
- },
- getCustomActionLabel: (obj, row) => {
- return "";
- },
- additionalCustomizations: (row, key, column, value, t, searchResult) => {
- switch (key) {
- case "CAMPAIGN_NAME":
- return (
-
-
- {String(value ? (column.translate ? t(column.prefix ? `${column.prefix}${value}` : value) : value) : t("ES_COMMON_NA"))}
-
-
- );
-
- case "CAMPAIGN_START_DATE":
- return Digit.DateUtils.ConvertEpochToDate(value);
- case "CAMPAIGN_END_DATE":
- return Digit.DateUtils.ConvertEpochToDate(value);
- default:
- return "case_not_found";
- }
- },
- onCardClick: (obj) => {
- // return `view-test-results?tenantId=${obj?.apiResponse?.businessObject?.tenantId}&id=${obj?.apiResponse?.businessObject?.testId}&from=TQM_BREAD_INBOX`;
- },
- onCardActionClick: (obj) => {
- // return `view-test-results?tenantId=${obj?.apiResponse?.businessObject?.tenantId}&id=${obj?.apiResponse?.businessObject?.testId}&from=TQM_BREAD_INBOX`;
- },
- getCustomActionLabel: (obj, row) => {
- return "TQM_VIEW_TEST_DETAILS";
- },
- },
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/addProductConfig.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/addProductConfig.js
deleted file mode 100644
index a13b5bc9c0e..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/addProductConfig.js
+++ /dev/null
@@ -1,19 +0,0 @@
-export const addProductConfig = [
- {
- body: [
- {
- type: "component",
- component: "AddProductField",
- withoutLabel: true,
- key: "addProduct",
- validation: {},
- populators: {
- validation: {},
- },
- customProps: {
- module: "Campaign",
- },
- },
- ],
- },
-];
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/attributeConfig.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/attributeConfig.js
deleted file mode 100644
index 75864d62ab5..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/attributeConfig.js
+++ /dev/null
@@ -1,23 +0,0 @@
-//migrated to mdms
-export const attributeConfig = [
- {
- key: 1,
- code: "Age",
- i18nKey: "CAMPAIGN_ATTRIBUTE_AGE",
- },
- {
- key: 2,
- code: "Height",
- i18nKey: "CAMPAIGN_ATTRIBUTE_HEIGHT",
- },
- {
- key: 3,
- code: "Weight",
- i18nKey: "CAMPAIGN_ATTRIBUTE_WEIGHT",
- },
- {
- key: 4,
- code: "Gender",
- i18nKey: "CAMPAIGN_ATTRIBUTE_GENDER",
- },
-];
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/baseTimeOut.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/baseTimeOut.js
deleted file mode 100644
index 97047c1596e..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/baseTimeOut.js
+++ /dev/null
@@ -1,6 +0,0 @@
-export const baseTimeOut =
- {
- baseTimeOut: 100,
- maxTime: 5000
- };
-
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/deliveryConfig.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/deliveryConfig.js
deleted file mode 100644
index 3d67d30818f..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/deliveryConfig.js
+++ /dev/null
@@ -1,206 +0,0 @@
-//migrated to mdms
-export const deliveryConfig = [
- {
- projectType: "LLIN-mz",
- attrAddDisable: true,
- deliveryAddDisable: true,
- customAttribute: true,
- cycleConfig: {
- cycle: 1,
- deliveries: 1,
- },
- deliveryConfig: [
- {
- attributeConfig: [
- {
- key: 1,
- label: "Custom",
- attrType: "text",
- attrValue: "CAMPAIGN_BEDNET_INDIVIDUAL_LABEL",
- },
- {
- key: 2,
- label: "Custom",
- attrType: "text",
- attrValue: "CAMPAIGN_BEDNET_HOUSEHOLD_LABEL",
- },
- ],
- productConfig: [
- {
- key: 1,
- count: 1,
- value: "PVAR-2024-05-03-000305",
- name: "SP - 250mg",
- },
- ],
- },
- ],
- },
- {
- projectType: "MR-DN",
- attrAddDisable: false,
- deliveryAddDisable: false,
- customAttribute: true,
- cycleConfig: {
- cycle: 3,
- deliveries: 3,
- },
- deliveryConfig: [
- {
- delivery: 1,
- conditionConfig: [
- {
- deliveryType: "DIRECT",
- disableDeliveryType: true,
- attributeConfig: [
- {
- key: 1,
- label: "Custom",
- attrType: "dropdown",
- attrValue: "Age",
- operatorValue: "IN_BETWEEN",
- fromValue: 3,
- toValue: 11,
- },
- ],
- productConfig: [
- {
- key: 1,
- count: 1,
- value: "PVAR-2024-01-24-000079",
- name: "AQ - 75mg",
- },
- {
- key: 1,
- count: 1,
- value: "PVAR-2024-05-03-000305",
- name: "SP - 250mg",
- },
- ],
- },
- {
- disableDeliveryType: true,
- deliveryType: "DIRECT",
- attributeConfig: [
- {
- key: 1,
- label: "Custom",
- attrType: "dropdown",
- attrValue: "Age",
- operatorValue: "IN_BETWEEN",
- fromValue: 12,
- toValue: 59,
- },
- ],
- productConfig: [
- {
- key: 1,
- count: 1,
- value: "PVAR-2024-01-24-000078",
- name: "AQ - 150mg",
- },
- ],
- },
- ],
- },
- {
- delivery: 2,
- conditionConfig: [
- {
- deliveryType: "INDIRECT",
- attributeConfig: [
- {
- key: 1,
- label: "Custom",
- attrType: "dropdown",
- attrValue: "Age",
- operatorValue: "IN_BETWEEN",
- fromValue: 3,
- toValue: 11,
- },
- ],
- productConfig: [
- {
- key: 1,
- count: 1,
- value: "PVAR-2024-01-24-000079",
- name: "AQ - 75mg",
- },
- ],
- },
- {
- deliveryType: "INDIRECT",
- attributeConfig: [
- {
- key: 1,
- label: "Custom",
- attrType: "dropdown",
- attrValue: "Age",
- operatorValue: "IN_BETWEEN",
- fromValue: 12,
- toValue: 59,
- },
- ],
- productConfig: [
- {
- key: 1,
- count: 1,
- value: "PVAR-2024-01-24-000078",
- name: "AQ - 150mg",
- },
- ],
- },
- ],
- },
- {
- delivery: 3,
- conditionConfig: [
- {
- deliveryType: "INDIRECT",
- attributeConfig: [
- {
- key: 1,
- label: "Custom",
- attrType: "dropdown",
- attrValue: "Age",
- operatorValue: "IN_BETWEEN",
- fromValue: 3,
- toValue: 11,
- },
- ],
- productConfig: [
- {
- key: 1,
- count: 1,
- value: "PVAR-2024-01-24-000079",
- name: "AQ - 75mg",
- },
- ],
- },
- {
- deliveryType: "INDIRECT",
- attributeConfig: [
- {
- key: 1,
- label: "Custom",
- attrType: "dropdown",
- attrValue: "Age",
- operatorValue: "IN_BETWEEN",
- fromValue: 12,
- toValue: 59,
- },
- ],
- productConfig: [
- {
- key: 1,
- count: 1,
- value: "PVAR-2024-01-24-000078",
- name: "AQ - 150mg",
- },
- ],
- },
- ],
- },
- ],
- },
-];
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/headerConfig.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/headerConfig.js
deleted file mode 100644
index 66ef03113f1..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/headerConfig.js
+++ /dev/null
@@ -1,20 +0,0 @@
-export const headerConfig = {
- boundary: [
- "HCM_ADMIN_CONSOLE_BOUNDARY_CODE", "HCM_ADMIN_CONSOLE_TARGET_AT_THE_SELECTED_BOUNDARY_LEVEL"
- ],
- facilityWithBoundary: [
- "HCM_ADMIN_CONSOLE_FACILITY_CODE",
- "HCM_ADMIN_CONSOLE_FACILITY_NAME",
- "HCM_ADMIN_CONSOLE_FACILITY_TYPE",
- "HCM_ADMIN_CONSOLE_FACILITY_STATUS",
- "HCM_ADMIN_CONSOLE_FACILITY_CAPACITY",
- "HCM_ADMIN_CONSOLE_BOUNDARY_CODE_MANDATORY"
- ],
- User: [
- "HCM_ADMIN_CONSOLE_USER_NAME",
- "HCM_ADMIN_CONSOLE_USER_PHONE_NUMBER",
- "HCM_ADMIN_CONSOLE_USER_ROLE",
- "HCM_ADMIN_CONSOLE_USER_EMPLOYMENT_TYPE",
- "HCM_ADMIN_CONSOLE_BOUNDARY_CODE_MANDATORY"
- ]
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/mailConfig.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/mailConfig.js
deleted file mode 100644
index 7bd788d976c..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/mailConfig.js
+++ /dev/null
@@ -1,5 +0,0 @@
-export const mailConfig =
- {
- mailId: "L1team@email.com"
- };
-
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/myCampaignConfig.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/myCampaignConfig.js
deleted file mode 100644
index 4152a57759e..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/myCampaignConfig.js
+++ /dev/null
@@ -1,667 +0,0 @@
-/* The above code defines a JavaScript object `myCampaignConfig` which contains configurations for
-different types of campaigns - ongoing, completed, and drafts. Each campaign type has its own search
-configuration with fields like campaign name, type, start date, end date, etc. The configurations
-also include API details for fetching data, UI styles, search result columns, pagination settings,
-and more. The object is exported for use in other parts of the codebase. */
-export const myCampaignConfig = {
- tenantId: "mz",
- moduleName: "commonCampaignUiConfig",
- showTab: true,
- myCampaignConfig: [
- {
- label: "CAMPAIGN_ONGOING",
- type: "search",
- apiDetails: {
- serviceName: "/project-factory/v1/project-type/search",
- requestParam: {},
- requestBody: {},
- minParametersForSearchForm: 0,
- minParametersForFilterForm: 0,
- masterName: "commonUiConfig",
- moduleName: "MyCampaignConfigOngoing",
- tableFormJsonPath: "requestBody.inbox",
- filterFormJsonPath: "requestBody.custom",
- searchFormJsonPath: "requestBody.custom",
- },
- sections: {
- search: {
- uiConfig: {
- headerLabel: "ES_COMMON_SEARCH",
- type: "search",
- typeMobile: "filter",
- searchWrapperStyles: {
- flexDirection: "column-reverse",
- marginTop: "1.4rem",
- alignItems: "center",
- justifyContent: "end",
- gridColumn: "3",
- },
- headerStyle: null,
- primaryLabel: "Search",
- secondaryLabel: "ES_COMMON_CLEAR_SEARCH",
- minReqFields: 0,
- defaultValues: {
- name: "",
- type: "",
- },
- fields: [
- {
- label: "CAMPAIGN_SEARCH_NAME",
- type: "text",
- isMandatory: false,
- disable: false,
- populators: {
- name: "campaignName",
- error: "TQM_ERR_VALID_CAMPAIGN_NAME",
- style: {
- marginBottom: "0px",
- },
- },
- },
- {
- label: "CAMPAIGN_SEARCH_TYPE",
- type: "apidropdown",
- isMandatory: false,
- disable: false,
- populators: {
- optionsCustomStyle: {
- top: "2.3rem",
- },
- name: "campaignType",
- optionsKey: "code",
- allowMultiSelect: false,
- masterName: "commonUiConfig",
- moduleName: "MyCampaignConfigOngoing",
- customfn: "populateCampaignTypeReqCriteria",
- },
- },
- ],
- },
- label: "",
- labelMobile: "ES_COMMON_SEARCH",
- children: {},
- show: true,
- },
- searchResult: {
- uiConfig: {
- columns: [
- {
- label: "CAMPAIGN_NAME",
- jsonPath: "campaignName",
- additionalCustomization: true,
- },
- {
- label: "CAMPAIGN_TYPE",
- jsonPath: "projectType",
- prefix: "CAMPAIGN_PROJECT_",
- translate: true,
- },
- {
- label: "CAMPAIGN_BENEFICIARY_TYPE",
- jsonPath: "additionalDetails.beneficiaryType",
- prefix: "",
- translate: true,
- },
- {
- label: "CAMPAIGN_START_DATE",
- jsonPath: "startDate",
- additionalCustomization: true,
- // disableSortBy: true,
- },
- {
- label: "CAMPAIGN_END_DATE",
- jsonPath: "endDate",
- additionalCustomization: true,
- // disableSortBy: true,
- },
- ],
- enableGlobalSearch: false,
- enableColumnSort: true,
- resultsJsonPath: "CampaignDetails",
- // customDefaultPagination: {
- // limit: 5,
- // offset: 0,
- // },
- // customPageSizesArray: [5, 10, 15, 20],
- tableClassName: "table campaign-table",
- },
- children: {},
- show: true,
- },
- links: {
- show: false,
- },
- filter: {
- show: false,
- },
- },
- additionalSections: {},
- persistFormData: true,
- showAsRemovableTagsInMobile: true,
- },
- {
- label: "CAMPAIGN_COMPLETED",
- type: "search",
- apiDetails: {
- serviceName: "/project-factory/v1/project-type/search",
- requestParam: {},
- requestBody: {},
- minParametersForSearchForm: 0,
- minParametersForFilterForm: 0,
- masterName: "commonUiConfig",
- moduleName: "MyCampaignConfigCompleted",
- tableFormJsonPath: "requestBody.inbox",
- filterFormJsonPath: "requestBody.custom",
- searchFormJsonPath: "requestBody.custom",
- },
- sections: {
- search: {
- uiConfig: {
- headerLabel: "ES_COMMON_SEARCH",
- type: "search",
- typeMobile: "filter",
- searchWrapperStyles: {
- flexDirection: "column-reverse",
- marginTop: "1.4rem",
- alignItems: "center",
- justifyContent: "end",
- gridColumn: "3",
- },
- headerStyle: null,
- primaryLabel: "Search",
- secondaryLabel: "ES_COMMON_CLEAR_SEARCH",
- minReqFields: 0,
- defaultValues: {
- name: "",
- type: "",
- },
- fields: [
- {
- label: "CAMPAIGN_SEARCH_NAME",
- type: "text",
- isMandatory: false,
- disable: false,
- populators: {
- name: "campaignName",
- error: "TQM_ERR_VALID_CAMPAIGN_NAME",
- style: {
- marginBottom: "0px",
- },
- },
- },
- {
- label: "CAMPAIGN_SEARCH_TYPE",
- type: "apidropdown",
- isMandatory: false,
- disable: false,
- populators: {
- optionsCustomStyle: {
- top: "2.3rem",
- },
- name: "campaignType",
- optionsKey: "code",
- allowMultiSelect: false,
- masterName: "commonUiConfig",
- moduleName: "MyCampaignConfigCompleted",
- customfn: "populateCampaignTypeReqCriteria",
- },
- },
- ],
- },
- label: "",
- labelMobile: "ES_COMMON_SEARCH",
- children: {},
- show: true,
- },
- searchResult: {
- uiConfig: {
- columns: [
- {
- label: "CAMPAIGN_NAME",
- jsonPath: "campaignName",
- additionalCustomization: true,
- },
- {
- label: "CAMPAIGN_TYPE",
- jsonPath: "projectType",
- prefix: "CAMPAIGN_PROJECT_",
- translate: true,
- },
- {
- label: "CAMPAIGN_BENEFICIARY_TYPE",
- jsonPath: "additionalDetails.beneficiaryType",
- prefix: "",
- translate: true,
- },
- {
- label: "CAMPAIGN_START_DATE",
- jsonPath: "startDate",
- additionalCustomization: true,
- // disableSortBy: true,
- },
- {
- label: "CAMPAIGN_END_DATE",
- jsonPath: "endDate",
- additionalCustomization: true,
- // disableSortBy: true,
- },
- ],
- enableGlobalSearch: false,
- enableColumnSort: true,
- resultsJsonPath: "CampaignDetails",
- // customDefaultPagination: {
- // limit: 5,
- // offset: 0,
- // },
- // customPageSizesArray: [5, 10, 15, 20],
- tableClassName: "table campaign-table",
- },
- children: {},
- show: true,
- },
- links: {
- show: false,
- },
- filter: {
- show: false,
- },
- },
- additionalSections: {},
- persistFormData: true,
- showAsRemovableTagsInMobile: true,
- },
- {
- label: "CAMPAIGN_UPCOMING",
- type: "search",
- apiDetails: {
- serviceName: "/project-factory/v1/project-type/search",
- requestParam: {},
- requestBody: {},
- minParametersForSearchForm: 0,
- minParametersForFilterForm: 0,
- masterName: "commonUiConfig",
- moduleName: "MyCampaignConfigUpcoming",
- tableFormJsonPath: "requestBody.inbox",
- filterFormJsonPath: "requestBody.custom",
- searchFormJsonPath: "requestBody.custom",
- },
- sections: {
- search: {
- uiConfig: {
- headerLabel: "ES_COMMON_SEARCH",
- type: "search",
- typeMobile: "filter",
- searchWrapperStyles: {
- flexDirection: "column-reverse",
- marginTop: "1.4rem",
- alignItems: "center",
- justifyContent: "end",
- gridColumn: "3",
- },
- headerStyle: null,
- primaryLabel: "Search",
- secondaryLabel: "ES_COMMON_CLEAR_SEARCH",
- minReqFields: 0,
- defaultValues: {
- name: "",
- type: "",
- },
- fields: [
- {
- label: "CAMPAIGN_SEARCH_NAME",
- type: "text",
- isMandatory: false,
- disable: false,
- populators: {
- name: "campaignName",
- error: "TQM_ERR_VALID_CAMPAIGN_NAME",
- style: {
- marginBottom: "0px",
- },
- },
- },
- {
- label: "CAMPAIGN_SEARCH_TYPE",
- type: "apidropdown",
- isMandatory: false,
- disable: false,
- populators: {
- optionsCustomStyle: {
- top: "2.3rem",
- },
- name: "campaignType",
- optionsKey: "code",
- allowMultiSelect: false,
- masterName: "commonUiConfig",
- moduleName: "MyCampaignConfigUpcoming",
- customfn: "populateCampaignTypeReqCriteria",
- },
- },
- ],
- },
- label: "",
- labelMobile: "ES_COMMON_SEARCH",
- children: {},
- show: true,
- },
- searchResult: {
- uiConfig: {
- columns: [
- {
- label: "CAMPAIGN_NAME",
- jsonPath: "campaignName",
- additionalCustomization: true,
- },
- {
- label: "CAMPAIGN_TYPE",
- jsonPath: "projectType",
- prefix: "CAMPAIGN_PROJECT_",
- translate: true,
- },
- {
- label: "CAMPAIGN_BENEFICIARY_TYPE",
- jsonPath: "additionalDetails.beneficiaryType",
- prefix: "",
- translate: true,
- },
- {
- label: "CAMPAIGN_START_DATE",
- jsonPath: "startDate",
- additionalCustomization: true,
- // disableSortBy: true,
- },
- {
- label: "CAMPAIGN_END_DATE",
- jsonPath: "endDate",
- additionalCustomization: true,
- // disableSortBy: true,
- },
- ],
- enableGlobalSearch: false,
- enableColumnSort: true,
- resultsJsonPath: "CampaignDetails",
- // customDefaultPagination: {
- // limit: 5,
- // offset: 0,
- // },
- // customPageSizesArray: [5, 10, 15, 20],
- tableClassName: "table campaign-table",
- },
- children: {},
- show: true,
- },
- links: {
- show: false,
- },
- filter: {
- show: false,
- },
- },
- additionalSections: {},
- persistFormData: true,
- showAsRemovableTagsInMobile: true,
- },
- {
- label: "CAMPAIGN_DRAFTS",
- type: "search",
- apiDetails: {
- serviceName: "/project-factory/v1/project-type/search",
- requestParam: {},
- requestBody: {},
- minParametersForSearchForm: 0,
- minParametersForFilterForm: 0,
- masterName: "commonUiConfig",
- moduleName: "MyCampaignConfigDrafts",
- tableFormJsonPath: "requestBody.inbox",
- filterFormJsonPath: "requestBody.custom",
- searchFormJsonPath: "requestBody.custom",
- },
- sections: {
- search: {
- uiConfig: {
- headerLabel: "ES_COMMON_SEARCH",
- type: "search",
- typeMobile: "filter",
- searchWrapperStyles: {
- flexDirection: "column-reverse",
- marginTop: "1.4rem",
- alignItems: "center",
- justifyContent: "end",
- gridColumn: "3",
- },
- headerStyle: null,
- primaryLabel: "Search",
- secondaryLabel: "ES_COMMON_CLEAR_SEARCH",
- minReqFields: 0,
- defaultValues: {
- campaignName: "",
- campaignType: "",
- },
- fields: [
- {
- label: "CAMPAIGN_SEARCH_NAME",
- type: "text",
- isMandatory: false,
- disable: false,
- populators: {
- name: "campaignName",
- error: "TQM_ERR_VALID_CAMPAIGN_NAME",
- style: {
- marginBottom: "0px",
- },
- },
- },
- {
- label: "CAMPAIGN_SEARCH_TYPE",
- type: "apidropdown",
- isMandatory: false,
- disable: false,
- populators: {
- optionsCustomStyle: {
- top: "2.3rem",
- },
- name: "campaignType",
- optionsKey: "code",
- allowMultiSelect: false,
- masterName: "commonUiConfig",
- moduleName: "MyCampaignConfigDrafts",
- customfn: "populateCampaignTypeReqCriteria",
- },
- },
- ],
- },
- label: "",
- labelMobile: "ES_COMMON_SEARCH",
- children: {},
- show: true,
- },
- searchResult: {
- uiConfig: {
- columns: [
- {
- label: "CAMPAIGN_NAME",
- jsonPath: "campaignName",
- additionalCustomization: true,
- },
- {
- label: "CAMPAIGN_TYPE",
- jsonPath: "projectType",
- prefix: "CAMPAIGN_PROJECT_",
- translate: true,
- },
- {
- label: "CAMPAIGN_BENEFICIARY_TYPE",
- jsonPath: "additionalDetails.beneficiaryType",
- prefix: "",
- translate: true,
- },
- {
- label: "CAMPAIGN_START_DATE",
- jsonPath: "startDate",
- additionalCustomization: true,
- // disableSortBy: true,
- },
- {
- label: "CAMPAIGN_END_DATE",
- jsonPath: "endDate",
- additionalCustomization: true,
- // disableSortBy: true,
- },
- ],
- enableGlobalSearch: false,
- enableColumnSort: true,
- resultsJsonPath: "CampaignDetails",
- // customDefaultPagination: {
- // limit: 5,
- // offset: 0,
- // },
- // customPageSizesArray: [5, 10, 15, 20],
- tableClassName: "table campaign-table",
- },
- children: {},
- show: true,
- },
- links: {
- show: false,
- },
- filter: {
- show: false,
- },
- },
- additionalSections: {},
- persistFormData: true,
- showAsRemovableTagsInMobile: true,
- },
- {
- label: "CAMPAIGN_FAILED",
- type: "search",
- apiDetails: {
- serviceName: "/project-factory/v1/project-type/search",
- requestParam: {},
- requestBody: {},
- minParametersForSearchForm: 0,
- minParametersForFilterForm: 0,
- masterName: "commonUiConfig",
- moduleName: "MyCampaignConfigFailed",
- tableFormJsonPath: "requestBody.inbox",
- filterFormJsonPath: "requestBody.custom",
- searchFormJsonPath: "requestBody.custom",
- },
- sections: {
- search: {
- uiConfig: {
- headerLabel: "ES_COMMON_SEARCH",
- type: "search",
- typeMobile: "filter",
- searchWrapperStyles: {
- flexDirection: "column-reverse",
- marginTop: "1.4rem",
- alignItems: "center",
- justifyContent: "end",
- gridColumn: "3",
- },
- headerStyle: null,
- primaryLabel: "Search",
- secondaryLabel: "ES_COMMON_CLEAR_SEARCH",
- minReqFields: 0,
- defaultValues: {
- name: "",
- type: "",
- },
- fields: [
- {
- label: "CAMPAIGN_SEARCH_NAME",
- type: "text",
- isMandatory: false,
- disable: false,
- populators: {
- name: "campaignName",
- error: "TQM_ERR_VALID_CAMPAIGN_NAME",
- style: {
- marginBottom: "0px",
- },
- },
- },
- {
- label: "CAMPAIGN_SEARCH_TYPE",
- type: "apidropdown",
- isMandatory: false,
- disable: false,
- populators: {
- optionsCustomStyle: {
- top: "2.3rem",
- },
- name: "campaignType",
- optionsKey: "code",
- allowMultiSelect: false,
- masterName: "commonUiConfig",
- moduleName: "MyCampaignConfigCompleted",
- customfn: "populateCampaignTypeReqCriteria",
- },
- },
- ],
- },
- label: "",
- labelMobile: "ES_COMMON_SEARCH",
- children: {},
- show: true,
- },
- searchResult: {
- uiConfig: {
- columns: [
- {
- label: "CAMPAIGN_NAME",
- jsonPath: "campaignName",
- additionalCustomization: true,
- },
- {
- label: "CAMPAIGN_TYPE",
- jsonPath: "projectType",
- prefix: "CAMPAIGN_PROJECT_",
- translate: true,
- },
- {
- label: "CAMPAIGN_BENEFICIARY_TYPE",
- jsonPath: "additionalDetails.beneficiaryType",
- prefix: "",
- translate: true,
- },
- {
- label: "CAMPAIGN_START_DATE",
- jsonPath: "startDate",
- additionalCustomization: true,
- // disableSortBy: true,
- },
- {
- label: "CAMPAIGN_END_DATE",
- jsonPath: "endDate",
- additionalCustomization: true,
- // disableSortBy: true,
- },
- ],
- enableGlobalSearch: false,
- enableColumnSort: true,
- resultsJsonPath: "CampaignDetails",
- // customDefaultPagination: {
- // limit: 5,
- // offset: 0,
- // },
- // customPageSizesArray: [5, 10, 15, 20],
- tableClassName: "table campaign-table",
- },
- children: {},
- show: true,
- },
- links: {
- show: false,
- },
- filter: {
- show: false,
- },
- },
- additionalSections: {},
- persistFormData: true,
- showAsRemovableTagsInMobile: true,
- },
- ],
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/operatorConfig.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/operatorConfig.js
deleted file mode 100644
index 94ffd6c4e56..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/operatorConfig.js
+++ /dev/null
@@ -1,27 +0,0 @@
-//migrated to mdms
-export const operatorConfig = [
- {
- key: 1,
- code: "LESS_THAN",
- },
- {
- key: 2,
- code: "GREATER_THAN",
- },
- {
- key: 3,
- code: "IN_BETWEEN",
- },
- {
- key: 4,
- code: "EQUAL_TO",
- },
- {
- key: 5,
- code: "GREATER_THAN_EQUAL_TO",
- },
- {
- key: 6,
- code: "LESSER_THAN_EQUAL_TO",
- },
-];
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/previewConfig.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/previewConfig.js
deleted file mode 100644
index 1e33ecd8e41..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/previewConfig.js
+++ /dev/null
@@ -1,124 +0,0 @@
-export const previewConfig = {
- HCM_CAMPAIGN_DATE: {
- campaignDates: {
- startDate: "2024-04-01",
- endDate: "2024-04-26",
- },
- },
- HCM_CAMPAIGN_TYPE: {
- projectType: {
- id: "84e28a7b-8c6d-4505-a7ef-5d714e0361f6",
- name: "mz project type configuration for LLIN Campaigns",
- code: "LLIN-mz",
- group: "MALARIA",
- beneficiaryType: "HOUSEHOLD",
- eligibilityCriteria: ["All households are eligible.", "Prison inmates are eligible."],
- dashboardUrls: {
- NATIONAL_SUPERVISOR: "/digit-ui/employee/dss/landing/national-health-dashboard",
- PROVINCIAL_SUPERVISOR: "/digit-ui/employee/dss/dashboard/provincial-health-dashboard",
- DISTRICT_SUPERVISOR: "/digit-ui/employee/dss/dashboard/district-health-dashboard",
- },
- taskProcedure: [
- "1 bednet is to be distributed per 2 household members.",
- "If there are 4 household members, 2 bednets should be distributed.",
- "If there are 5 household members, 3 bednets should be distributed.",
- ],
- resources: [
- {
- productVariantId: "PVAR-2024-02-13-000211",
- isBaseUnitVariant: false,
- },
- ],
- },
- },
- HCM_CAMPAIGN_NAME: {
- campaignName: "sdkfkdhsdjkhkjsdh",
- },
- HCM_CAMPAIGN_CYCLE_CONFIGURE: {
- cycleConfigure: {
- cycleConfgureDate: {
- cycle: 2,
- deliveries: 1,
- },
- cycleData: [
- {
- key: 1,
- fromDate: "2001-12-12",
- toDate: "2002-11-11",
- },
- {
- key: 2,
- fromDate: "2002-01-12",
- toDate: "2011-11-11",
- },
- ],
- },
- },
- HCM_CAMPAIGN_DELIVERY_DATA: {
- deliveryRule: [
- {
- cycleIndex: "1",
- active: false,
- deliveries: [
- {
- deliveryIndex: "1",
- active: true,
- deliveryRules: [
- {
- ruleKey: 1,
- delivery: {},
- attributes: [
- {
- key: 1,
- attribute: {
- key: 1,
- code: "Age",
- },
- operator: {
- key: 1,
- code: "LESS_THAN",
- },
- value: "576",
- },
- ],
- products: [],
- },
- ],
- },
- ],
- },
- {
- cycleIndex: "2",
- active: true,
- deliveries: [
- {
- deliveryIndex: "1",
- active: true,
- deliveryRules: [
- {
- ruleKey: 1,
- delivery: {},
- attributes: [
- {
- key: 1,
- attribute: {
- key: 1,
- code: "Age",
- },
- operator: {
- key: 2,
- code: "GREATER_THAN",
- },
- value: "65",
- },
- ],
- products: [],
- },
- ],
- },
- ],
- },
- ],
- },
- undefined: {},
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/productType.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/productType.js
deleted file mode 100644
index 449b55450b1..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/productType.js
+++ /dev/null
@@ -1,15 +0,0 @@
-//migrated to mdms
-export const productType = [
- {
- key: 1,
- code: "BEDNET",
- },
- {
- key: 2,
- code: "TABLET",
- },
- {
- key: 3,
- code: "DRUG",
- },
-];
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/schemaConfig.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/schemaConfig.js
deleted file mode 100644
index 48611ca7a41..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/configs/schemaConfig.js
+++ /dev/null
@@ -1,80 +0,0 @@
-export const schemaConfig = {
- Boundary: {
- $schema: "http://json-schema.org/draft-07/schema#",
- title: "BoundaryTemplateSchema",
- type: "object",
- properties: {
- "Boundary Code": {
- type: "string",
- minLength: 1,
- },
- "Target at the Selected Boundary level": {
- type: "integer",
- minimum: 1,
- maximum: 100000000,
- },
- },
- required: ["Boundary Code"],
- },
- facilityWithBoundary: {
- $schema: "http://json-schema.org/draft-07/schema#",
- title: "FacilityTemplateSchema",
- type: "object",
- properties: {
- "Facility Name": {
- type: "string",
- maxLength: 2000,
- minLength: 1,
- },
- "Facility Type": {
- type: "string",
- enum: ["Warehouse", "Health Facility"],
- },
- "Facility Status": {
- type: "string",
- enum: ["Temporary", "Permanent"],
- },
- Capacity: {
- type: "integer",
- minimum: 1,
- maximum: 100000000,
- multipleOf: 1,
- },
- "Boundary Code": {
- type: "string",
- minLength: 1,
- },
- },
- required: ["Facility Name", "Facility Type", "Facility Status", "Capacity", "Boundary Code"],
- },
- User: {
- $schema: "http://json-schema.org/draft-07/schema#",
- title: "UserTemplateSchema",
- type: "object",
- properties: {
- "Name of the Person (Mandatory)": {
- type: "string",
- maxLength: 128,
- minLength: 1,
- },
- "Phone Number": {
- type: "integer",
- minimum: 100000000,
- maximum: 9999999999,
- },
- "Role (Mandatory)": {
- type: "string",
- },
- "Employment Type (Mandatory)": {
- type: "string",
- enum: ["Temporary", "Permanent"],
- },
- "Capacity": {
- "type": "number",
- "minimum": 1,
- "maximum": 100000000
- }
- },
- required: ["Name of the Person (Mandatory)", "Phone Number (Mandatory)", "Role (Mandatory)", "Employment Type (Mandatory)"],
- },
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/index.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/index.js
deleted file mode 100644
index feb20e7a340..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/index.js
+++ /dev/null
@@ -1,47 +0,0 @@
-import utils from "../utils";
-import { useSearchCampaign } from "./services/useSearchCampaign";
-import useCreateCampaign from "./useCreateCampaign";
-import { useProductList } from "./useProductList";
-import useUpdateCampaign from "./useUpdateCampaign";
-import { useGenerateIdCampaign } from "./useGenerateIdCampaign";
-import { useResourceData } from "./useResourceData";
-import useCreateProductVariant from "./useCreateProductVariant";
-import useCreateProduct from "./useCreateProduct";
-import useParallelSearch from "./useParallelSearch";
-
-const UserService = {};
-
-const workbench = {};
-
-const contracts = {};
-
-const campaign = {
- useProductList,
- useCreateCampaign,
- useSearchCampaign,
- useUpdateCampaign,
- useGenerateIdCampaign,
- useResourceData,
- useCreateProduct,
- useCreateProductVariant,
- useParallelSearch,
-};
-
-const Hooks = {
- campaign,
-};
-
-const Utils = {
- browser: {
- sample: () => {},
- },
- workbench: {
- ...utils,
- },
-};
-
-export const CustomisedHooks = {
- Hooks,
- UserService,
- Utils,
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/services/createCampaignService.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/services/createCampaignService.js
deleted file mode 100644
index d78f2255133..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/services/createCampaignService.js
+++ /dev/null
@@ -1,19 +0,0 @@
-const createCampaignService = async (req, tenantId) => {
- try {
- const response = await Digit.CustomService.getResponse({
- url: "/project-factory/v1/project-type/create",
- body: {
- CampaignDetails: req,
- },
- });
- return response;
- } catch (error) {
- if (!error?.response?.data?.Errors[0].description) {
- throw new Error(error?.response?.data?.Errors[0].code);
- } else {
- throw new Error(error?.response?.data?.Errors[0].description);
- }
- }
-};
-
-export default createCampaignService;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/services/updateCampaignService.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/services/updateCampaignService.js
deleted file mode 100644
index 3fae8e281ac..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/services/updateCampaignService.js
+++ /dev/null
@@ -1,20 +0,0 @@
-const updateCampaignService = async (req, tenantId) => {
- try {
- const response = await Digit.CustomService.getResponse({
- url: "/project-factory/v1/project-type/update",
- body: {
- CampaignDetails: req,
- },
- });
- return response;
- } catch (error) {
- // throw new Error(error?.response?.data?.Errors[0].message);
- if (!error?.response?.data?.Errors[0].description) {
- throw new Error(error?.response?.data?.Errors[0].code);
- } else {
- throw new Error(error?.response?.data?.Errors[0].description);
- }
- }
-};
-
-export default updateCampaignService;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/services/useSearchCampaign.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/services/useSearchCampaign.js
deleted file mode 100644
index dbc5fc52040..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/services/useSearchCampaign.js
+++ /dev/null
@@ -1,21 +0,0 @@
-import { useQuery } from "react-query";
-
-const searchCampaignService = async ({ tenantId, filter, pagination }) => {
- const response = await Digit.CustomService.getResponse({
- url: "/project-factory/v1/project-type/search",
- body: {
- CampaignDetails: {
- tenantId: tenantId,
- ...filter,
- pagination: {
- ...pagination,
- },
- },
- },
- });
- return response?.CampaignDetails;
-};
-
-export const useSearchCampaign = ({ tenantId, filter, pagination, config = {} }) => {
- return useQuery(["SEARCH_CAMPAIGN", tenantId, filter, pagination], () => searchCampaignService({ tenantId, filter, pagination }), config);
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useCreateCampaign.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useCreateCampaign.js
deleted file mode 100644
index cf01fe94ef4..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useCreateCampaign.js
+++ /dev/null
@@ -1,10 +0,0 @@
-import { useMutation } from "react-query";
-import createCampaignService from "./services/createCampaignService";
-
-const useCreateCampaign = (tenantId) => {
- return useMutation((reqData) => {
- return createCampaignService(reqData, tenantId);
- });
-};
-
-export default useCreateCampaign;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useCreateProduct.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useCreateProduct.js
deleted file mode 100644
index 70954c9802d..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useCreateProduct.js
+++ /dev/null
@@ -1,24 +0,0 @@
-import { useMutation } from "react-query";
-
-const createProductService = async (req, tenantId) => {
- try {
- const response = await Digit.CustomService.getResponse({
- url: "/product/v1/_create",
- body: {
- Product: req,
- apiOperation: "CREATE",
- },
- });
- return response;
- } catch (error) {
- throw new Error(error?.response?.data?.Errors?.[0].description);
- }
-};
-
-const useCreateProduct = (tenantId) => {
- return useMutation((reqData) => {
- return createProductService(reqData, tenantId);
- });
-};
-
-export default useCreateProduct;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useCreateProductVariant.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useCreateProductVariant.js
deleted file mode 100644
index 4063f6dc24c..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useCreateProductVariant.js
+++ /dev/null
@@ -1,24 +0,0 @@
-import { useMutation } from "react-query";
-
-const createProductVariantService = async (req, tenantId) => {
- try {
- const response = await Digit.CustomService.getResponse({
- url: "/product/variant/v1/_create",
- body: {
- ProductVariant: req,
- apiOperation: "CREATE",
- },
- });
- return response;
- } catch (error) {
- throw new Error(error?.response?.data?.Errors?.[0].description);
- }
-};
-
-const useCreateProductVariant = (tenantId) => {
- return useMutation((reqData) => {
- return createProductVariantService(reqData, tenantId);
- });
-};
-
-export default useCreateProductVariant;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useGenerateIdCampaign.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useGenerateIdCampaign.js
deleted file mode 100644
index af75746abdd..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useGenerateIdCampaign.js
+++ /dev/null
@@ -1,26 +0,0 @@
-export const useGenerateIdCampaign = ({ type, hierarchyType, filters, campaignId, config = {}, forceUpdate = "true" }) => {
- const updatedFilters = filters?.map(({ type, ...rest }) => ({
- ...rest,
- boundaryType: type,
- }));
- const reqCriteria = {
- url: `/project-factory/v1/data/_generate`,
- changeQueryName: `${type}${hierarchyType}${filters}`,
- params: {
- tenantId: Digit.ULBService.getCurrentTenantId(),
- type: type,
- forceUpdate: forceUpdate,
- hierarchyType: hierarchyType,
- campaignId: campaignId,
- },
- body: type === "boundary" ? (updatedFilters === undefined ? { Filters: null } : { Filters: { boundaries: updatedFilters } }) : {},
- config: {
- ...config,
- cacheTime: 0,
- staleTime: 0,
- },
- };
- const { data: Data, refetch, isLoading } = Digit.Hooks.useCustomAPIHook(reqCriteria);
-
- return { isLoading: isLoading, data: Data?.GeneratedResource?.[0]?.id, refetch };
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useParallelSearch.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useParallelSearch.js
deleted file mode 100644
index 6a2adb07f10..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useParallelSearch.js
+++ /dev/null
@@ -1,88 +0,0 @@
-const useParallelSearch = async ({ parentArray, tenantId, boundaryType, hierarchy, targetedData }) => {
- let cacheData = window.Digit.SessionStorage.get("HCM_CAMPAIGN_BOUNDARY_DATA") ? window.Digit.SessionStorage.get("HCM_CAMPAIGN_BOUNDARY_DATA") : {};
- let missingParent = null;
- let removeData = null;
-
- function findMissingCodes(d, c) {
- let missingCodes = [];
-
- for (let i = 0; i < d?.length; i++) {
- let found = false;
- for (let j = 0; j < c?.length; j++) {
- if (d?.[i] === c?.[j]?.parentCode) {
- found = true;
- break;
- }
- }
- if (!found) {
- missingCodes?.push(d[i]);
- }
- }
-
- return missingCodes;
- }
-
- function removeMissingParentCodes(cacheData, parentArray) {
- const validParentCodes = new Set(parentArray);
-
- return cacheData?.filter((obj) => validParentCodes?.has(obj?.parentCode));
- }
-
- function checkremoveMissingParentCodes(cacheData, parentArray) {
- const validParentCodes = new Set(parentArray);
- return cacheData?.filter((obj) => !validParentCodes?.has(obj?.parentCode));
- }
-
- function checkParentCodePresence(data, array) {
- return array.every((item) => data.some((entry) => entry.parentCode === item));
- }
- if (parentArray?.length > cacheData?.[targetedData]?.length) {
- missingParent = findMissingCodes(parentArray, cacheData?.[targetedData]);
- const requests = missingParent.map((parentCode) => {
- return Digit.CustomService.getResponse({
- url: "/boundary-service/boundary-relationships/_search",
- params: {
- tenantId: tenantId,
- hierarchyType: hierarchy,
- boundaryType: boundaryType,
- parent: parentCode,
- },
- body: {},
- }).then((boundaryTypeData) => ({ parentCode, boundaryTypeData }));
- });
- const newData = await Promise.all(requests);
- const setcacheData = { ...cacheData, [targetedData]: cacheData?.[targetedData] ? [...cacheData?.[targetedData], ...newData] : [...newData] };
- window.Digit.SessionStorage.set("HCM_CAMPAIGN_BOUNDARY_DATA", setcacheData);
- return setcacheData?.[targetedData];
- } else if (cacheData?.[targetedData]?.length > parentArray?.length && checkParentCodePresence(cacheData?.[targetedData], parentArray)) {
- removeData = removeMissingParentCodes(cacheData?.[targetedData], parentArray);
- const setcacheData = { ...cacheData, [targetedData]: [...removeData] };
- // window.Digit.SessionStorage.set("HCM_CAMPAIGN_BOUNDARY_DATA", setcacheData);
- return setcacheData?.[targetedData];
- } else if (
- parentArray?.length === cacheData?.[targetedData]?.length &&
- !checkremoveMissingParentCodes(cacheData?.[targetedData], parentArray)?.length &&
- findMissingCodes(parentArray, cacheData?.[targetedData])?.length === 0
- ) {
- return cacheData?.[targetedData];
- } else {
- const requests = parentArray.map((parentCode) => {
- return Digit.CustomService.getResponse({
- url: "/boundary-service/boundary-relationships/_search",
- params: {
- tenantId: tenantId,
- hierarchyType: hierarchy,
- boundaryType: boundaryType,
- parent: parentCode,
- },
- body: {},
- }).then((boundaryTypeData) => ({ parentCode, boundaryTypeData }));
- });
- const newData = await Promise.all(requests);
- const setcacheData = { ...cacheData, [targetedData]: cacheData?.targetedData ? [...cacheData?.targetedData, ...newData] : [...newData] };
- window.Digit.SessionStorage.set("HCM_CAMPAIGN_BOUNDARY_DATA", setcacheData);
- return setcacheData?.[targetedData];
- }
-};
-
-export default useParallelSearch;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useProductList.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useProductList.js
deleted file mode 100644
index cb102a128e7..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useProductList.js
+++ /dev/null
@@ -1,53 +0,0 @@
-export const useProductList = (tenantId) => {
- const reqCriteriaVariant = {
- url: `/product/variant/v1/_search`,
- params: { tenantId: tenantId, limit: 1000, offset: 0 },
- body: {
- ProductVariant: {},
- },
- config: {
- enabled: true,
- select: (data) => {
- return data?.ProductVariant;
- },
- },
- };
-
- const { isLoading, data: productVariant, isFetching } = Digit.Hooks.useCustomAPIHook(reqCriteriaVariant);
-
- const reqCriteriaProduct = {
- url: `/product/v1/_search`,
- params: { tenantId: tenantId, limit: 1000, offset: 0 },
- body: {
- Product: {
- id: productVariant?.map((i) => i?.productId),
- },
- },
- config: {
- enabled: productVariant && !isLoading ? true : false,
- select: (data) => {
- return data?.Product;
- },
- },
- };
-
- const { isLoading: isProductLoading, data: product } = Digit.Hooks.useCustomAPIHook(reqCriteriaProduct);
-
- let productList;
- if (productVariant && product) {
- productList = productVariant
- ?.map((item) => {
- const target = product?.find((j) => j.id === item.productId);
- if (!target?.name || !item?.variation) {
- return null;
- }
- return {
- ...item,
- displayName: `${target?.name} - ${item?.variation}`,
- };
- })
- ?.filter((i) => i !== null);
- }
-
- return productList;
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useResourceData.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useResourceData.js
deleted file mode 100644
index 0c8f41f8288..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useResourceData.js
+++ /dev/null
@@ -1,107 +0,0 @@
-import axios from 'axios';
-import * as XLSX from 'xlsx';
-import { baseTimeOut } from '../configs/baseTimeOut';
-export const useResourceData = async (data, hierarchyType, type, tenantId, id , baseTimeOut) => {
-
-
- let Type;
- let jsonDataLength;
- let Error = {
- isError: false,
- error: {},
- };
- let response;
- if (type === "facilityWithBoundary") {
- Type = "facility";
- } else if (type === "userWithBoundary") {
- Type = "user";
- } else {
- Type = "boundaryWithTarget";
- }
- try {
- if(data){
- axios
- .get("/filestore/v1/files/id", {
- responseType: "arraybuffer",
- headers: {
- "Content-Type": "application/json",
- Accept: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
- "auth-token": Digit.UserService.getUser()?.["access_token"],
- },
- params: {
- tenantId: Digit.ULBService.getCurrentTenantId(),
- fileStoreId: data?.[0]?.filestoreId,
- },
- })
- .then(async (res) => {
- const fileData = res.data;
- const workbook = XLSX.read(fileData, { type: 'buffer' });
- const sheetName = workbook.SheetNames[1];
- const worksheet = workbook.Sheets[sheetName];
- const jsonData = XLSX.utils.sheet_to_json(worksheet);
- jsonDataLength = jsonData.length;
- });
- }
- const responseTemp = await Digit.CustomService.getResponse({
- url: "/project-factory/v1/data/_create",
- body: {
- ResourceDetails: {
- type: Type,
- hierarchyType: hierarchyType,
- tenantId: Digit.ULBService.getCurrentTenantId(),
- fileStoreId: data?.[0]?.filestoreId,
- action: "validate",
- campaignId: id,
- additionalDetails: {},
- },
- },
- });
-
- response = responseTemp;
-
- } catch (error) {
- if (error?.response && error?.response?.data) {
- const errorMessage = error?.response?.data?.Errors?.[0]?.message;
- const errorDescription = error?.response?.data?.Errors?.[0]?.description;
- if (errorDescription) {
- Error.error = `${errorMessage} : ${errorDescription}`;
- Error.isError = true;
- return Error;
- } else {
- Error = errorMessage;
- Error.isError = true;
- return Error;
- }
- }
- }
-
- let searchResponse;
- let status = "validation-started";
- const baseDelay = baseTimeOut?.baseTimeout?.[0]?.baseTimeOut;
- const maxTime = baseTimeOut?.baseTimeout?.[0]?.maxTime;
- let retryInterval = Math.min(baseDelay * jsonDataLength , maxTime);
-
- await new Promise((resolve) => setTimeout(resolve, retryInterval));
-
- // Retry until a response is received
- while (status !== "failed" && status !== "invalid" && status !== "completed") {
- searchResponse = await Digit.CustomService.getResponse({
- url: "/project-factory/v1/data/_search",
- body: {
- SearchCriteria: {
- id: [response?.ResourceDetails?.id],
- tenantId: tenantId,
- type: Type,
- },
- },
- });
- status = searchResponse?.ResourceDetails?.[0]?.status;
- if (status !== "failed" && status !== "invalid" && status !== "completed") {
- await new Promise((resolve) => setTimeout(resolve, retryInterval));
- }
- }
- if (Error.isError) {
- return Error;
- }
- return searchResponse?.ResourceDetails?.[0];
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useUpdateCampaign.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useUpdateCampaign.js
deleted file mode 100644
index 7123ace38c8..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/hooks/useUpdateCampaign.js
+++ /dev/null
@@ -1,10 +0,0 @@
-import { useMutation } from "react-query";
-import updateCampaignService from "./services/updateCampaignService";
-
-const useUpdateCampaign = (tenantId) => {
- return useMutation((reqData) => {
- return updateCampaignService(reqData, tenantId);
- });
-};
-
-export default useUpdateCampaign;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/AddProduct.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/AddProduct.js
deleted file mode 100644
index 1ce059dbbef..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/AddProduct.js
+++ /dev/null
@@ -1,161 +0,0 @@
-import { Loader, FormComposerV2, Header } from "@egovernments/digit-ui-react-components";
-import React, { useState, useEffect } from "react";
-import { useTranslation } from "react-i18next";
-import { useHistory, useLocation } from "react-router-dom";
-import { addProductConfig } from "../../configs/addProductConfig";
-import { Toast } from "@egovernments/digit-ui-components";
-
-function AddProduct() {
- const { t } = useTranslation();
- const history = useHistory();
- const tenantId = Digit.ULBService.getCurrentTenantId();
- const [showToast, setShowToast] = useState(null);
- const { state } = useLocation();
- const { mutate: createProduct } = Digit.Hooks.campaign.useCreateProduct(tenantId);
- const { mutate: createProductVariant } = Digit.Hooks.campaign.useCreateProductVariant(tenantId);
-
- const checkValid = (formData) => {
- const target = formData?.["addProduct"];
- let isValid = false;
- if (target) {
- isValid = target?.some((i) => !i.name || !i.type || !i.variant);
- return !isValid;
- } else {
- return isValid;
- }
- };
- const closeToast = () => {
- setShowToast(null);
- };
-
- useEffect(() => {
- if (showToast) {
- setTimeout(closeToast, 5000);
- }
- }, [showToast]);
-
- const onSubmit = async (formData) => {
- const isValid = checkValid(formData);
- const invalidName = formData?.addProduct
- ?.map((i) => {
- if (i?.name?.length > 2 && i?.name?.length < 101) {
- return true;
- } else {
- return false;
- }
- })
- ?.includes(false);
-
- const invalidVariant = formData?.addProduct
- ?.map((i) => {
- if (i?.variant?.length > 2 && i?.variant?.length < 101) {
- return true;
- } else {
- return false;
- }
- })
- ?.includes(false);
-
- if (!isValid) {
- setShowToast({ key: "error", label: "CAMPAIGN_ADD_PRODUCT_MANDATORY_ERROR", isError: true });
- return;
- }
-
- if (invalidName) {
- setShowToast({ key: "error", label: "CAMPAIGN_PRODUCT_NAME_ERROR", isError: true });
- return;
- }
-
- if (invalidVariant) {
- setShowToast({ key: "error", label: "CAMPAIGN_PRODUCT_VARIANT_ERROR", isError: true });
- return;
- }
-
- const payloadData = formData?.["addProduct"]?.map((i) => ({
- tenantId: tenantId,
- type: i?.type?.code,
- name: i?.name,
- }));
-
- await createProduct(payloadData, {
- onError: (error, variables) => {
- console.log(error);
- setShowToast({ key: "error", label: error, isError: true });
- },
- onSuccess: async (data) => {
- const resData = data?.Product;
- const variantPayload = resData.map((i) => {
- const target = formData?.["addProduct"]?.find((f) => f.name === i.name);
- if (target) {
- return {
- tenantId: tenantId,
- productId: i?.id,
- variation: target?.variant,
- sku: `${target?.name} - ${target?.variant}`,
- };
- }
- return;
- });
- await createProductVariant(variantPayload, {
- onError: (error, variables) => {
- console.log(error);
- setShowToast({ key: "error", label: error, isError: true });
- },
- onSuccess: async (data) => {
- history.push(`/${window.contextPath}/employee/campaign/response?isSuccess=${true}`, {
- message: "ES_PRODUCT_CREATE_SUCCESS_RESPONSE",
- preText: "ES_PRODUCT_CREATE_SUCCESS_RESPONSE_PRE_TEXT",
- boldText: "ES_PRODUCT_CREATE_SUCCESS_RESPONSE_BOLD_TEXT",
- postText: "ES_PRODUCT_CREATE_SUCCESS_RESPONSE_POST_TEXT",
- actionLabel: "ES_PRODUCT_RESPONSE_ACTION",
- actionLink: `/${window.contextPath}/employee/campaign/setup-campaign${state?.urlParams}`,
- });
- },
- });
- },
- });
- return;
- };
- const onFormValueChange = (setValue, formData, formState, reset, setError, clearErrors, trigger, getValues) => {
- return;
- };
-
- const onSecondayActionClick = () => {
- history.push(`/${window.contextPath}/employee/campaign/setup-campaign${state?.urlParams}`);
- };
-
- return (
-
- {
- return {
- ...config,
- };
- })}
- onSubmit={onSubmit}
- fieldStyle={{ marginRight: 0 }}
- noBreakLine={true}
- cardClassName={"page-padding-fix"}
- onFormValueChange={onFormValueChange}
- actionClassName={"addProductActionClass"}
- showSecondaryLabel={true}
- secondaryLabel={t("HCM_BACK")}
- onSecondayActionClick={onSecondayActionClick}
- />
-
- {showToast && (
- setShowToast(false)}
- />
- )}
-
- );
-}
-
-export default AddProduct;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/CycleConfiguration.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/CycleConfiguration.js
deleted file mode 100644
index 78691266b13..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/CycleConfiguration.js
+++ /dev/null
@@ -1,248 +0,0 @@
-import React, { useReducer, Fragment, useEffect, useState } from "react";
-import { CardText, LabelFieldPair, Card, CardLabel, CardSubHeader, Paragraph, Header } from "@egovernments/digit-ui-react-components";
-import { useTranslation } from "react-i18next";
-import { TextInput, InfoCard } from "@egovernments/digit-ui-components";
-// import { deliveryConfig } from "../../configs/deliveryConfig";
-
-const initialState = (saved, filteredDeliveryConfig, refetch) => {
- const data = {
- cycleConfgureDate: {
- cycle:
- saved?.cycleConfgureDate?.cycle && !refetch
- ? saved?.cycleConfgureDate?.cycle
- : filteredDeliveryConfig?.cycleConfig
- ? filteredDeliveryConfig?.cycleConfig?.cycle
- : 1,
- deliveries:
- saved?.cycleConfgureDate?.deliveries && !refetch
- ? saved?.cycleConfgureDate?.deliveries
- : filteredDeliveryConfig?.cycleConfig
- ? filteredDeliveryConfig?.cycleConfig?.deliveries
- : 1,
- },
- cycleData: saved?.cycleData ? [...saved?.cycleData] : [],
- };
- // onSelect("cycleConfigure", state);
- return data;
-};
-
-const reducer = (state, action) => {
- switch (action.type) {
- case "RELOAD":
- return initialState(action.saved, action.filteredDeliveryConfig, action.refetch);
- case "UPDATE_CYCLE":
- return { ...state, cycleConfgureDate: { ...state.cycleConfgureDate, cycle: action.payload } };
- case "UPDATE_DELIVERY":
- return { ...state, cycleConfgureDate: { ...state.cycleConfgureDate, deliveries: action.payload } };
- case "SELECT_TO_DATE":
- return {
- ...state,
- cycleData: updateCycleData(state.cycleData, action.index, { toDate: action.payload }),
- // cycleData: state.cycleData.map((item) => (item.key === action.index ? { ...item, toDate: action.payload } : item)),
- };
- case "SELECT_FROM_DATE":
- return {
- ...state,
- cycleData: updateCycleData(state.cycleData, action.index, { fromDate: action.payload }),
- // cycleData: state.cycleData.map((item) => (item.key === action.index ? { ...item, fromDate: action.payload } : item)),
- };
- default:
- return state;
- }
-};
-
-const updateCycleData = (cycleData, index, update) => {
- const existingItem = cycleData.find((item) => item.key === index);
-
- if (!existingItem) {
- // If the item with the specified key doesn't exist, add a new item
- return [...cycleData, { key: index, ...update }];
- }
-
- // If the item exists, update it
- return cycleData.map((item) => (item.key === index ? { ...item, ...update } : item));
-};
-
-function CycleConfiguration({ onSelect, formData, control, ...props }) {
- const tenantId = Digit.ULBService.getCurrentTenantId();
- const selectedProjectType = window.Digit.SessionStorage.get("HCM_CAMPAIGN_MANAGER_FORM_DATA")?.HCM_CAMPAIGN_TYPE?.projectType?.code;
- const { isLoading: deliveryConfigLoading, data: filteredDeliveryConfig } = Digit.Hooks.useCustomMDMS(
- tenantId,
- "HCM-ADMIN-CONSOLE",
- [{ name: "deliveryConfig" }],
- {
- select: (data) => {
- const temp = data?.["HCM-ADMIN-CONSOLE"]?.deliveryConfig;
- return temp?.find((i) => i?.projectType === selectedProjectType);
- // return deliveryConfig?.find((i) => i?.projectType === selectedProjectType);
- },
- }
- );
- const saved = Digit.SessionStorage.get("HCM_CAMPAIGN_MANAGER_FORM_DATA")?.HCM_CAMPAIGN_CYCLE_CONFIGURE?.cycleConfigure;
- const refetch = Digit.SessionStorage.get("HCM_CAMPAIGN_MANAGER_FORM_DATA")?.HCM_CAMPAIGN_CYCLE_CONFIGURE?.cycleConfigure?.cycleConfgureDate
- ?.refetch;
- const tempSession = Digit.SessionStorage.get("HCM_CAMPAIGN_MANAGER_FORM_DATA");
- const [state, dispatch] = useReducer(reducer, initialState(saved, filteredDeliveryConfig, refetch));
- const { cycleConfgureDate, cycleData } = state;
- const { t } = useTranslation();
- const [dateRange, setDateRange] = useState({
- startDate: tempSession?.HCM_CAMPAIGN_DATE?.campaignDates?.startDate,
- endDate: tempSession?.HCM_CAMPAIGN_DATE?.campaignDates?.endDate,
- });
- const [executionCount, setExecutionCount] = useState(0);
-
- useEffect(() => {
- if (!deliveryConfigLoading) {
- dispatch({
- type: "RELOAD",
- saved: saved,
- filteredDeliveryConfig: filteredDeliveryConfig,
- refetch: refetch,
- });
- }
- }, [filteredDeliveryConfig, deliveryConfigLoading]);
- useEffect(() => {
- onSelect("cycleConfigure", state);
- }, [state]);
-
- useEffect(() => {
- if (executionCount < 5) {
- onSelect("cycleConfigure", state);
- setExecutionCount((prevCount) => prevCount + 1);
- }
- });
-
- const updateCycle = (d) => {
- if (d === 0 || d > 5) return;
- if (Number(d?.target?.value) === 0 || Number(d?.target?.value) > 5) return;
- // if (d?.target?.value.trim() === "") return;
- dispatch({ type: "UPDATE_CYCLE", payload: d?.target?.value ? Number(d?.target?.value) : d?.target?.value === "" ? d.target.value : d });
- };
-
- const updateDelivery = (d) => {
- if (d === 0 || d > 5) return;
- if (Number(d?.target?.value) === 0 || Number(d?.target?.value) > 5) return;
- // if (d?.target?.value.trim() === "") return;
- dispatch({ type: "UPDATE_DELIVERY", payload: d?.target?.value ? Number(d?.target?.value) : d });
- };
-
- const selectToDate = (index, d) => {
- dispatch({ type: "SELECT_TO_DATE", index, payload: d });
- };
-
- const selectFromDate = (index, d) => {
- dispatch({ type: "SELECT_FROM_DATE", index, payload: d });
- };
-
- return (
- <>
-
- {t(
- `CAMPAIGN_PROJECT_${
- tempSession?.HCM_CAMPAIGN_TYPE?.projectType?.code
- ? tempSession?.HCM_CAMPAIGN_TYPE?.projectType?.code?.toUpperCase()
- : tempSession?.HCM_CAMPAIGN_TYPE?.projectType?.toUpperCase()
- }`
- )}
-
-
- ,
- {t(
- `CAMPAIGN_CYCLE_INFO_${
- tempSession?.HCM_CAMPAIGN_TYPE?.projectType?.code
- ? tempSession?.HCM_CAMPAIGN_TYPE?.projectType?.code?.toUpperCase()
- : tempSession?.HCM_CAMPAIGN_TYPE?.projectType?.toUpperCase()
- }`
- )},
- ]}
- label={"Info"}
- headerClassName={"headerClassName"}
- />
-
-
- {t(
- `CAMPAIGN_CYCLE_CONFIGURE_HEADING_${
- tempSession?.HCM_CAMPAIGN_TYPE?.projectType?.code
- ? tempSession?.HCM_CAMPAIGN_TYPE?.projectType?.code?.toUpperCase()
- : tempSession?.HCM_CAMPAIGN_TYPE?.projectType?.toUpperCase()
- }`
- )}
-
-
-
- {t(`CAMPAIGN_NO_OF_CYCLE`)}
- *
-
- updateCycle(d)} />
- {/* updateCycle(d)} /> */}
-
-
-
- {t(`CAMPAIGN_NO_OF_DELIVERY`)}
- *
-
- updateDelivery(d)} />
- {/* updateDelivery(d)} /> */}
-
-
-
- {t(`CAMPAIGN_ADD_START_END_DATE_TEXT`)}
- {[...Array(cycleConfgureDate.cycle)].map((_, index) => (
-
-
- {t(`CAMPAIGN_CYCLE`)} {index + 1}
-
-
- j.key === index + 1)?.fromDate}
- min={
- index > 0 && cycleData?.find((j) => j.key === index)?.toDate
- ? new Date(new Date(cycleData?.find((j) => j.key === index)?.toDate)?.getTime() + 86400000)?.toISOString()?.split("T")?.[0]
- : dateRange?.startDate
- }
- max={dateRange?.endDate}
- onChange={(d) => selectFromDate(index + 1, d)}
- />
- j.key === index + 1)?.toDate}
- min={
- cycleData?.find((j) => j.key === index + 1)?.fromDate
- ? new Date(new Date(cycleData?.find((j) => j.key === index + 1)?.fromDate)?.getTime() + 86400000)?.toISOString()?.split("T")?.[0]
- : null
- }
- max={dateRange?.endDate}
- onChange={(d) => selectToDate(index + 1, d)}
- />
-
-
- ))}
-
- >
- );
-}
-
-export default CycleConfiguration;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/MyCampaign.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/MyCampaign.js
deleted file mode 100644
index 4e72d9f98e1..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/MyCampaign.js
+++ /dev/null
@@ -1,80 +0,0 @@
-import React, { useMemo, useState, useEffect } from "react";
-import { useTranslation } from "react-i18next";
-import { Button, Header, InboxSearchComposer, Loader } from "@egovernments/digit-ui-react-components";
-import { useHistory, useLocation } from "react-router-dom";
-import { myCampaignConfig } from "../../configs/myCampaignConfig";
-
-/**
- * The `MyCampaign` function is a React component that displays a header with a campaign search title
- * and an inbox search composer with tabs for different configurations.
- * @returns The `MyCampaign` component is returning a React fragment containing a Header component with
- * a title fetched using the `useTranslation` hook, and a div with a className of
- * "inbox-search-wrapper" that contains an `InboxSearchComposer` component. The `InboxSearchComposer`
- * component is being passed props such as `configs`, `showTab`, `tabData`, and `onTabChange
- */
-const MyCampaign = () => {
- const { t } = useTranslation();
- const location = useLocation();
- const history = useHistory();
- const moduleName = Digit?.Utils?.getConfigModuleName() || "commonCampaignUiConfig";
- const tenant = Digit.ULBService.getStateId();
- const tenantId = Digit.ULBService.getCurrentTenantId();
- const [config, setConfig] = useState(myCampaignConfig?.myCampaignConfig?.[0]);
- const [tabData, setTabData] = useState(
- myCampaignConfig?.myCampaignConfig?.map((configItem, index) => ({ key: index, label: configItem.label, active: index === 0 ? true : false }))
- );
-
- const onTabChange = (n) => {
- setTabData((prev) => prev.map((i, c) => ({ ...i, active: c === n ? true : false })));
- setConfig(myCampaignConfig?.myCampaignConfig?.[n]);
- };
-
- useEffect(() => {
- window.Digit.SessionStorage.del("HCM_CAMPAIGN_MANAGER_FORM_DATA");
- window.Digit.SessionStorage.del("HCM_CAMPAIGN_MANAGER_UPLOAD_ID");
- }, []);
-
- const onClickRow = ({ original: row }) => {
- const currentTab = tabData?.find((i) => i?.active === true)?.label;
- switch (currentTab) {
- case "CAMPAIGN_ONGOING":
- history.push(`/${window.contextPath}/employee/campaign/setup-campaign?id=${row.id}&preview=${true}&action=${false}`);
- break;
- case "CAMPAIGN_COMPLETED":
- history.push(`/${window.contextPath}/employee/campaign/setup-campaign?id=${row.id}&preview=${true}&action=${false}`);
- break;
- case "CAMPAIGN_UPCOMING":
- history.push(`/${window.contextPath}/employee/campaign/setup-campaign?id=${row.id}&preview=${true}&action=${false}`);
- break;
- case "CAMPAIGN_DRAFTS":
- history.push(`/${window.contextPath}/employee/campaign/setup-campaign?id=${row.id}&draft=${true}&fetchBoundary=${true}`);
- break;
- case "CAMPAIGN_FAILED":
- history.push(`/${window.contextPath}/employee/campaign/setup-campaign?id=${row.id}&preview=${true}&action=${false}`);
- break;
- default:
- break;
- }
- };
-
- return (
-
- {t("CAMPAIGN_SEARCH_TITLE")}
-
-
-
-
- );
-};
-
-export default MyCampaign;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/Response.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/Response.js
deleted file mode 100644
index 8e981b17965..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/Response.js
+++ /dev/null
@@ -1,65 +0,0 @@
-import React, { useState, Fragment } from "react";
-import { Link, useHistory, useLocation } from "react-router-dom";
-import { useTranslation } from "react-i18next";
-import { ActionBar, SubmitBar } from "@egovernments/digit-ui-react-components";
-import { PanelCard } from "@egovernments/digit-ui-components";
-
-const Response = () => {
- const { t } = useTranslation();
- const history = useHistory();
- const queryStrings = Digit.Hooks.useQueryParams();
- const [campaignId, setCampaignId] = useState(queryStrings?.campaignId);
- const [isResponseSuccess, setIsResponseSuccess] = useState(
- queryStrings?.isSuccess === "true" ? true : queryStrings?.isSuccess === "false" ? false : true
- );
- const { state } = useLocation();
- const isMobile = window.Digit.Utils.browser.isMobile();
-
- const navigate = (page) => {
- switch (page) {
- case "contracts-inbox": {
- history.push(`/${window.contextPath}/employee/tqm/summary`);
- }
- }
- };
-
- const children = [
-
- {state?.boldText ? (
-
- {t(state?.preText)}
- {t(state?.boldText)}
- {t(state?.postText)}
-
- ) : (
- t(state?.text, { CAMPAIGN_ID: campaignId })
- )}
-
,
- ];
-
- return (
- <>
-
- {isMobile ? (
-
-
-
- ) : (
-
-
-
-
-
- )}
- >
- );
-};
-
-export default Response;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/SetupCampaign.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/SetupCampaign.js
deleted file mode 100644
index 0dc19dab4d7..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/SetupCampaign.js
+++ /dev/null
@@ -1,1491 +0,0 @@
-import { Loader, FormComposerV2, Header, MultiUploadWrapper, Button, Close, LogoutIcon } from "@egovernments/digit-ui-react-components";
-import React, { useState, useEffect, useMemo } from "react";
-import { useTranslation } from "react-i18next";
-import { useHistory, useParams } from "react-router-dom";
-import { CampaignConfig } from "../../configs/CampaignConfig";
-import { QueryClient, useQueryClient } from "react-query";
-import { Stepper, Toast } from "@egovernments/digit-ui-components";
-import _ from "lodash";
-
-/**
- * The `SetupCampaign` function in JavaScript handles the setup and management of campaign details,
- * including form data handling, validation, and submission.
- * @returns The `SetupCampaign` component is being returned. It consists of a form setup for creating
- * or updating a campaign with multiple steps like campaign details, delivery details, boundary
- * details, targets, facility details, user details, and review details. The form data is validated at
- * each step, and the user can navigate between steps using a stepper component. The form submission
- * triggers API calls to create or update the campaign
- */
-
-function loopAndReturn(dataa) {
- let newArray = [];
- const data = dataa?.map((i) => ({ ...i, operator: { code: i?.operator }, attribute: { code: i?.attribute } }));
-
- data.forEach((item) => {
- // Check if an object with the same attribute already exists in the newArray
- const existingIndex = newArray.findIndex((element) => element.attribute.code === item.attribute.code);
- if (existingIndex !== -1) {
- // If an existing item is found, replace it with the new object
- const existingItem = newArray[existingIndex];
- newArray[existingIndex] = {
- attribute: existingItem.attribute,
- operator: { code: "IN_BETWEEN" },
- toValue: existingItem.value && item.value ? Math.min(existingItem.value, item.value) : null,
- fromValue: existingItem.value && item.value ? Math.max(existingItem.value, item.value) : null,
- };
- }
- // else if (item?.operator?.code === "EQUAL_TO" && item?.attribute?.code === "Gender") {
- // newArray.push({
- // ...item,
- // value: item?.value
- // ? {
- // code: item?.value,
- // }
- // : null,
- // });
- // }
- else {
- // If no existing item with the same attribute is found, push the current item
- // if (item?.operator?.code === "EQUAL_TO" && item?.attribute?.code === "Gender") {
- // newArray.push({
- // ...item,
- // value: {
- // code: item?.value,
- // },
- // });
- // } else {
- newArray.push(item);
- // }
- }
- });
-
- const withKey = newArray.map((i, c) => ({ key: c + 1, ...i }));
- return withKey;
-}
-
-function cycleDataRemap(data) {
- if (!data) return null;
- const uniqueCycleObjects = Object.values(
- data?.reduce((acc, obj) => {
- acc[obj?.cycleNumber] = acc[obj?.cycleNumber] || obj;
- return acc;
- }, {})
- );
- return uniqueCycleObjects.map((i, n) => {
- return {
- key: i.cycleNumber,
- fromDate: i?.startDate ? new Date(i?.startDate)?.toISOString()?.split("T")?.[0] : null,
- toDate: i?.endDate ? new Date(i?.endDate)?.toISOString()?.split("T")?.[0] : null,
- };
- });
-}
-
-// function reverseDeliveryRemap(data) {
-// if (!data) return null;
-// const reversedData = [];
-// let currentCycleIndex = null;
-// let currentDeliveryIndex = null;
-// let currentCycle = null;
-// let currentDelivery = null;
-
-// data.forEach((item, index) => {
-// if (currentCycleIndex !== item.cycleNumber) {
-// currentCycleIndex = item.cycleNumber;
-// currentCycle = {
-// cycleIndex: currentCycleIndex.toString(),
-// active: index === 0, // Set active to true only for the first index
-// deliveries: [],
-// };
-// reversedData.push(currentCycle);
-// }
-
-// if (currentDeliveryIndex !== item.deliveryNumber) {
-// currentDeliveryIndex = item.deliveryNumber;
-// currentDelivery = {
-// deliveryIndex: currentDeliveryIndex.toString(),
-// active: item?.deliveryNumber === 1, // Set active to true only for the first index
-// deliveryRules: [],
-// };
-// currentCycle.deliveries.push(currentDelivery);
-// }
-
-// currentDelivery.deliveryRules.push({
-// ruleKey: currentDelivery.deliveryRules.length + 1,
-// delivery: {},
-// attributes: loopAndReturn(item.conditions),
-// products: [...item.products],
-// });
-// });
-
-// return reversedData;
-// }
-
-function reverseDeliveryRemap(data) {
- if (!data) return null;
- const reversedData = [];
- let currentCycleIndex = null;
- let currentCycle = null;
-
- data.forEach((item, index) => {
- if (currentCycleIndex !== item.cycleNumber) {
- currentCycleIndex = item.cycleNumber;
- currentCycle = {
- cycleIndex: currentCycleIndex.toString(),
- active: index === 0, // Initialize active to false
- deliveries: [],
- };
- reversedData.push(currentCycle);
- }
-
- const deliveryIndex = item.deliveryNumber.toString();
-
- let delivery = currentCycle.deliveries.find((delivery) => delivery.deliveryIndex === deliveryIndex);
-
- if (!delivery) {
- delivery = {
- deliveryIndex: deliveryIndex,
- active: item.deliveryNumber === 1, // Set active to true only for the first delivery
- deliveryRules: [],
- };
- currentCycle.deliveries.push(delivery);
- }
-
- delivery.deliveryRules.push({
- ruleKey: item.deliveryRuleNumber,
- delivery: {},
- deliveryType: item?.deliveryType,
- attributes: loopAndReturn(item.conditions),
- products: [...item.products],
- });
- });
-
- return reversedData;
-}
-
-function groupByType(data) {
- if (!data) return null;
- const result = {};
-
- data.forEach((item) => {
- if (result[item.type]) {
- result[item.type].push(item);
- } else {
- result[item.type] = [item];
- }
- });
-
- return {
- TenantBoundary: {
- boundary: result,
- },
- };
-}
-
-function groupByTypeRemap(data) {
- if (!data) return null;
-
- const result = {};
-
- data.forEach((item) => {
- const type = item?.type;
- const boundaryType = item?.type;
- const parentCode = item?.parent;
- const obj = {
- parentCode,
- boundaryTypeData: {
- TenantBoundary: [
- {
- boundary: [{ ...item, boundaryType }],
- },
- ],
- },
- };
-
- if (result[type]) {
- result[type][0].boundaryTypeData.TenantBoundary[0].boundary.push(item);
- } else {
- result[type] = [obj];
- }
- });
-
- return result;
-}
-
-// Example usage:
-// updateUrlParams({ id: 'sdjkhsdjkhdshfsdjkh', anotherParam: 'value' });
-function updateUrlParams(params) {
- const url = new URL(window.location.href);
- Object.entries(params).forEach(([key, value]) => {
- url.searchParams.set(key, value);
- });
- window.history.replaceState({}, "", url);
-}
-
-const SetupCampaign = ({ hierarchyType }) => {
- const tenantId = Digit.ULBService.getCurrentTenantId();
- const { t } = useTranslation();
- const history = useHistory();
- const [currentStep, setCurrentStep] = useState(0);
- const [totalFormData, setTotalFormData] = useState({});
- const [isSubmitting, setIsSubmitting] = useState(false);
- const [campaignConfig, setCampaignConfig] = useState(CampaignConfig(totalFormData, null, isSubmitting));
- const [shouldUpdate, setShouldUpdate] = useState(false);
- const [params, setParams, clearParams] = Digit.Hooks.useSessionStorage("HCM_CAMPAIGN_MANAGER_FORM_DATA", {});
- const [dataParams, setDataParams] = Digit.Hooks.useSessionStorage("HCM_CAMPAIGN_MANAGER_UPLOAD_ID", {});
- const [showToast, setShowToast] = useState(null);
- const [summaryErrors, setSummaryErrors] = useState({});
- const { mutate } = Digit.Hooks.campaign.useCreateCampaign(tenantId);
- const { mutate: updateCampaign } = Digit.Hooks.campaign.useUpdateCampaign(tenantId);
- const searchParams = new URLSearchParams(location.search);
- const id = searchParams.get("id");
- const isPreview = searchParams.get("preview");
- const isSummary = searchParams.get("summary");
- const noAction = searchParams.get("action");
- const isDraft = searchParams.get("draft");
- const isSkip = searchParams.get("skip");
- const keyParam = searchParams.get("key");
- const [isDraftCreated, setIsDraftCreated] = useState(false);
- const filteredBoundaryData = params?.HCM_CAMPAIGN_SELECTING_BOUNDARY_DATA?.boundaryType?.selectedData;
- const client = useQueryClient();
- // const hierarchyType2 = params?.HCM_CAMPAIGN_SELECTING_BOUNDARY_DATA?.boundaryType?.hierarchy?.hierarchyType
- const [currentKey, setCurrentKey] = useState(() => {
- const keyParam = searchParams.get("key");
- return keyParam ? parseInt(keyParam) : 1;
- });
-
- // const [lowest, setLowest] = useState(null);
- const [fetchBoundary, setFetchBoundary] = useState(() => Boolean(searchParams.get("fetchBoundary")));
- const [fetchUpload, setFetchUpload] = useState(false);
- const [enabled, setEnabled] = useState(false);
- const [targetEnabled, setTargetEnabled] = useState(false);
- const [facilityEnabled, setFacilityEnabled] = useState(false);
- const [userEnabled, setUserEnabled] = useState(false);
- const [active, setActive] = useState(0);
- const { data: hierarchyConfig } = Digit.Hooks.useCustomMDMS(tenantId, "HCM-ADMIN-CONSOLE", [{ name: "hierarchyConfig" }]);
- const [refetchGenerate, setRefetchGenerate] = useState(null);
- // const hierarchyType = hierarchyConfig?.["HCM-ADMIN-CONSOLE"]?.hierarchyConfig?.[0]?.hierarchy;
-
- // const lowestHierarchy = hierarchyConfig?.["HCM-ADMIN-CONSOLE"]?.hierarchyConfig?.[0]?.lowestHierarchy;
- const lowestHierarchy = useMemo(() => hierarchyConfig?.["HCM-ADMIN-CONSOLE"]?.hierarchyConfig?.[0]?.lowestHierarchy, [hierarchyConfig]);
-
- const reqCriteria = {
- url: `/boundary-service/boundary-hierarchy-definition/_search`,
- changeQueryName: `${hierarchyType}`,
- body: {
- BoundaryTypeHierarchySearchCriteria: {
- tenantId: tenantId,
- limit: 2,
- offset: 0,
- hierarchyType: hierarchyType,
- },
- },
- };
-
- const { data: hierarchyDefinition } = Digit.Hooks.useCustomAPIHook(reqCriteria);
-
- // useEffect(() => {
- // if (hierarchyDefinition) {
- // setLowest(
- // hierarchyDefinition?.BoundaryHierarchy?.[0]?.boundaryHierarchy?.filter(
- // (e) => !hierarchyDefinition?.BoundaryHierarchy?.[0]?.boundaryHierarchy?.find((e1) => e1?.parentBoundaryType == e?.boundaryType)
- // )
- // );
- // }
- // }, [hierarchyDefinition]);
- const { isLoading: draftLoading, data: draftData, error: draftError, refetch: draftRefetch } = Digit.Hooks.campaign.useSearchCampaign({
- tenantId: tenantId,
- filter: {
- ids: [id],
- },
- config: {
- enabled: id ? true : false,
- select: (data) => {
- return data?.[0];
- },
- },
- });
-
- const { isLoading, data: projectType } = Digit.Hooks.useCustomMDMS(tenantId, "HCM-PROJECT-TYPES", [{ name: "projectTypes" }]);
-
- useEffect(() => {
- if (fetchUpload) {
- setFetchUpload(false);
- }
- if (fetchBoundary && currentKey > 5) {
- setFetchBoundary(false);
- }
- }, [fetchUpload, fetchBoundary]);
-
- useEffect(() => {
- if (isPreview === "true") {
- setIsDraftCreated(true);
- setCurrentKey(10);
- return;
- }
- if (isDraft === "true") {
- setIsDraftCreated(true);
- if (isSkip === "false") {
- currentKey !== 1 ? null : setCurrentKey(1);
- } else {
- setCurrentKey(draftData?.additionalDetails?.key);
- }
- return;
- }
- }, [isPreview, isDraft, draftData]);
-
- useEffect(() => {
- setTotalFormData(params);
- }, [params]);
-
- //DATA STRUCTURE
- useEffect(() => {
- if (isLoading) return;
- if (Object.keys(params).length !== 0) return;
- if (!draftData) return;
- const delivery = Array.isArray(draftData?.deliveryRules) ? draftData?.deliveryRules : [];
- const filteredProjectType = projectType?.["HCM-PROJECT-TYPES"]?.projectTypes?.filter((i) => i?.code === draftData?.projectType);
- const restructureFormData = {
- HCM_CAMPAIGN_TYPE: { projectType: filteredProjectType?.[0] },
- HCM_CAMPAIGN_NAME: {
- campaignName: draftData?.campaignName,
- },
- HCM_CAMPAIGN_DATE: {
- campaignDates: {
- startDate: draftData?.startDate ? new Date(draftData?.startDate)?.toISOString()?.split("T")?.[0] : "",
- endDate: draftData?.endDate ? new Date(draftData?.endDate)?.toISOString()?.split("T")?.[0] : "",
- },
- },
- HCM_CAMPAIGN_CYCLE_CONFIGURE: {
- cycleConfigure: {
- cycleConfgureDate: draftData?.additionalDetails?.cycleData?.cycleConfgureDate
- ? draftData?.additionalDetails?.cycleData?.cycleConfgureDate
- : {
- cycle: delivery?.map((obj) => obj?.cycleNumber)?.length > 0 ? Math.max(...delivery?.map((obj) => obj?.cycleNumber)) : 1,
- deliveries: delivery?.map((obj) => obj?.deliveryNumber)?.length > 0 ? Math.max(...delivery?.map((obj) => obj?.deliveryNumber)) : 1,
- refetch: true,
- },
- cycleData: draftData?.additionalDetails?.cycleData?.cycleData
- ? draftData?.additionalDetails?.cycleData?.cycleData
- : cycleDataRemap(delivery),
- },
- },
- HCM_CAMPAIGN_DELIVERY_DATA: {
- deliveryRule: reverseDeliveryRemap(delivery),
- },
- HCM_CAMPAIGN_SELECTING_BOUNDARY_DATA: {
- boundaryType: {
- boundaryData: groupByTypeRemap(draftData?.boundaries),
- selectedData: draftData?.boundaries,
- },
- },
- HCM_CAMPAIGN_UPLOAD_BOUNDARY_DATA: {
- uploadBoundary: { uploadedFile: draftData?.resources?.filter((i) => i?.type === "boundaryWithTarget"),
- isSuccess : draftData?.resources?.filter((i) => i?.type === "boundaryWithTarget").length>0
- },
- },
- HCM_CAMPAIGN_UPLOAD_FACILITY_DATA: {
- uploadFacility: { uploadedFile: draftData?.resources?.filter((i) => i?.type === "facility") ,
- isSuccess : draftData?.resources?.filter((i) => i?.type === "facility").length>0
- }
- },
- HCM_CAMPAIGN_UPLOAD_USER_DATA: {
- uploadUser: { uploadedFile: draftData?.resources?.filter((i) => i?.type === "user") ,
- isSuccess : draftData?.resources?.filter((i) => i?.type === "user").length>0
- },
- },
- };
- setParams({ ...restructureFormData });
- }, [params, draftData, isLoading, projectType]);
-
- useEffect(() => {
- setTimeout(() => {
- setEnabled(fetchUpload || (fetchBoundary && currentKey > 3));
- setFacilityEnabled(refetchGenerate || (!dataParams?.boundaryId && (fetchUpload || (fetchBoundary && currentKey > 3))));
- setTargetEnabled(refetchGenerate || (!dataParams?.facilityId && (fetchUpload || (fetchBoundary && currentKey > 3))));
- setUserEnabled(refetchGenerate || (!dataParams?.userId && (fetchUpload || (fetchBoundary && currentKey > 3))));
- }, 3000);
- if (refetchGenerate === true) {
- setRefetchGenerate(false);
- }
- }, [fetchUpload, fetchBoundary, currentKey, dataParams, refetchGenerate]);
-
- const { data: facilityId, isLoading: isFacilityLoading, refetch: refetchFacility } = Digit.Hooks.campaign.useGenerateIdCampaign({
- type: "facilityWithBoundary",
- hierarchyType: hierarchyType,
- campaignId: id,
- // config: {
- // enabled: setTimeout(fetchUpload || (fetchBoundary && currentKey > 6)),
- // },
- config: {
- enabled: facilityEnabled,
- },
- });
-
- const { data: boundaryId, isLoading: isBoundaryLoading, refetch: refetchBoundary } = Digit.Hooks.campaign.useGenerateIdCampaign({
- type: "boundary",
- hierarchyType: hierarchyType,
- campaignId: id,
- // config: {
- // enabled: fetchUpload || (fetchBoundary && currentKey > 6),
- // },
- config: {
- enabled: targetEnabled,
- },
- });
-
- const { data: userId, isLoading: isUserLoading, refetch: refetchUser } = Digit.Hooks.campaign.useGenerateIdCampaign({
- type: "userWithBoundary",
- hierarchyType: hierarchyType,
- campaignId: id,
- // config: {
- // enabled: fetchUpload || (fetchBoundary && currentKey > 6),
- // },
- config: {
- enabled: userEnabled,
- },
- });
-
- useEffect(() => {
- if (draftData?.additionalDetails?.facilityId && draftData?.additionalDetails?.targetId && draftData?.additionalDetails?.userId) {
- setDataParams({
- ...dataParams,
- boundaryId: draftData?.additionalDetails?.targetId,
- facilityId: draftData?.additionalDetails?.facilityId,
- userId: draftData?.additionalDetails?.userId,
- hierarchyType: hierarchyType,
- hierarchy: hierarchyDefinition?.BoundaryHierarchy?.[0],
- });
- }
- }, [isBoundaryLoading, isFacilityLoading, isUserLoading, facilityId, boundaryId, userId, hierarchyDefinition?.BoundaryHierarchy?.[0], draftData]); // Only run if dataParams changes
-
-
- useEffect(() => {
- if (hierarchyDefinition?.BoundaryHierarchy?.[0]) {
- setDataParams({
- ...dataParams,
- facilityId: facilityId,
- boundaryId: boundaryId,
- userId: userId,
- hierarchyType: hierarchyType,
- hierarchy: hierarchyDefinition?.BoundaryHierarchy?.[0],
- isBoundaryLoading,
- isFacilityLoading,
- isUserLoading,
- });
- }
- }, [isBoundaryLoading, isFacilityLoading, isUserLoading, facilityId, boundaryId, userId, hierarchyDefinition?.BoundaryHierarchy?.[0], draftData]);
- useEffect(() => {
- setCampaignConfig(CampaignConfig(totalFormData, dataParams, isSubmitting, summaryErrors));
- }, [totalFormData, dataParams, isSubmitting, summaryErrors]);
-
- useEffect(() => {
- setIsSubmitting(false);
- if (currentKey === 10 && isSummary !== "true") {
- updateUrlParams({ key: currentKey, summary: true });
- } else {
- updateUrlParams({ key: currentKey, summary: false });
- setSummaryErrors(null);
- }
- }, [currentKey]);
-
- function restructureData(data) {
- const dateData = totalFormData?.HCM_CAMPAIGN_CYCLE_CONFIGURE?.cycleConfigure?.cycleData;
- const restructuredData = [];
-
- data.forEach((cycle) => {
- cycle.deliveries.forEach((delivery, index) => {
- delivery.deliveryRules.forEach((rule) => {
- const restructuredRule = {
- startDate: Digit.Utils.date.convertDateToEpoch(dateData?.find((i) => i.key == cycle.cycleIndex)?.fromDate), // Hardcoded for now
- endDate: Digit.Utils.date.convertDateToEpoch(dateData?.find((i) => i?.key == cycle?.cycleIndex)?.toDate), // Hardcoded for now
- cycleNumber: parseInt(cycle.cycleIndex),
- deliveryNumber: parseInt(delivery.deliveryIndex),
- deliveryType: rule?.deliveryType,
- deliveryRuleNumber: parseInt(rule.ruleKey), // New key added
- products: [],
- conditions: [],
- };
-
- rule.attributes.forEach((attribute) => {
- if (attribute?.operator?.code === "IN_BETWEEN") {
- restructuredRule.conditions.push({
- attribute: attribute?.attribute?.code
- ? attribute?.attribute?.code
- : typeof attribute?.attribute === "string"
- ? attribute?.attribute
- : null,
- operator: "LESS_THAN_EQUAL_TO",
- value: attribute.fromValue ? Number(attribute.fromValue) : null,
- });
-
- restructuredRule.conditions.push({
- attribute: attribute?.attribute?.code
- ? attribute?.attribute?.code
- : typeof attribute?.attribute === "string"
- ? attribute?.attribute
- : null,
- operator: "GREATER_THAN_EQUAL_TO",
- value: attribute.toValue ? Number(attribute.toValue) : null,
- });
- } else {
- restructuredRule.conditions.push({
- attribute: attribute?.attribute?.code
- ? attribute?.attribute?.code
- : typeof attribute?.attribute === "string"
- ? attribute?.attribute
- : null,
- operator: attribute.operator ? attribute.operator.code : null,
- value:
- attribute?.attribute?.code === "Gender" && attribute?.value?.length > 0
- ? attribute?.value
- : attribute?.value
- ? Number(attribute?.value)
- : null,
- });
- }
- });
-
- rule.products.forEach((prod) => {
- restructuredRule.products.push({
- value: prod?.value,
- name: prod?.name,
- count: prod?.count,
- });
- });
-
- restructuredData.push(restructuredRule);
- });
- });
- });
-
- return restructuredData;
- }
-
- function resourceData(facilityData, boundaryData, userData) {
- const resources = [facilityData, boundaryData, userData].filter((data) => data !== null && data !== undefined);
- return resources;
- }
-
- useEffect(async () => {
- if (totalFormData?.HCM_CAMPAIGN_DELIVERY_DATA?.deliveryRule) {
- const temp = restructureData(totalFormData?.HCM_CAMPAIGN_DELIVERY_DATA?.deliveryRule);
- }
- }, [shouldUpdate]);
-
- const compareIdentical = (draftData, payload) => {
- return _.isEqual(draftData, payload);
- };
- //API CALL
- useEffect(async () => {
- if (shouldUpdate === true) {
- if (filteredConfig?.[0]?.form?.[0]?.body?.[0]?.skipAPICall && !id) {
- return;
- } else if (filteredConfig?.[0]?.form?.[0]?.isLast) {
- const reqCreate = async () => {
- let payloadData = { ...draftData };
- payloadData.hierarchyType = hierarchyType;
- payloadData.startDate = totalFormData?.HCM_CAMPAIGN_DATE?.campaignDates?.startDate
- ? Digit.Utils.date.convertDateToEpoch(totalFormData?.HCM_CAMPAIGN_DATE?.campaignDates?.startDate)
- : null;
- payloadData.endDate = totalFormData?.HCM_CAMPAIGN_DATE?.campaignDates?.endDate
- ? Digit.Utils.date.convertDateToEpoch(totalFormData?.HCM_CAMPAIGN_DATE?.campaignDates?.endDate)
- : null;
- payloadData.tenantId = tenantId;
- payloadData.action = "create";
- payloadData.campaignName = totalFormData?.HCM_CAMPAIGN_NAME?.campaignName;
- if (totalFormData?.HCM_CAMPAIGN_SELECTING_BOUNDARY_DATA?.boundaryType?.selectedData) {
- payloadData.boundaries = totalFormData?.HCM_CAMPAIGN_SELECTING_BOUNDARY_DATA?.boundaryType?.selectedData;
- }
- const temp = resourceData(
- totalFormData?.HCM_CAMPAIGN_UPLOAD_FACILITY_DATA?.uploadFacility?.uploadedFile?.[0],
- totalFormData?.HCM_CAMPAIGN_UPLOAD_BOUNDARY_DATA?.uploadBoundary?.uploadedFile?.[0],
- totalFormData?.HCM_CAMPAIGN_UPLOAD_USER_DATA?.uploadUser?.uploadedFile?.[0]
- );
- payloadData.resources = temp;
- payloadData.projectType = totalFormData?.HCM_CAMPAIGN_TYPE?.projectType?.code;
- payloadData.additionalDetails = {
- beneficiaryType: totalFormData?.HCM_CAMPAIGN_TYPE?.projectType?.beneficiaryType,
- key: currentKey,
- targetId: dataParams?.boundaryId,
- facilityId: dataParams?.facilityId,
- userId: dataParams?.userId,
- };
- if (totalFormData?.HCM_CAMPAIGN_DELIVERY_DATA?.deliveryRule) {
- const temp = restructureData(totalFormData?.HCM_CAMPAIGN_DELIVERY_DATA?.deliveryRule);
- payloadData.deliveryRules = temp;
- }
-
- // await mutate(payloadData, {
- // onError: (error, variables) => {},
- // onSuccess: async (data) => {
- // draftRefetch();
- // history.push(
- // `/${window.contextPath}/employee/campaign/response?campaignId=${data?.CampaignDetails?.campaignNumber}&isSuccess=${true}`,
- // {
- // message: "ES_CAMPAIGN_CREATE_SUCCESS_RESPONSE",
- // text: "ES_CAMPAIGN_CREATE_SUCCESS_RESPONSE_TEXT",
- // }
- // );
- // Digit.SessionStorage.del("HCM_CAMPAIGN_MANAGER_FORM_DATA");
- // },
- // });
- if (compareIdentical(draftData, payloadData) === false) {
- await updateCampaign(payloadData, {
- onError: (error, variables) => {
- console.log(error);
- setShowToast({ key: "error", label: error?.message ? error?.message : error });
- },
- onSuccess: async (data) => {
- draftRefetch();
- history.push(
- `/${window.contextPath}/employee/campaign/response?campaignId=${data?.CampaignDetails?.campaignNumber}&isSuccess=${true}`,
- {
- message: t("ES_CAMPAIGN_CREATE_SUCCESS_RESPONSE"),
- text: t("ES_CAMPAIGN_CREATE_SUCCESS_RESPONSE_TEXT"),
- info: t("ES_CAMPAIGN_SUCCESS_INFO_TEXT"),
- actionLabel: t("HCM_CAMPAIGN_SUCCESS_RESPONSE_ACTION"),
- actionLink: `/${window.contextPath}/employee/campaign/my-campaign`,
- }
- );
- Digit.SessionStorage.del("HCM_CAMPAIGN_MANAGER_FORM_DATA");
- },
- });
- }
- };
-
- reqCreate();
- } else if (!isDraftCreated && !id) {
- const reqCreate = async () => {
- let payloadData = {};
- payloadData.hierarchyType = hierarchyType;
- if (totalFormData?.HCM_CAMPAIGN_DATE?.campaignDates?.startDate) {
- payloadData.startDate = totalFormData?.HCM_CAMPAIGN_DATE?.campaignDates?.startDate
- ? Digit.Utils.date.convertDateToEpoch(totalFormData?.HCM_CAMPAIGN_DATE?.campaignDates?.startDate)
- : null;
- }
- if (totalFormData?.HCM_CAMPAIGN_DATE?.campaignDates?.endDate) {
- payloadData.endDate = totalFormData?.HCM_CAMPAIGN_DATE?.campaignDates?.endDate
- ? Digit.Utils.date.convertDateToEpoch(totalFormData?.HCM_CAMPAIGN_DATE?.campaignDates?.endDate)
- : null;
- }
- payloadData.tenantId = tenantId;
- payloadData.action = "draft";
- payloadData.campaignName = totalFormData?.HCM_CAMPAIGN_NAME?.campaignName;
- if (totalFormData?.HCM_CAMPAIGN_SELECTING_BOUNDARY_DATA?.boundaryType?.selectedData) {
- payloadData.boundaries = totalFormData?.HCM_CAMPAIGN_SELECTING_BOUNDARY_DATA?.boundaryType?.selectedData;
- }
- const temp = resourceData(
- totalFormData?.HCM_CAMPAIGN_UPLOAD_FACILITY_DATA?.uploadFacility?.uploadedFile?.[0],
- totalFormData?.HCM_CAMPAIGN_UPLOAD_BOUNDARY_DATA?.uploadBoundary?.uploadedFile?.[0],
- totalFormData?.HCM_CAMPAIGN_UPLOAD_USER_DATA?.uploadUser?.uploadedFile?.[0]
- );
- payloadData.resources = temp;
- payloadData.projectType = totalFormData?.HCM_CAMPAIGN_TYPE?.projectType?.code;
- payloadData.additionalDetails = {
- beneficiaryType: totalFormData?.HCM_CAMPAIGN_TYPE?.projectType?.beneficiaryType,
- key: currentKey,
- targetId: dataParams?.boundaryId,
- facilityId: dataParams?.facilityId,
- userId: dataParams?.userId,
- };
- if (totalFormData?.HCM_CAMPAIGN_DELIVERY_DATA?.deliveryRule) {
- const temp = restructureData(totalFormData?.HCM_CAMPAIGN_DELIVERY_DATA?.deliveryRule);
- payloadData.deliveryRules = temp;
- }
-
- await mutate(payloadData, {
- onError: (error, variables) => {
- if (filteredConfig?.[0]?.form?.[0]?.body?.[0]?.mandatoryOnAPI) {
- setShowToast({ key: "error", label: error?.message ? error?.message : error });
- }
- },
- onSuccess: async (data) => {
- updateUrlParams({ id: data?.CampaignDetails?.id });
- setIsDraftCreated(true);
- draftRefetch();
- if (filteredConfig?.[0]?.form?.[0]?.body?.[0]?.mandatoryOnAPI) {
- setCurrentKey(currentKey + 1);
- }
- },
- });
- };
-
- reqCreate();
- } else {
- const reqCreate = async () => {
- let payloadData = { ...draftData };
- payloadData.hierarchyType = hierarchyType;
- if (totalFormData?.HCM_CAMPAIGN_DATE?.campaignDates?.startDate) {
- payloadData.startDate = totalFormData?.HCM_CAMPAIGN_DATE?.campaignDates?.startDate
- ? Digit.Utils.date.convertDateToEpoch(totalFormData?.HCM_CAMPAIGN_DATE?.campaignDates?.startDate)
- : null;
- }
- if (totalFormData?.HCM_CAMPAIGN_DATE?.campaignDates?.endDate) {
- payloadData.endDate = totalFormData?.HCM_CAMPAIGN_DATE?.campaignDates?.endDate
- ? Digit.Utils.date.convertDateToEpoch(totalFormData?.HCM_CAMPAIGN_DATE?.campaignDates?.endDate)
- : null;
- }
- payloadData.tenantId = tenantId;
- payloadData.action = "draft";
- payloadData.campaignName = totalFormData?.HCM_CAMPAIGN_NAME?.campaignName;
- if (totalFormData?.HCM_CAMPAIGN_SELECTING_BOUNDARY_DATA?.boundaryType?.selectedData) {
- payloadData.boundaries = totalFormData?.HCM_CAMPAIGN_SELECTING_BOUNDARY_DATA?.boundaryType?.selectedData;
- }
- const temp = resourceData(
- totalFormData?.HCM_CAMPAIGN_UPLOAD_FACILITY_DATA?.uploadFacility?.uploadedFile?.[0],
- totalFormData?.HCM_CAMPAIGN_UPLOAD_BOUNDARY_DATA?.uploadBoundary?.uploadedFile?.[0],
- totalFormData?.HCM_CAMPAIGN_UPLOAD_USER_DATA?.uploadUser?.uploadedFile?.[0]
- );
- payloadData.resources = temp;
- payloadData.projectType = totalFormData?.HCM_CAMPAIGN_TYPE?.projectType?.code;
- payloadData.additionalDetails = {
- beneficiaryType: totalFormData?.HCM_CAMPAIGN_TYPE?.projectType?.beneficiaryType,
- key: currentKey,
- targetId: dataParams?.boundaryId,
- facilityId: dataParams?.facilityId,
- userId: dataParams?.userId,
- };
- if (totalFormData?.HCM_CAMPAIGN_CYCLE_CONFIGURE?.cycleConfigure) {
- payloadData.additionalDetails.cycleData = totalFormData?.HCM_CAMPAIGN_CYCLE_CONFIGURE?.cycleConfigure;
- } else {
- payloadData.additionalDetails.cycleData = {};
- }
- if (totalFormData?.HCM_CAMPAIGN_DELIVERY_DATA?.deliveryRule) {
- const temp = restructureData(totalFormData?.HCM_CAMPAIGN_DELIVERY_DATA?.deliveryRule);
- payloadData.deliveryRules = temp;
- } else {
- payloadData.deliveryRules = [];
- }
- if (!payloadData?.startDate && !payloadData?.endDate) {
- delete payloadData?.startDate;
- delete payloadData?.endDate;
- }
- if (compareIdentical(draftData, payloadData) === false) {
- await updateCampaign(payloadData, {
- onError: (error, variables) => {
- console.log(error);
- if (filteredConfig?.[0]?.form?.[0]?.body?.[0]?.mandatoryOnAPI) {
- setShowToast({ key: "error", label: error?.message ? error?.message : error });
- }
- },
- onSuccess: async (data) => {
- updateUrlParams({ id: data?.CampaignDetails?.id });
- draftRefetch();
- if (filteredConfig?.[0]?.form?.[0]?.body?.[0]?.mandatoryOnAPI) {
- setCurrentKey(currentKey + 1);
- }
- },
- });
- } else {
- setCurrentKey(currentKey + 1);
- }
- };
-
- reqCreate();
- }
- setShouldUpdate(false);
- }
- }, [shouldUpdate]);
-
- function validateCycleData(data) {
- const { cycle, deliveries } = data?.cycleConfigure?.cycleConfgureDate;
- const cycleData = data.cycleConfigure.cycleData;
- let dateError = [];
- // Validate cycle and deliveries
- // if (cycle <= 0 || deliveries <= 0) {
- // return { error: true, message: "DELIVERY_CYCLE_EMPTY_ERROR" };
- // }
-
- [...Array(cycle)].forEach((item, index) => {
- const check = cycleData?.find((i) => i?.key === index + 1);
- if (!check?.fromDate || !check?.toDate) {
- dateError.push({
- name: `CYCLE_${index + 1}`,
- cycle: index + 1,
- dateError: true,
- // error: `Dates are missing in Cycle {CYCLE_NO}${index + 1}`,
- error: t(`CAMPAIGN_SUMMARY_DATE_MISSING_ERROR`, { CYCLE_NO: index + 1 }),
- button: t(`CAMPAIGN_SUMMARY_ADD_DATE_ACTION`),
- });
- }
- });
- // setSummaryErrors((prev) => {
- // return {
- // ...prev,
- // deliveryErrors: prev?.deliveryErrors ? [...prev.deliveryErrors, ...dateError] : [...dateError],
- // };
- // });
- // Validate cycleData length
- // if (cycleData.length !== cycle) {
- // return { error: true, message: "DELIVERY_CYCLE_MISMATCH_LENGTH_ERROR" };
- // }
-
- // Validate fromDate and startDate in cycleData
- // for (const item of cycleData) {
- // if (!item.fromDate || !item.toDate) {
- // return { error: true, message: "DELIVERY_CYCLE_DATE_ERROR" };
- // }
- // }
-
- return dateError;
- }
-
- function validateDeliveryRules(data, projectType, cycleConfigureData) {
- let isValid = true;
- let deliveryRulesError = [];
- let dateError = validateCycleData(cycleConfigureData);
-
- // Iterate over deliveryRule array
- data.deliveryRule.forEach((cycle) => {
- cycle.deliveries.forEach((delivery) => {
- delivery.deliveryRules.forEach((rule) => {
- // Validate attributes and products length
- if (projectType !== "LLIN-MZ" && !rule?.deliveryType) {
- isValid = false;
- deliveryRulesError?.push({
- name: `CYCLE_${cycle?.cycleIndex}`,
- cycle: cycle?.cycleIndex,
- // error: `Delivery Type missing in delivery condition ${rule?.ruleKey} delivery ${delivery?.deliveryIndex}`,
- error: t(`CAMPAIGN_SUMMARY_DELIVERY_TYPE_MISSING_ERROR`, {
- CONDITION_NO: rule?.ruleKey,
- DELIVERY_NO: delivery?.deliveryIndex,
- CYCLE_NO: cycle?.cycleIndex,
- }),
- button: t(`CAMPAIGN_SUMMARY_ADD_DELIVERY_TYPE_ACTION`),
- });
- // return;
- }
- if (rule.attributes.length === 0) {
- isValid = false;
- deliveryRulesError?.push({
- name: `CYCLE_${cycle?.cycleIndex}`,
- cycle: cycle?.cycleIndex,
- // error: `Values missing in delivery condition ${rule?.ruleKey} delivery ${delivery?.deliveryIndex}`,
- error: t(`CAMPAIGN_SUMMARY_VALUES_MISSING_ERROR`, {
- CONDITION_NO: rule?.ruleKey,
- DELIVERY_NO: delivery?.deliveryIndex,
- CYCLE_NO: cycle?.cycleIndex,
- }),
- button: t(`CAMPAIGN_SUMMARY_ADD_VALUES_ACTION`),
- });
- // return;
- }
- if (rule.products.length === 0) {
- isValid = false;
- deliveryRulesError?.push({
- name: `CYCLE_${cycle?.cycleIndex}`,
- cycle: cycle?.cycleIndex,
- // error: `Product missing in delivery condition ${rule?.ruleKey} delivery ${delivery?.deliveryIndex}`,
- error: t(`CAMPAIGN_SUMMARY_PRODUCT_MISSING_ERROR`, {
- CONDITION_NO: rule?.ruleKey,
- DELIVERY_NO: delivery?.deliveryIndex,
- CYCLE_NO: cycle?.cycleIndex,
- }),
- button: t(`CAMPAIGN_SUMMARY_ADD_PRODUCT_ACTION`),
- });
- // return;
- }
-
- rule.attributes.forEach((attribute) => {
- // Check if attribute, operator, and value are empty
- if (attribute.attribute === "" || attribute.operator === null || attribute.value === "") {
- if (attribute?.operator?.code === "IN_BETWEEN" && attribute?.toValue !== "" && attribute?.fromValue !== "") {
- isValid = true;
- } else {
- deliveryRulesError?.push({
- name: `CYCLE_${cycle?.cycleIndex}`,
- cycle: cycle?.cycleIndex,
- error: t(`CAMPAIGN_SUMMARY_ATTRIBUTES_MISSING_ERROR`, {
- CONDITION_NO: rule?.ruleKey,
- DELIVERY_NO: delivery?.deliveryIndex,
- CYCLE_NO: cycle?.cycleIndex,
- }),
- // error: `Attributes missing in delivery condition ${rule?.ruleKey} delivery ${delivery?.deliveryIndex}`,
- button: t(`CAMPAIGN_SUMMARY_ADD_ATTRIBUTES_ACTION`),
- });
- isValid = false;
- }
- }
- });
-
- rule.products.forEach((product) => {
- // Check if count and value are empty
- if (product.count === null || product.value === null) {
- isValid = false;
- }
- });
- });
- });
- });
-
- setSummaryErrors((prev) => {
- return {
- ...prev,
- deliveryErrors: [...deliveryRulesError, ...dateError],
- };
- });
- return isValid;
- // ? "Delivery rules are valid"
- // : "Attributes, operators, values, count, or value are not empty in delivery rules or attributes/products length is 0";
- }
-
- function checkAttributeValidity(data) {
- for (const rule of data?.deliveryRule) {
- for (const delivery of rule?.deliveries) {
- for (const rule of delivery?.deliveryRules) {
- for (const attribute of rule?.attributes) {
- if (
- attribute?.operator &&
- attribute?.operator?.code === "IN_BETWEEN" &&
- attribute?.fromValue &&
- attribute?.toValue &&
- attribute?.fromValue !== "" &&
- attribute?.toValue !== "" &&
- Number(attribute?.toValue) >= Number(attribute?.fromValue)
- ) {
- // return `Error: Attribute "${attribute?.attribute?.code ? attribute?.attribute?.code : attribute?.attribute}" has invalid range (${
- // attribute.toValue
- // } to ${attribute.fromValue})`;
- return "CAMPAIGN_IN_BETWEEN_ERROR";
- } else if (attribute?.value === 0 || attribute?.value === "0") {
- return "CAMPAIGN_VALUE_ZERO_ERROR";
- }
- }
- }
- }
- }
- return false;
- }
-
- // function validateBoundaryLevel(data) {
- // // Extracting boundary types from hierarchy response
- // const boundaryTypes = new Set(hierarchyDefinition?.BoundaryHierarchy?.[0]?.boundaryHierarchy.map((item) => item?.boundaryType));
-
- // // Extracting unique boundary types from data
- // const uniqueDataBoundaryTypes = new Set(data?.map((item) => item.type));
-
- // // Checking if all unique boundary types from hierarchy response are present in data
- // const allBoundaryTypesPresent = [...boundaryTypes].every((type) => uniqueDataBoundaryTypes.has(type));
-
- // return allBoundaryTypesPresent;
- // }
-
- function validateBoundaryLevel(data) {
- // Extracting boundary hierarchy from hierarchy definition
- const boundaryHierarchy = hierarchyDefinition?.BoundaryHierarchy?.[0]?.boundaryHierarchy || [];
-
- // Find the index of the lowest hierarchy
- const lowestIndex = boundaryHierarchy.findIndex((item) => item?.boundaryType === lowestHierarchy);
-
- // Create a set of boundary types including only up to the lowest hierarchy
- const boundaryTypes = new Set(boundaryHierarchy.filter((_, index) => index <= lowestIndex).map((item) => item?.boundaryType));
-
- // Extracting unique boundary types from data
- const uniqueDataBoundaryTypes = new Set(data?.map((item) => item.type));
-
- // Checking if all boundary types from the filtered hierarchy are present in data
- const allBoundaryTypesPresent = [...boundaryTypes].every((type) => uniqueDataBoundaryTypes.has(type));
-
- return allBoundaryTypesPresent;
- }
-
- // function recursiveParentFind(filteredData) {
- // const parentChildrenMap = {};
-
- // // Build the parent-children map
- // filteredData?.forEach((item) => {
- // if (item?.parent) {
- // if (!parentChildrenMap[item?.parent]) {
- // parentChildrenMap[item?.parent] = [];
- // }
- // parentChildrenMap[item?.parent].push(item.code);
- // }
- // });
-
- // // Check for missing children
- // const missingParents = filteredData?.filter((item) => item?.parent && !parentChildrenMap[item.code]);
- // const extraParent = missingParents?.filter((i) => i?.type !== lowest?.[0]?.boundaryType);
-
- // return extraParent;
- // }
-
- function recursiveParentFind(filteredData) {
- const parentChildrenMap = {};
-
- // Build the parent-children map
- filteredData?.forEach((item) => {
- if (item?.parent) {
- if (!parentChildrenMap[item?.parent]) {
- parentChildrenMap[item?.parent] = [];
- }
- parentChildrenMap[item?.parent].push(item.code);
- }
- });
-
- // Check for missing children
- const missingParents = filteredData?.filter((item) => item?.parent && !parentChildrenMap[item.code]);
- const extraParent = missingParents?.filter((i) => i?.type !== lowestHierarchy);
-
- return extraParent;
- }
-
- // validating the screen data on clicking next button
- const handleValidate = (formData) => {
- const key = Object.keys(formData)?.[0];
- switch (key) {
- case "campaignName":
- if (typeof formData?.campaignName !== "string" || !formData?.campaignName.trim()) {
- setShowToast({ key: "error", label: "CAMPAIGN_NAME_MISSING_TYPE_ERROR" });
- return false;
- } else if (formData.campaignName.length > 250) {
- setShowToast({ key: "error", label: "CAMPAIGN_NAME_TOO_LONG_ERROR" });
- return false;
- } else {
- setShowToast(null);
- return true;
- }
- case "projectType":
- if (!formData?.projectType) {
- setShowToast({ key: "error", label: "PROJECT_TYPE_UNDEFINED_ERROR" });
- return false;
- } else {
- setShowToast(null);
- return true;
- }
- case "campaignDates":
- const startDateObj = new Date(formData?.campaignDates?.startDate);
- const endDateObj = new Date(formData?.campaignDates?.endDate);
- if (!formData?.campaignDates?.startDate || !formData?.campaignDates?.endDate) {
- setShowToast({ key: "error", label: `${t("HCM_CAMPAIGN_DATE_MISSING")}` });
- return false;
- } else if (endDateObj.getTime() === startDateObj.getTime()) {
- setShowToast({ key: "error", label: `${t("HCM_CAMPAIGN_END_DATE_EQUAL_START_DATE")}` });
- return false;
- } else if (endDateObj.getTime() < startDateObj) {
- setShowToast({ key: "error", label: `${t("HCM_CAMPAIGN_END_DATE_BEFORE_START_DATE")}` });
- return false;
- } else {
- setShowToast(null);
- return true;
- }
- case "boundaryType":
- if (formData?.boundaryType?.selectedData) {
- const validateBoundary = validateBoundaryLevel(formData?.boundaryType?.selectedData);
- const missedType = recursiveParentFind(formData?.boundaryType?.selectedData);
- if (!validateBoundary) {
- setShowToast({ key: "error", label: t("HCM_CAMPAIGN_ALL_THE_LEVELS_ARE_MANDATORY") });
- return false;
- } else if (recursiveParentFind(formData?.boundaryType?.selectedData).length > 0) {
- setShowToast({
- key: "error",
- label: `${t(`HCM_CAMPAIGN_FOR`)} ${t(`${hierarchyType}_${missedType?.[0]?.type}`?.toUpperCase())} ${t(missedType?.[0]?.code)} ${t(
- `HCM_CAMPAIGN_CHILD_NOT_PRESENT`
- )}`,
- });
- return false;
- }
- setShowToast(null);
- const checkEqual = _.isEqual(
- formData?.boundaryType?.selectedData,
- totalFormData?.HCM_CAMPAIGN_SELECTING_BOUNDARY_DATA?.boundaryType?.selectedData
- );
- console.log("HSHSHS", checkEqual);
- setFetchUpload(true);
- setRefetchGenerate(checkEqual === false ? true : false);
- return true;
- } else {
- setShowToast({ key: "error", label: `${t("HCM_SELECT_BOUNDARY")}` });
- return false;
- }
-
- case "uploadBoundary":
- if (formData?.uploadBoundary?.isValidation) {
- setShowToast({ key: "info", label: `${t("HCM_FILE_VALIDATION_PROGRESS")}`, transitionTime: 6000000000 });
- return false;
- } else if (formData?.uploadBoundary?.isError) {
- if (formData?.uploadBoundary?.apiError) {
- setShowToast({ key: "error", label: formData?.uploadBoundary?.apiError, transitionTime: 6000000000 });
- } else setShowToast({ key: "error", label: `${t("HCM_FILE_VALIDATION")}` });
- return false;
- } else {
- setShowToast(null);
- return true;
- }
-
- case "uploadFacility":
- if (formData?.uploadFacility?.isValidation) {
- setShowToast({ key: "info", label: `${t("HCM_FILE_VALIDATION_PROGRESS")}`, transitionTime: 6000000000 });
- return false;
- } else if (formData?.uploadFacility?.isError) {
- if (formData?.uploadFacility?.apiError) {
- setShowToast({ key: "error", label: formData?.uploadFacility?.apiError, transitionTime: 6000000000 });
- } else setShowToast({ key: "error", label: `${t("HCM_FILE_VALIDATION")}` });
- return false;
- } else {
- setShowToast(null);
- return true;
- }
- case "uploadUser":
- if (formData?.uploadUser?.isValidation) {
- setShowToast({ key: "info", label: `${t("HCM_FILE_VALIDATION_PROGRESS")}`, transitionTime: 6000000000 });
- return false;
- } else if (formData?.uploadUser?.isError) {
- if (formData?.uploadUser?.apiError) {
- setShowToast({ key: "error", label: formData?.uploadUser?.apiError, transitionTime: 6000000000 });
- } else setShowToast({ key: "error", label: `${t("HCM_FILE_VALIDATION")}` });
- return false;
- } else {
- setShowToast(null);
- return true;
- }
-
- case "cycleConfigure":
- const cycleNumber = formData?.cycleConfigure?.cycleConfgureDate?.cycle;
- const deliveryNumber = formData?.cycleConfigure?.cycleConfgureDate?.deliveries;
- if (cycleNumber === "" || cycleNumber === 0 || deliveryNumber === "" || deliveryNumber === 0) {
- setShowToast({ key: "error", label: "DELIVERY_CYCLE_ERROR" });
- return false;
- } else {
- setShowToast(null);
- return true;
- }
- case "deliveryRule":
- const isAttributeValid = checkAttributeValidity(formData);
- if (isAttributeValid) {
- setShowToast({ key: "error", label: isAttributeValid });
- return false;
- }
- setShowToast(null);
- return;
- case "summary":
- const cycleConfigureData = totalFormData?.HCM_CAMPAIGN_CYCLE_CONFIGURE;
- const isCycleError = validateCycleData(cycleConfigureData);
- const deliveryCycleData = totalFormData?.HCM_CAMPAIGN_DELIVERY_DATA;
- const isDeliveryError = validateDeliveryRules(
- deliveryCycleData,
- totalFormData?.["HCM_CAMPAIGN_TYPE"]?.projectType?.code?.toUpperCase(),
- cycleConfigureData
- );
- const isTargetError = totalFormData?.HCM_CAMPAIGN_UPLOAD_BOUNDARY_DATA?.uploadBoundary?.uploadedFile?.[0]?.filestoreId
- ? false
- : (setSummaryErrors((prev) => {
- return {
- ...prev,
- target: [
- {
- name: `target`,
- error: t(`TARGET_FILE_MISSING`),
- },
- ],
- };
- }),
- true);
- const isFacilityError = totalFormData?.HCM_CAMPAIGN_UPLOAD_FACILITY_DATA?.uploadFacility?.uploadedFile?.[0]?.filestoreId
- ? false
- : (setSummaryErrors((prev) => {
- return {
- ...prev,
- facility: [
- {
- name: `facility`,
- error: t(`FACILITY_FILE_MISSING`),
- },
- ],
- };
- }),
- true);
- const isUserError = totalFormData?.HCM_CAMPAIGN_UPLOAD_USER_DATA?.uploadUser?.uploadedFile?.[0]?.filestoreId
- ? false
- : (setSummaryErrors((prev) => {
- return {
- ...prev,
- user: [
- {
- name: `user`,
- error: t(`USER_FILE_MISSING`),
- },
- ],
- };
- }),
- true);
- if (isCycleError?.length > 0) {
- setShowToast({ key: "error", label: "DELIVERY_CYCLE_MISMATCH_LENGTH_ERROR" });
- return false;
- }
- if (isDeliveryError === false) {
- setShowToast({ key: "error", label: "DELIVERY_RULES_ERROR" });
- return false;
- }
- if (isTargetError) {
- setShowToast({ key: "error", label: "TARGET_DETAILS_ERROR" });
- return false;
- }
- if (isFacilityError) {
- setShowToast({ key: "error", label: "FACILITY_DETAILS_ERROR" });
- return false;
- }
- if (isUserError) {
- setShowToast({ key: "error", label: "USER_DETAILS_ERROR" });
- return false;
- }
- setShowToast(null);
- return true;
- default:
- break;
- }
- };
-
- useEffect(() => {
- if (showToast) {
- setTimeout(closeToast, 10000);
- }
- }, [showToast]);
-
- const onSubmit = (formData, cc) => {
- setIsSubmitting(true);
- const checkValid = handleValidate(formData);
- if (checkValid === false) {
- return;
- }
-
- const name = filteredConfig?.[0]?.form?.[0]?.name;
-
- if (name === "HCM_CAMPAIGN_TYPE" && totalFormData?.["HCM_CAMPAIGN_TYPE"]?.projectType?.code !== formData?.projectType?.code) {
- setTotalFormData((prevData) => ({
- [name]: formData,
- }));
- //to set the data in the local storage
- setParams({
- [name]: { ...formData },
- });
- } else if (name === "HCM_CAMPAIGN_SELECTING_BOUNDARY_DATA" && formData?.boundaryType?.updateBoundary === true) {
- setTotalFormData((prevData) => ({
- ...prevData,
- [name]: formData,
- ["HCM_CAMPAIGN_UPLOAD_BOUNDARY_DATA"]: {},
- ["HCM_CAMPAIGN_UPLOAD_FACILITY_DATA"]: {},
- ["HCM_CAMPAIGN_UPLOAD_USER_DATA"]: {},
- }));
- //to set the data in the local storage
- setParams({
- ...params,
- [name]: { ...formData },
- ["HCM_CAMPAIGN_UPLOAD_BOUNDARY_DATA"]: {},
- ["HCM_CAMPAIGN_UPLOAD_FACILITY_DATA"]: {},
- ["HCM_CAMPAIGN_UPLOAD_USER_DATA"]: {},
- });
- } else {
- setTotalFormData((prevData) => ({
- ...prevData,
- [name]: formData,
- }));
- //to set the data in the local storage
- setParams({
- ...params,
- [name]: { ...formData },
- });
- }
-
- if (
- filteredConfig?.[0]?.form?.[0]?.isLast ||
- !filteredConfig[0].form[0].body[0].skipAPICall ||
- (filteredConfig[0].form[0].body[0].skipAPICall && id)
- ) {
- setShouldUpdate(true);
- }
-
- if (!filteredConfig?.[0]?.form?.[0]?.isLast && !filteredConfig[0].form[0].body[0].mandatoryOnAPI) {
- setCurrentKey(currentKey + 1);
- }
- if (isDraft === "true" && isSkip !== "false") {
- updateUrlParams({ skip: "false" });
- }
- return;
- };
-
- const onStepClick = (step) => {
- if ((currentKey === 5 || currentKey === 6) && step > 1) {
- return;
- }
- const filteredSteps = campaignConfig[0].form.filter((item) => item.stepCount === String(step + 1));
-
- const key = parseInt(filteredSteps[0].key);
- const name = filteredSteps[0].name;
-
- if (step === 6 && Object.keys(totalFormData).includes("HCM_CAMPAIGN_UPLOAD_USER_DATA")) {
- setCurrentKey(10);
- setCurrentStep(7);
- } else if (step === 1 && totalFormData["HCM_CAMPAIGN_NAME"] && totalFormData["HCM_CAMPAIGN_NAME"]) {
- setCurrentKey(3);
- setCurrentStep(1);
- } else if (!totalFormData["HCM_CAMPAIGN_NAME"] || !totalFormData["HCM_CAMPAIGN_NAME"]) {
- // Do not set stepper and key
- } else if (Object.keys(totalFormData).includes(name)) {
- setCurrentKey(key);
- setCurrentStep(step);
- // Do not set stepper and key
- }
- };
-
- const filterNonEmptyValues = (obj) => {
- const keys = [];
- for (const key in obj) {
- if (typeof obj[key] === "object" && obj[key] !== null) {
- // Check if any nested value is non-null and non-empty
- if (hasNonEmptyValue(obj[key])) {
- keys.push(key);
- }
- } else if (obj[key] !== null && obj[key] !== "") {
- keys.push(key);
- }
- }
- return keys;
- };
-
- const hasNonEmptyValue = (obj) => {
- for (const key in obj) {
- if (obj[key] !== null && obj[key] !== "") {
- if (typeof obj[key] === "object") {
- if (hasNonEmptyValue(obj[key])) {
- return true;
- }
- } else {
- return true;
- }
- }
- }
- return false;
- };
-
- const findHighestStepCount = () => {
- const totalFormDataKeys = Object.keys(totalFormData);
-
- const nonNullFormDataKeys = filterNonEmptyValues(totalFormData);
-
- const relatedSteps = campaignConfig?.[0]?.form.filter((step) => nonNullFormDataKeys.includes(step.name));
-
- const highestStep = relatedSteps.reduce((max, step) => Math.max(max, parseInt(step.stepCount)), 0);
- if(isDraft == "true"){
- const filteredSteps = campaignConfig?.[0]?.form.find((item) => item.key === keyParam)?.stepCount;
- setActive(filteredSteps);
- }
- else{
- setActive(highestStep);
- }
-
- // setActive(highestStep);
- };
-
- useEffect(() => {
- findHighestStepCount();
- }, [totalFormData, campaignConfig]);
-
- const onSecondayActionClick = () => {
- if (currentKey > 1) {
- setShouldUpdate(false);
- setCurrentKey(currentKey - 1);
- }
- };
-
- // filtering the config on the basis of the screen or key
- // const filteredConfig = campaignConfig
- // .map((config) => {
- // return {
- // ...config,
- // form: config?.form.filter((step) => parseInt(step.key) == currentKey),
- // };
- // })
- // .filter((config) => config.form.length > 0);
-
- const filterCampaignConfig = (campaignConfig, currentKey) => {
- return campaignConfig
- .map((config) => {
- return {
- ...config,
- form: config?.form.filter((step) => parseInt(step.key) === currentKey),
- };
- })
- .filter((config) => config.form.length > 0);
- };
-
- const [filteredConfig, setFilteredConfig] = useState(filterCampaignConfig(campaignConfig, currentKey));
-
- useEffect(() => {
- setFilteredConfig(filterCampaignConfig(campaignConfig, currentKey));
- }, [campaignConfig, currentKey]);
-
- const config = filteredConfig?.[0];
-
- // setting the current step when the key is changed on the basis of the config
- useEffect(() => {
- setCurrentStep(Number(filteredConfig?.[0]?.form?.[0]?.stepCount - 1));
- // setShowToast(null);
- }, [currentKey, filteredConfig]);
-
- useEffect(() => {
- // setCurrentStep(Number(filteredConfig?.[0]?.form?.[0]?.stepCount - 1));
- setShowToast(null);
- }, [currentKey]);
-
- const closeToast = () => {
- setShowToast(null);
- };
-
- if (isPreview === "true" && !draftData) {
- return ;
- }
-
- if (isDraft === "true" && !draftData) {
- return ;
- }
-
- return (
-
- {noAction !== "false" && (
-
- )}
- {
- return {
- ...config,
- body: config?.body.filter((a) => !a.hideInEmployee),
- };
- })}
- onSubmit={onSubmit}
- showSecondaryLabel={currentKey > 1 ? true : false}
- secondaryLabel={noAction === "false" ? null : t("HCM_BACK")}
- actionClassName={"actionBarClass"}
- className="setup-campaign"
- cardClassName="setup-campaign-card"
- noCardStyle={currentKey === 4 || currentStep === 7 || currentStep === 0 ? false : true}
- onSecondayActionClick={onSecondayActionClick}
- label={noAction === "false" ? null : filteredConfig?.[0]?.form?.[0]?.isLast === true ? t("HCM_SUBMIT") : t("HCM_NEXT")}
- />
- {showToast && (
-
- )}
-
- );
-};
-
-export default SetupCampaign;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/deliveryRule/AddDeliverycontext.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/deliveryRule/AddDeliverycontext.js
deleted file mode 100644
index 3630f7aba53..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/deliveryRule/AddDeliverycontext.js
+++ /dev/null
@@ -1,813 +0,0 @@
-import {
- LabelFieldPair,
- AddIcon,
- CardLabel,
- Dropdown,
- // TextInput,
- Button,
- Card,
- CardHeader,
- Modal,
- CloseSvg,
-} from "@egovernments/digit-ui-react-components";
-import { SVG } from "@egovernments/digit-ui-react-components";
-import React, { Fragment, useContext, useEffect, useRef, useState } from "react";
-import { useTranslation } from "react-i18next";
-// import { attributeConfig } from "../../../configs/attributeConfig";
-// import { operatorConfig } from "../../../configs/operatorConfig";
-import RemoveableTagNew from "../../../components/RemovableTagNew";
-import AddProducts from "./AddProductscontext";
-import { CycleContext } from ".";
-import { RadioButtons, TextInput } from "@egovernments/digit-ui-components";
-import { PRIMARY_COLOR } from "../../../utils";
-
-const DustbinIcon = () => (
-
-);
-
-const makeSequential = (jsonArray, keyName) => {
- return jsonArray.map((item, index) => ({
- ...item,
- [keyName]: index + 1,
- }));
-};
-
-const AddAttributeField = ({
- config,
- deliveryRuleIndex,
- delivery,
- deliveryRules,
- setDeliveryRules,
- attribute,
- setAttributes,
- index,
- onDelete,
- attributeConfig,
- operatorConfig,
- genderConfig,
-}) => {
- const [val, setVal] = useState("");
- const [showAttribute, setShowAttribute] = useState(null);
- const [showOperator, setShowOperator] = useState(null);
- const [addedOption, setAddedOption] = useState(null);
- const { t } = useTranslation();
-
- useEffect(() => {
- setAddedOption(delivery?.attributes?.map((i) => i?.attribute?.code)?.filter((i) => i));
- }, [delivery, deliveryRules]);
-
- const selectValue = (e) => {
- let val = e.target.value;
- val = val.replace(/[^\d.]/g, "");
- val = val.match(/^\d*\.?\d{0,2}/)[0] || "";
- // if (val.startsWith("-")) {
- // val = val.slice(1); // Remove the negative sign
- // }
- if (isNaN(val) || [" ", "e", "E"].some((f) => val.includes(f))) {
- val = val.slice(0, -1);
- return;
- }
- // setAttributes((pre) => pre.map((item) => (item.key === attribute.key ? { ...item, value: e.target.value } : item)));
- const updatedData = deliveryRules.map((item, index) => {
- if (item.ruleKey === deliveryRuleIndex) {
- item.attributes.find((i) => i.key === attribute.key).value = val;
- }
- return item;
- });
- setDeliveryRules(updatedData);
- };
-
- const selectGender = (value) => {
- // setAttributes((pre) => pre.map((item) => (item.key === attribute.key ? { ...item, value: e.target.value } : item)));
- const updatedData = deliveryRules.map((item, index) => {
- if (item.ruleKey === deliveryRuleIndex) {
- item.attributes.find((i) => i.key === attribute.key).value = value?.code;
- }
- return item;
- });
- setDeliveryRules(updatedData);
- };
-
- const selectToFromValue = (e, range) => {
- let val = e.target.value;
- val = val.replace(/[^\d.]/g, "");
- val = val.match(/^\d*\.?\d{0,2}/)[0] || "";
- // if (val.startsWith("-")) {
- // val = val.slice(1); // Remove the negative sign
- // }
-
- if (isNaN(val) || [" ", "e", "E"].some((f) => val.includes(f))) {
- val = val.slice(0, -1);
- return;
- }
- if (range === "to") {
- const updatedData = deliveryRules.map((item, index) => {
- if (item.ruleKey === deliveryRuleIndex) {
- item.attributes.find((i) => i.key === attribute.key).toValue = val;
- }
- return item;
- });
- setDeliveryRules(updatedData);
- } else {
- const updatedData = deliveryRules.map((item, index) => {
- if (item.ruleKey === deliveryRuleIndex) {
- item.attributes.find((i) => i.key === attribute.key).fromValue = val;
- }
- return item;
- });
- setDeliveryRules(updatedData);
- }
- };
-
- const selectAttribute = (value) => {
- // setAttributes((pre) => pre.map((item) => (item.key === attribute.key ? { ...item, value: e.target.value } : item)));
- const updatedData = deliveryRules.map((item, index) => {
- if (item.ruleKey === deliveryRuleIndex) {
- item.attributes.find((i) => i.key === attribute.key).attribute = value;
- item.attributes.find((i) => i.key === attribute.key).value = "";
- item.attributes.find((i) => i.key === attribute.key).toValue = "";
- item.attributes.find((i) => i.key === attribute.key).fromValue = "";
- if (value.code === "Gender") {
- item.attributes.find((i) => i.key === attribute.key).operator = {
- code: "EQUAL_TO",
- };
- }
- }
- return item;
- });
- setShowAttribute(value);
- setDeliveryRules(updatedData);
- };
-
- const selectOperator = (value) => {
- // setAttributes((pre) => pre.map((item) => (item.key === attribute.key ? { ...item, value: e.target.value } : item)));
- const updatedData = deliveryRules.map((item, index) => {
- if (item.ruleKey === deliveryRuleIndex) {
- item.attributes.find((i) => i.key === attribute.key).operator = value;
- delete item.attributes.find((i) => i.key === attribute.key).toValue;
- delete item.attributes.find((i) => i.key === attribute.key).fromValue;
- }
- return item;
- });
- setShowOperator(value);
- setDeliveryRules(updatedData);
- };
-
- return (
-
-
-
- {t(`CAMPAIGN_ATTRIBUTE_LABEL`)}
-
- item?.code === attribute?.attribute?.code)}
- disable={false}
- isMandatory={true}
- option={addedOption ? attributeConfig?.filter((item) => !addedOption.includes(item.code)) : attributeConfig}
- select={(value) => selectAttribute(value)}
- optionKey="i18nKey"
- t={t}
- />
-
-
-
- {t(`CAMPAIGN_OPERATOR_LABEL`)}
-
- selectOperator(value)}
- optionKey="code"
- t={t}
- />
-
-
- {attribute?.operator?.code === "IN_BETWEEN" ? (
-
-
- {t(`CAMPAIGN_FROM_LABEL`)}
-
-
- selectToFromValue(e, "to")}
- disable={false}
- />
-
-
-
-
- {t(`CAMPAIGN_TO_LABEL`)}
-
-
- selectToFromValue(e, "from")}
- disable={false}
- />
-
-
-
-
- ) : (
-
- {t(`CAMPAIGN_VALUE_LABEL`)}
-
- {attribute?.attribute?.code === "Gender" ? (
- selectGender(value)}
- optionKey="code"
- t={t}
- />
- ) : (
-
- )}
-
-
- )}
- {delivery.attributes.length !== 1 && (
-
onDelete()}
- style={{
- cursor: "pointer",
- fontWeight: "600",
- marginLeft: "1rem",
- fontSize: "1rem",
- color: PRIMARY_COLOR,
- display: "flex",
- gap: "0.5rem",
- alignItems: "center",
- marginTop: "1rem",
- }}
- >
-
- {t(`CAMPAIGN_DELETE_ROW_TEXT`)}
-
- )}
-
- );
-};
-
-const AddCustomAttributeField = ({
- config,
- deliveryRuleIndex,
- delivery,
- deliveryRules,
- setDeliveryRules,
- attribute,
- setAttributes,
- index,
- onDelete,
- operatorConfig,
- genderConfig,
-}) => {
- const [val, setVal] = useState("");
- const [showAttribute, setShowAttribute] = useState(null);
- const [showOperator, setShowOperator] = useState(null);
- const [addedOption, setAddedOption] = useState(null);
- const { t } = useTranslation();
- const { attrConfig } = useContext(CycleContext);
-
- useEffect(() => {
- setAddedOption(delivery?.attributes?.map((i) => i?.attribute?.code)?.filter((i) => i));
- }, [delivery]);
-
- const selectValue = (e) => {
- let val = e.target.value;
- val = val.replace(/[^\d.]/g, "");
- val = val.match(/^\d*\.?\d{0,2}/)[0] || "";
- // if (val.startsWith("-")) {
- // val = val.slice(1); // Remove the negative sign
- // }
- if (isNaN(val) || [" ", "e", "E"].some((f) => val.includes(f))) {
- val = val.slice(0, -1);
- }
- // setAttributes((pre) => pre.map((item) => (item.key === attribute.key ? { ...item, value: e.target.value } : item)));
- const updatedData = deliveryRules.map((item, index) => {
- if (item.ruleKey === deliveryRuleIndex) {
- item.attributes.find((i) => i.key === attribute.key).value = val;
- }
- return item;
- });
- setDeliveryRules(updatedData);
- };
-
- const selectOperator = (value) => {
- // setAttributes((pre) => pre.map((item) => (item.key === attribute.key ? { ...item, value: e.target.value } : item)));
- const updatedData = deliveryRules.map((item, index) => {
- if (item.ruleKey === deliveryRuleIndex) {
- item.attributes.find((i) => i.key === attribute.key).operator = value;
- }
- return item;
- });
- setShowOperator(value);
- setDeliveryRules(updatedData);
- };
-
- const selectToFromValue = (e, range) => {
- let val = e.target.value;
- val = val.replace(/[^\d.]/g, "");
- val = val.match(/^\d*\.?\d{0,2}/)[0] || "";
- // if (val.startsWith("-")) {
- // val = val.slice(1); // Remove the negative sign
- // }
- if (isNaN(val) || [" ", "e", "E"].some((f) => val.includes(f))) {
- val = val.slice(0, -1);
- return;
- }
- if (range === "to") {
- const updatedData = deliveryRules.map((item, index) => {
- if (item.ruleKey === deliveryRuleIndex) {
- item.attributes.find((i) => i.key === attribute.key).toValue = val;
- }
- return item;
- });
- setDeliveryRules(updatedData);
- } else {
- const updatedData = deliveryRules.map((item, index) => {
- if (item.ruleKey === deliveryRuleIndex) {
- item.attributes.find((i) => i.key === attribute.key).fromValue = val;
- }
- return item;
- });
- setDeliveryRules(updatedData);
- }
- };
-
- return (
-
-
-
- {t(`CAMPAIGN_ATTRIBUTE_LABEL`)}
-
-
-
-
- {/* !addedOption.includes(item.code)) : attributeConfig}
- select={(value) => selectAttribute(value)}
- optionKey="code"
- t={t}
- /> */}
-
-
-
- {t(`CAMPAIGN_OPERATOR_LABEL`)}
-
- selectOperator(value)}
- optionKey="code"
- t={t}
- />
-
- {attribute?.operator?.code === "IN_BETWEEN" ? (
-
-
- {t(`CAMPAIGN_FROM_LABEL`)}
-
-
- selectToFromValue(e, "to")}
- disable={false}
- />
-
-
-
-
- {t(`CAMPAIGN_TO_LABEL`)}
-
-
- selectToFromValue(e, "from")}
- disable={false}
- />
-
-
-
-
- ) : (
-
- {t(`CAMPAIGN_VALUE_LABEL`)}
-
- {attribute?.attribute?.code === "Gender" ? (
- selectGender(value)}
- optionKey="code"
- t={t}
- />
- ) : (
-
- )}
-
-
- )}
-
- );
-};
-
-const AddAttributeWrapper = ({ targetedData, deliveryRuleIndex, delivery, deliveryRules, setDeliveryRules, index, key }) => {
- const { campaignData, dispatchCampaignData, filteredDeliveryConfig } = useContext(CycleContext);
- const { t } = useTranslation();
- const tenantId = Digit.ULBService.getCurrentTenantId();
- const { isLoading: attributeConfigLoading, data: attributeConfig } = Digit.Hooks.useCustomMDMS(
- tenantId,
- "HCM-ADMIN-CONSOLE",
- [{ name: "attributeConfig" }],
- {
- select: (data) => {
- return data?.["HCM-ADMIN-CONSOLE"]?.attributeConfig;
- },
- }
- );
- const { isLoading: operatorConfigLoading, data: operatorConfig } = Digit.Hooks.useCustomMDMS(
- tenantId,
- "HCM-ADMIN-CONSOLE",
- [{ name: "operatorConfig" }],
- {
- select: (data) => {
- return data?.["HCM-ADMIN-CONSOLE"]?.operatorConfig;
- },
- }
- );
- const { isLoading: genderConfigLoading, data: genderConfig } = Digit.Hooks.useCustomMDMS(tenantId, "common-masters", [{ name: "GenderType" }], {
- select: (data) => {
- return data?.["common-masters"]?.GenderType?.filter((i) => i.active !== false);
- },
- });
- const [attributes, setAttributes] = useState([{ key: 1, deliveryRuleIndex, attribute: "", operator: "", value: "" }]);
- const reviseIndexKeys = () => {
- setAttributes((prev) => prev.map((unit, index) => ({ ...unit, key: index + 1 })));
- };
-
- const addMoreAttribute = () => {
- setDeliveryRules((prev) =>
- prev.map((item, index) =>
- index + 1 === deliveryRuleIndex
- ? {
- ...item,
- attributes: [...item.attributes, { key: item.attributes.length + 1, attribute: "", operator: "", value: "" }],
- }
- : item
- )
- );
- };
-
- const deleteAttribute = (_, d) => {
- // setAttributes((prev) => prev.filter((i) => i.key !== item.key));
- const newData = deliveryRules.map((item) => {
- if (item.ruleKey === deliveryRuleIndex) {
- // If ruleKey matches, remove the specified attribute from attributes array
- const updatedAttributes = item.attributes.filter((attribute) => attribute.key !== _.key);
-
- // Reassign keys in sequential order
- const updatedAttributesSequential = makeSequential(updatedAttributes, "key");
-
- return {
- ...item,
- attributes: updatedAttributesSequential,
- };
- }
- return item;
- });
- setDeliveryRules(newData);
- };
-
- return (
-
- {filteredDeliveryConfig?.customAttribute && filteredDeliveryConfig?.projectType === "LLIN-mz"
- ? delivery.attributes.map((item, index) => (
- deleteAttribute(item, deliveryRuleIndex)}
- operatorConfig={operatorConfig}
- genderConfig={genderConfig}
- />
- ))
- : delivery.attributes.map((item, index) => (
- deleteAttribute(item, deliveryRuleIndex)}
- attributeConfig={attributeConfig}
- operatorConfig={operatorConfig}
- genderConfig={genderConfig}
- />
- ))}
- {!filteredDeliveryConfig?.attrAddDisable && delivery.attributes.length !== attributeConfig?.length && (
- }
- onButtonClick={addMoreAttribute}
- />
- )}
-
- );
-};
-
-const AddDeliveryRule = ({ targetedData, deliveryRules, setDeliveryRules, index, key, delivery, onDelete }) => {
- const { campaignData, dispatchCampaignData, filteredDeliveryConfig } = useContext(CycleContext);
- const [showModal, setShowModal] = useState(false);
- const [showToast, setShowToast] = useState(null);
- const { t } = useTranslation();
- const prodRef = useRef();
- const tenantId = Digit.ULBService.getCurrentTenantId();
- const closeToast = () => setShowToast(null);
- const { isLoading: deliveryTypeConfigLoading, data: deliveryTypeConfig } = Digit.Hooks.useCustomMDMS(
- tenantId,
- "HCM-ADMIN-CONSOLE",
- [{ name: "deliveryTypeConfig" }],
- {
- select: (data) => {
- return data?.["HCM-ADMIN-CONSOLE"]?.deliveryTypeConfig;
- },
- }
- );
- useEffect(() => {
- if (showToast) {
- setTimeout(closeToast, 5000);
- }
- }, [showToast]);
-
- const confirmResources = () => {
- const isValid = prodRef.current?.every((item) => item?.count !== null && item?.value !== null);
- if (!isValid) {
- setShowToast({ key: "error", label: "CAMPAIGN_PRODUCT_MISSING_ERROR" });
- return;
- }
- dispatchCampaignData({
- type: "ADD_PRODUCT",
- payload: {
- productData: prodRef.current,
- delivery: delivery,
- },
- });
- setShowModal(false);
- };
-
- const removeProduct = (item) => {
- const temp = delivery;
- setDeliveryRules((prevState) => {
- const updatedDeliveryRules = prevState.map((delivery) => {
- if (delivery.ruleKey === temp.ruleKey) {
- const updatedProducts = delivery.products
- .filter((product) => product.value !== item.value)
- .map((product, index) => ({ ...product, key: index + 1 }));
- return { ...delivery, products: updatedProducts };
- }
- return delivery;
- });
- return updatedDeliveryRules;
- });
- };
-
- const updateDeliveryType = (value) => {
- const temp = delivery;
- setDeliveryRules((prevState) => {
- const updatedDeliveryRules = prevState.map((delivery) => {
- if (delivery.ruleKey === temp.ruleKey) {
- return { ...delivery, deliveryType: value?.code };
- }
- return delivery;
- });
- return updatedDeliveryRules;
- });
- };
-
- return (
- <>
-
-
-
- {t(`CAMPAIGN_DELIVERY_RULE_LABEL`)} {delivery.ruleKey}
-
- {deliveryRules.length !== 1 && (
- onDelete()}
- style={{
- fontWeight: "600",
- fontSize: "1rem",
- color: PRIMARY_COLOR,
- display: "flex",
- gap: "0.5rem",
- alignItems: "center",
- cursor: "pointer",
- }}
- >
- {t(`CAMPAIGN_DELETE_CONDITION_LABEL`)}
-
- )}
-
- {filteredDeliveryConfig?.customAttribute && filteredDeliveryConfig?.projectType !== "LLIN-mz" && (
-
-
- {`${t("HCM_DELIVERY_TYPE")}`}
-
- i?.code === delivery?.deliveryType)}
- optionsKey="code"
- onSelect={(value) => updateDeliveryType(value)}
- t={t}
- disabled={
- filteredDeliveryConfig?.deliveryConfig?.find((i, n) => n === targetedData?.deliveryIndex - 1)?.conditionConfig?.[delivery?.ruleKey - 1]
- ?.disableDeliveryType
- ? true
- : false
- }
- />
-
- )}
-
-
- {delivery?.products?.length > 0 &&
- delivery?.products?.map((i) => {
- return i?.value && i?.count ? (
- removeProduct(i)}
- />
- ) : null;
- })}
-
- }
- onButtonClick={() => setShowModal(true)}
- />
-
- {showModal && (
- setShowModal(false)}>
-
-
- }
- children={
-
- }
- />
- )}
- >
- );
-};
-
-const AddDeliveryRuleWrapper = ({}) => {
- const { campaignData, dispatchCampaignData, filteredDeliveryConfig } = useContext(CycleContext);
- const [targetedData, setTargetedData] = useState(campaignData?.find((i) => i?.active === true)?.deliveries?.find((d) => d?.active === true));
- const [deliveryRules, setDeliveryRules] = useState(targetedData?.deliveryRules);
- const { t } = useTranslation();
-
- useEffect(() => {
- const dd = campaignData?.find((i) => i?.active === true)?.deliveries?.find((d) => d?.active === true);
- setTargetedData(dd);
- }, [campaignData]);
-
- useEffect(() => {
- const tt = targetedData?.deliveryRules;
- setDeliveryRules(tt);
- }, [targetedData]);
-
- useEffect(() => {
- dispatchCampaignData({
- type: "UPDATE_CAMPAIGN_DATA",
- payload: {
- currentDeliveryRules: deliveryRules,
- },
- });
- }, [deliveryRules]);
-
- const addMoreDelivery = () => {
- dispatchCampaignData({
- type: "ADD_DELIVERY_RULE",
- payload: {
- currentDeliveryRules: deliveryRules,
- },
- });
- };
-
- const deleteDeliveryRule = (item) => {
- dispatchCampaignData({
- type: "REMOVE_DELIVERY_RULE",
- payload: {
- item: item,
- },
- });
- };
-
- return (
- <>
- {deliveryRules?.map((item, index) => (
- deleteDeliveryRule(item)}
- />
- ))}
- {!filteredDeliveryConfig?.deliveryAddDisable && deliveryRules?.length < 5 && (
- }
- onButtonClick={addMoreDelivery}
- />
- )}
- >
- );
-};
-
-export default AddDeliveryRuleWrapper;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/deliveryRule/AddProductscontext.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/deliveryRule/AddProductscontext.js
deleted file mode 100644
index 75e0afe5c2c..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/deliveryRule/AddProductscontext.js
+++ /dev/null
@@ -1,290 +0,0 @@
-import { AddIcon, Button, CardText, Label, LabelFieldPair } from "@egovernments/digit-ui-react-components";
-import React, { Fragment, useContext, useEffect, useState } from "react";
-import PlusMinusInput from "../../../components/PlusMinusInput";
-import { useTranslation } from "react-i18next";
-import { Dropdown, TextInput, Toast } from "@egovernments/digit-ui-components";
-import { Link } from "react-router-dom";
-import { CycleContext } from ".";
-import { PRIMARY_COLOR } from "../../../utils";
-
-const DustbinIcon = () => (
-
-);
-function AddProducts({ stref, selectedDelivery, showToast, closeToast }) {
- const { t } = useTranslation();
- const oldSessionData = window.Digit.SessionStorage.get("HCM_CAMPAIGN_MANAGER_FORM_DATA");
- const { campaignData, dispatchCampaignData } = useContext(CycleContext);
- const tenantId = Digit.ULBService.getStateId();
- const updateSession = () => {
- const newData = {
- ...oldSessionData,
- HCM_CAMPAIGN_DELIVERY_DATA: {
- deliveryRule: campaignData,
- },
- };
- window.Digit.SessionStorage.set("HCM_CAMPAIGN_MANAGER_FORM_DATA", newData);
- };
- const searchParams = new URLSearchParams(location.search);
- const id = searchParams.get("id");
- const [products, setProducts] = useState([
- {
- key: 1,
- count: 1,
- value: null,
- },
- ]);
- const data = Digit.Hooks.campaign.useProductList(tenantId);
-
- const filteredData = data?.filter((item) => !selectedDelivery?.products?.some((entry) => entry?.value === item?.id));
- const temp = filteredData?.filter((item) => !products?.some((entry) => entry?.value?.id === item?.id));
-
- // const onDeleteProduct = (i, c) => {
- // const updatedProducts = selectedDelivery.products.filter((product) => product.key !== i.key);
- // const updatedProductsSequentialKeys = updatedProducts.map((product, index) => ({ ...product, key: index + 1 }));
- // const updatedDelivery = { ...selectedDelivery, products: updatedProductsSequentialKeys };
- // const updatedCampaignData = campaignData.map((cycle) => {
- // if (cycle.active) {
- // cycle.deliveries.forEach((delivery) => {
- // if (delivery.active) {
- // const deliveryRule = delivery.deliveryRules.find((rule) => rule.ruleKey === updatedDelivery.ruleKey);
- // if (deliveryRule) {
- // // Update the delivery rule with the updated delivery
- // deliveryRule.products = updatedDelivery.products;
- // }
- // }
- // });
- // }
- // return cycle;
- // });
- // setCampaignData(updatedCampaignData);
- // };
-
- // const incrementCount = (item, d) => {
- // const updatedProducts = selectedDelivery.products.map((i) => {
- // if (i.key === item.key) {
- // return {
- // ...i,
- // count: d,
- // };
- // }
- // return i;
- // });
- // const updatedDelivery = { ...selectedDelivery, products: updatedProducts };
- // const updatedCampaignData = campaignData.map((cycle) => {
- // if (cycle.active) {
- // cycle.deliveries.forEach((delivery) => {
- // if (delivery.active) {
- // const deliveryRule = delivery.deliveryRules.find((rule) => rule.ruleKey === updatedDelivery.ruleKey);
- // if (deliveryRule) {
- // // Update the delivery rule with the updated delivery
- // deliveryRule.products = updatedDelivery.products;
- // }
- // }
- // });
- // }
- // return cycle;
- // });
- // setCampaignData(updatedCampaignData);
- // setProducts(updatedProducts);
- // };
-
- // const updatedProductValue = (item, d) => {
- // const updatedProducts = selectedDelivery.products.map((i) => {
- // if (i.key === item.key) {
- // return {
- // ...i,
- // value: d.id,
- // };
- // }
- // return i;
- // });
- // const updatedDelivery = { ...selectedDelivery, products: updatedProducts };
- // const updatedCampaignData = campaignData.map((cycle) => {
- // if (cycle.active) {
- // cycle.deliveries.forEach((delivery) => {
- // if (delivery.active) {
- // const deliveryRule = delivery.deliveryRules.find((rule) => rule.ruleKey === updatedDelivery.ruleKey);
- // if (deliveryRule) {
- // // Update the delivery rule with the updated delivery
- // deliveryRule.products = updatedDelivery.products;
- // }
- // }
- // });
- // }
- // return cycle;
- // });
- // setCampaignData(updatedCampaignData);
- // setProducts(updatedProducts);
- // };
-
- // const addMoreResource = () => {
- // const updatedState = campaignData.map((cycle) => {
- // if (cycle.active) {
- // const updatedDeliveries = cycle.deliveries.map((dd) => {
- // if (dd.active) {
- // const updatedRules = dd.deliveryRules.map((rule) => {
- // if (rule.ruleKey === selectedDelivery.ruleKey) {
- // const productToAdd = {
- // key: rule.products.length + 1,
- // value: null,
- // count: 1, // You can set the initial count as per your requirement
- // };
- // return {
- // ...rule,
- // products: [...rule.products, productToAdd],
- // };
- // }
- // return rule;
- // });
- // return {
- // ...dd,
- // deliveryRules: updatedRules,
- // };
- // }
- // return dd;
- // });
- // return {
- // ...cycle,
- // deliveries: updatedDeliveries,
- // };
- // }
- // return cycle;
- // });
- // setCampaignData(updatedState);
- // };
-
- const add = () => {
- setProducts((prevState) => [
- ...prevState,
- {
- key: prevState.length + 1,
- value: null,
- count: 1,
- },
- ]);
- };
-
- const deleteItem = (data) => {
- const fil = products.filter((i) => i.key !== data.key);
- const up = fil.map((item, index) => ({ ...item, key: index + 1 }));
- setProducts(up);
- };
-
- const incrementC = (data, value) => {
- if (value?.target?.value.trim() === "") return;
- if (value?.target?.value.trim() === 0 || value?.target?.value.trim() > 10) return;
- if (value === 0) return;
- if (value > 10) return;
- setProducts((prevState) => {
- return prevState.map((item) => {
- if (item.key === data.key) {
- return { ...item, count: value?.target?.value ? Number(value?.target?.value) : value };
- }
- return item;
- });
- });
- };
-
- const updateValue = (key, newValue) => {
- setProducts((prevState) => {
- return prevState.map((item) => {
- if (item.key === key.key) {
- return { ...item, value: newValue };
- }
- return item;
- });
- });
- };
-
- useEffect(() => {
- stref.current = products; // Update the ref with the latest child state
- }, [products, stref]);
-
- return (
-
- {products.map((i, c) => (
-
-
-
- {t(`CAMPAIGN_RESOURCE`)} {c + 1}
-
- {products?.length > 1 ? (
-
deleteItem(i, c)}>
-
-
- ) : null}
-
-
-
-
- updateValue(i, d)}
- optionKey="displayName"
- />
-
-
-
-
- incrementC(i, d)} />
-
-
-
- ))}
- {(temp === undefined || temp.length > 0) && (
-
}
- onButtonClick={add}
- />
- )}
-
-
{t("CAMPAIGN_NEW_PRODUCT_TEXT")}
-
-
- {t("ES_CAMPAIGN_ADD_PRODUCT_LINK")}
-
-
-
- {showToast && (
-
- )}
-
- );
-}
-
-export default AddProducts;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/deliveryRule/MultiTabcontext.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/deliveryRule/MultiTabcontext.js
deleted file mode 100644
index e99f0a36de9..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/deliveryRule/MultiTabcontext.js
+++ /dev/null
@@ -1,265 +0,0 @@
-import React, { Fragment, useContext, useState } from "react";
-import { Card, Header, Paragraph, CardHeader, CardSubHeader, CardText } from "@egovernments/digit-ui-react-components";
-import AddDeliveryRuleWrapper from "./AddDeliverycontext";
-import { CycleContext } from ".";
-import { useTranslation } from "react-i18next";
-import { InfoCard } from "@egovernments/digit-ui-components";
-//just pass campaign data here
-// function restructureData(data) {
-// const restructuredData = [];
-
-// data.forEach((cycle) => {
-// cycle.deliveries.forEach((delivery) => {
-// delivery.deliveryRules.forEach((rule) => {
-// const restructuredRule = {
-// startDate: 1665497225000, // Hardcoded for now
-// endDate: 1665497225000, // Hardcoded for now
-// cycleNumber: parseInt(cycle.cycleIndex),
-// deliveryNumber: parseInt(delivery.deliveryIndex),
-// deliveryRuleNumber: parseInt(rule.ruleKey), // New key added
-// products: [],
-// conditions: [],
-// };
-
-// rule.attributes.forEach((attribute) => {
-// restructuredRule.conditions.push({
-// attribute: attribute.attribute ? attribute.attribute.code : null,
-// operator: attribute.operator ? attribute.operator.code : null,
-// value: parseInt(attribute.value),
-// });
-// });
-
-// restructuredData.push(restructuredRule);
-// });
-// });
-// });
-
-// return restructuredData;
-// }
-
-//with between logic
-// function restructureData(data) {
-// const restructuredData = [];
-
-// data.forEach((cycle) => {
-// cycle.deliveries.forEach((delivery) => {
-// delivery.deliveryRules.forEach((rule) => {
-// const restructuredRule = {
-// startDate: 1665497225000, // Hardcoded for now
-// endDate: 1665497225000, // Hardcoded for now
-// cycleNumber: parseInt(cycle.cycleIndex),
-// deliveryNumber: parseInt(delivery.deliveryIndex),
-// deliveryRuleNumber: parseInt(rule.ruleKey),
-// products: [],
-// conditions: [],
-// };
-
-// rule.attributes.forEach((attribute) => {
-// if (attribute.operator && attribute.operator.code === "IN_BETWEEN") {
-// // Replace "IN_BETWEEN" with "LESS_THAN" and "GREATER_THAN"
-// restructuredRule.conditions.push({
-// attribute: attribute.attribute ? attribute.attribute.code : null,
-// operator: "LESS_THAN",
-// value: parseInt(attribute.fromValue),
-// });
-// restructuredRule.conditions.push({
-// attribute: attribute.attribute ? attribute.attribute.code : null,
-// operator: "GREATER_THAN",
-// value: parseInt(attribute.toValue),
-// });
-// } else {
-// restructuredRule.conditions.push({
-// attribute: attribute.attribute ? attribute.attribute.code : null,
-// operator: attribute.operator ? attribute.operator.code : null,
-// value: parseInt(attribute.value),
-// });
-// }
-// });
-
-// restructuredData.push(restructuredRule);
-// });
-// });
-// });
-
-// return restructuredData;
-// }
-
-// for retransform just pass the deliveries
-// function bbb(data) {
-// const reversedData = [];
-// let currentCycleIndex = null;
-// let currentDeliveryIndex = null;
-// let currentCycle = null;
-// let currentDelivery = null;
-
-// data.forEach((item, index) => {
-// if (currentCycleIndex !== item.cycleNumber) {
-// currentCycleIndex = item.cycleNumber;
-// currentCycle = {
-// cycleIndex: currentCycleIndex.toString(),
-// active: index === 0, // Set active to true only for the first index
-// deliveries: [],
-// };
-// reversedData.push(currentCycle);
-// }
-
-// if (currentDeliveryIndex !== item.deliveryNumber) {
-// currentDeliveryIndex = item.deliveryNumber;
-// currentDelivery = {
-// deliveryIndex: currentDeliveryIndex.toString(),
-// active: index === 0, // Set active to true only for the first index
-// deliveryRules: [],
-// };
-// currentCycle.deliveries.push(currentDelivery);
-// }
-
-// currentDelivery.deliveryRules.push({
-// ruleKey: currentDelivery.deliveryRules.length + 1,
-// delivery: {},
-// attributes: item.conditions.map((i, c) => ({ key: c + 1, ...i })),
-// products: [...item.products],
-// });
-// });
-
-// return reversedData;
-// }
-
-const Tabs = ({ onTabChange }) => {
- const { campaignData, dispatchCampaignData } = useContext(CycleContext);
- const { t } = useTranslation();
-
- return (
-
- {campaignData.map((_, index) => (
-
onTabChange(_.cycleIndex, index)}
- >
-
- {t(`CAMPAIGN_CYCLE`)} {index + 1}
-
-
- ))}
-
- );
-};
-
-const TabContent = ({ activeSubTab, subTabCount = 3, onSubTabChange, project }) => {
- const { campaignData, dispatchCampaignData } = useContext(CycleContext);
- const { t } = useTranslation();
-
- return (
-
-
-
- {t(`CAMPAIGN_TAB_TEXT`)}
- {t(`CAMPAIGN_TAB_SUB_TEXT_${project?.code ? project?.code?.toUpperCase() : project?.toUpperCase()}`)}
-
- {/* Add content specific to each tab as needed */}
- ,
-
- {t(`CAMPAIGN_TAB_INFO_TEXT_${project?.code ? project?.code?.toUpperCase() : project?.toUpperCase()}`)}
-
- ]}
- label={"Info"}
- />
-
- );
-};
-
-const SubTabs = ({ onSubTabChange }) => {
- const { campaignData, dispatchCampaignData } = useContext(CycleContext);
- const { t } = useTranslation();
-
- return (
-
- {campaignData
- ?.find((i) => i?.active === true)
- ?.deliveries.map((_, index) => (
- onSubTabChange(_.deliveryIndex, index)}
- >
- {t(`CAMPAIGN_DELIVERY`)} {index + 1}
-
- ))}
-
- );
-};
-
-const MultiTab = ({ tabCount = 3, subTabCount = 2 }) => {
- const [activeTab, setActiveTab] = useState(0);
- const [activeSubTab, setActiveSubTab] = useState(0);
- const { campaignData, dispatchCampaignData } = useContext(CycleContext);
- const { t } = useTranslation();
- const tempSession = Digit.SessionStorage.get("HCM_CAMPAIGN_MANAGER_FORM_DATA");
- const handleTabChange = (tabIndex, index) => {
- dispatchCampaignData({
- type: "TAB_CHANGE_UPDATE",
- payload: { tabIndex: tabIndex, index: index }, // Your updated campaign data
- });
- setActiveTab(index);
- setActiveSubTab(0); // Reset sub-tab when changing the main tab
- };
-
- const handleSubTabChange = (subTabIndex, itemIndex) => {
- dispatchCampaignData({
- type: "SUBTAB_CHANGE_UPDATE",
- payload: { subTabIndex: subTabIndex }, // Your updated campaign data
- });
- };
-
- return (
- <>
-
- {t(
- `CAMPAIGN_PROJECT_${
- tempSession?.HCM_CAMPAIGN_TYPE?.projectType?.code
- ? tempSession?.HCM_CAMPAIGN_TYPE?.projectType?.code?.toUpperCase()
- : tempSession?.HCM_CAMPAIGN_TYPE?.projectType?.toUpperCase()
- }`
- )}
-
-
-
- >
- );
-};
-
-export default MultiTab;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/deliveryRule/index.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/deliveryRule/index.js
deleted file mode 100644
index ebdf2c5088f..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/deliveryRule/index.js
+++ /dev/null
@@ -1,531 +0,0 @@
-import React, { createContext, useContext, useEffect, useReducer, useState } from "react";
-import MultiTab from "./MultiTabcontext";
-import { Loader } from "@egovernments/digit-ui-react-components";
-// import { deliveryConfig } from "../../../configs/deliveryConfig";
-
-const CycleContext = createContext();
-
-function makeSequential(jsonArray, keyName) {
- return jsonArray.map((item, index) => ({
- ...item,
- [keyName]: index + 1,
- }));
-}
-
-function DeliverySetup({ onSelect, config, formData, control, tabCount = 2, subTabCount = 3, ...props }) {
- // Campaign Tab Skeleton function
- const [cycleData, setCycleData] = useState(config?.customProps?.sessionData?.["HCM_CAMPAIGN_CYCLE_CONFIGURE"]?.cycleConfigure);
- const saved = window.Digit.SessionStorage.get("HCM_CAMPAIGN_MANAGER_FORM_DATA")?.HCM_CAMPAIGN_DELIVERY_DATA?.deliveryRule;
- const selectedProjectType = window.Digit.SessionStorage.get("HCM_CAMPAIGN_MANAGER_FORM_DATA")?.HCM_CAMPAIGN_TYPE?.projectType?.code;
- const tenantId = Digit.ULBService.getCurrentTenantId();
- const searchParams = new URLSearchParams(location.search);
- const activeCycle = searchParams.get("activeCycle");
- const { isLoading: deliveryConfigLoading, data: filteredDeliveryConfig } = Digit.Hooks.useCustomMDMS(
- tenantId,
- "HCM-ADMIN-CONSOLE",
- [{ name: "deliveryConfig" }],
- {
- select: (data) => {
- const temp = data?.["HCM-ADMIN-CONSOLE"]?.deliveryConfig;
- return temp?.find((i) => i?.projectType === selectedProjectType);
- // return deliveryConfig?.find((i) => i?.projectType === selectedProjectType);
- },
- }
- );
- // const [filteredDeliveryConfig, setFilteredDeliveryConfig] = useState(deliveryConfig?.find((i) => i?.projectType === selectedProjectType));
- // useEffect(() => {
- // if (!deliveryConfigLoading) {
- // const temp = deliveryConfig?.find((i) => i?.projectType === selectedProjectType);
- // setFilteredDeliveryConfig(temp);
- // }
- // }, [deliveryConfigLoading, filteredDeliveryConfig]);
- // const filteredDeliveryConfig = deliveryConfig.find((i) => i.projectType === selectedProjectType);
- useEffect(() => {
- setCycleData(config?.customProps?.sessionData?.["HCM_CAMPAIGN_CYCLE_CONFIGURE"]?.cycleConfigure);
- }, [config?.customProps?.sessionData?.["HCM_CAMPAIGN_CYCLE_CONFIGURE"]?.cycleConfigure]);
-
- const generateTabsData = (tabs, subTabs) => {
- if (!saved || saved?.length === 0) {
- return [...Array(tabs)].map((_, tabIndex) => ({
- cycleIndex: `${tabIndex + 1}`,
- active: activeCycle == tabIndex + 1 ? true : tabIndex === 0 ? true : false,
- deliveries: [...Array(subTabs || 1)].map((_, subTabIndex) => ({
- deliveryIndex: `${subTabIndex + 1}`,
- active: subTabIndex === 0 ? true : false,
- deliveryRules:
- filteredDeliveryConfig?.projectType === "LLIN-mz"
- ? filteredDeliveryConfig?.deliveryConfig?.map((item, index) => {
- return {
- ruleKey: index + 1,
- delivery: {},
- attributes: item?.attributeConfig
- ? item?.attributeConfig?.map((i, c) => {
- if (i?.operatorValue === "IN_BETWEEN") {
- return {
- key: c + 1,
- attribute: { code: i?.attrValue },
- operator: { code: i?.operatorValue },
- toValue: i?.fromValue,
- fromValue: i?.toValue,
- };
- }
- return {
- key: c + 1,
- attribute: { code: i?.attrValue },
- operator: { code: i?.operatorValue },
- value: i?.value,
- };
- })
- : [{ key: 1, attribute: null, operator: null, value: "" }],
- // products: [],
- products: item?.productConfig
- ? item?.productConfig?.map((i, c) => ({
- ...i,
- }))
- : [],
- };
- })
- : filteredDeliveryConfig && filteredDeliveryConfig?.deliveryConfig?.[subTabIndex]
- ? filteredDeliveryConfig?.deliveryConfig?.[subTabIndex]?.conditionConfig?.map((item, index) => {
- if (item) {
- return {
- ruleKey: index + 1,
- delivery: {},
- deliveryType: item?.deliveryType,
- attributes: item?.attributeConfig
- ? item?.attributeConfig?.map((i, c) => {
- if (i?.operatorValue === "IN_BETWEEN") {
- return {
- key: c + 1,
- attribute: { code: i?.attrValue },
- operator: { code: i?.operatorValue },
- toValue: i?.fromValue,
- fromValue: i?.toValue,
- };
- }
- return {
- key: c + 1,
- attribute: { code: i?.attrValue },
- operator: { code: i?.operatorValue },
- value: i?.value,
- };
- })
- : [{ key: 1, attribute: null, operator: null, value: "" }],
- // products: [],
- products: item?.productConfig
- ? item?.productConfig?.map((i, c) => ({
- ...i,
- }))
- : [],
- };
- } else {
- return {
- ruleKey: index + 1,
- delivery: {},
- deliveryType: null,
- attributes: [{ key: 1, attribute: null, operator: null, value: "" }],
- products: [],
- };
- }
- })
- : [
- {
- ruleKey: 1,
- delivery: {},
- attributes:
- filteredDeliveryConfig && filteredDeliveryConfig?.attributeConfig
- ? filteredDeliveryConfig?.attributeConfig?.map((i, c) => ({
- key: c + 1,
- attribute: { code: i?.attrValue },
- operator: { code: i?.operatorValue },
- value: i?.value,
- }))
- : // : filteredDeliveryConfig?.projectType === "LLIN-mz"
- // ? filteredDeliveryConfig?.attributeConfig?.map((i, c) => ({ key: c + 1, attribute: i.attrValue, operator: null, value: "" }))
- [{ key: 1, attribute: null, operator: null, value: "" }],
- products: [],
- },
- ],
- })),
- }));
- }
- // if no change
- if (saved && saved?.length == tabs && saved?.[0]?.deliveries?.length === subTabs) {
- return saved.map((i, n) => {
- return {
- ...i,
- active: activeCycle ? (activeCycle == n + 1 ? true : false) : n === 0 ? true : false,
- };
- });
- }
- // if cycle number decrease
- if (saved?.length > tabs) {
- // const temp = saved;
- saved.splice(tabs);
- // return temp;
- }
- // if cycle number increase
- if (tabs > saved?.length) {
- // const temp = saved;
- for (let i = saved.length + 1; i <= tabs; i++) {
- const newIndex = i.toString();
- saved.push({
- cycleIndex: newIndex,
- active: false,
- deliveries: [...Array(subTabs || 1)].map((_, subTabIndex) => ({
- deliveryIndex: `${subTabIndex + 1}`,
- active: subTabIndex === 0,
- deliveryRules:
- filteredDeliveryConfig?.projectType === "LLIN-mz"
- ? filteredDeliveryConfig?.deliveryConfig?.map((item, index) => {
- return {
- ruleKey: index + 1,
- delivery: {},
- attributes: item?.attributeConfig
- ? item?.attributeConfig?.map((i, c) => {
- if (i?.operatorValue === "IN_BETWEEN") {
- return {
- key: c + 1,
- attribute: { code: i?.attrValue },
- operator: { code: i?.operatorValue },
- toValue: i?.fromValue,
- fromValue: i?.toValue,
- };
- }
- return {
- key: c + 1,
- attribute: { code: i?.attrValue },
- operator: { code: i?.operatorValue },
- value: i?.value,
- };
- })
- : [{ key: 1, attribute: null, operator: null, value: "" }],
- // products: [],
- products: item?.productConfig
- ? item?.productConfig?.map((i, c) => ({
- ...i,
- }))
- : [],
- };
- })
- : filteredDeliveryConfig && filteredDeliveryConfig?.deliveryConfig?.[subTabIndex]?.conditionConfig
- ? filteredDeliveryConfig?.deliveryConfig?.[subTabIndex]?.conditionConfig?.map((item, index) => {
- if (item) {
- return {
- ruleKey: index + 1,
- delivery: {},
- deliveryType: item?.deliveryType,
- attributes: item?.attributeConfig
- ? item?.attributeConfig?.map((i, c) => {
- if (i?.operatorValue === "IN_BETWEEN") {
- return {
- key: c + 1,
- attribute: { code: i?.attrValue },
- operator: { code: i?.operatorValue },
- toValue: i?.fromValue,
- fromValue: i?.toValue,
- };
- }
- return {
- key: c + 1,
- attribute: { code: i?.attrValue },
- operator: { code: i?.operatorValue },
- value: i?.value,
- };
- })
- : [{ key: 1, attribute: null, operator: null, value: "" }],
- // products: [],
- products: item?.productConfig
- ? item?.productConfig?.map((i, c) => ({
- ...i,
- }))
- : [],
- };
- } else {
- return {
- ruleKey: index + 1,
- delivery: {},
- deliveryType: null,
- attributes: [{ key: 1, attribute: null, operator: null, value: "" }],
- products: [],
- };
- }
- })
- : [
- {
- ruleKey: 1,
- delivery: {},
- deliveryType: null,
- attributes:
- // filteredDeliveryConfig?.projectType === "MR-DN"
- // ? filteredDeliveryConfig?.attributeConfig?.map((i, c) => ({
- // key: c + 1,
- // attribute: { code: i?.attrValue },
- // operator: { code: i?.operatorValue },
- // value: i?.value,
- // }))
- // : filteredDeliveryConfig?.projectType === "LLIN-mz"
- // ? filteredDeliveryConfig?.attributeConfig?.map((i, c) => ({
- // key: c + 1,
- // attribute: i.attrValue,
- // operator: null,
- // value: "",
- // }))
- // :
- [{ key: 1, attribute: null, operator: null, value: "" }],
- // products: [],
- products: [],
- },
- ],
- })),
- });
- }
- // return temp;
- }
- // if delivery number decrease
-
- saved.forEach((cycle) => {
- // Remove deliveries if there are more deliveries than the specified number
- if (cycle.deliveries.length > subTabs) {
- cycle.deliveries.splice(subTabs);
- }
-
- // Add deliveries if there are fewer deliveries than the specified number
- if (subTabs > cycle.deliveries.length) {
- for (let i = cycle.deliveries.length + 1; i <= subTabs; i++) {
- const newIndex = i.toString();
- cycle.deliveries.push({
- deliveryIndex: newIndex,
- active: false,
- deliveryRules:
- filteredDeliveryConfig?.projectType === "LLIN-mz"
- ? filteredDeliveryConfig?.deliveryConfig?.map((item, index) => {
- return {
- ruleKey: index + 1,
- delivery: {},
- attributes: item?.attributeConfig
- ? item?.attributeConfig?.map((i, c) => {
- if (i?.operatorValue === "IN_BETWEEN") {
- return {
- key: c + 1,
- attribute: { code: i?.attrValue },
- operator: { code: i?.operatorValue },
- toValue: i?.fromValue,
- fromValue: i?.toValue,
- };
- }
- return {
- key: c + 1,
- attribute: { code: i?.attrValue },
- operator: { code: i?.operatorValue },
- value: i?.value,
- };
- })
- : [{ key: 1, attribute: null, operator: null, value: "" }],
- // products: [],
- products: item?.productConfig
- ? item?.productConfig?.map((i, c) => ({
- ...i,
- }))
- : [],
- };
- })
- : [
- {
- ruleKey: 1,
- delivery: {},
- attributes: [{ key: 1, attribute: null, operator: null, value: "" }],
- products: [],
- },
- ],
- });
- }
- }
- });
-
- return saved;
- // if delivery number increase
-
- //if no above case
- };
-
- // Reducer function
- const campaignDataReducer = (state, action) => {
- switch (action.type) {
- case "GENERATE_CAMPAIGN_DATA":
- return generateTabsData(action.cycle, action.deliveries);
- case "UPDATE_CAMPAIGN_DATA":
- const changeUpdate = state.map((i) => {
- if (i.active) {
- const activeDelivery = i.deliveries.find((j) => j.active === true);
- if (activeDelivery) {
- return {
- ...i,
- deliveries: i.deliveries.map((j) => ({
- ...j,
- deliveryRules: j.active ? action.payload.currentDeliveryRules : j.deliveryRules,
- })),
- };
- }
- }
- return i;
- });
- return changeUpdate;
- case "TAB_CHANGE_UPDATE":
- const temp = state.map((i) => ({
- ...i,
- active: i.cycleIndex == action.payload.tabIndex ? true : false,
- }));
- return temp;
- // return action.payload;
- case "SUBTAB_CHANGE_UPDATE":
- const tempSub = state.map((camp, index) => {
- if (camp.active === true) {
- return {
- ...camp,
- deliveries: camp.deliveries.map((deliver) => ({
- ...deliver,
- active: deliver.deliveryIndex == action.payload.subTabIndex ? true : false,
- })),
- };
- }
- return camp;
- });
- return tempSub;
- case "ADD_DELIVERY_RULE":
- const updatedDeliveryRules = [
- ...action.payload.currentDeliveryRules,
- {
- ruleKey: action.payload.currentDeliveryRules.length + 1,
- delivery: {},
- attributes: [{ key: 1, attribute: null, operator: null, value: "" }],
- products: [],
- },
- ];
- const updatedData = state.map((i) => {
- if (i.active) {
- const activeDelivery = i.deliveries.find((j) => j.active);
- if (activeDelivery) {
- return {
- ...i,
- deliveries: i.deliveries.map((j) => ({
- ...j,
- deliveryRules: j.active ? updatedDeliveryRules : j.deliveryRules,
- })),
- };
- }
- }
- return i;
- });
- return updatedData;
- case "REMOVE_DELIVERY_RULE":
- const updatedDeleted = state.map((i) => {
- if (i.active) {
- const activeDelivery = i.deliveries.find((j) => j.active);
- const w = makeSequential(
- activeDelivery.deliveryRules.filter((j) => j.ruleKey != action.payload.item.ruleKey),
- "ruleKey"
- );
- if (activeDelivery) {
- return {
- ...i,
- deliveries: i.deliveries.map((j) => ({
- ...j,
- deliveryRules: j.active ? w : j.deliveryRules,
- })),
- };
- }
- }
- return i;
- });
- return updatedDeleted;
- case "UPDATE_DELIVERY_RULE":
- return action.payload;
- case "ADD_ATTRIBUTE":
- return action.payload;
- case "REMOVE_ATTRIBUTE":
- return action.payload;
- case "UPDATE_ATTRIBUTE":
- return action.payload;
- case "ADD_PRODUCT":
- const prodTemp = action.payload.productData.map((i) => ({ ...i, value: i?.value?.id, name: i?.value?.displayName }));
- const updatedState = state.map((cycle) => {
- if (cycle.active) {
- const updatedDeliveries = cycle.deliveries.map((dd) => {
- if (dd.active) {
- const updatedRules = dd.deliveryRules.map((rule) => {
- if (rule.ruleKey === action.payload.delivery.ruleKey) {
- return {
- ...rule,
- products: [...rule.products, ...prodTemp],
- };
- }
- return rule;
- });
- return {
- ...dd,
- deliveryRules: updatedRules,
- };
- }
- return dd;
- });
- return {
- ...cycle,
- deliveries: updatedDeliveries,
- };
- }
- return cycle;
- });
- return updatedState;
- case "REMOVE_PRODUCT":
- return action.payload;
- case "UPDATE_PRODUCT":
- return action.payload;
- default:
- return state;
- }
- };
-
- const [campaignData, dispatchCampaignData] = useReducer(
- campaignDataReducer,
- generateTabsData(cycleData?.cycleConfgureDate?.cycle, cycleData?.cycleConfgureDate?.deliveries)
- );
- const [executionCount, setExecutionCount] = useState(0);
-
- useEffect(() => {
- dispatchCampaignData({
- type: "GENERATE_CAMPAIGN_DATA",
- cycle: cycleData?.cycleConfgureDate?.cycle,
- deliveries: cycleData?.cycleConfgureDate?.deliveries,
- });
- }, [cycleData]);
-
- useEffect(() => {
- onSelect("deliveryRule", campaignData);
- }, [campaignData]);
-
- useEffect(() => {
- if (executionCount < 5) {
- onSelect("deliveryRule", campaignData);
- setExecutionCount((prevCount) => prevCount + 1);
- }
- });
-
- if (deliveryConfigLoading) {
- return ;
- }
- return (
-
-
-
- );
-}
-
-export default DeliverySetup;
-export { CycleContext };
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/index.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/index.js
deleted file mode 100644
index 2353f85fc50..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/pages/employee/index.js
+++ /dev/null
@@ -1,102 +0,0 @@
-import React, { useEffect } from "react";
-import { Switch, useLocation } from "react-router-dom";
-import { useTranslation } from "react-i18next";
-import { PrivateRoute, AppContainer, BreadCrumb } from "@egovernments/digit-ui-react-components";
-// import CampaignHeader from "../../components/CampaignHeader";
-import SetupCampaign from "./SetupCampaign";
-import SelectingBoundaries from "../../components/SelectingBoundaries";
-
-/**
- * The CampaignBreadCrumb function generates breadcrumb navigation for a campaign setup page in a React
- * application.
- * @returns The CampaignBreadCrumb component is returning a BreadCrumb component with the specified
- * crumbs array and spanStyle prop. The crumbs array contains two objects with path, content, and show
- * properties for each breadcrumb item. The spanStyle prop is set to { maxWidth: "min-content" }.
- */
-const CampaignBreadCrumb = ({ location, defaultPath }) => {
- const { t } = useTranslation();
- const search = useLocation().search;
- const pathVar = location.pathname.replace(defaultPath + "/", "").split("?")?.[0];
-
- const crumbs = [
- {
- path: `/${window?.contextPath}/employee`,
- content: t("CAMPAIGN_HOME"),
- show: true,
- },
- {
- path: pathVar === "my-campaign" ? "" : `/${window?.contextPath}/employee/campaign/my-campaign`,
- content: t("MY_CAMPAIGN"),
- show: pathVar === "my-campaign" ? true : false,
- },
- {
- path: pathVar === "setup-campaign" ? "" : `/${window?.contextPath}/employee/campaign/setup-campaign`,
- content: t("CREATE_NEW_CAMPAIGN"),
- show: pathVar === "setup-campaign" ? true : false,
- },
- ];
-
- return ;
-};
-
-/**
- * The `App` function in JavaScript defines a component that handles different routes and renders
- * corresponding components based on the path provided.
- * @returns The `App` component is returning a JSX structure that includes a `div` with a className of
- * "wbh-header-container" containing a `CampaignBreadCrumb` component and a `Switch` component. Inside
- * the `Switch` component, there are several `PrivateRoute` components with different paths and
- * corresponding components such as `UploadBoundaryData`, `CycleConfiguration`, `DeliveryRule`, `
- */
-const App = ({ path, BOUNDARY_HIERARCHY_TYPE }) => {
- const location = useLocation();
- const UploadBoundaryData = Digit?.ComponentRegistryService?.getComponent("UploadBoundaryData");
- const CycleConfiguration = Digit?.ComponentRegistryService?.getComponent("CycleConfiguration");
- const DeliveryRule = Digit?.ComponentRegistryService?.getComponent("DeliveryRule");
- const MyCampaign = Digit?.ComponentRegistryService?.getComponent("MyCampaign");
- const CampaignSummary = Digit?.ComponentRegistryService?.getComponent("CampaignSummary");
- const Response = Digit?.ComponentRegistryService?.getComponent("Response");
- const AddProduct = Digit?.ComponentRegistryService?.getComponent("AddProduct");
-
- useEffect(() => {
- if (window.location.pathname !== "/workbench-ui/employee/campaign/setup-campaign") {
- window.Digit.SessionStorage.del("HCM_CAMPAIGN_MANAGER_FORM_DATA");
- window.Digit.SessionStorage.del("HCM_CAMPAIGN_MANAGER_UPLOAD_ID");
- }
- if (window.location.pathname === "/workbench-ui/employee/campaign/response") {
- window.Digit.SessionStorage.del("HCM_CAMPAIGN_MANAGER_FORM_DATA");
- window.Digit.SessionStorage.del("HCM_CAMPAIGN_MANAGER_UPLOAD_ID");
- }
- return () => {
- if (window.location.pathname !== "/workbench-ui/employee/campaign/setup-campaign") {
- window.Digit.SessionStorage.del("HCM_CAMPAIGN_MANAGER_FORM_DATA");
- window.Digit.SessionStorage.del("HCM_CAMPAIGN_MANAGER_UPLOAD_ID");
- }
- };
- }, []);
- return (
-
-
- {window?.location?.pathname === "/workbench-ui/employee/campaign/add-product" ||
- window?.location?.pathname === "/workbench-ui/employee/campaign/response" ? null : (
-
- )}
- {/* */}
-
-
-
- } />
- } />
- } />
- } />
- } />
- } />
- } />
- } />
- } />
-
-
-
- );
-};
-
-export default App;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/TourSteps.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/TourSteps.js
deleted file mode 100644
index 5ab880c52cf..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/TourSteps.js
+++ /dev/null
@@ -1,144 +0,0 @@
-export const TourSteps = {
- '/workbench-ui/employee/workbench/manage-master-data':[
- {
- content:
- 'Welcome to Manage Master Data screen. Here you can search and update any master data that is configured for the logged in user tenant',
- target: '.manage-master-wrapper',
- disableBeacon: true,
- placement: 'bottom',
- title:"Manage Master Data"
- },
- {
- content:
- 'Select any module name where the master is present',
- target: '.wbh-mdms-module-name',
- disableBeacon: true,
- placement: 'center',
- title:"Manage Master Data"
- },
-
- {
- content:
- 'Select any master name where the master is present',
- target: '.wbh-mdms-master-name',
- disableBeacon: true,
- placement: 'center',
- title:"Manage Master Data"
- },
- ],
- '/workbench-ui/employee/workbench/mdms-search-v2':[
- {
- content:
- 'Welcome to the master data search screen. Here you can search the master data added under this master',
- target: '.search-wrapper',
- disableBeacon: true,
- placement: 'bottom',
- title:"Manage Master Data"
- },
- {
- content:
- 'Select any field value and enter the text by which data can be filtered',
- target: '.label-field-pair',
- disableBeacon: true,
- placement: 'bottom',
- title:"Manage Master Data"
- },
- {
- content:
- 'Filter the master data by clicking on this search by selecting any field and exact value',
- target: '.search-button-wrapper',
- disableBeacon: true,
- placement: 'bottom',
- title:"Manage Master Data"
- },
- {
- content:
- 'To add new master data under this master click on the Add Master Data button',
- target: '.mdms-add-btn',
- disableBeacon: true,
- placement: 'auto',
- title:"Manage Master Data"
- },
-
- ],
- '/workbench-ui/employee/workbench/mdms-add-v2':[
- {
- content:
- 'Welcome to the master data search screen. Here you can search the master data added under this master',
- target: '.field-string',
- disableBeacon: true,
- placement: 'bottom',
- title:"Manage Master Data"
- },
- {
- content:
- 'select the Reference master data',
- target: '.form-select ',
- disableBeacon: true,
- placement: 'bottom',
- title:"Manage Master Data"
- },
- {
- content:
- 'Fill all the details by clicking on the Add Master Data',
- target: '.submit-bar',
- disableBeacon: true,
- placement: 'auto',
- title:"Manage Master Data"
- },
-
- ],
- '/workbench-ui/employee/workbench/mdms-view':[
- {
- content:
- 'Welcome to the master data search screen. Here you can search the master data added under this master',
- target: '.action-bar-wrap',
- disableBeacon: true,
- placement: 'bottom',
- title:"Manage Master Data"
- },
- {
- content:
- 'select the Reference master data',
- target: '.menu-wrap',
- disableBeacon: true,
- placement: 'bottom',
- title:"Manage Master Data"
- }
- ],
- '/workbench-ui/employee/workbench/localisation-search':[
- {
- content:
- 'Welcome to the master data search screen. Here you can search the master data added under this master',
- target: '.search-wrapper',
- disableBeacon: true,
- placement: 'bottom',
- title:"Manage Master Data"
- },
- {
- content:
- 'Select any field value and enter the text by which data can be filtered',
- target: '.label-field-pair',
- disableBeacon: true,
- placement: 'bottom',
- title:"Manage Master Data"
- },
- {
- content:
- 'Filter the master data by clicking on this search by selecting any field and exact value',
- target: '.search-button-wrapper',
- disableBeacon: true,
- placement: 'bottom',
- title:"Manage Master Data"
- },
- {
- content:
- 'To add new master data under this master click on the Add Master Data button',
- target: '.mdms-add-btn',
- disableBeacon: true,
- placement: 'auto',
- title:"Manage Master Data"
- },
-
- ],
-}
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/downloadExcel.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/downloadExcel.js
deleted file mode 100644
index 978ea2bfd74..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/downloadExcel.js
+++ /dev/null
@@ -1,46 +0,0 @@
-import axios from "axios";
-
-/* Fetching sheet as json object from the API , converting them into blob and downloading it.
- * Way to use the function. Just import the funtion downloadExcelWithCustomName and pass the filestoreid and customName you want to download the file.
- * Rest this function will take care for you and download it in your system.
- *
- * Eg. ->
- * const handleDownload = (id, name) => {
- * downloadExcelWithCustomName({fileStoreId: id, customName: name});
- * }
- *
- */
-
-export const downloadExcelWithCustomName = ({ fileStoreId = null, customName = null }) => {
- const downloadExcel = (blob, fileName) => {
- const link = document.createElement("a");
- link.href = URL.createObjectURL(blob);
- link.download = fileName + ".xlsx";
- document.body.append(link);
- link.click();
- link.remove();
- setTimeout(() => URL.revokeObjectURL(link.href), 7000);
- };
-
- if (fileStoreId) {
- axios
- .get("/filestore/v1/files/id", {
- responseType: "arraybuffer",
- headers: {
- "Content-Type": "application/json",
- Accept: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
- "auth-token": Digit.UserService.getUser()?.["access_token"],
- },
- params: {
- tenantId: Digit.ULBService.getCurrentTenantId(),
- fileStoreId: fileStoreId,
- },
- })
- .then(async (res) => {
- downloadExcel(
- new Blob([res.data], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }),
- customName ? customName : "download"
- );
- });
- }
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/index.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/index.js
deleted file mode 100644
index 5e308bf82f7..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/campaign-manager/src/utils/index.js
+++ /dev/null
@@ -1,6 +0,0 @@
-import _ from "lodash";
-import { downloadExcelWithCustomName } from "./downloadExcel";
-
-export default {};
-export { downloadExcelWithCustomName };
-export const PRIMARY_COLOR = "#C84C0E";
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/package.json b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/package.json
deleted file mode 100644
index 6fcb736c4e5..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/package.json
+++ /dev/null
@@ -1,62 +0,0 @@
-{
- "name": "@egovernments/digit-ui-module-hcmmicroplanning",
- "version": "0.0.1",
- "description": "HCM-Microplanning",
- "main": "dist/index.js",
- "module": "dist/index.modern.js",
- "source": "src/Module.js",
- "files": [
- "dist"
- ],
- "scripts": {
- "start": "microbundle-crl watch --no-compress --format modern,cjs",
- "build": "microbundle-crl --compress --no-sourcemap --format cjs",
- "prepublish": "yarn build"
- },
- "peerDependencies": {
- "react": "17.0.2",
- "react-router-dom": "5.3.0"
- },
- "dependencies": {
- "@cyntler/react-doc-viewer": "1.10.3",
- "@egovernments/digit-ui-components": "0.0.2-beta.2",
- "@egovernments/digit-ui-react-components": "1.8.2-beta.4",
- "@egovernments/digit-ui-svg-components": "1.0.8",
- "@rjsf/core": "5.10.0",
- "@rjsf/utils": "5.10.0",
- "@rjsf/validator-ajv8": "5.10.0",
- "@turf/turf": "^6.5.0",
- "ajv": "^8.12.0",
- "axios": "^1.6.8",
- "chroma-js": "^2.4.2",
- "exceljs": "^4.4.0",
- "focus-trap-react": "^10.2.3",
- "geojson-validation": "^1.0.2",
- "jszip": "^3.10.1",
- "leaflet": "^1.9.4",
- "react": "17.0.2",
- "react-date-range": "^1.4.0",
- "react-dom": "17.0.2",
- "react-drag-drop-files": "^2.3.10",
- "react-hook-form": "6.15.8",
- "react-i18next": "11.16.2",
- "react-joyride": "2.5.5",
- "react-query": "3.6.1",
- "react-router-dom": "5.3.0",
- "react-select": "5.7.4",
- "safe-buffer": "^5.2.1",
- "shpjs": "^4.0.4",
- "uuid": "^9.0.1",
- "xlsx": "0.17.5"
- },
- "license": "MIT",
- "keywords": [
- "digit",
- "egov",
- "dpg",
- "digit-ui",
- "workbench",
- "workbench-hcm",
- "hcm-microplanning"
- ]
-}
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/Module.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/Module.js
deleted file mode 100644
index b27e7b19922..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/Module.js
+++ /dev/null
@@ -1,99 +0,0 @@
-import { Loader, TourProvider } from "@egovernments/digit-ui-react-components";
-import React from "react";
-import { useRouteMatch } from "react-router-dom";
-import EmployeeApp from "./pages/employee";
-import { CustomisedHooks } from "./hooks";
-import { UICustomizations } from "./configs/UICustomizations";
-// import WorkbenchCard from "./components/WorkbenchCard";
-import MicroplanningCard from "./components/MicroplanningCard";
-import MicroplanDetails from "./components/MicroplanDetails";
-import { ProviderContext } from "./utils/context";
-
-const MicroplanningModule = ({ stateCode, userType, tenants }) => {
- const tenantId = Digit.ULBService.getCurrentTenantId();
- const { data: BOUNDARY_HIERARCHY_TYPE } = Digit.Hooks.useCustomMDMS(tenantId, "HCM-ADMIN-CONSOLE", [{ name: "hierarchyConfig" }], {
- select: (data) => {
- return data?.["HCM-ADMIN-CONSOLE"]?.hierarchyConfig?.[0]?.hierarchy;
- },
- });
- const moduleCode = ["Microplanning", `boundary-${BOUNDARY_HIERARCHY_TYPE}`, "hcm-admin-schemas"];
- const { path, url } = useRouteMatch();
- const language = Digit.StoreData.getCurrentLanguage();
- const { isLoading, data: store } = Digit.Services.useStore({
- stateCode,
- moduleCode,
- language,
- });
-
- if (isLoading) {
- return ;
- }
-
- return (
-
-
-
-
-
- );
-};
-
-const componentsToRegister = {
- MicroplanningModule,
- MicroplanningCard,
- MicroplanDetails,
- // DigitJSONForm,
- // DSSCard: null, // TO HIDE THE DSS CARD IN HOME SCREEN as per workbench
- // HRMSCard // Overridden the HRMS card as per workbench
-};
-
-const overrideHooks = () => {
- Object.keys(CustomisedHooks).map((ele) => {
- if (ele === "Hooks") {
- Object.keys(CustomisedHooks[ele]).map((hook) => {
- Object.keys(CustomisedHooks[ele][hook]).map((method) => {
- setupHooks(hook, method, CustomisedHooks[ele][hook][method]);
- });
- });
- } else if (ele === "Utils") {
- Object.keys(CustomisedHooks[ele]).map((hook) => {
- Object.keys(CustomisedHooks[ele][hook]).map((method) => {
- setupHooks(hook, method, CustomisedHooks[ele][hook][method], false);
- });
- });
- } else {
- Object.keys(CustomisedHooks[ele]).map((method) => {
- setupLibraries(ele, method, CustomisedHooks[ele][method]);
- });
- }
- });
-};
-
-/* To Overide any existing hook we need to use similar method */
-const setupHooks = (HookName, HookFunction, method, isHook = true) => {
- window.Digit = window.Digit || {};
- window.Digit[isHook ? "Hooks" : "Utils"] = window.Digit[isHook ? "Hooks" : "Utils"] || {};
- window.Digit[isHook ? "Hooks" : "Utils"][HookName] = window.Digit[isHook ? "Hooks" : "Utils"][HookName] || {};
- window.Digit[isHook ? "Hooks" : "Utils"][HookName][HookFunction] = method;
-};
-/* To Overide any existing libraries we need to use similar method */
-const setupLibraries = (Library, service, method) => {
- window.Digit = window.Digit || {};
- window.Digit[Library] = window.Digit[Library] || {};
- window.Digit[Library][service] = method;
-};
-
-/* To Overide any existing config/middlewares we need to use similar method */
-const updateCustomConfigs = () => {
- setupLibraries("Customizations", "commonUiConfig", { ...window?.Digit?.Customizations?.commonUiConfig, ...UICustomizations });
-};
-
-const initMicroplanningComponents = () => {
- overrideHooks();
- updateCustomConfigs();
- Object.entries(componentsToRegister).forEach(([key, value]) => {
- Digit.ComponentRegistryService.setComponent(key, value);
- });
-};
-
-export { initMicroplanningComponents };
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/CommonComponents.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/CommonComponents.js
deleted file mode 100644
index a358dbbedb1..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/CommonComponents.js
+++ /dev/null
@@ -1,61 +0,0 @@
-import { AutoRenew, Close, FileDownload } from "@egovernments/digit-ui-svg-components";
-import React, { useCallback } from "react";
-import PropTypes from "prop-types";
-
-export const ButtonType1 = (props) => {
- return (
-
- );
-};
-
-ButtonType1.propTypes = {
- text: PropTypes.string.isRequired,
-};
-
-export const ButtonType2 = (props) => {
- return (
-
- {props.showDownloadIcon && (
-
-
-
- )}
-
{props.text}
-
- );
-};
-
-ButtonType2.propTypes = {
- text: PropTypes.string.isRequired,
- showDownloadIcon: PropTypes.bool,
-};
-
-export const ModalHeading = (props) => {
- return (
-
- {props.label}
-
- );
-};
-
-ModalHeading.propTypes = {
- label: PropTypes.string.isRequired,
- className: PropTypes.string,
- style: PropTypes.object,
-};
-
-export const CloseButton = ({ clickHandler, style = {} }) => {
- return (
-
- {" "}
-
-
- );
-};
-
-CloseButton.propTypes = {
- clickHandler: PropTypes.func.isRequired,
- style: PropTypes.object,
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/CustomScaleControl.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/CustomScaleControl.js
deleted file mode 100644
index f2deacbd46d..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/CustomScaleControl.js
+++ /dev/null
@@ -1,41 +0,0 @@
-import React, { useEffect, useState } from "react";
-
-const CustomScaleControl = ({ map }) => {
- if (!map) return null;
- const [scaleText, setScaleText] = useState("");
- // Function to calculate and update the scale text
- const updateScale = () => {
- // Calculate the scale based on the map's current zoom level
- const maxWidthMeters = map.containerPointToLatLng([0, map.getSize().y]).distanceTo(map.containerPointToLatLng([100, map.getSize().y]));
- const scale = maxWidthMeters / 1000; // Convert to kilometers
-
- // Format the scale text
- const scaleTextData = scale < 1 ? `${Math.round(scale * 1000)} m` : `${Math.round(Math.round(scale.toFixed(0) / 10) * 10)} km`;
-
- // Update the scale text in the container element
- setScaleText(scaleTextData);
- };
-
- // Effect to update the scale text when the map component mounts and on map zoom change
- useEffect(() => {
- // Update the scale text initially
- updateScale();
-
- // Register the map's zoom events to update the scale text
- map.on("zoomend", updateScale);
-
- // Clean up event listener when the component unmounts
- return () => {
- map.off("zoomend", updateScale);
- };
- }, [map]);
-
- return (
-
- );
-};
-
-export default CustomScaleControl;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/Hypothesis.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/Hypothesis.js
deleted file mode 100644
index c2cf8bac4fb..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/Hypothesis.js
+++ /dev/null
@@ -1,607 +0,0 @@
-import React, { useState, useEffect, useCallback, Fragment, useRef } from "react";
-import { useTranslation } from "react-i18next";
-import { Trash } from "@egovernments/digit-ui-svg-components";
-import { CloseButton, ModalHeading } from "./CommonComponents";
-import { Dropdown, TextInput, Toast } from "@egovernments/digit-ui-components";
-import { useMyContext } from "../utils/context";
-import { tourSteps } from "../configs/tourSteps";
-import { v4 as uuidv4 } from "uuid";
-import { PlusWithSurroundingCircle } from "../icons/Svg";
-import { PRIMARY_THEME_COLOR } from "../configs/constants";
-import { Button, Modal } from "@egovernments/digit-ui-react-components";
-const page = "hypothesis";
-
-const Hypothesis = ({
- campaignType = Digit.SessionStorage.get("microplanHelperData")?.campaignData?.projectType,
- microplanData,
- setMicroplanData,
- checkDataCompletion,
- setCheckDataCompletion,
- currentPage,
- pages,
- setToast,
-}) => {
- const { t } = useTranslation();
-
- // States
- const [editable, setEditable] = useState(true);
- const [modal, setModalState] = useState("none");
- const [assumptions, setAssumptions] = useState([]);
- const [hypothesisAssumptionsList, setHypothesisAssumptionsList] = useState([]);
- const [itemForDeletion, setItemForDeletion] = useState();
- const [exampleOption, setExampleOption] = useState("");
- // const [toast, setToast] = useState();
- const [autofillHypothesis, setAutofillHypothesis] = useState([]);
- const { state, dispatch } = useMyContext();
- const [orignalHypothesisCount, setOrignalHypothesisCount] = useState(0);
-
- // Set TourSteps
- useEffect(() => {
- const tourData = tourSteps(t)?.[page] || {};
- if (state?.tourStateData?.name === page) return;
- dispatch({
- type: "SETINITDATA",
- state: { tourStateData: tourData },
- });
- }, []);
-
- const setModal = (modalString) => {
- const elements = document.querySelectorAll(".popup-wrap-rest-unfocus");
- elements.forEach((element) => {
- element.classList.toggle("popup-wrap-rest-unfocus-active");
- });
- setModalState(modalString);
- };
-
- // UseEffect to extract data on first render
- useEffect(() => {
- if (pages) {
- const previouspage = pages[currentPage?.id - 1];
- if (previouspage?.checkForCompleteness && !microplanData?.status?.[previouspage?.name]) setEditable(false);
- else setEditable(true);
- }
- if (microplanData?.hypothesis) {
- const temp = microplanData?.hypothesis;
- setAssumptions(temp);
- }
-
- fetchDataAndUpdateState();
- }, []);
-
- const fetchDataAndUpdateState = useCallback(() => {
- const hypothesisAssumptions = state?.HypothesisAssumptions || [];
- const temp = hypothesisAssumptions.find((item) => item.campaignType === campaignType);
- if (!temp?.assumptions) return;
-
- const hypothesisAssumptionsList = Array.isArray(temp.assumptions) ? temp.assumptions : [];
- setOrignalHypothesisCount(hypothesisAssumptionsList.length);
- setExampleOption(hypothesisAssumptionsList.length !== 0 ? hypothesisAssumptionsList[0] : "");
-
- const currentHypothesis = microplanData?.hypothesis || assumptions;
- const newAssumptions = setAutofillHypothesisData(hypothesisAssumptionsList, currentHypothesis, setAssumptions);
-
- const newHypothesislist = filterHypothesisList(
- newAssumptions.length !== 0 ? newAssumptions : microplanData.hypothesis,
- hypothesisAssumptionsList
- );
- setHypothesisAssumptionsList(newHypothesislist);
- }, [campaignType, microplanData, state, assumptions, setAssumptions]);
-
- // UseEffect for checking completeness of data before moveing to next section
- useEffect(() => {
- if (!assumptions || checkDataCompletion !== "true" || !setCheckDataCompletion) return;
- // uncomment to activate data change save check
- // if (!microplanData?.hypothesis || !_.isEqual(assumptions, microplanData.hypothesis)) setModal("data-change-check");
- // else
- updateData(true);
- }, [checkDataCompletion]);
-
- // UseEffect to store current data
- useEffect(() => {
- if (!assumptions || !setMicroplanData) return;
- setMicroplanData((previous) => ({ ...previous, hypothesis: assumptions }));
- }, [assumptions]);
-
- // UseEffect to add a event listener for keyboard
- useEffect(() => {
- window.addEventListener("keydown", handleKeyPress);
-
- return () => window.removeEventListener("keydown", handleKeyPress);
- }, [modal]);
-
- const handleKeyPress = (event) => {
- // if (modal !== "upload-guidelines") return;
- if (["x", "Escape"].includes(event.key)) {
- // Perform the desired action when "x" or "esc" is pressed
- // if (modal === "upload-guidelines")
- setCheckDataCompletion("false");
- setModal("none");
- }
- };
-
- // check if data has changed or not
- const updateData = useCallback(
- (check) => {
- if (!assumptions || !setMicroplanData) return;
- if (check) {
- if (assumptions.some((item) => item.active && parseFloat(item.value) === 0)) {
- setToast({ state: "error", message: t("ERROR_HYPOTHESIS_VALUE_SHOULD_NOT_BE_ZERO") });
- setCheckDataCompletion("false");
- return;
- }
- let newAssumptions = assumptions.map((item) => {
- if (parseFloat(item.value) === 0) {
- return { ...item, value: 0.01 };
- }
- return item;
- });
- setMicroplanData((previous) => ({ ...previous, hypothesis: newAssumptions }));
- setAssumptions(newAssumptions);
- let checkValid = validateAssumptions(assumptions);
- checkValid = checkValid && assumptions.filter((subItem) => subItem?.active).length !== 0;
- if (checkValid) setCheckDataCompletion("valid");
- else setCheckDataCompletion("invalid");
- } else {
- let checkValid = microplanData?.hypothesis?.every((item) => Object.values(item).every((data) => data !== ""));
- checkValid = checkValid && assumptions.length !== 0;
- if (checkValid) setCheckDataCompletion("valid");
- else setCheckDataCompletion("invalid");
- }
- },
- [assumptions, setMicroplanData, microplanData, setCheckDataCompletion]
- );
-
- const validateAssumptions = useCallback((assumptions) => {
- return assumptions.filter((item) => item?.active).every((item) => Object.values(item).every((data) => data !== "")) && assumptions.length !== 0;
- }, []);
-
- const cancelUpdateData = useCallback(() => {
- setCheckDataCompletion("false");
- setModal("none");
- }, [setCheckDataCompletion, setModal]);
-
- const closeModal = useCallback(() => {
- setModal("none");
- }, []);
-
- // Function to Delete an assumption
- const deleteAssumptionHandlerCallback = useCallback(() => {
- deleteAssumptionHandler(itemForDeletion, setItemForDeletion, setAssumptions, setHypothesisAssumptionsList, setToast, t);
- closeModal();
- }, [itemForDeletion, deleteAssumptionHandler, setItemForDeletion, setAssumptions, setHypothesisAssumptionsList, closeModal, setToast, t]);
-
- const sectionClass = `jk-header-btn-wrapper hypothesis-section ${editable ? "" : "non-editable-component"} popup-wrap-rest-unfocus `;
-
- return (
- <>
-
-
- {/* NonInterractable Section */}
-
- {/* Interractable Section that includes the example as well as the assumptions */}
-
-
-
}
- className="add-button"
- onButtonClick={() => addAssumptionsHandler(setAssumptions)}
- label={t("ADD_ROW")}
- isDisabled={assumptions?.filter((item) => item.active)?.length === orignalHypothesisCount}
- />
-
-
- {modal === "delete-conformation" && (
-
}
- actionCancelLabel={t("YES")}
- actionCancelOnSubmit={deleteAssumptionHandlerCallback}
- actionSaveLabel={t("NO")}
- actionSaveOnSubmit={closeModal}
- >
-
-
{t("HYPOTHESIS_INSTRUCTIONS_DELETE_ENTRY_CONFIRMATION")}
-
-
- )}
-
- >
- );
-};
-
-// Function to add a new assumption
-const addAssumptionsHandler = (setAssumptions) => {
- const uuid = uuidv4();
- setAssumptions((previous) => [
- ...previous,
- {
- id: uuid,
- // previous.length ? previous[previous.length - 1].id + 1 : 0,
- key: "",
- value: "",
- active: true,
- },
- ]);
-};
-
-// Defination for NonInterractable Section
-const NonInterractableSection = React.memo(({ t }) => {
- return (
-
-
{t("HEADING_HYPOTHESIS")}
-
{t("INSTRUCTION_HYPOTHESIS")}
-
- );
-});
-
-// Defination for NonInterractable Section
-const InterractableSection = React.memo(
- ({ assumptions, setAssumptions, hypothesisAssumptionsList, setHypothesisAssumptionsList, setModal, setItemForDeletion, exampleOption, t }) => {
- const itemRefs = useRef([]);
- const [expandedIndex, setExpandedIndex] = useState(null);
- const scrollContainerRef = useRef(null);
- const [renderCycle, setRenderCycle] = useState(0);
-
- useEffect(() => {
- if (expandedIndex !== null) {
- setRenderCycle(0); // Reset render cycle count when expandedIndex changes
- }
- }, [expandedIndex]);
-
- useEffect(() => {
- // Scroll to the expanded item after the state has updated and the DOM has re-rendered
- if (renderCycle < 2) {
- setRenderCycle((prev) => prev + 1); // Increment render cycle count
- } else if (expandedIndex !== null && itemRefs.current[expandedIndex]) {
- try {
- const parentElement = itemRefs.current[expandedIndex];
- const childElement = itemRefs.current[expandedIndex].children[1];
-
- if (parentElement) {
- const scrollContainer = scrollContainerRef.current;
- const parentRect = parentElement.getBoundingClientRect();
- const containerRect = scrollContainer.getBoundingClientRect();
-
- // Calculate the offset from the top of the container
- const offset = parentRect.top - containerRect.top;
-
- // Scroll the container
- scrollContainer.scrollTo({
- top: scrollContainer.scrollTop + offset - 10,
- behavior: "smooth",
- });
- }
-
- if (childElement) {
- childElement.focus();
- }
- } catch (error) {
- console.error("Error scrolling to element:", error);
- }
- }
- }, [renderCycle, expandedIndex]);
-
- useEffect(() => {
- if (expandedIndex !== null) {
- const observer = new MutationObserver(() => {
- setRenderCycle((prev) => prev + 1); // Trigger render cycle when the DOM changes
- });
-
- if (itemRefs.current[expandedIndex]) {
- observer.observe(itemRefs.current[expandedIndex], { childList: true, subtree: true });
- }
-
- return () => observer.disconnect();
- }
- }, [expandedIndex]);
-
- const toggleExpand = (index) => {
- setExpandedIndex(index === expandedIndex ? null : index);
- };
-
- // Handler for deleting an assumption on conformation
- const deleteHandler = useCallback(
- (item) => {
- setModal("delete-conformation");
- setItemForDeletion(item);
- },
- [setModal, setItemForDeletion]
- );
-
- return (
-
-
-
-
-
-
-
-
deleteHandler(item)}>
- {Trash && }
- {t("DELETE")}
-
-
-
- {assumptions
- ?.filter((item) => item.active)
- ?.map((item, index) => (
-
item.active)?.length - 1 ? "last-container" : ""
- } `}
- >
-
{
- itemRefs.current[index] = el;
- }}
- onClick={() => {
- toggleExpand(index);
- }}
- >
-
-
-
-
-
-
-
deleteHandler(item)}
- onKeyDown={(e) => e.key === "Enter" && deleteHandler(item)}
- aria-label={t("DELETE")}
- role="button"
- >
- {Trash && }
- {t("DELETE")}
-
-
-
- ))}
-
-
- );
- }
-);
-
-const Example = ({ exampleOption, t }) => {
- return (
-
-
{t("EXAMPLE")}
-
-
-
{t("KEY")}
-
-
{t("HYPOTHESIS_KEY_HELP_TEXT")}
-
-
-
{t("VALUE")}
-
-
{t("HYPOTHESIS_VALUE_HELP_TEXT")}
-
-
-
- );
-};
-
-const deleteAssumptionHandler = (item, setItemForDeletion, setAssumptions, setHypothesisAssumptionsList, setToast, t) => {
- let add = true;
- setAssumptions((previous) => {
- if (!previous.length) return [];
- if (previous.filter((item) => item.active)?.length <= 1) {
- setToast({ state: "error", message: t("ERROR_CANNOT_DELETE_LAST_HYPOTHESIS") });
- add = false;
- return previous;
- }
- // const filteredData = previous.filter((data) => data.id !== item.id);
- const deletionElementIndex = previous.findIndex((data) => data.id === item.id);
- const filteredData = previous.map((data, index) => (index === deletionElementIndex ? { ...data, active: false } : data));
- return filteredData || [];
- });
- if (add && item && item.key)
- setHypothesisAssumptionsList((previous) => {
- if (!previous.includes(item.key)) return [...previous, item.key];
- return previous; // Return previous array if key already exists
- });
- setItemForDeletion();
-};
-
-const Select = React.memo(({ item, assumptions, setAssumptions, disabled = false, options, setOptions, t }) => {
- const [selected, setSelected] = useState();
- const [filteredOptions, setFilteredOptions] = useState([]);
-
- useEffect(() => {
- if (item?.key) setSelected({ code: item.key });
- }, [item]);
-
- useEffect(() => {
- if (!options) return;
- const filteredOptions = options.length ? options : [];
- if (item?.key && !filteredOptions.includes(item.key)) {
- setFilteredOptions([item.key, ...filteredOptions]);
- } else setFilteredOptions(filteredOptions);
- }, [options]);
-
- const selectChangeHandler = useCallback(
- (e) => {
- const existingEntry = assumptions.find((item) => item?.active && item?.key === e?.code);
- if (existingEntry) return;
- const newDataSegment = {
- ...item,
- id: item.id,
- key: e?.code,
- value: item.value,
- };
- setAssumptions((previous) => {
- const filteredAssumptionsList = previous.map((data) => {
- if (data.id === item.id) return newDataSegment;
- return data;
- });
- return filteredAssumptionsList;
- });
-
- setOptions((previous) => {
- let newOptions = previous.filter((item) => item !== e?.code);
- if (selected && !newOptions.includes(selected?.code)) newOptions.unshift(selected?.code);
- return newOptions;
- });
- },
- [assumptions, item, selected, setAssumptions, setOptions]
- );
-
- return (
- ({ code: item }))}
- selected={selected}
- optionKey="code"
- select={selectChangeHandler}
- // style={{ width: "100%", backgroundColor: "rgb(0,0,0,0)", position:"sticky" }}
- optionCardStyles={{ position: "absolute" }}
- placeholder={t("SELECT_OPTION")}
- showToolTip={true}
- />
- );
-});
-
-const Input = React.memo(({ item, setAssumptions, t, disabled = false }) => {
- const [inputValue, setInputValue] = useState("");
-
- useEffect(() => {
- if (item) setInputValue(item.value);
- }, [item]);
-
- const inputChangeHandler = useCallback(
- (e) => {
- if (e.target.value.includes("+") || e.target.value.includes("e")) return;
- if ((e.target.value < 0 || e.target.value > 10000000000) && e.target.value !== "") return;
- let value;
- const decimalIndex = e.target.value.indexOf(".");
- if (decimalIndex !== -1) {
- const numDecimals = e.target.value.length - decimalIndex - 1;
- value = e.target.value;
- if (numDecimals <= 2) {
- value = e.target.value;
- } else if (numDecimals > 2) {
- value = value.substring(0, decimalIndex + 3);
- }
- } else value = Number.parseFloat(e.target.value);
-
- setInputValue(!Number.isNaN(value) ? value : "");
- const newDataSegment = {
- ...item,
- id: item.id,
- key: item.key,
- value: !Number.isNaN(value) ? value : "",
- };
- setAssumptions((previous) => {
- const filteredAssumptionsList = previous.map((data) => {
- if (data.id === item.id) {
- return newDataSegment;
- }
- return data;
- });
- return filteredAssumptionsList;
- });
- },
- [item, setAssumptions]
- );
-
- return (
-
- );
-});
-
-const setAutofillHypothesisData = (autofillHypothesis, assumptions, setAssumptions) => {
- if (assumptions?.length !== 0) return [];
- let newAssumptions = [];
- for (let i in autofillHypothesis) {
- const uuid = uuidv4();
- newAssumptions.push({
- id: uuid,
- key: autofillHypothesis[Number(i)],
- value: "",
- active: true,
- });
- }
- setAssumptions(newAssumptions);
- return newAssumptions;
-};
-
-const filterHypothesisList = (assumptions, hypothesisList) => {
- let alreadySelectedHypothesis = assumptions.filter((item) => item?.active).map((item) => item?.key) || [];
- return hypothesisList.filter((item) => !alreadySelectedHypothesis.includes(item));
-};
-
-export default Hypothesis;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/JsonPreviewInExcelForm.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/JsonPreviewInExcelForm.js
deleted file mode 100644
index 23bbef8ae29..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/JsonPreviewInExcelForm.js
+++ /dev/null
@@ -1,113 +0,0 @@
-import { Button, DownloadIcon, SVG } from "@egovernments/digit-ui-react-components";
-import React, { useState } from "react";
-import { useTranslation } from "react-i18next";
-import { PRIMARY_THEME_COLOR } from "../configs/constants";
-
-export const JsonPreviewInExcelForm = (props) => {
- const { t } = useTranslation();
- const sheetsData = props?.sheetsData;
- const [currentSheetName, setCurrentSheetName] = useState(Object.keys(sheetsData).length > 0 ? Object.keys(sheetsData)[0] : undefined);
- return (
-
-
- }
- type="button"
- onButtonClick={() => props?.onBack()}
- />
- }
- type="button"
- onButtonClick={() => props?.onDownload()}
- />
-
-
- {props?.errorLocationObject?.[currentSheetName] &&
{t("USER_DIRECTIONS_FOR_ERROR_MESSAGE")}
}
- {/* {Object.entries(sheetsData).map(([sheetName, sheetData], index) => ( */}
-
-
-
-
- {sheetsData?.[currentSheetName]?.[0]
- ?.filter((header) => header)
- .map((header) => (
- {t(header)} |
- ))}
-
-
-
- {sheetsData?.[currentSheetName]?.slice(1).map((rowData, rowIndex) => (
-
- {Object.values(sheetsData?.[currentSheetName]?.[0])?.map((_, cellIndex) => {
- const headerName = sheetsData?.[currentSheetName]?.[0]?.[cellIndex];
- const error = headerName ? props?.errorLocationObject?.[currentSheetName]?.[rowIndex]?.[headerName] : undefined;
- let convertedError;
- if (typeof error?.[0] === "object") {
- let { error: actualError, ...otherProperties } = error[0];
- convertedError = t(actualError, otherProperties?.values);
- } else {
- convertedError = t(error);
- }
- const rowHasError =
- typeof props?.errorLocationObject?.[currentSheetName]?.[rowIndex] === "object"
- ? Object.keys(props?.errorLocationObject?.[currentSheetName]?.[rowIndex]).length !== 0
- : undefined;
- return (
-
- {cellIndex === 0 && rowHasError && }
-
- {rowData[cellIndex] || rowData[cellIndex] === 0 ? rowData[cellIndex] : ""}
- |
- );
- })}
-
- ))}
-
-
-
-
- {Object.entries(sheetsData).map(([sheetName, sheetData], index) => (
- {
- setCurrentSheetName(sheetName);
- }}
- style={{
- ...(props?.errorLocationObject?.[sheetName] ? { backgroundColor: "rgb(250,148,148)", color: "black" } : {}),
- }}
- >
- {sheetName}
-
- ))}
-
- {/* ))} */}
-
-
- );
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/Mapping.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/Mapping.js
deleted file mode 100644
index 75f953c8804..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/Mapping.js
+++ /dev/null
@@ -1,445 +0,0 @@
-// Importing necessary modules
-import { Card, Header } from "@egovernments/digit-ui-components";
-import L from "leaflet";
-import "leaflet/dist/leaflet.css";
-import React, { useCallback, useEffect, useRef, useState, Fragment } from "react";
-import { useTranslation } from "react-i18next";
-import ZoomControl from "./ZoomControl";
-import CustomScaleControl from "./CustomScaleControl";
-import * as DigitSvgs from "@egovernments/digit-ui-svg-components";
-import { LoaderWithGap } from "@egovernments/digit-ui-react-components";
-import { tourSteps } from "../configs/tourSteps";
-import { useMyContext } from "../utils/context";
-import {
- MapFilterIndex,
- MapChoroplethIndex,
- ChoroplethSelection,
- FilterSection,
- BoundarySelection,
- BaseMapSwitcher,
-} from "./MappingHelperComponents";
-import {
- enableMapInteractions,
- disableMapInteractions,
- removeAllLayers,
- filterBoundarySelection,
- findBounds,
- addGeojsonToMap,
- addFilterProperties,
- addChoroplethProperties,
- prepareGeojson,
- extractGeoData,
-} from "../utils/mappingUtils";
-
-const page = "mapping";
-
-// Mapping component definition
-const Mapping = ({
- campaignType = Digit.SessionStorage.get("microplanHelperData")?.campaignData?.projectType,
- microplanData,
- setMicroplanData,
- checkDataCompletion,
- setCheckDataCompletion,
- currentPage,
- pages,
- setToast,
- ...props
-}) => {
- //fetch campaign data
- const { id = "" } = Digit.Hooks.useQueryParams();
- const { isLoading: isCampaignLoading, data: campaignData } = Digit.Hooks.microplan.useSearchCampaign(
- {
- CampaignDetails: {
- tenantId: Digit.ULBService.getCurrentTenantId(),
- ids: [id],
- },
- },
- {
- enabled: !!id,
- }
- );
-
- // request body for boundary hierarchy api
- var reqCriteria = {
- url: `/boundary-service/boundary-hierarchy-definition/_search`,
- params: {},
- body: {
- BoundaryTypeHierarchySearchCriteria: {
- tenantId: Digit.ULBService.getStateId(),
- // hierarchyType: "Microplan",
- hierarchyType: campaignData?.hierarchyType,
- },
- },
- config: {
- enabled: !!campaignData?.hierarchyType,
- select: (data) => {
- return (
- data?.BoundaryHierarchy?.[0]?.boundaryHierarchy?.map((item) => ({
- ...item,
- parentBoundaryType: item?.parentBoundaryType
- ? `${campaignData?.hierarchyType}_${Digit.Utils.microplan.transformIntoLocalisationCode(item?.parentBoundaryType)}`
- : null,
- boundaryType: `${campaignData?.hierarchyType}_${Digit.Utils.microplan.transformIntoLocalisationCode(item?.boundaryType)}`,
- })) || {}
- );
- },
- },
- };
- const { isLoading: ishierarchyLoading, data: hierarchy } = Digit.Hooks.useCustomAPIHook(reqCriteria);
- // request body for boundary hierarchy api
- var reqCriteria = {
- url: `/boundary-service/boundary/_search`,
- params: { codes: Digit.ULBService.getCurrentTenantId(), tenantId: Digit.ULBService.getCurrentTenantId() },
- body: {},
- config: {
- select: (data) => {
- return data?.Boundary || {};
- },
- },
- };
- const { isLoading: isBoundaryLoading, data: Boundary } = Digit.Hooks.useCustomAPIHook(reqCriteria);
-
- // Setting up state variables
- const [editable, setEditable] = useState(true);
- const { t } = useTranslation();
- var [map, setMap] = useState(null);
- var [_mapNode, set__mapNode] = useState("map");
- const [layers, setLayer] = useState([]);
- const [validationSchemas, setValidationSchemas] = useState([]);
- const [filterDataOrigin, setFilterDataOrigin] = useState({});
- const [dataAvailability, setDataAvailability] = useState("true");
- // const [toast, setToast] = useState();
- const [baseMaps, setBaseMaps] = useState({});
- const [selectedBaseMap, setSelectedBaseMap] = useState({});
- const [selectedBaseMapName, setSelectedBaseMapName] = useState("");
- const [showBaseMapSelector, setShowBaseMapSelector] = useState(false);
- const [boundaryData, setBoundaryData] = useState({}); // State for boundary data
- const [filterData, setFilterData] = useState({}); // State for facility data
- const [boundarySelections, setBoundarySelections] = useState({});
- const [isboundarySelectionSelected, setIsboundarySelectionSelected] = useState(false);
- const { state, dispatch } = useMyContext();
- const [filterPropertyNames, setFilterPropertyNames] = useState();
- const [filterProperties, setFilterProperties] = useState();
- const [showFilterOptions, setShowFilterOptions] = useState(false);
- const [filterSelections, setFilterSelections] = useState([]);
- const [choroplethProperties, setChoroplethProperties] = useState([]);
- const [showChoroplethOptions, setShowChoroplethOptions] = useState(false);
- const [choroplethProperty, setChoroplethProperty] = useState();
- const [dataCompleteness, setDataCompleteness] = useState();
- const basemapRef = useRef();
- const filterBoundaryRef = useRef();
- const showChoroplethOptionRef = useRef();
- const showFilterOptionRef = useRef();
- const [loader, setLoader] = useState(false);
-
- // Set TourSteps
- useEffect(() => {
- const tourData = tourSteps(t)?.[page] || {};
- if (state?.tourStateData?.name === page) return;
- dispatch({
- type: "SETINITDATA",
- state: { tourStateData: tourData },
- });
- }, []);
-
- // Effect to initialize map when data is fetched
- useEffect(() => {
- if (!state || !Boundary) return;
- const UIConfiguration = state?.UIConfiguration;
- if (UIConfiguration) {
- const filterDataOriginList = UIConfiguration.find((item) => item.name === "mapping");
- setFilterDataOrigin(filterDataOriginList);
- }
- const BaseMapLayers = state?.BaseMapLayers;
- const schemas = state?.Schemas;
- if (schemas) setValidationSchemas(schemas);
- if (!BaseMapLayers || (BaseMapLayers && BaseMapLayers.length === 0)) return;
- let baseMaps = {};
- let defaultBaseMap = undefined;
- BaseMapLayers.forEach((item) => {
- if (item.url) {
- const layer = L.tileLayer(item.url, {
- minZoom: item?.minZoom,
- maxZoom: item?.maxZoom,
- attribution: item?.attribution,
- });
- baseMaps[item?.name] = {
- metadata: item,
- layer,
- };
- if (!defaultBaseMap)
- defaultBaseMap = {
- name: item?.name,
- layer,
- };
- }
- });
- setSelectedBaseMapName(defaultBaseMap?.name);
- setBaseMaps(baseMaps);
- if (!map) {
- init(_mapNode, defaultBaseMap, Boundary);
- }
- }, [Boundary]);
-
- useEffect(() => {
- if (map && filterDataOrigin && Object.keys(filterDataOrigin).length !== 0) {
- setLoader("LOADING");
- // Check if all the data is present or not, if it is then extract it in a format that can be used for mapping and other mapping related operations
- extractGeoData(
- campaignType,
- microplanData,
- filterDataOrigin,
- validationSchemas,
- setToast,
- setDataAvailability,
- hierarchy,
- setBoundaryData,
- setFilterData,
- setFilterProperties,
- setFilterSelections,
- setFilterPropertyNames,
- state,
- setChoroplethProperties,
- setDataCompleteness,
- t
- );
- setLoader(false);
- }
- }, [filterDataOrigin, hierarchy]);
-
- // Function to initialize map
- const init = (id, defaultBaseMap, Boundary) => {
- if (map !== null) return;
-
- // let bounds = findBounds(Boundary);
-
- let mapConfig = {
- center: [0, 0],
- zoomControl: false,
- zoom: 3,
- scrollwheel: true,
- minZoom: 3,
- };
-
- let map_i = L.map(id, mapConfig);
- var verticalBounds = L.latLngBounds(L.latLng(-90, -170), L.latLng(85, 190));
- map_i.on("drag", () => {
- map_i.panInsideBounds(verticalBounds, { animate: true });
- });
- map_i.on("zoom", () => {
- map_i.panInsideBounds(verticalBounds, { animate: true });
- });
- const defaultBaseLayer = defaultBaseMap?.layer.addTo(map_i);
- // if (bounds) map_i.fitBounds(bounds);
- setSelectedBaseMap(defaultBaseLayer);
- setMap(map_i);
- };
-
- const handleBaseMapToggle = (newBaseMap) => {
- if (map) {
- const currentBaseLayer = selectedBaseMap;
- if (currentBaseLayer) {
- currentBaseLayer.remove();
- }
- const newBaseLayer = baseMaps[newBaseMap].layer.addTo(map);
- // Add the new base layer to the bottom of the layer stack
- newBaseLayer.addTo(map);
-
- // Update the baseLayer state
- setSelectedBaseMap(newBaseLayer);
- setSelectedBaseMapName(newBaseMap);
- }
- };
-
- // showing selected boundary data
- useEffect(() => {
- if (!boundarySelections && !choroplethProperty && !filterSelections) return;
- setLoader("LOADING");
- try {
- removeAllLayers(map, layers);
- const { filteredSelection, childrenList } = filterBoundarySelection(boundaryData, boundarySelections);
- let newLayer = [];
- let addOn = {
- fillColor: "rgba(255, 107, 43, 0)",
- weight: 3.5,
- opacity: 1,
- color: "rgba(176, 176, 176, 1)",
- fillOpacity: 0,
- fill: "rgb(4,136,219,1)",
- child: !childrenList || childrenList.length === 0, // so that this layer also has mounse in and mouse out events
- };
- let geojsonsBase = prepareGeojson(boundaryData, "ALL", addOn);
- if (geojsonsBase) {
- let baseLayer = addGeojsonToMap(map, geojsonsBase, t);
- if (baseLayer) newLayer.push(baseLayer);
- let bounds = findBounds(geojsonsBase);
- if (bounds) map.fitBounds(bounds);
- }
-
- addOn = {
- fillColor: "rgba(255, 107, 43, 1)",
- weight: 2.5,
- opacity: 1,
- color: "rgba(255, 255, 255, 1)",
- fillOpacity: 0.22,
- fill: "rgb(4,136,219)",
- };
-
- let geojsonLayer;
- if (choroplethProperty) {
- if (dataCompleteness === "partial" || dataCompleteness === "false" || dataCompleteness === undefined) {
- setToast({
- state: "warning",
- message: t("DISPLAYING_DATA_ONLY_FOR_UPLOADED_BOUNDARIES"),
- });
- }
-
- let choroplethGeojson = prepareGeojson(boundaryData, "ALL", { ...addOn, child: true, fillColor: "rgb(0,0,0,0)" }) || [];
- if (choroplethGeojson && choroplethGeojson.length !== 0)
- choroplethGeojson = addChoroplethProperties(choroplethGeojson, choroplethProperty, filteredSelection);
- geojsonLayer = addGeojsonToMap(map, choroplethGeojson, t);
- if (geojsonLayer) {
- newLayer.push(geojsonLayer);
- }
- }
- geojsonLayer = null;
- const geojsons = prepareGeojson(boundaryData, filteredSelection, addOn);
- if (geojsons && geojsons.length > 0) {
- geojsonLayer = addGeojsonToMap(map, geojsons, t);
- newLayer.push(geojsonLayer);
- let bounds = findBounds(geojsons);
- if (bounds) map.fitBounds(bounds);
- }
-
- const childrenGeojson = prepareGeojson(boundaryData, childrenList, { ...addOn, opacity: 0, fillOpacity: 0, child: true });
- let childrenGeojsonLayer = addGeojsonToMap(map, childrenGeojson, t);
- if (childrenGeojsonLayer) newLayer.push(childrenGeojsonLayer);
-
- //filters
- const filterGeojsons = prepareGeojson(filterData, filteredSelection && filteredSelection.length !== 0 ? filteredSelection : "ALL", addOn);
- const filterGeojsonWithProperties = addFilterProperties(filterGeojsons, filterSelections, filterPropertyNames, state?.MapFilters);
- let filterGeojsonLayer = addGeojsonToMap(map, filterGeojsonWithProperties, t);
- if (filterGeojsonLayer) newLayer.push(filterGeojsonLayer);
-
- setLayer(newLayer);
- } catch (error) {
- console.error("Error while adding geojson to map: ", error.message);
- }
- setLoader(false);
- }, [boundarySelections, choroplethProperty, filterSelections]);
-
- const handleOutsideClickAndSubmitSimultaneously = useCallback(() => {
- if (isboundarySelectionSelected) setIsboundarySelectionSelected(false);
- if (showBaseMapSelector) setShowBaseMapSelector(false);
- if (showFilterOptions) setShowFilterOptions(false);
- if (showChoroplethOptions) setShowChoroplethOptions(false);
- }, [
- isboundarySelectionSelected,
- showBaseMapSelector,
- showFilterOptions,
- showChoroplethOptions,
- setIsboundarySelectionSelected,
- setShowBaseMapSelector,
- setShowFilterOptions,
- setShowChoroplethOptions,
- ]);
- Digit?.Hooks.useClickOutside(filterBoundaryRef, handleOutsideClickAndSubmitSimultaneously, isboundarySelectionSelected, { capture: true });
- Digit?.Hooks.useClickOutside(basemapRef, handleOutsideClickAndSubmitSimultaneously, showBaseMapSelector, { capture: true });
- Digit?.Hooks.useClickOutside(showFilterOptionRef, handleOutsideClickAndSubmitSimultaneously, showFilterOptions, { capture: true });
- Digit?.Hooks.useClickOutside(showChoroplethOptionRef, handleOutsideClickAndSubmitSimultaneously, showChoroplethOptions, { capture: true });
-
- // function to stop mouse event propogation from custom comopents to leaflet map
- const handleMouseDownAndScroll = (event) => {
- event?.stopPropagation();
- disableMapInteractions(map);
- };
-
- const handleMouseUpAndScroll = (event) => {
- enableMapInteractions(map);
- };
- useEffect(() => {
- if (isboundarySelectionSelected || showBaseMapSelector || showFilterOptions || showChoroplethOptions) handleMouseDownAndScroll();
- else handleMouseUpAndScroll();
- }, [isboundarySelectionSelected, showBaseMapSelector, showFilterOptions, showChoroplethOptions, choroplethProperty, filterPropertyNames]);
-
- // Rendering component
- return (
-
-
-
-
- {/* Container for map */}
-
-
-
-
-
-
- {filterProperties && Object.keys(filterProperties).length !== 0 && (
-
- )}
-
-
-
-
-
-
- {DigitSvgs.NorthArrow && }
-
-
-
-
-
- {filterSelections && filterSelections.length > 0 && (
-
- )}
- {choroplethProperty && }
-
-
-
-
- {loader &&
}
-
- );
-};
-
-// Exporting Mapping component
-export default Mapping;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/MappingHelperComponents.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/MappingHelperComponents.js
deleted file mode 100644
index 9cea19a943f..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/MappingHelperComponents.js
+++ /dev/null
@@ -1,513 +0,0 @@
-// Importing necessary modules
-import { Card, CardLabel, MultiSelectDropdown, Button, CheckBox, RadioButtons } from "@egovernments/digit-ui-components";
-import "leaflet/dist/leaflet.css";
-import React, { memo, useCallback, useEffect, useMemo, useRef, useState, Fragment } from "react";
-import * as DigitSvgs from "@egovernments/digit-ui-svg-components";
-import { CardSectionHeader, InfoIconOutline, LoaderWithGap, Modal } from "@egovernments/digit-ui-react-components";
-import { fetchDropdownValues } from "../utils/processHierarchyAndData";
-import { MapChoroplethGradientColors, PRIMARY_THEME_COLOR } from "../configs/constants";
-import { ModalHeading } from "./CommonComponents";
-import * as MicroplanIconCollection from "../icons/Svg";
-import { generatePreviewUrl } from "../utils/mappingUtils";
-
-const IconCollection = { ...MicroplanIconCollection, ...DigitSvgs };
-
-export function checkTruthyKeys(obj) {
- for (let key in obj) {
- if (Object.hasOwn(obj, key)) {
- if (obj[key] && !(Array.isArray(obj[key]) && obj[key].length === 0)) {
- return true;
- }
- }
- }
- return false;
-}
-
-export const MapFilterIndex = ({ filterSelections, MapFilters, t }) => {
- return (
-
- {filterSelections && filterSelections.length > 0 ? (
- <>
- {filterSelections.map((item, index) => (
- //
- ))}
- >
- ) : (
- ""
- )}
-
- );
-};
-
-// Function to create the gradient from the colors array for choropleth index
-export const MapChoroplethIndex = ({ t, choroplethProperty }) => {
- const createGradientString = (colors) => {
- return colors.map((color) => `${color.color} ${color.percent}%`).join(", ");
- };
-
- const gradientString = createGradientString(MapChoroplethGradientColors);
- const gradientStyle = {
- background: `linear-gradient(to right, ${gradientString})`,
- };
-
- return (
-
-
-
{t(choroplethProperty)}
-
- );
-};
-
-export const FilterItemBuilder = ({ item, MapFilters, t }) => {
- let temp = MapFilters?.find((e) => e?.name === item)?.icon?.index;
- let DynamicIcon = IconCollection?.[temp];
- // let icon;
- // if (typeof DynamicIcon === "function") icon = DynamicIcon({});
- return DynamicIcon && typeof DynamicIcon === "function" ? (
-
- ) : (
- //
- ""
- );
-};
-
-export const ChoroplethSelection = memo(
- ({
- choroplethProperties,
- showChoroplethOptions,
- showChoroplethOptionRef,
- setShowChoroplethOptions,
- choroplethProperty,
- setChoroplethProperty,
- t,
- }) => {
- const handleChange = useCallback(
- (value) => {
- setChoroplethProperty(value?.code);
- },
- [choroplethProperties]
- );
-
- return (
-
-
setShowChoroplethOptions((previous) => !previous)}
- onKeyUp={() => setShowChoroplethOptions((previous) => !previous)}
- tabIndex={0}
- >
-
{t("VISUALIZATIONS")}
-
- {DigitSvgs.FilterAlt && }
-
-
- {showChoroplethOptions && (
-
-
- ({ name: item, id: item, code: item }))}
- optionsKey="name"
- onSelect={handleChange}
- selectedOption={choroplethProperty}
- />
-
-
setChoroplethProperty()}
- />
-
- )}
-
- );
- }
-);
-
-export const FilterSection = memo(
- ({ filterProperties, showFilterOptionRef, showFilterOptions, setShowFilterOptions, filterSelections, setFilterSelections, t }) => {
- const handleChange = useCallback(
- (e, item) => {
- let tempFilterSelections = [...filterSelections]; // Clone the array to avoid mutating state directly
- if (filterSelections.includes(item)) {
- tempFilterSelections = tempFilterSelections.filter((element) => element !== item);
- } else {
- tempFilterSelections.push(item);
- }
- setFilterSelections(tempFilterSelections);
- },
- [filterSelections]
- );
-
- return (
-
-
setShowFilterOptions((previous) => !previous)}
- onKeyUp={() => setShowFilterOptions((previous) => !previous)}
- tabIndex={0}
- >
-
{t("FILTERS")}
-
- {DigitSvgs.FilterAlt && }
-
-
- {showFilterOptions && (
-
-
- {filterProperties.map((item) => (
-
- handleChange(e, item)}
- label={t(item)}
- checked={!!filterSelections.includes(item)}
- mainClassName="mainClassName"
- labelClassName="labelClassName"
- inputWrapperClassName="inputWrapperClassName"
- inputClassName="inputClassName"
- inputIconClassname="inputIconClassname"
- iconFill={PRIMARY_THEME_COLOR}
- onLabelClick={(e) => handleChange(e, item)}
- />
-
- ))}
-
-
setFilterSelections([])}
- />
-
- )}
-
- );
- }
-);
-
-export const BoundarySelection = memo(
- ({
- boundarySelections,
- setBoundarySelections,
- boundaryData,
- hierarchy,
- filterBoundaryRef,
- isboundarySelectionSelected,
- setIsboundarySelectionSelected,
- t,
- }) => {
- const [processedHierarchy, setProcessedHierarchy] = useState([]);
- const [isLoading, setIsLoading] = useState(false);
- const [showConfirmationModal, setShowConformationModal] = useState(false);
- const itemRefs = useRef([]);
- const [expandedIndex, setExpandedIndex] = useState(null);
- const scrollContainerRef = useRef(null);
- const [changedBoundaryType, setChangedBoundaryType] = useState("");
- const [isScrollable, setIsScrollable] = useState(false);
-
- useEffect(() => {
- // Scroll to the expanded item's child element after the state has updated and the DOM has re-rendered
- if (expandedIndex !== null && itemRefs.current[expandedIndex]) {
- // Use a timeout to ensure the DOM has updated
- setTimeout(() => {
- const childElement = itemRefs.current[expandedIndex].children[0]; // Assuming child content is the second child
- // if (childElement) {
- // childElement.scrollIntoView({ behavior: 'smooth' });
- // }
- if (childElement) {
- const scrollContainer = scrollContainerRef.current;
- const childElementBound = childElement.getBoundingClientRect();
- const containerRect = scrollContainer.getBoundingClientRect();
-
- // Calculate the offset from the top of the container
- const offset = childElementBound.top - containerRect.top;
-
- // Scroll the container
- scrollContainer.scrollTo({
- top: scrollContainer.scrollTop + offset - 10,
- behavior: "smooth",
- });
- }
- }, 0);
- }
- }, [expandedIndex]);
-
- const toggleExpand = (index) => {
- setExpandedIndex(index === expandedIndex ? null : index);
- };
-
- // Filtering out dropdown values
- useEffect(() => {
- if (!boundaryData || !hierarchy) return;
- const processedHierarchyTemp = fetchDropdownValues(
- boundaryData,
- processedHierarchy.length !== 0 ? processedHierarchy : hierarchy,
- boundarySelections,
- changedBoundaryType
- );
- setProcessedHierarchy(processedHierarchyTemp);
- setIsLoading(false);
- }, [boundaryData, hierarchy, boundarySelections]);
-
- const handleClearAll = () => {
- setShowConformationModal(true);
- };
-
- const handleSubmitConfModal = () => {
- setBoundarySelections({});
- setShowConformationModal(false);
- };
-
- const handleCancelConfModal = () => {
- setShowConformationModal(false);
- };
-
- const checkScrollbar = () => {
- if (scrollContainerRef.current) {
- setIsScrollable(scrollContainerRef.current.scrollHeight > scrollContainerRef.current.clientHeight);
- }
- };
-
- useEffect(() => {
- // Initial check
- checkScrollbar();
-
- // Check on resize
- window.addEventListener("resize", checkScrollbar);
-
- // Cleanup event listeners on component unmount
- return () => {
- window.removeEventListener("resize", checkScrollbar);
- };
- }, [isboundarySelectionSelected]);
-
- useEffect(() => {
- const content = scrollContainerRef.current;
- content.addEventListener("scroll", checkScrollbar);
-
- return () => {
- content.removeEventListener("scroll", checkScrollbar);
- };
- }, [scrollContainerRef]);
-
- return (
-
- {isLoading &&
}
-
setIsboundarySelectionSelected((previous) => !previous)}
- />
-
-
- {t("SELECT_A_BOUNDARY")}
-
-
-
- {processedHierarchy?.map((item, index) => (
-
{
- itemRefs.current[index] = el;
- }}
- onClick={() => toggleExpand(index)}
- >
- {t(item?.boundaryType)}
- {item?.parentBoundaryType === null ? (
- 5 ? { height: "13.75rem" } : {}}
- type={"multiselectdropdown"}
- t={t}
- options={item?.dropDownOptions || []}
- optionsKey="name"
- addSelectAllCheck={true}
- onSelect={(e) => {
- setChangedBoundaryType(item?.boundaryType);
- Digit.Utils.microplan.handleSelection(
- e,
- item?.boundaryType,
- boundarySelections,
- hierarchy,
- setBoundarySelections,
- boundaryData,
- setIsLoading
- );
- }}
- />
- ) : (
- 5 ? { height: "13.75rem" } : {}}
- type={"multiselectdropdown"}
- t={t}
- options={Digit.Utils.microplan.processDropdownForNestedMultiSelect(item?.dropDownOptions) || []}
- optionsKey="name"
- addSelectAllCheck={true}
- onSelect={(e) => {
- setChangedBoundaryType(item?.boundaryType);
- Digit.Utils.microplan.handleSelection(
- e,
- item?.boundaryType,
- boundarySelections,
- hierarchy,
- setBoundarySelections,
- boundaryData,
- setIsLoading
- );
- }}
- variant="nestedmultiselect"
- />
- )}
-
- ))}
-
- {checkTruthyKeys(boundarySelections) && (
-
- )}
- {showConfirmationModal && (
-
-
}
- actionCancelLabel={t("YES")}
- actionCancelOnSubmit={handleSubmitConfModal}
- actionSaveLabel={t("NO")}
- actionSaveOnSubmit={handleCancelConfModal}
- >
-
-
{t("CLEAR_ALL_CONFIRMATION_MSG")}
-
-
-
- )}
-
-
- );
- }
-);
-
-export const BaseMapSwitcher = ({
- baseMaps,
- showBaseMapSelector,
- setShowBaseMapSelector,
- handleBaseMapToggle,
- selectedBaseMapName,
- basemapRef,
- t,
-}) => {
- if (!baseMaps) return null;
- return (
-
-
setShowBaseMapSelector((previous) => !previous)}
- onKeyUp={() => setShowBaseMapSelector((previous) => !previous)}
- tabIndex={0}
- >
-
{t("LAYERS")}
-
{DigitSvgs.Layers && }
-
-
- {showBaseMapSelector && (
-
- {Object.entries(baseMaps).map(([name, baseMap], index) => {
- return (
-
-
handleBaseMapToggle(name)}
- />
-
{t(name)}
-
- );
- })}
-
- )}
-
-
- );
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/MicroplanCreatedScreen.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/MicroplanCreatedScreen.js
deleted file mode 100644
index b6a2fb9a205..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/MicroplanCreatedScreen.js
+++ /dev/null
@@ -1,111 +0,0 @@
-import React, { memo } from "react";
-import { ActionBar, ArrowForward, Banner } from "@egovernments/digit-ui-components";
-import { useTranslation } from "react-i18next";
-import { ArrowBack, FileDownload } from "@egovernments/digit-ui-svg-components";
-import { convertJsonToXlsx, writeWorkbookToBuffer } from "../utils/jsonToExcelBlob";
-import { Button } from "@egovernments/digit-ui-react-components";
-import { useHistory } from "react-router-dom";
-import { Link } from "react-router-dom/cjs/react-router-dom.min";
-import { PRIMARY_THEME_COLOR, commonColumn } from "../configs/constants";
-import { colorHeaders } from "../utils/uploadUtils";
-
-const MicroplanCreatedScreen = memo(({ microplanData, ...props }) => {
- const { t } = useTranslation();
- const history = useHistory();
-
- const downloadMicroplan = async () => {
- try {
- if (!microplanData?.microplanPreview) return;
- const data = _.cloneDeep(microplanData?.microplanPreview?.previewData);
- const commonColumnIndex = data[0]?.findIndex((item) => item === commonColumn);
- data[0] = data[0].map((item) => t(item));
-
- for (const i in data) {
- data[i] = data[i].map((item, index) =>
- item ? (typeof item === "number" ? item : index === commonColumnIndex ? item : t(item)) : t("NO_DATA")
- );
- }
-
- const headers = data?.[0] || [];
- const workbook = await convertJsonToXlsx({ [microplanData?.microplanDetails?.name]: data }, {}, true);
- colorHeaders(workbook, headers, [], []);
- const blob = await writeWorkbookToBuffer(workbook);
-
- if (!blob) {
- return;
- }
-
- const url = URL.createObjectURL(blob);
- const link = document.createElement("a");
- link.href = url;
-
- const fileNameParts = microplanData?.microplanDetails?.name;
- if (!fileNameParts) {
- return;
- }
-
- link.download = fileNameParts;
- link.click();
- URL.revokeObjectURL(url);
- } catch (error) {
- console.error(`Failed to download microplan: ${error.message}`, error);
- }
- };
-
- const clickGoHome = () => {
- history.push("/microplan-ui/employee");
- };
-
- return (
-
-
-
-
-
-
{t("MICROPLAN_GENERATED_SUCCESSFULLY_DESCRIPTIION")}
-
- }
- isSuffix={false}
- />
-
-
-
-
- {/* Back button */}
- }
- />
- {/* Next/Submit button */}
-
-
-
-
-
- );
-});
-
-export default MicroplanCreatedScreen;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/MicroplanDetails.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/MicroplanDetails.js
deleted file mode 100644
index fbc73bd6569..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/MicroplanDetails.js
+++ /dev/null
@@ -1,294 +0,0 @@
-import React, { Fragment, useState, useEffect, useCallback } from "react";
-import {
- Card,
- CardSubHeader,
- CardSectionHeader,
- StatusTable,
- Row,
- Loader,
- LabelFieldPair,
- CardLabel,
- TextInput,
- LoaderWithGap,
-} from "@egovernments/digit-ui-react-components";
-import { useTranslation } from "react-i18next";
-import { tourSteps } from "../configs/tourSteps";
-import { useMyContext } from "../utils/context";
-import { InfoCard, Modal, Toast } from "@egovernments/digit-ui-components";
-import { CloseButton, ModalHeading } from "./CommonComponents";
-import { PRIMARY_THEME_COLOR } from "../configs/constants";
-import SearchPlanConfig from "../services/SearchPlanConfig";
-
-const page = "microplanDetails";
-
-const MicroplanDetails = ({
- MicroplanName = "default",
- campaignType = Digit.SessionStorage.get("microplanHelperData")?.campaignData?.projectType,
- microplanData,
- setMicroplanData,
- checkDataCompletion,
- setCheckDataCompletion,
- currentPage,
- pages,
- setToast,
- ...props
-}) => {
- const { t } = useTranslation();
- const [microplan, setMicroplan] = useState(Digit.SessionStorage.get("microplanData")?.microplanDetails?.name);
- const { state, dispatch } = useMyContext();
- const [modal, setModal] = useState("none");
- // const [toast, setToast] = useState();
- const [showNamingConventions, setShowNamingConventions] = useState(false);
- const [loader, setLoader] = useState(false);
-
- //fetch campaign data
- const { id = "" } = Digit.Hooks.useQueryParams();
- const { isLoading: isCampaignLoading, data: campaignData } = Digit.Hooks.microplan.useSearchCampaign(
- {
- CampaignDetails: {
- tenantId: Digit.ULBService.getCurrentTenantId(),
- ids: [id],
- },
- },
- {
- enabled: !!id,
- select: (data) => {
- const campaignCard = [
- {
- label: t("CAMPAIGN_NAME"),
- value: data?.campaignName ? data?.campaignName : t("ES_COMMON_NA"),
- },
- {
- label: t(`CAMPAIGN_TYPE`),
- value: data?.projectType ? t(`CAMPAIGN_TYPE_${data?.projectType}`) : t("ES_COMMON_NA"),
- },
- {
- label: t(`CAMPAIGN_BENEFICIARY_TYPE`),
- value: data?.additionalDetails?.beneficiaryType
- ? t(`CAMPAIGN_BENEFICIARY_TYPE${data?.additionalDetails?.beneficiaryType}`)
- : t("ES_COMMON_NA"),
- },
- {
- label: t("CAMPAIGN_DATE"),
- value: data.startDate
- ? data.endDate
- ? `${Digit.DateUtils.ConvertEpochToDate(data.startDate)} - ${Digit.DateUtils.ConvertEpochToDate(data.endDate)}`
- : Digit.DateUtils.ConvertEpochToDate(data.startDate)
- : t("ES_COMMON_NA"),
- },
- ];
- return campaignCard;
- },
- }
- );
-
- // Set TourSteps
- useEffect(() => {
- const tourData = tourSteps(t)?.[page] || {};
- if (state?.tourStateData?.name === page) return;
- dispatch({
- type: "SETINITDATA",
- state: { tourStateData: tourData },
- });
- }, []);
-
- // Save data to ssn of data change
- useEffect(() => {
- setMicroplanData((previous) => ({
- ...previous,
- microplanDetails: {
- name: microplan,
- },
- }));
- }, [microplan]);
-
- useEffect(() => {
- if (checkDataCompletion !== "true" || !setCheckDataCompletion) return;
-
- updateData(true);
- }, [checkDataCompletion]);
-
- // UseEffect to add a event listener for keyboard
- useEffect(() => {
- window.addEventListener("keydown", handleKeyPress);
-
- return () => window.removeEventListener("keydown", handleKeyPress);
- }, [modal]);
-
- const handleKeyPress = (event) => {
- // if (modal !== "upload-guidelines") return;
- if (["x", "Escape"].includes(event.key)) {
- // Perform the desired action when "x" or "esc" is pressed
- // if (modal === "upload-guidelines")
- setCheckDataCompletion("false");
- setModal("none");
- }
- };
- const validateMicroplanName = async () => {
- try {
- setLoader("LOADING");
- const body = {
- PlanConfigurationSearchCriteria: {
- name: microplan,
- tenantId: Digit.ULBService.getCurrentTenantId(),
- },
- };
- const response = await SearchPlanConfig(body);
- if (response?.PlanConfiguration?.length === 0) {
- return true;
- }
- if (response?.PlanConfiguration?.length === 1) {
- if (response?.PlanConfiguration[0].id === microplanData?.planConfigurationId) {
- setLoader();
- return true;
- }
- }
- setLoader();
- return false;
- } catch (error) {
- console.error("Error while checking microplan name duplication: ", error.message);
- setLoader();
- return false;
- }
- };
- // check if data has changed or not
- const updateData = useCallback(
- async (check) => {
- if (checkDataCompletion !== "true" || !setCheckDataCompletion) return;
- if (!microplan || !validateName(microplan)) {
- setCheckDataCompletion("false");
- setShowNamingConventions(true);
- return setToast({ state: "error", message: t("ERROR_MICROPLAN_NAME_CRITERIA") });
- }
- const valid = await validateMicroplanName();
- if (!valid) {
- setToast({ state: "error", message: t("ERROR_DUPLICATE_MICROPLAN_NAME") });
- setCheckDataCompletion("false");
- return;
- }
- if (check) {
- setMicroplanData((previous) => ({
- ...previous,
- microplanDetails: {
- name: microplan,
- },
- }));
- if (!["", null, undefined].includes(microplan)) {
- setCheckDataCompletion("valid");
- } else {
- setCheckDataCompletion("invalid");
- }
- } else {
- if (!["", null, undefined].includes(microplanData?.microplanDetails?.name)) {
- setCheckDataCompletion("valid");
- } else {
- setCheckDataCompletion("invalid");
- }
- }
- },
- [checkDataCompletion, microplan, microplanData, setCheckDataCompletion, setMicroplanData, validateMicroplanName]
- );
-
- // const cancelUpdateData = useCallback(() => {
- // setCheckDataCompletion(false);
- // setModal('none');
- // }, [setCheckDataCompletion, setModal]);
- function validateName(name) {
- const microplanNamingRegxString = state?.UIConfiguration?.find((item) => item.name === "microplanNamingRegx")?.microplanNamingRegx;
- const namePattern = new RegExp(microplanNamingRegxString);
- return namePattern.test(name);
- }
- const onChangeMicroplanName = (e) => {
- setMicroplan(e.target.value);
- };
-
- if (isCampaignLoading) {
- return ;
- }
-
- return (
- <>
- {loader && }
-
-
- {t("CAMPAIGN_DETAILS")}
-
-
-
- {campaignData?.length > 0 &&
- campaignData?.map((row, idx) => {
- return (
-
- );
- })}
-
-
-
- {t("NAME_YOUR_MP")}
- {t("MP_FOOTER")}
-
-
- {`${t("NAME_OF_MP")} `} *
-
-
-
-
-
-
-
- {state?.UIConfiguration?.find((item) => item.name === "microplanNamingConvention")?.microplanNamingConvention?.map((item, index) => (
-
-
- {t(index + 1)}.
-
-
- {t(item)}
-
-
- ))}
- ,
- ]}
- />
- >
- );
-};
-
-export default MicroplanDetails;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/MicroplanPreview.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/MicroplanPreview.js
deleted file mode 100644
index 1be6619e7a7..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/MicroplanPreview.js
+++ /dev/null
@@ -1,478 +0,0 @@
-import { Header, Loader } from "@egovernments/digit-ui-components";
-import React, { useCallback, useEffect, useMemo, useState, Fragment } from "react";
-import { useTranslation } from "react-i18next";
-import { processHierarchyAndData } from "../utils/processHierarchyAndData";
-import { ModalHeading } from "./CommonComponents";
-import { PRIMARY_THEME_COLOR } from "../configs/constants";
-import { LoaderWithGap, Modal } from "@egovernments/digit-ui-react-components";
-import { tourSteps } from "../configs/tourSteps";
-import { useMyContext } from "../utils/context";
-import {
- fetchMicroplanPreviewData,
- filterObjects,
- updateHyothesisAPICall,
- filterMicroplanDataToShowWithHierarchySelection,
-} from "../utils/microplanPreviewUtils";
-import {
- HypothesisValues,
- BoundarySelection,
- DataPreview,
- AppplyChangedHypothesisConfirmation,
- Aggregates,
-} from "./MicroplanPreviewHelperCompoenents";
-
-const page = "microplanPreview";
-
-const MicroplanPreview = ({
- campaignType = Digit.SessionStorage.get("microplanHelperData")?.campaignData?.projectType,
- microplanData,
- setMicroplanData,
- checkDataCompletion,
- setCheckDataCompletion,
- currentPage,
- pages,
- navigationEvent,
- setToast,
- ...props
-}) => {
- const { mutate: UpdateMutate } = Digit.Hooks.microplan.useUpdatePlanConfig();
- const userInfo = Digit.SessionStorage.get("User")?.info;
- const { id: campaignId = "" } = Digit.Hooks.useQueryParams();
- const { t } = useTranslation();
- const [hypothesisAssumptionsList, setHypothesisAssumptionsList] = useState([]);
- const [data, setData] = useState([]);
- const [dataToShow, setDataToShow] = useState([]);
- const [joinByColumns, setJoinByColumns] = useState([]);
- const [validationSchemas, setValidationSchemas] = useState([]);
- const [resources, setResources] = useState([]);
- const [formulaConfiguration, setFormulaConfiguration] = useState([]);
- const [boundarySelections, setBoundarySelections] = useState({}); // state for hierarchy from the data available from uploaded data
- const [boundaryData, setBoundaryData] = useState({}); // State for boundary data
- // const [toast, setToast] = useState();
- const [modal, setModal] = useState("none");
- const [operatorsObject, setOperatorsObject] = useState([]);
-
- const [loaderActivation, setLoaderActivation] = useState(false);
-
- const [userEditedResources, setUserEditedResources] = useState({}); // state to maintain a record of the resources that the user has edited ( boundaryCode : {resource : value})
- const [microplanPreviewAggregates, setMicroplaPreviewAggregates] = useState();
- const { state, dispatch } = useMyContext();
- const [updateHypothesis, setUpdateHypothesis] = useState(false);
- //fetch campaign data
- const { id = "" } = Digit.Hooks.useQueryParams();
- const { isLoading: isCampaignLoading, data: campaignData } = Digit.Hooks.microplan.useSearchCampaign(
- {
- CampaignDetails: {
- tenantId: Digit.ULBService.getCurrentTenantId(),
- ids: [id],
- },
- },
- {
- enabled: !!id,
- }
- );
-
- // request body for boundary hierarchy api
- const reqCriteria = {
- url: `/boundary-service/boundary-hierarchy-definition/_search`,
- params: {},
- body: {
- BoundaryTypeHierarchySearchCriteria: {
- tenantId: Digit.ULBService.getStateId(),
- hierarchyType: campaignData?.hierarchyType,
- },
- },
- config: {
- enabled: !!campaignData?.hierarchyType,
- select: (data) => {
- return (
- data?.BoundaryHierarchy?.[0]?.boundaryHierarchy?.map((item) => ({
- ...item,
- parentBoundaryType: item?.parentBoundaryType
- ? `${campaignData?.hierarchyType}_${Digit.Utils.microplan.transformIntoLocalisationCode(item?.parentBoundaryType)}`
- : null,
- boundaryType: `${campaignData?.hierarchyType}_${Digit.Utils.microplan.transformIntoLocalisationCode(item?.boundaryType)}`,
- })) || {}
- );
- },
- },
- };
- const { isLoading: ishierarchyLoading, data: hierarchyRawData } = Digit.Hooks.useCustomAPIHook(reqCriteria);
- const hierarchy = useMemo(() => {
- return hierarchyRawData?.map((item) => item?.boundaryType);
- }, [hierarchyRawData]);
- // Set TourSteps
- useEffect(() => {
- const tourData = tourSteps(t)?.[page] || {};
- if (state?.tourStateData?.name === page) return;
- dispatch({
- type: "SETINITDATA",
- state: { tourStateData: tourData },
- });
- }, []);
-
- // UseEffect to extract data on first render
- useEffect(() => {
- if (microplanData && (microplanData?.ruleEngine || microplanData?.hypothesis)) {
- const hypothesisAssumptions = microplanData?.hypothesis || [];
- const formulaConfiguration = microplanData?.ruleEngine?.filter((item) => Object.values(item).every((key) => key !== "")) || [];
- if (hypothesisAssumptions.length !== 0 && hypothesisAssumptionsList.length === 0) {
- setHypothesisAssumptionsList(hypothesisAssumptions);
- }
- if (formulaConfiguration.length !== 0) {
- setFormulaConfiguration(formulaConfiguration);
- }
- }
- if (microplanData?.microplanPreview?.userEditedResources) {
- setUserEditedResources(microplanData?.microplanPreview?.userEditedResources);
- }
- }, []);
-
- // Fetch and assign MDMS data
- useEffect(() => {
- if (!state) return;
- const UIConfiguration = state?.UIConfiguration;
- const schemas = state?.Schemas;
- let resourcelist = state?.Resources;
- let microplanPreviewAggregatesList = state?.MicroplanPreviewAggregates;
- microplanPreviewAggregatesList = microplanPreviewAggregatesList.find((item) => item.campaignType === campaignType)?.data;
- if (schemas) setValidationSchemas(schemas);
- resourcelist = resourcelist.find((item) => item.campaignType === campaignType)?.data;
- if (resourcelist) setResources(resourcelist);
- if (UIConfiguration) {
- const joinWithColumns = UIConfiguration.find((item) => item.name === "microplanPreview")?.joinWithColumns;
- setJoinByColumns(joinWithColumns);
- }
- let temp;
- if (UIConfiguration) temp = UIConfiguration.find((item) => item.name === "ruleConfigure");
- if (temp?.ruleConfigureOperators) {
- setOperatorsObject(temp.ruleConfigureOperators);
- }
- if (microplanPreviewAggregatesList) setMicroplaPreviewAggregates(microplanPreviewAggregatesList);
- }, []);
-
- // UseEffect for checking completeness of data before moveing to next section
- useEffect(() => {
- if (!dataToShow || checkDataCompletion !== "true" || !setCheckDataCompletion) return;
- const check = filterObjects(hypothesisAssumptionsList, microplanData?.hypothesis);
- if (check.length === 0) {
- if (navigationEvent?.name === "next") return setModal("confirm-microplan-generation");
- return createMicroplan(false, false);
- }
- setModal("confirm-apply-changed-hypothesis");
- }, [checkDataCompletion]);
-
- // check if data has changed or not
- const updateData = useCallback(
- (doPerform) => {
- // Update the microplan data with selected hierarchy and resources
- // This function also handles setting the completion check based on the action to be performed
- if (!setMicroplanData) return;
- try {
- let tempData = filterMicroplanDataToShowWithHierarchySelection(data, {}, hierarchy);
- // Adding resources to the data we need to show
- tempData = Digit.Utils.microplan.addResourcesToFilteredDataToShow(
- tempData,
- resources,
- hypothesisAssumptionsList,
- formulaConfiguration,
- userEditedResources,
- t
- );
- setMicroplanData((previous) => ({
- ...previous,
- microplanPreview: {
- previewData: tempData,
- userEditedResources,
- },
- }));
- if (doPerform) {
- return setCheckDataCompletion("perform-action");
- }
- setCheckDataCompletion("false");
- } catch (error) {
- console.error("Failed to update data:", error);
- }
- },
- [
- resources,
- boundarySelections,
- hierarchy,
- hypothesisAssumptionsList,
- formulaConfiguration,
- userEditedResources,
- setMicroplanData,
- setCheckDataCompletion,
- ]
- );
-
- const cancelUpdateData = useCallback(() => {
- setUpdateHypothesis(false);
- if (navigationEvent?.name === "next") setModal("confirm-microplan-generation");
- else createMicroplan(false, false);
- }, [setCheckDataCompletion, setModal]);
-
- useEffect(() => {
- if (boundarySelections && Object.values(boundarySelections).every((item) => item.length === 0) && hierarchy) {
- const tempBoundarySelection = {};
- for (const item of hierarchy) {
- tempBoundarySelection[item] = [];
- }
- setBoundarySelections(tempBoundarySelection);
- }
- }, [hierarchy]);
-
- // UseEffect to add a event listener for keyboard
- useEffect(() => {
- window.addEventListener("keydown", handleKeyPress);
-
- return () => window.removeEventListener("keydown", handleKeyPress);
- }, [modal]);
-
- const handleKeyPress = (event) => {
- // if (modal !== "upload-guidelines") return;
- if (["x", "Escape"].includes(event.key)) {
- // Perform the desired action when "x" or "esc" is pressed
- setCheckDataCompletion("false");
- setModal("none");
- }
- };
-
- const cancleNavigation = () => {
- if (navigationEvent?.name !== "next") setCheckDataCompletion("false");
- setModal("none");
- };
-
- const createMicroplan = useCallback(
- (doCreation, updateHypothesis) => {
- if (!hypothesisAssumptionsList || !setMicroplanData) return;
- const updateDataWrapper = () => {
- if (doCreation || navigationEvent?.name !== "next") {
- return updateData(true);
- }
- updateData(false);
- };
- const setCheckDataCompletionWrapper = (value) => {
- if (!doCreation) {
- return setCheckDataCompletion("false");
- }
- setCheckDataCompletion(value);
- };
- const microData = updateHypothesis ? updateMicroplanData(hypothesisAssumptionsList) : microplanData;
- setLoaderActivation(true);
- updateHyothesisAPICall(
- microData,
- setMicroplanData,
- operatorsObject,
- microData?.microplanDetails?.name,
- campaignId,
- UpdateMutate,
- setToast,
- updateDataWrapper,
- setLoaderActivation,
- doCreation && navigationEvent?.name === "next" ? "GENERATED" : "DRAFT",
- cancleNavigation,
- state,
- campaignType,
- navigationEvent,
- setCheckDataCompletionWrapper,
- t
- );
-
- setUpdateHypothesis(false);
- setModal("none");
- },
- [
- hypothesisAssumptionsList,
- setMicroplanData,
- operatorsObject,
- campaignId,
- UpdateMutate,
- setToast,
- updateData,
- setLoaderActivation,
- navigationEvent,
- t,
- ]
- );
-
- const updateMicroplanData = useCallback(
- (hypothesisAssumptionsList) => {
- let microData = {};
- setMicroplanData((previous) => {
- microData = { ...previous, hypothesis: hypothesisAssumptionsList };
- return microData;
- });
- return microData;
- },
- [setMicroplanData]
- );
-
- // Set microplan preview data
- useEffect(() => {
- if (data?.length !== 0 || !hierarchyRawData || !hierarchy || validationSchemas?.length === 0) return;
-
- const combinedData = fetchMicroplanPreviewData(campaignType, microplanData, validationSchemas, hierarchy);
- // process and form hierarchy
- if (combinedData && hierarchy) {
- const { hierarchyLists, hierarchicalData } = processHierarchyAndData(hierarchyRawData, [combinedData]);
- setBoundaryData({ Microplan: { hierarchyLists, hierarchicalData } });
- }
- if (combinedData) {
- setData(combinedData);
- setDataToShow(combinedData);
- }
- }, [hierarchy, hierarchyRawData, microplanData]);
-
- useEffect(() => {
- if (!boundarySelections && !resources) return;
- let tempData = filterMicroplanDataToShowWithHierarchySelection(data, boundarySelections, hierarchy);
- // Adding resources to the data we need to show
- tempData = Digit.Utils.microplan.addResourcesToFilteredDataToShow(
- tempData,
- resources,
- hypothesisAssumptionsList,
- formulaConfiguration,
- userEditedResources,
- t
- );
- setDataToShow(tempData);
- setMicroplanData((previous) => ({ ...previous, microplanPreview: { ...previous.microplanPreview, previewData: tempData, userEditedResources } }));
- }, [boundarySelections, resources, hypothesisAssumptionsList, userEditedResources]);
-
- if (isCampaignLoading || ishierarchyLoading) {
- return (
-
-
-
- );
- }
-
- return (
- <>
-
-
-
{t(campaignData?.campaignName)}
-
{t(microplanData?.microplanDetails?.name)}
-
{t("MICROPLAN_PREVIEW_CREATE_BY", { username: userInfo?.name })}
-
-
-
-
-
-
{t("MICROPLAN_PREVIEW_HYPOTHESIS_HEADING")}
-
{t("MICROPLAN_PREVIEW_HYPOTHESIS_INSTRUCTIONS")}
-
-
-
- {dataToShow?.length != 0 ? (
-
- ) : (
-
{t("NO_DATA_AVAILABLE")}
- )}
-
-
- {modal === "confirm-apply-changed-hypothesis" && (
-
}
- actionCancelLabel={t("YES")}
- actionCancelOnSubmit={() => {
- setUpdateHypothesis(true);
- if (navigationEvent?.name === "next") setModal("confirm-microplan-generation");
- else createMicroplan(false, true);
- }}
- actionSaveLabel={t("NO")}
- actionSaveOnSubmit={cancelUpdateData}
- formId="modal-action"
- >
-
-
- )}
- {modal === "confirm-microplan-generation" && (
-
}
- actionCancelLabel={t("YES")}
- actionCancelOnSubmit={() => createMicroplan(true, updateHypothesis)}
- actionSaveLabel={t("NO")}
- actionSaveOnSubmit={() => createMicroplan(false, updateHypothesis)}
- formId="modal-action"
- >
-
-
{t("INSTRUCTIONS_MICROPLAN_GENERATION_CONFIRMATION")}
-
-
- )}
-
- {loaderActivation && }
- >
- );
-};
-
-export default MicroplanPreview;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/MicroplanPreviewHelperCompoenents.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/MicroplanPreviewHelperCompoenents.js
deleted file mode 100644
index e92335d6581..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/MicroplanPreviewHelperCompoenents.js
+++ /dev/null
@@ -1,434 +0,0 @@
-import { CardLabel, Loader, MultiSelectDropdown, TextInput } from "@egovernments/digit-ui-components";
-import React, { memo, useCallback, useEffect, useMemo, useState, Fragment, useRef } from "react";
-import { fetchDropdownValues } from "../utils/processHierarchyAndData";
-import { CloseButton, ModalHeading } from "./CommonComponents";
-import { PRIMARY_THEME_COLOR, commonColumn } from "../configs/constants";
-import { Button, LoaderWithGap, Modal } from "@egovernments/digit-ui-react-components";
-import { useNumberFormatter } from "../hooks/useNumberFormatter";
-import { calculateAggregateValue, filterObjects, useHypothesis } from "../utils/microplanPreviewUtils";
-
-export const HypothesisValues = memo(({ boundarySelections, hypothesisAssumptionsList, setHypothesisAssumptionsList, setToast, setModal, t }) => {
- const [tempHypothesisList, setTempHypothesisList] = useState(hypothesisAssumptionsList || []);
- const { valueChangeHandler } = useHypothesis(tempHypothesisList, hypothesisAssumptionsList);
- const contentRef = useRef(null);
- const [isScrollable, setIsScrollable] = useState(false);
-
- const applyNewHypothesis = () => {
- if (tempHypothesisList.some((item) => item.active && (Number.isNaN(parseFloat(item.value)) || parseFloat(item.value) === 0))) {
- setToast({ state: "error", message: t("ERROR_HYPOTHESIS_VALUE_SHOULD_NOT_BE_ZERO") });
- return;
- }
- if (Object.keys(boundarySelections).length !== 0 && Object.values(boundarySelections)?.every((item) => item?.length !== 0))
- return setToast({ state: "error", message: t("HYPOTHESIS_CAN_BE_ONLY_APPLIED_ON_ADMIN_LEVEL_ZORO") });
- setHypothesisAssumptionsList(tempHypothesisList);
- };
- const checkScrollbar = () => {
- if (contentRef.current) {
- setIsScrollable(contentRef.current.scrollHeight > contentRef.current.clientHeight);
- }
- };
-
- useEffect(() => {
- // Initial check
- checkScrollbar();
-
- // Check on resize
- window.addEventListener("resize", checkScrollbar);
-
- // Cleanup event listeners on component unmount
- return () => {
- window.removeEventListener("resize", checkScrollbar);
- };
- }, []);
-
- useEffect(() => {
- const content = contentRef.current;
- content.addEventListener("scroll", checkScrollbar);
-
- return () => {
- content.removeEventListener("scroll", checkScrollbar);
- };
- }, [contentRef]);
-
- return (
-
-
- {tempHypothesisList
- .filter((item) => item?.active)
- ?.filter((item) => item.key !== "")
- .map((item, index) => (
-
-
{t(item?.key)}
-
- {/* Dropdown for boundaries */}
-
- valueChangeHandler({ item, newValue: value?.target?.value }, setTempHypothesisList, boundarySelections, setToast, t)
- }
- disable={false}
- />
-
-
- ))}
-
-
-
-
-
- );
-});
-
-export const BoundarySelection = memo(({ boundarySelections, setBoundarySelections, boundaryData, hierarchy, t }) => {
- const [processedHierarchy, setProcessedHierarchy] = useState([]);
- const [isLoading, setIsLoading] = useState(false);
- const [changedBoundaryType, setChangedBoundaryType] = useState("");
-
- // Filtering out dropdown values
- useEffect(() => {
- if (!boundaryData || !hierarchy) return;
-
- const processedHierarchyTemp = fetchDropdownValues(
- boundaryData,
- processedHierarchy.length !== 0 ? processedHierarchy : hierarchy,
- boundarySelections,
- changedBoundaryType
- );
- setProcessedHierarchy(processedHierarchyTemp);
- setIsLoading(false);
- }, [boundaryData, hierarchy, boundarySelections]);
-
- return (
-
- {isLoading &&
}
- {processedHierarchy?.map((item, index) => (
-
- {t(item?.boundaryType)}
- {item?.parentBoundaryType === null ? (
- 5 ? { height: "13.75rem" } : {}}
- type={"multiselectdropdown"}
- t={t}
- options={item?.dropDownOptions || []}
- optionsKey="name"
- addSelectAllCheck={true}
- onSelect={(e) => {
- setChangedBoundaryType(item?.boundaryType);
- Digit.Utils.microplan.handleSelection(
- e,
- item?.boundaryType,
- boundarySelections,
- hierarchy,
- setBoundarySelections,
- boundaryData,
- setIsLoading
- );
- }}
- />
- ) : (
- 5 ? { height: "13.75rem" } : {}}
- type={"multiselectdropdown"}
- t={t}
- options={Digit.Utils.microplan.processDropdownForNestedMultiSelect(item?.dropDownOptions) || []}
- optionsKey="name"
- addSelectAllCheck={true}
- onSelect={(e) => {
- setChangedBoundaryType(item?.boundaryType);
- Digit.Utils.microplan.handleSelection(
- e,
- item?.boundaryType,
- boundarySelections,
- hierarchy,
- setBoundarySelections,
- boundaryData,
- setIsLoading
- );
- }}
- variant="nestedmultiselect"
- />
- )}
-
- ))}
-
- );
-});
-
-export const DataPreview = memo(
- ({ previewData, isCampaignLoading, ishierarchyLoading, resources, userEditedResources, setUserEditedResources, modal, setModal, data, t }) => {
- if (!previewData) return;
- const [tempResourceChanges, setTempResourceChanges] = useState(userEditedResources);
- const [selectedRow, setSelectedRow] = useState();
- const conmmonColumnIndex = useMemo(() => {
- return previewData?.[0]?.indexOf(commonColumn);
- }, [previewData]);
- if (isCampaignLoading || ishierarchyLoading) {
- return (
-
-
-
- );
- }
-
- const rowClick = useCallback((rowIndex) => {
- setSelectedRow(rowIndex);
- setModal("change-preview-data");
- }, []);
-
- const finaliseRowDataChange = () => {
- setUserEditedResources(tempResourceChanges);
- setModal("none");
- setSelectedRow(undefined);
- };
-
- const modalCloseHandler = () => {
- setModal("none");
- setSelectedRow(undefined);
- };
-
- return (
-
-
-
-
-
- {previewData[0].map((header, columnIndex) => (
-
- {t(header)}
- |
- ))}
-
-
-
- {previewData.slice(1).map((rowData, rowIndex) => {
- const rowDataList = Object.values(previewData[0]).map((header, cellIndex) => (
-
- {cellIndex === 0 &&
- userEditedResources?.[rowData?.[conmmonColumnIndex]] &&
- Object.keys(userEditedResources?.[rowData?.[conmmonColumnIndex]]).length !== 0 && }
-
- {rowData[cellIndex] || rowData[cellIndex] === 0 ? rowData[cellIndex] : t("NO_DATA")}
- |
- ));
- return (
- {
- rowClick(rowIndex + 1);
- }}
- // style={{...(userEditedResources?.[rowData?.[conmmonColumnIndex]] && Object.keys(userEditedResources?.[rowData?.[conmmonColumnIndex]]).length !==0
- // ? { borderL: "1px solid rgba(244, 119, 56, 0.12)" }
- // : {}),}}
- >
- {rowDataList}
-
- );
- })}
-
-
-
- {modal === "change-preview-data" && (
-
- }
- headerBarEnd={}
- actionCancelLabel={t("CANCLE")}
- actionCancelOnSubmit={modalCloseHandler}
- actionSaveLabel={t("SAVE_CHANGES")}
- actionSaveOnSubmit={finaliseRowDataChange}
- formId="modal-action"
- >
-
-
-
- )}
-
- );
- }
-);
-
-export const AppplyChangedHypothesisConfirmation = ({ newhypothesisList, hypothesisList, t }) => {
- const data = filterObjects(newhypothesisList, hypothesisList);
- return (
-
-
-
{t("INSTRUCTION_PROCEED_WITH_NEW_HYPOTHESIS")}
-
-
- {t("MICROPLAN_PREVIEW_HYPOTHESIS")}
-
-
-
-
-
- {t("KEYS")} |
- {t("OLD_VALUE")} |
- {t("NEW_VALUE")} |
-
-
-
- {data?.map((row, index) => (
-
- {t(row?.key)} |
- {t(row?.oldValue)} |
- {t(row?.value)} |
-
- ))}
-
-
-
-
- );
-};
-
-export const EditResourceData = ({ previewData, selectedRow, resources, tempResourceChanges, setTempResourceChanges, data, t }) => {
- const conmmonColumnData = useMemo(() => {
- const index = previewData?.[0]?.indexOf(commonColumn);
- if (index === -1) return;
- return previewData?.[selectedRow]?.[index];
- }, [previewData]);
-
- const valueChangeHandler = (item, value) => {
- if (!conmmonColumnData) return;
- if (isNaN(value) || (!isFinite(value) && value !== "")) return;
- let changedDataAgainstBoundaryCode = tempResourceChanges?.[conmmonColumnData] || {};
- changedDataAgainstBoundaryCode[item] = value === "" ? undefined : parseFloat(value);
- setTempResourceChanges((previous) => ({ ...previous, [conmmonColumnData]: changedDataAgainstBoundaryCode }));
- };
-
- return (
-
-
-
-
- {t("COLUMNS")} |
- {t("OLD_VALUE")} |
- {t("NEW_VALUE")} |
-
-
-
- {data[0].map((item) => {
- let index = data?.[0]?.indexOf(item);
- if (index === -1) return;
- const currentData = data?.[selectedRow]?.[index];
- return (
-
-
- {t(item)}
- |
-
- {currentData || t("NO_DATA")}
- |
-
-
- |
-
- );
- })}
- {resources.map((item) => {
- let index = previewData?.[0]?.indexOf(item);
- if (index === -1) return;
- const currentData = previewData?.[selectedRow]?.[index];
-
- return (
-
-
- {t(item)}
- |
-
- {currentData || t("NO_DATA")}
- |
-
- valueChangeHandler(item, value.target.value)}
- />
- |
-
- );
- })}
-
-
-
- );
-};
-
-export const Aggregates = memo(({ microplanPreviewAggregates, dataToShow, NumberFormatMappingForTranslation, t }) => {
- const { formatNumber } = useNumberFormatter(NumberFormatMappingForTranslation?.reduce((acc, obj) => Object.assign(acc, obj), {}));
-
- if (!microplanPreviewAggregates) return null;
- return (
-
- {microplanPreviewAggregates.map((item, index) => {
- const aggregate = calculateAggregateValue(item, dataToShow);
- return (
-
-
{isNaN(parseInt(aggregate)) ? 0 : formatNumber(parseInt(aggregate))}
-
{typeof item === "object" && item.name ? t(item.name) : t(item)}
-
- );
- })}
-
- );
-});
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/MicroplanningCard.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/MicroplanningCard.js
deleted file mode 100644
index 9a1dd8f5500..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/MicroplanningCard.js
+++ /dev/null
@@ -1,34 +0,0 @@
-import { EmployeeModuleCard, WorksMgmtIcon } from "@egovernments/digit-ui-react-components";
-import React from "react";
-import { useTranslation } from "react-i18next";
-
-const ROLES = {
- MICROPLAN: ["MICROPLAN_ADMIN"],
-};
-
-const MicroplanningCard = () => {
- const { t } = useTranslation();
- const tenantId = Digit.ULBService.getCurrentTenantId();
-
- const generateLink = (labelKey, pathSuffix) => {
- return {
- label: t(labelKey),
- link: `/${window?.contextPath}/employee/microplanning/${pathSuffix}`,
- roles: ROLES.MICROPLAN,
- };
- };
-
- let links = [generateLink("CREATE_NEW_MICROPLAN", "select-campaign"), generateLink("OPEN_SAVED_MICROPLANS", "saved-microplans")];
-
- links = links.filter((link) => (link?.roles && link?.roles?.length > 0 ? Digit.Utils.didEmployeeHasAtleastOneRole(link?.roles) : true));
-
- const propsForModuleCard = {
- Icon: ,
- moduleName: t("Microplanning"),
- kpis: [],
- links: links,
- };
- return ;
-};
-
-export default MicroplanningCard;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/MicroplanningHeader.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/MicroplanningHeader.js
deleted file mode 100644
index 2a35e9c0995..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/MicroplanningHeader.js
+++ /dev/null
@@ -1,29 +0,0 @@
-import { Help, Tutorial, useTourState } from "@egovernments/digit-ui-react-components";
-import React, { Fragment } from "react";
-import { useTranslation } from "react-i18next";
-import { useLocation } from "react-router-dom";
-import { useMyContext } from "../utils/context";
-import { PRIMARY_THEME_COLOR } from "../configs/constants";
-
-const MicroplanningHeader = () => {
- const { tourState, setTourState } = useTourState();
- const { state } = useMyContext();
- const { t } = useTranslation();
- //using location.pathname we can update the stepIndex accordingly when help is clicked from any other screen(other than home screen)
- const { pathname } = useLocation();
-
- const startTour = () => {
- if (state?.tourStateData) setTourState(state.tourStateData);
- };
-
- return (
- <>
-
-
-
-
- >
- );
-};
-
-export default MicroplanningHeader;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/Modal.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/Modal.js
deleted file mode 100644
index 0792ee2e52d..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/Modal.js
+++ /dev/null
@@ -1,158 +0,0 @@
-import React, { useEffect } from "react";
-import { PopUp, HeaderBar, Toast, CloseButton, ButtonSelector } from "@egovernments/digit-ui-react-components";
-import { Close } from "@egovernments/digit-ui-svg-components";
-import { PRIMARY_THEME_COLOR } from "../configs/constants";
-
-const Modal = ({
- headerBarMain,
- headerBarEnd,
- popupStyles,
- children = {},
- actionCancelLabel,
- actionCancelOnSubmit,
- actionSaveLabel,
- actionSaveOnSubmit,
- error,
- setError,
- formId,
- isDisabled,
- hideSubmit,
- style = {},
- footerLeftButtonstyle = {},
- footerRightButtonstyle = {},
- footerLeftButtonBody,
- footerRightButtonBody,
- popupModuleMianStyles,
- headerBarMainStyle,
- isOBPSFlow = false,
- popupModuleActionBarStyles = {},
-}) => {
- /**
- * TODO: It needs to be done from the desgin changes
- */
- const mobileView = Digit.Utils.browser.isMobile();
- useEffect(() => {
- document.body.style.overflowY = "hidden";
- return () => {
- document.body.style.overflowY = "auto";
- };
- }, []);
-
- return (
-
-
-
-
- {children}
-
- {actionCancelLabel || footerLeftButtonBody ? (
- 0 ? style : footerLeftButtonstyle}
- />
- ) : null}
- {!hideSubmit ? (
- 0 ? style : footerRightButtonstyle}
- />
- ) : null}
-
-
-
- {error && setError(null)} type="error" />}
-
- );
-};
-
-const moduleActionBarStyle = (isOBPSFlow, popupModuleActionBarStyles) => {
- return isOBPSFlow
- ? !mobileView
- ? { marginRight: "18px" }
- : { position: "absolute", bottom: "5%", right: "10%", left: window.location.href.includes("employee") ? "0%" : "7%" }
- : popupModuleActionBarStyles;
-};
-
-// Wrapper for modal
-export const ModalWrapper = ({
- closeModal,
- LeftButtonHandler,
- RightButtonHandler,
- footerLeftButtonBody,
- footerRightButtonBody,
- header,
- bodyText,
- body,
- popupStyles,
- headerBarMainStyle,
- popupModuleActionBarStyles,
- hideSubmit,
- closeButton = false,
- actionCancelLabel,
-}) => {
- return (
-
- {" "}
-
-
- ) : (
- ""
- )
- }
- actionCancelOnSubmit={LeftButtonHandler}
- actionSaveOnSubmit={RightButtonHandler}
- formId="microplanning"
- popupStyles={{ width: "33.375rem", borderRadius: "0.25rem", ...(popupStyles ? popupStyles : {}) }}
- headerBarMainStyle={{ margin: 0, width: "33.375rem", overflow: "hidden", ...(headerBarMainStyle ? headerBarMainStyle : {}) }}
- popupModuleMianStyles={{ margin: 0, padding: 0 }}
- popupModuleActionBarStyles={popupModuleActionBarStyles ? popupModuleActionBarStyles : { justifyContent: "space-between", padding: "1rem" }}
- style={{}}
- hideSubmit={hideSubmit ? hideSubmit : false}
- footerLeftButtonstyle={{
- padding: 0,
- alignSelf: "flex-start",
- height: "fit-content",
- textStyles: { fontWeight: "600" },
- backgroundColor: "rgba(255, 255, 255, 1)",
- color: PRIMARY_THEME_COLOR,
- minWidth: "15.063rem",
- border: `0.063rem solid ${PRIMARY_THEME_COLOR}`,
- }}
- footerRightButtonstyle={{
- padding: 0,
- alignSelf: "flex-end",
- height: "fit-content",
- textStyles: { fontWeight: "500" },
- backgroundColor: PRIMARY_THEME_COLOR,
- color: "rgba(255, 255, 255, 1)",
- minWidth: "15.063rem",
- boxShadow: "0px -2px 0px 0px rgba(11, 12, 12, 1) inset",
- }}
- footerLeftButtonBody={footerLeftButtonBody}
- footerRightButtonBody={footerRightButtonBody}
- actionCancelLabel={actionCancelLabel}
- >
- {bodyText && (
-
- )}
- {body ? body : ""}
-
- );
-};
-
-export default Modal;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/Nagivator.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/Nagivator.js
deleted file mode 100644
index 06d04ef2296..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/Nagivator.js
+++ /dev/null
@@ -1,272 +0,0 @@
-import { ActionBar, Stepper, Toast } from "@egovernments/digit-ui-components";
-import PropTypes from "prop-types";
-import React, { useState, useEffect, useCallback } from "react";
-import { useTranslation } from "react-i18next";
-import { Button } from "@egovernments/digit-ui-react-components";
-import { ArrowBack, ArrowForward } from "@egovernments/digit-ui-svg-components";
-import { PRIMARY_THEME_COLOR } from "../configs/constants";
-import { memo } from "react";
-
-/**
- *
- * @param { config: Object, checkDataCompleteness: boolean, components: Object, childProps: Object, stepNavigationActive: boolean, nextEventAddon: function, setCurrentPageExternally: function, completeNavigation } props
- * @returns
- *
- */
-// Main component for creating a microplan
-const Navigator = memo((props) => {
- // States
- const [currentPage, setCurrentPage] = useState();
- // const [toast, setToast] = useState();
- const [navigationEvent, setNavigationEvent] = useState();
- const [activeSteps, setActiveSteps] = useState(Digit.SessionStorage.get("microplanHelperData")?.activeSteps || -1);
- /**
- * checkDataCompletion
- * "true": check for data completeness
- * "false": do nothing
- * "valid": data is present
- * "invalid": whole or a part of the data is missing
- * "perform-action": move to the respective step ( had to add this as mutate addons need some buffer time)
- */
- const [checkDataCompletion, setCheckDataCompletion] = useState("false");
-
- const { t } = useTranslation();
-
- // Effect to set initial current page when timeline options change
- useEffect(() => {
- if (!props.config || props.config.length === 0) return;
- let response;
- if (props.setCurrentPageExternally) {
- response = props.setCurrentPageExternally({ setCurrentPage, method: "set" });
- }
- if (!response) setCurrentPage(props.config[0]);
- }, [props.config]);
-
- // Might need it later
- // Effect to handle data completion validation and show toast
- useEffect(() => {
- if (checkDataCompletion === "invalid") {
- if (navigationEvent && navigationEvent.name === "next") {
- props?.setToast({ state: "error", message: t("MICROPLAN_PLEASE_FILL_ALL_THE_FIELDS_AND_RESOLVE_ALL_THE_ERRORS") });
- } else if (navigationEvent && navigationEvent.name === "step" && navigationEvent.step !== undefined) {
- if (navigationEvent.step > currentPage.id)
- props?.setToast({ state: "error", message: t("MICROPLAN_PLEASE_FILL_ALL_THE_FIELDS_AND_RESOLVE_ALL_THE_ERRORS") });
- else onStepClick(navigationEvent.step);
- } else if (navigationEvent && navigationEvent.name === "previousStep") previousStep();
- setCheckDataCompletion("false");
- }
- }, [checkDataCompletion]);
-
- // Effect to handle navigation events and transition between steps
- useEffect(() => {
- // if (checkDataCompletion !== "valid" || navigationEvent === undefined) return;
- if (
- checkDataCompletion === "valid" &&
- ((navigationEvent.step && currentPage.id + 1 === navigationEvent.step) || currentPage.id > navigationEvent.step || !navigationEvent.step)
- ) {
- if (typeof props.nextEventAddon === "function") {
- if (LoadCustomComponent({ component: props.components[currentPage?.component] }) !== null)
- props.nextEventAddon(currentPage, checkDataCompletion, setCheckDataCompletion);
- else props.nextEventAddon(currentPage, true, setCheckDataCompletion);
- } else {
- setCheckDataCompletion("perform-action");
- }
- }
- }, [navigationEvent, checkDataCompletion, props.nextEventAddon]);
-
- useEffect(() => {
- handleNavigationEvent(
- checkDataCompletion,
- navigationEvent,
- currentPage,
- setCheckDataCompletion,
- setNavigationEvent,
- onStepClick,
- nextStep,
- previousStep,
- props
- );
- }, [checkDataCompletion, navigationEvent]);
-
- // Function to navigate to the next step
- const nextStep = useCallback(() => {
- if (!currentPage) return;
- changeCurrentPage(props.config[currentPage?.id + 1]);
- if (currentPage?.id + 1 > props.config.length - 1) return;
- setCurrentPage((previous) => props.config[previous?.id + 1]);
- }, [currentPage]);
-
- // Function to navigate to the previous step
- const previousStep = useCallback(() => {
- changeCurrentPage(props.config[currentPage?.id - 1]);
- setCurrentPage((previous) => props.config[previous?.id - 1]);
- }, [currentPage]);
-
- // Function to handle step click and navigate to the selected step
- const onStepClick = useCallback((index) => {
- const newCurrentPage = props.config.find((item) => item.id === index);
- changeCurrentPage(newCurrentPage);
- setCurrentPage(newCurrentPage);
- });
-
- // Function to handle next button click
- const previousbuttonClickHandler = useCallback(() => {
- if (
- (props.checkDataCompleteness &&
- props?.config[currentPage?.id]?.checkForCompleteness &&
- LoadCustomComponent({ component: props.components[currentPage?.component] }) !== null) ||
- currentPage?.id === props.config[props.config.length - 1].id
- ) {
- setNavigationEvent({ name: "previousStep" });
- setCheckDataCompletion("true");
- } else previousStep();
- }, [props.checkDataCompleteness, previousStep, setNavigationEvent]);
-
- // Function to handle next button click
- const nextbuttonClickHandler = useCallback(() => {
- if (
- props.checkDataCompleteness &&
- props?.config[currentPage?.id]?.checkForCompleteness &&
- LoadCustomComponent({ component: props.components[currentPage?.component] }) !== null
- ) {
- setCheckDataCompletion("true");
- setNavigationEvent({ name: "next" });
- } else nextStep();
- }, [props.checkDataCompleteness, nextStep, setNavigationEvent]);
-
- // Function to handle step click
- const stepClickHandler = useCallback(
- (index) => {
- if (index === currentPage?.id) return;
- if (!props.stepNavigationActive) return;
- if (
- (props.checkDataCompleteness &&
- props?.config[currentPage?.id]?.checkForCompleteness &&
- LoadCustomComponent({ component: props.components[currentPage?.component] }) !== null) ||
- currentPage?.id === props.config[props.config.length - 1].id
- ) {
- setCheckDataCompletion("true");
- setNavigationEvent({ name: "step", step: index });
- } else {
- onStepClick(index);
- }
- },
- [props.checkDataCompleteness, props.stepNavigationActive, onStepClick]
- );
-
- // Function to set current page
- const changeCurrentPage = (newPage) => {
- if (props.setCurrentPageExternally) {
- props.setCurrentPageExternally({ currentPage: newPage, method: "save" });
- }
- };
-
- const completeNavigation = () => {
- setNavigationEvent({ name: "next" });
- setCheckDataCompletion("true");
- };
-
- // changing active state
- useEffect(() => {
- if (currentPage?.id > activeSteps) {
- setActiveSteps(currentPage?.id);
- Digit.SessionStorage.set("microplanHelperData", { ...(Digit.SessionStorage.get("microplanHelperData") || {}), activeSteps: currentPage?.id });
- }
- }, [currentPage]);
-
- return (
-
- {/* Stepper component */}
-
t(item.name))}
- direction="horizontal"
- activeSteps={activeSteps >= 0 ? activeSteps + 1 : null}
- onStepClick={stepClickHandler}
- />
-
- {/* Load custom component based on current page */}
- {props?.components[currentPage?.component] ? (
- LoadCustomComponent({ component: props.components[currentPage?.component] }) !== null ? (
-
- ) : (
- {t("COMMON_DATA_NOT_PRESENT")}
- )
- ) : (
- ""
- )}
-
- {/* Action bar */}
-
- {/* Back button */}
- {currentPage?.id > 0 && (
- }
- />
- )}
- {/* Next/Submit button */}
-
-
-
-
-
- );
-});
-
-// Component to load custom component based on current page
-const LoadCustomComponent = (props) => {
- if (props && !props.component) return null;
- const secondaryProps = props.secondaryProps;
- return ;
-};
-LoadCustomComponent.propTypes = {
- component: PropTypes.elementType.isRequired,
- secondaryProps: PropTypes.object,
-};
-
-const handleNavigationEvent = (
- checkDataCompletion,
- navigationEvent,
- currentPage,
- setCheckDataCompletion,
- setNavigationEvent,
- onStepClick,
- nextStep,
- previousStep,
- props
-) => {
- if (checkDataCompletion === "perform-action") {
- if (navigationEvent && navigationEvent.name === "next") {
- if (currentPage?.id === props.config.length - 1 && typeof props?.completeNavigation === "function") {
- return props?.completeNavigation();
- }
- nextStep();
- } else if (navigationEvent && navigationEvent.name === "step" && navigationEvent.step !== undefined) onStepClick(navigationEvent.step);
- else if (navigationEvent && navigationEvent.name === "previousStep") previousStep();
- setCheckDataCompletion("false");
- setNavigationEvent(undefined);
- }
-};
-
-export default Navigator;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/RuleEngine.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/RuleEngine.js
deleted file mode 100644
index 7ece3cce04d..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/RuleEngine.js
+++ /dev/null
@@ -1,876 +0,0 @@
-import React, { useState, useEffect, useCallback, Fragment, useRef } from "react";
-import { useTranslation } from "react-i18next";
-import { Info, Trash } from "@egovernments/digit-ui-svg-components";
-import { ModalHeading } from "./CommonComponents";
-import { Button, Modal } from "@egovernments/digit-ui-react-components";
-import { Dropdown, InfoCard, Toast } from "@egovernments/digit-ui-components";
-import { tourSteps } from "../configs/tourSteps";
-import { useMyContext } from "../utils/context";
-import { v4 as uuidv4 } from "uuid";
-import { PlusWithSurroundingCircle } from "../icons/Svg";
-import { PRIMARY_THEME_COLOR } from "../configs/constants";
-
-const page = "ruleEngine";
-
-const RuleEngine = ({
- campaignType = Digit.SessionStorage.get("microplanHelperData")?.campaignData?.projectType,
- microplanData,
- setMicroplanData,
- checkDataCompletion,
- setCheckDataCompletion,
- currentPage,
- pages,
- setToast,
-}) => {
- const { t } = useTranslation();
-
- // States
- const [editable, setEditable] = useState(true);
- const [modal, setModalState] = useState("none");
- const [rules, setRules] = useState([]);
- const [hypothesisAssumptionsList, setHypothesisAssumptionsList] = useState([]);
- const [itemForDeletion, setItemForDeletion] = useState();
- const [exampleOption, setExampleOption] = useState("");
- const [inputs, setInputs] = useState([]);
- const [outputs, setOutputs] = useState([]);
- const [operators, setOperators] = useState([]);
- const [validationSchemas, setValidationSchemas] = useState([]);
- const [autofillData, setAutoFillData] = useState([]);
- const { state, dispatch } = useMyContext();
- const [originalRuleOutputCount, setOriginalRuleOutputCount] = useState(0);
- // const [toast, setToast] = useState();
- const [pureInputList, setPureInputList] = useState([]);
- // Set TourSteps
- useEffect(() => {
- const tourData = tourSteps(t)?.[page] || {};
- if (state?.tourStateData?.name === page) return;
- dispatch({
- type: "SETINITDATA",
- state: { tourStateData: tourData },
- });
- }, []);
-
- const setModal = (modalString) => {
- const elements = document.querySelectorAll(".popup-wrap-rest-unfocus");
- elements.forEach((element) => {
- element.classList.toggle("popup-wrap-rest-unfocus-active");
- });
- setModalState(modalString);
- };
-
- // UseEffect to extract data on first render
- useEffect(() => {
- if (pages) {
- const previouspage = pages[currentPage?.id - 1];
- if (previouspage?.checkForCompleteness && !microplanData?.status?.[previouspage?.name]) setEditable(false);
- else setEditable(true);
- }
- }, []);
-
- // UseEffect for checking completeness of data before moveing to next section
- useEffect(() => {
- if (!rules || checkDataCompletion !== "true" || !setCheckDataCompletion) return;
- // uncomment to activate data change save check
- // if (!microplanData?.ruleEngine || !_.isEqual(rules, microplanData.ruleEngine)) setModal("data-change-check");
- // else
- updateData(true);
- }, [checkDataCompletion]);
-
- // UseEffect to store current data
- useEffect(() => {
- if (!rules || !setMicroplanData) return;
- setMicroplanData((previous) => ({ ...previous, ruleEngine: rules }));
- }, [rules]);
-
- // UseEffect to add a event listener for keyboard
- useEffect(() => {
- window.addEventListener("keydown", handleKeyPress);
-
- return () => window.removeEventListener("keydown", handleKeyPress);
- }, [modal]);
-
- const handleKeyPress = (event) => {
- // if (modal !== "upload-guidelines") return;
- if (["x", "Escape"].includes(event.key)) {
- // Perform the desired action when "x" or "esc" is pressed
- // if (modal === "upload-guidelines")
- setCheckDataCompletion("false");
- setModal("none");
- }
- };
-
- // check if data has changed or not
- const updateData = useCallback(
- (check) => {
- if (!rules || !setMicroplanData) return;
- if (check) {
- setMicroplanData((previous) => ({ ...previous, ruleEngine: rules }));
- const activeRules = rules.filter((item) => item.active);
- const isValid = activeRules.every((item) => Object.values(item).every((data) => data !== "")) && activeRules.length !== 0;
- if (isValid) setCheckDataCompletion("valid");
- else setCheckDataCompletion("invalid");
- } else {
- let isValid = microplanData?.ruleEngine?.every((item) => Object.values(item).every((data) => data !== ""));
- isValid = isValid && rules.length !== 0;
- if (isValid) setCheckDataCompletion("valid");
- else setCheckDataCompletion("invalid");
- }
- },
- [rules, setMicroplanData, microplanData, setCheckDataCompletion]
- );
-
- const cancelUpdateData = useCallback(() => {
- setCheckDataCompletion(false);
- setModal("none");
- }, [setCheckDataCompletion, setModal]);
-
- // useEffect to initialise the data from MDMS
- useEffect(() => {
- if (!state) return;
- const schemas = state?.Schemas;
- const hypothesisAssumptions = [];
- microplanData?.hypothesis?.filter((item) => item.active).forEach((item) => (item.key !== "" ? hypothesisAssumptions.push(item.key) : null));
- const ruleConfigureOutput = state?.RuleConfigureOutput;
- const UIConfiguration = state?.UIConfiguration;
- const ruleConfigureInputs = getRuleConfigInputsFromSchema(campaignType, microplanData, schemas) || [];
- let AutoFilledRuleConfigurationsList = state?.AutoFilledRuleConfigurations;
- AutoFilledRuleConfigurationsList = AutoFilledRuleConfigurationsList.find((item) => item.campaignType === campaignType)?.data;
- microplanData?.ruleEngine?.forEach((item) => {
- if (Object.values(item).every((e) => e !== "")) ruleConfigureInputs.push(item?.output);
- });
- if (schemas) setValidationSchemas(schemas);
-
- let temp;
- setHypothesisAssumptionsList(hypothesisAssumptions);
- let outputs;
- if (ruleConfigureOutput) temp = ruleConfigureOutput?.find((item) => item.campaignType === campaignType);
- if (temp?.data) {
- let data = temp.data;
- setOriginalRuleOutputCount(data.length);
- microplanData?.ruleEngine?.forEach((item) => {
- if (item.active) {
- const filteredData = data.filter((e) => e !== item?.output);
- data = filteredData;
- }
- });
- outputs = data;
- setOutputs(data);
- }
-
- if (ruleConfigureInputs) setInputs(ruleConfigureInputs);
- let operator;
- if (UIConfiguration) temp = UIConfiguration.find((item) => item.name === "ruleConfigure");
- if (temp?.ruleConfigureOperators) {
- temp = temp.ruleConfigureOperators.map((item) => item.name);
- operator = temp;
- setOperators(temp);
- }
- // if (AutoFilledRuleConfigurationsList) setAutoFillData(AutoFilledRuleConfigurationsList);
- // Pure inputs - output not there
- const pureInputs = getRuleConfigInputsFromSchema(campaignType, microplanData, schemas);
- setPureInputList(pureInputs);
-
- const ssnRuleOutputs = microplanData?.ruleEngine?.reduce((acc, item) => {
- if (item?.active && item?.output) acc.push(item?.output);
- return acc;
- }, []);
- const tempOutput = [...outputs, ...(ssnRuleOutputs ? ssnRuleOutputs : [])];
- setExampleOption({
- output: tempOutput.length ? tempOutput[0] : "",
- input: pureInputs.length ? pureInputs[0] : "",
- operator: operator.length ? operator[0] : "",
- assumptionValue: hypothesisAssumptions.length ? hypothesisAssumptions[0] : "",
- });
-
- let filteredRules = [];
- let response;
- if (microplanData?.ruleEngine && microplanData?.hypothesis) {
- const hypothesisAssumptions = microplanData?.hypothesis?.filter((item) => item.active && item.key !== "").map((item) => item.key) || [];
- if (hypothesisAssumptions.length !== 0) {
- setHypothesisAssumptionsList(hypothesisAssumptions);
- response = filterRulesAsPerConstrains(
- microplanData.ruleEngine,
- [],
- hypothesisAssumptions,
- tempOutput,
- operator,
- pureInputs,
- setInputs,
- setOutputs,
- false
- );
- filteredRules = response?.rules;
-
- // setRuleEngineDataFromSsn(microplanData.ruleEngine, hypothesisAssumptions, setRules);
- }
- }
- if (response?.rulesDeleted)
- setToast({
- state: "warning",
- message: t("WARNING_RULES_DELETED_DUE_TO_PRIOR_SECTION_DATA_CHANGES"),
- });
- if (!AutoFilledRuleConfigurationsList || !outputs || !hypothesisAssumptions || !schemas) return;
-
- response = filterRulesAsPerConstrains(
- AutoFilledRuleConfigurationsList,
- filteredRules,
- hypothesisAssumptions,
- outputs,
- operator,
- pureInputs,
- setInputs,
- setOutputs,
- true
- );
-
- if (response?.rules) setRules(response?.rules);
- }, []);
-
- const closeModal = useCallback(() => {
- setModal("none");
- }, [setModal]);
-
- // Function to Delete an assumption
- const deleteAssumptionHandlerCallback = useCallback(() => {
- deleteAssumptionHandler(itemForDeletion, setItemForDeletion, setRules, setOutputs, setInputs, pureInputList);
- closeModal();
- }, [itemForDeletion, deleteAssumptionHandler, setItemForDeletion, setRules, setOutputs, setInputs, closeModal, pureInputList]);
-
- const sectionClass = `jk-header-btn-wrapper rule-engine-section ${editable ? "" : "non-editable-component"} popup-wrap-rest-unfocus`;
- return (
- <>
-
-
-
- {/* NonInterractable Section */}
-
- {/* Interractable Section that includes the example as well as the rules */}
-
-
-
-
}
- className="add-button"
- onButtonClick={() => addRulesHandler(setRules)}
- label={t("ADD_ROW")}
- isDisabled={rules?.filter((item) => item.active)?.length === originalRuleOutputCount}
- />
-
-
- {/* delete conformation */}
-
- {modal === "delete-conformation" && (
-
}
- actionCancelLabel={t("YES")}
- actionCancelOnSubmit={deleteAssumptionHandlerCallback}
- actionSaveLabel={t("NO")}
- actionSaveOnSubmit={closeModal}
- >
-
-
{t("RULE_ENGINE_INSTRUCTIONS_DELETE_ENTRY_CONFIRMATION")}
-
-
- )}
-
- >
- );
-};
-
-// Function to add a new assumption
-const addRulesHandler = (setRules) => {
- const uuid = uuidv4();
- setRules((previous) => [
- ...previous,
- {
- id: uuid,
- // previous.length ? previous[previous.length - 1].id + 1 : 0,
- output: "",
- input: "",
- operator: "",
- assumptionValue: "",
- active: true,
- },
- ]);
-};
-
-// Defination for NonInterractable Section
-const NonInterractableSection = React.memo(({ t }) => {
- return (
-
-
{t("HEADING_RULE_ENGINE")}
-
{t("INSTRUCTION_RULE_ENGINE")}
-
- );
-});
-
-// Defination for NonInterractable Section
-const InterractableSection = React.memo(
- ({
- rules,
- setRules,
- hypothesisAssumptionsList,
- setHypothesisAssumptionsList,
- setModal,
- setItemForDeletion,
- exampleOption,
- inputs,
- outputs,
- operators,
- setInputs,
- setOutputs,
- setOperators,
- pureInputList,
- t,
- }) => {
- // References to the items in the list
- const itemRefs = useRef([]);
- // State to keep track of the currently expanded item index
- const [expandedIndex, setExpandedIndex] = useState(null);
- // Reference to the scroll container
- const scrollContainerRef = useRef(null);
- // State to track the render cycle count
- const [renderCycle, setRenderCycle] = useState(0);
-
- // Effect to reset the render cycle count whenever the expandedIndex changes
- useEffect(() => {
- if (expandedIndex !== null) {
- setRenderCycle(0);
- }
- }, [expandedIndex]);
-
- // Effect to handle scrolling to the expanded item after the DOM has updated
- useEffect(() => {
- if (renderCycle < 3) {
- // Increment render cycle count to ensure multiple render checks
- setRenderCycle((prev) => prev + 1);
- } else if (expandedIndex !== null && itemRefs.current[expandedIndex]) {
- try {
- const parentElement = itemRefs.current[expandedIndex];
- const childElement = itemRefs.current[expandedIndex].children[1];
-
- if (parentElement) {
- const scrollContainer = scrollContainerRef.current;
- const parentRect = parentElement.getBoundingClientRect();
- const containerRect = scrollContainer.getBoundingClientRect();
-
- // Calculate the offset from the top of the container
- const offset = parentRect.top - containerRect.top;
-
- // Scroll the container to the target position
- scrollContainer.scrollTo({
- top: scrollContainer.scrollTop + offset - 100,
- behavior: "smooth",
- });
- }
-
- if (childElement) {
- // Focus the child element if it exists
- childElement.focus();
- }
- } catch (error) {
- console.error("Error scrolling to element:", error);
- }
- }
- }, [renderCycle, expandedIndex]);
-
- // Effect to observe DOM changes in the expanded item and trigger render cycle
- useEffect(() => {
- if (expandedIndex !== null) {
- const observer = new MutationObserver(() => {
- setRenderCycle((prev) => prev + 1);
- });
-
- if (itemRefs.current[expandedIndex]) {
- observer.observe(itemRefs.current[expandedIndex], { childList: true, subtree: true });
- }
-
- return () => observer.disconnect();
- }
- }, [expandedIndex]);
-
- // Function to toggle the expanded state of an item
- const toggleExpand = (index) => {
- setExpandedIndex(index === expandedIndex ? null : index);
- };
-
- // Handler for deleting an assumption on conformation
- const deleteHandler = useCallback(
- (item) => {
- setModal("delete-conformation");
- setItemForDeletion(item);
- },
- [setModal, setItemForDeletion]
- );
-
- return (
-
-
-
-
-
-
=
-
-
{t("RULE_ENGINE_INPUT")}
-
-
-
{t("RULE_ENGINE_OPERATOR")}
-
-
-
-
deleteHandler(item)} aria-label={t("DELETE")} role="button" type="button">
- {Trash && }
- {t("DELETE")}
-
-
-
- {rules
- .filter((item) => item.active)
- .map((item, index) => (
-
{
- itemRefs.current[index] = el;
- }}
- onClick={() => toggleExpand(index)}
- >
-
-
-
-
-
=
-
-
-
-
-
-
-
-
-
-
-
-
deleteHandler(item)}
- onKeyDown={(e) => e.key === "Enter" && deleteHandler(item)}
- aria-label={t("DELETE")}
- role="button"
- type="button"
- >
- {Trash && }
- {t("DELETE")}
-
-
-
- ))}
-
-
- );
- }
-);
-
-const Example = ({ exampleOption, t }) => {
- return (
-
-
-
{t("EXAMPLE")}
-
-
-
{t("VALUE")}
-
-
{t("RULE_ENGINE_VALUE_HELP_TEXT")}
-
-
-
-
-
-
{t("RULE_ENGINE_INPUT")}
-
-
{t("RULE_ENGINE_INPUT_HELP_TEXT")}
-
-
-
{t("RULE_ENGINE_OPERATOR")}
-
-
{t("RULE_ENGINE_OPERATOR_HELP_TEXT")}
-
-
-
{t("KEY")}
-
-
{t("RULE_ENGINE_KEY_HELP_TEXT")}
-
-
-
-
-
- {Trash && }
- {t("DELETE")}
-
-
-
- );
-};
-
-const deleteAssumptionHandler = (item, setItemForDeletion, setRules, setOutputs, setInputs, pureInputList) => {
- try {
- const outputToRemove = [];
- setRules((previous) => {
- if (!previous.length) return [];
- const deletionElementIndex = previous.findIndex((data) => data.id === item.id);
- const filteredData = previous.map((data, index) => (index === deletionElementIndex ? { ...data, active: false } : data));
- const newRules = filteredData.reduce((acc, dataItem, index) => {
- if (dataItem.active) {
- const possibleOutputs = acc.reduce((reducedData, element, index) => {
- if (element.active && !Object.values(element).some((e) => e === "")) reducedData.push(element?.output);
- return reducedData;
- }, []);
- possibleOutputs.push(...pureInputList);
- if (!possibleOutputs.includes(dataItem?.input)) {
- if (dataItem?.output !== "") outputToRemove.push(dataItem.output);
- acc.push({ ...dataItem, input: "", oldInput: dataItem?.input ? dataItem?.input : dataItem?.oldInput });
- } else {
- acc.push(dataItem);
- }
- } else {
- acc.push(dataItem);
- }
- return acc;
- }, []);
-
- return newRules || [];
- });
- if (item?.output) {
- setOutputs((previous) => {
- if (!previous?.includes(item.output)) return previous ? [...previous, item.output] : [item.output];
- });
- setInputs((previous) => {
- return previous?.filter((e) => e !== item.output && !outputToRemove.includes(e));
- });
- }
- setItemForDeletion();
- } catch (error) {
- console.error("Error while deleting a rule: ", error.message);
- }
-};
-
-const Select = React.memo(
- ({ item, rules, setRules, disabled = false, options, setOptions, toChange, unique, setInputs, outputs, pureInputList, t }) => {
- const [selected, setSelected] = useState("");
- const [filteredOptions, setFilteredOptions] = useState([]);
-
- useEffect(() => {
- if (item) {
- if (outputs?.some((e) => e === item.input)) {
- if (rules.filter((item) => item.active).some((e) => e?.output === item?.input)) setSelected({ code: item?.[toChange] });
- } else setSelected({ code: item[toChange] });
- }
- }, [item]);
-
- useEffect(() => {
- if (!options) return;
- const filteredOptions = options.length ? options : [];
- let filteredOptionPlaceHolder = [];
- if (item?.[toChange] && !filteredOptions.includes(item[toChange])) {
- filteredOptionPlaceHolder = [item[toChange], ...filteredOptions];
- } else filteredOptionPlaceHolder = filteredOptions;
-
- if (toChange === "input") {
- const currentRuleIndex = rules.findIndex((e) => e?.id === item?.id);
- filteredOptionPlaceHolder = filteredOptionPlaceHolder.filter((data) => {
- let priorOutputs = [];
- if (currentRuleIndex !== -1) {
- priorOutputs = rules.reduce((acc, item, index) => {
- if (item.active && index < currentRuleIndex) acc.push(item?.output);
- return acc;
- }, []);
- }
- priorOutputs.push(...pureInputList);
- return data !== item.output && priorOutputs.includes(data);
- });
- }
- setFilteredOptions(filteredOptionPlaceHolder);
- }, [options]);
-
- const selectChangeHandler = useCallback(
- (e) => {
- if (e.code === "SELECT_OPTION") return;
- const existingEntry = rules.find((item) => item.active && item[toChange] === e.code);
- if (existingEntry && unique) {
- console.error("Attempted to add a duplicate entry where uniqueness is required.");
- return;
- }
- const newDataSegment = { ...item };
- newDataSegment[toChange] = e.code;
- setRules((previous) => {
- const filteredAssumptionsList = previous.map((data) => {
- if (data.id === item.id) return newDataSegment;
- return data;
- });
- return filteredAssumptionsList;
- });
- if (typeof setInputs === "function") {
- setInputs((previous) => {
- let temp = _.cloneDeep(previous);
- if (toChange === "output") {
- temp = temp.filter((item) => item !== selected?.code);
- }
- if (!temp.includes(newDataSegment.output) && Object.values(newDataSegment).every((item) => item !== ""))
- temp = [...temp, newDataSegment.output];
-
- const currentRuleIndex = rules.findIndex((e) => e?.id === item?.id);
- temp = temp.filter((data) => {
- let priorOutputs = [];
- if (currentRuleIndex !== -1) {
- priorOutputs = rules.reduce((acc, item, index) => {
- if (index < currentRuleIndex) acc.push(item?.output);
- return acc;
- }, []);
- }
- priorOutputs.push(...pureInputList);
- return data !== item.output && priorOutputs.includes(data);
- });
- return temp;
- });
- }
- if (unique)
- setOptions((previous) => {
- const newOptions = previous.filter((item) => item !== e.code);
- if (selected?.code && !newOptions.includes(selected?.code)) newOptions.unshift(selected?.code);
- return newOptions;
- });
- },
- [rules, item, selected, setRules, setOptions, setInputs]
- );
-
- return (
- ({ code: item }))}
- selected={selected}
- select={selectChangeHandler}
- optionKey="code"
- placeholder={t("SELECT_OPTION")}
- showToolTip={true}
- />
- );
- }
-);
-
-// get schema for validation
-const getRuleConfigInputsFromSchema = (campaignType, microplanData, schemas) => {
- if (!schemas || !microplanData || !microplanData?.upload || !campaignType) return [];
- const sortData = [];
- if (!schemas) return;
- for (const value of microplanData?.upload?.filter((value) => value?.active && value?.error === null) || []) {
- sortData.push({ section: value?.section, fileType: value?.fileType });
- }
- const filteredSchemas =
- schemas?.filter((schema) => {
- if (schema.campaignType) {
- return schema.campaignType === campaignType && sortData.some((entry) => entry.section === schema.section && entry.fileType === schema.type);
- }
- return sortData.some((entry) => entry.section === schema.section && entry.fileType === schema.type);
- }) || [];
- const finalData = filteredSchemas
- ?.flatMap((item) =>
- Object.entries(item?.schema?.Properties || {}).reduce((acc, [key, value]) => {
- if (value?.isRuleConfigureInputs) {
- acc.push(key);
- }
- return acc;
- }, [])
- )
- .filter((item) => !!item);
- return [...new Set(finalData)];
-};
-
-// This function adding the rules configures in MDMS with respect to the canpaign when rule section is empty
-const filterRulesAsPerConstrains = (autofillData, rules, hypothesisAssumptionsList, outputs, operators, inputs, setInputs, setOutputs, autofill) => {
- if (rules && rules.filter((item) => item.active).length !== 0) return { rules };
-
- let wereRulesNotDeleted = true;
- const newRules = [];
- const ruleOuputList = rules ? rules.filter((item) => item.active).map((item) => item?.output) : [];
- let rulePlusInputs;
- if (ruleOuputList) rulePlusInputs = [...inputs, ...ruleOuputList];
- else rulePlusInputs = inputs;
- for (const item of autofillData) {
- let active = !(item && item.active === false);
- const ruleNotCompleteCheck = (!autofill && item && Object.values(item).filter((e) => e === "").length === 0) || autofill;
- if (
- (ruleOuputList?.includes(item?.output) ||
- (outputs && !outputs.includes(item?.output)) ||
- (rulePlusInputs && !rulePlusInputs.includes(item?.input)) ||
- (operators && !operators.includes(item?.operator)) ||
- (hypothesisAssumptionsList && !hypothesisAssumptionsList.includes(item?.assumptionValue)) ||
- !outputs ||
- !rulePlusInputs ||
- !operators ||
- !hypothesisAssumptionsList) &&
- ruleNotCompleteCheck
- ) {
- if (autofill) {
- continue;
- }
- if (active) {
- wereRulesNotDeleted = false;
- active = false;
- }
- }
- if (!item["id"]) {
- const uuid = uuidv4();
- item["id"] = uuid;
- }
- item.active = active;
- newRules.push(item);
- if (active && ruleNotCompleteCheck) {
- rulePlusInputs?.push(item?.output);
- ruleOuputList?.push(item?.output);
- }
- }
- if (newRules.length !== 0) {
- let newOutputs = [];
- outputs.forEach((e) => {
- if (!ruleOuputList.includes(e)) {
- newOutputs.push(e);
- }
- });
- setOutputs(newOutputs);
- setInputs(rulePlusInputs);
- // setRules((previous) => [...previous, ...newRules]);
- }
-
- return { rules: [...(rules ? rules : []), ...newRules], rulesDeleted: !autofill && !wereRulesNotDeleted };
-};
-
-export default RuleEngine;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/Upload.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/Upload.js
deleted file mode 100644
index e6309dd74f3..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/Upload.js
+++ /dev/null
@@ -1,1137 +0,0 @@
-import React, { useState, useEffect, useMemo, Fragment, useCallback } from "react";
-import { useTranslation } from "react-i18next";
-import { LoaderWithGap, Modal } from "@egovernments/digit-ui-react-components";
-import { ModalWrapper } from "./Modal";
-import { geojsonPropertiesValidation } from "../utils/geojsonValidations";
-import { SpatialDataPropertyMapping } from "./resourceMapping";
-import { JsonPreviewInExcelForm } from "./JsonPreviewInExcelForm";
-import { ButtonType1, ButtonType2, CloseButton, ModalHeading } from "./CommonComponents";
-import { Loader } from "@egovernments/digit-ui-components";
-import { EXCEL, FILE_STORE, GEOJSON, PRIMARY_THEME_COLOR, SHAPEFILE } from "../configs/constants";
-import { tourSteps } from "../configs/tourSteps";
-import { useMyContext } from "../utils/context";
-import { v4 as uuidv4 } from "uuid";
-import {
- handleExcelFile,
- validateNamingConvention,
- findReadMe,
- downloadTemplate,
- getSchema,
- prepareExcelFileBlobWithErrors,
- boundaryDataGeneration,
- handleGeojsonFile,
- handleShapefiles,
- convertToSheetArray,
- findGuideLine,
- delay,
-} from "../utils/uploadUtils";
-import { UploadGuideLines, UploadedFile, FileUploadComponent, UploadComponents, UploadInstructions, UploadSection } from "./UploadHelperComponents";
-
-const page = "upload";
-
-const Upload = ({
- MicroplanName = "default",
- campaignType = Digit.SessionStorage.get("microplanHelperData")?.campaignData?.projectType,
- microplanData,
- setMicroplanData,
- checkDataCompletion,
- setCheckDataCompletion,
- currentPage,
- pages,
- navigationEvent,
- setToast,
-}) => {
- const { t } = useTranslation();
-
- // States
- const [editable, setEditable] = useState(true);
- const [sections, setSections] = useState([]);
- const [selectedSection, setSelectedSection] = useState(null);
- const [modal, setModalState] = useState("none");
- const [selectedFileType, setSelectedFileType] = useState(null);
- const [dataPresent, setDataPresent] = useState(false);
- const [dataUpload, setDataUpload] = useState(false);
- const [loader, setLoader] = useState(false);
- const [fileData, setFileData] = useState();
- const [uploadedFileError, setUploadedFileError] = useState();
- const [fileDataList, setFileDataList] = useState([]);
- const [validationSchemas, setValidationSchemas] = useState([]);
- const [template, setTemplate] = useState([]);
- const [resourceMapping, setResourceMapping] = useState([]);
- const [previewUploadedData, setPreviewUploadedData] = useState();
- const { state, dispatch } = useMyContext();
-
- //fetch campaign data
- const { id = "" } = Digit.Hooks.useQueryParams();
- const { isLoading: isCampaignLoading, data: campaignData } = Digit.Hooks.microplan.useSearchCampaign(
- {
- CampaignDetails: {
- tenantId: Digit.ULBService.getCurrentTenantId(),
- ids: [id],
- },
- },
- {
- enabled: !!id,
- }
- );
-
- // request body for boundary hierarchy api
- const reqCriteria = {
- url: `/boundary-service/boundary-hierarchy-definition/_search`,
- params: {},
- body: {
- BoundaryTypeHierarchySearchCriteria: {
- tenantId: Digit.ULBService.getCurrentTenantId(),
- hierarchyType: campaignData?.hierarchyType,
- // hierarchyType: "Microplan",
- },
- },
- config: {
- enabled: !!campaignData?.hierarchyType,
- select: (data) => {
- return (
- data?.BoundaryHierarchy?.[0]?.boundaryHierarchy?.map(
- (item) => `${campaignData?.hierarchyType}_${Digit.Utils.microplan.transformIntoLocalisationCode(item?.boundaryType)}`
- ) || {}
- );
- },
- },
- };
- const { isLoading: ishierarchyLoading, data: hierarchy } = Digit.Hooks.useCustomAPIHook(reqCriteria);
- // Set TourSteps
- useEffect(() => {
- const tourData = tourSteps(t)?.[page] || {};
- if (state?.tourStateData?.name === page) return;
- dispatch({
- type: "SETINITDATA",
- state: { tourStateData: tourData },
- });
- }, [t]);
-
- const setModal = (modalString) => {
- const elements = document.querySelectorAll(".popup-wrap-rest-unfocus");
- elements.forEach((element) => {
- element.classList.toggle("popup-wrap-rest-unfocus-active");
- });
- setModalState(modalString);
- };
-
- // UseEffect for checking completeness of data before moveing to next section
- useEffect(() => {
- if (!fileDataList || checkDataCompletion !== "true" || !setCheckDataCompletion) return;
- updateData(true);
- }, [checkDataCompletion]);
-
- // UseEffect to store current data
- useEffect(() => {
- if (!fileDataList || !setMicroplanData) return;
- setMicroplanData((previous) => ({ ...previous, upload: fileDataList }));
- }, [fileDataList]);
-
- // check if data has changed or not
- const updateData = useCallback(
- (check) => {
- if (!fileDataList || !setMicroplanData) return;
-
- // if user has selected a file type and wants to go back to file type selection he/she can click back buttom
- const currentSectionIndex = sections.findIndex((item) => item.id === selectedSection.id);
- if (!dataPresent) {
- if (navigationEvent?.name !== "step") {
- if (navigationEvent?.name === "next") {
- if (currentSectionIndex < sections.length - 1) {
- setSelectedSection(sections[currentSectionIndex + 1]);
- setCheckDataCompletion("false");
- return;
- }
- } else if (navigationEvent?.name === "previousStep") {
- if (dataUpload) {
- setDataUpload(false);
- setSelectedFileType(null);
- setCheckDataCompletion("false");
- return;
- }
- if (currentSectionIndex > 0) {
- setSelectedSection(sections[currentSectionIndex - 1]);
- setCheckDataCompletion("false");
- return;
- }
- }
- }
- } else {
- if (navigationEvent?.name === "next") {
- if (currentSectionIndex < sections.length - 1) {
- setSelectedSection(sections[currentSectionIndex + 1]);
- setCheckDataCompletion("false");
- return;
- }
- } else if (navigationEvent?.name === "previousStep") {
- if (currentSectionIndex > 0) {
- setSelectedSection(sections[currentSectionIndex - 1]);
- setCheckDataCompletion("false");
- return;
- }
- }
- }
-
- if (check) {
- setMicroplanData((previous) => ({ ...previous, upload: fileDataList }));
- const valueList = fileDataList ? fileDataList : [];
- const sectionCheckList = sections?.filter((item) => item.required);
-
- if (
- valueList.length !== 0 &&
- sectionCheckList.every((item) => {
- const filteredList = fileDataList?.filter((e) => e.active && e.templateIdentifier === item.id);
- if (filteredList?.length === 0) return false;
- return filteredList?.every((element) => element?.error === null) && fileDataList && !fileDataList.some((e) => e?.active && e?.error);
- })
- )
- setCheckDataCompletion("valid");
- else setCheckDataCompletion("invalid");
- } else {
- const valueList = microplanData?.Upload ? Object.values(microplanData?.Upload) : [];
- if (
- valueList.length !== 0 &&
- sectionCheckList.every((item) =>
- fileDataList?.filter((e) => e.templateIdentifier === item.id)?.every((element) => element.active && element?.error === null)
- )
- )
- setCheckDataCompletion("valid");
- else setCheckDataCompletion("invalid");
- }
- },
- [fileDataList, setMicroplanData, microplanData, setCheckDataCompletion, dataPresent, dataUpload, navigationEvent]
- );
-
- // UseEffect to extract data on first render
- useEffect(() => {
- if (microplanData?.upload) {
- setFileDataList(microplanData.upload);
- }
-
- if (pages) {
- const previouspage = pages[currentPage?.id - 1];
- if (previouspage?.checkForCompleteness && !microplanData?.status?.[previouspage?.name]) setEditable(false);
- else setEditable(true);
- }
- }, []);
-
- // UseEffect to add a event listener for keyboard
- useEffect(() => {
- window.addEventListener("keydown", handleKeyPress);
-
- return () => window.removeEventListener("keydown", handleKeyPress);
- }, [modal, previewUploadedData]);
-
- const handleKeyPress = (event) => {
- // if (modal !== "upload-guidelines") return;
- if (["x", "Escape"].includes(event.key)) {
- // Perform the desired action when "x" or "esc" is pressed
- if (modal === "upload-guidelines") {
- setModal("none");
- }
- if (previewUploadedData) setPreviewUploadedData(undefined);
- }
- };
-
- // Effect to update sections and selected section when data changes
- useEffect(() => {
- if (state) {
- const uploadSections = state?.UploadConfiguration;
- const schemas = state?.Schemas;
- if (schemas) setValidationSchemas(schemas);
- if (uploadSections) {
- setSelectedSection(uploadSections.length > 0 ? uploadSections[0] : null);
- setSections(uploadSections);
- }
- }
- }, []);
-
- // Memoized section options to prevent unnecessary re-renders
- const sectionOptions = useMemo(() => {
- if (!sections) return [];
- return sections.map((item) => (
- e.active && e.templateIdentifier === item.id && !e.error)?.length !== 0}
- />
- ));
- }, [sections, selectedSection, fileDataList]);
-
- const showDownloadTemplate = () => {
- if (selectedSection?.UploadFileTypes) {
- const schema = getSchema(campaignType, selectedFileType?.id, selectedSection.id, validationSchemas);
- if (schema?.template?.showTemplateDownload) return true;
- }
- return false;
- };
-
- // Handler for when a file type is selected for uplaod
- const selectFileTypeHandler = (e) => {
- if (selectedSection?.UploadFileTypes) {
- const schema = getSchema(campaignType, e.target.name, selectedSection.id, validationSchemas);
- setSelectedFileType(selectedSection.UploadFileTypes.find((item) => item.id === e.target.name));
- if (schema?.template?.showTemplateDownload) setModal("upload-modal");
- else UploadFileClickHandler(false);
- return;
- }
- setToast({
- state: "error",
- message: t("ERROR_UNKNOWN"),
- });
- setLoader(false);
- return;
- };
-
- // Memoized section components to prevent unnecessary re-renders
- const sectionComponents = useMemo(() => {
- if (!sections) return;
- return sections.map((item) => (
-
- ));
- }, [sections, selectedSection, selectedFileType]);
-
- // Close model click handler
- const closeModal = () => {
- setResourceMapping([]);
- setModal("none");
- };
-
- // handler for show file upload screen
- const UploadFileClickHandler = (download = false) => {
- if (download) {
- downloadTemplateHandler();
- }
- setModal("none");
- setDataUpload(true);
- };
- const readMeConstant = state?.CommonConstants?.find((item) => item?.name === "readMeSheetName");
- const downloadTemplateHandler = () => {
- const downloadParams = {
- campaignType,
- type: selectedFileType.id,
- section: selectedSection.id,
- setToast,
- campaignData,
- hierarchyType: campaignData?.hierarchyType,
- Schemas: validationSchemas,
- HierarchyConfigurations: state?.HierarchyConfigurations,
- setLoader,
- hierarchy,
- readMeData: state?.ReadMeData,
- readMeSheetName: readMeConstant ? readMeConstant.value : undefined,
- t,
- };
- downloadTemplate(downloadParams);
- };
- // Effect for updating current session data in case of section change
- useEffect(() => {
- if (selectedSection) {
- let file = fileDataList?.find((item) => item.active && item.templateIdentifier === selectedSection.id);
- if (file?.resourceMapping) {
- setSelectedFileType(selectedSection.UploadFileTypes.find((item) => item?.id === file?.fileType));
- setUploadedFileError(file?.error);
- setFileData(file);
- setDataPresent(true);
- } else {
- resetSectionState();
- }
- } else {
- resetSectionState();
- }
- }, [selectedSection]);
-
- const resetSectionState = () => {
- setUploadedFileError(null);
- setSelectedFileType(null);
- setDataPresent(false);
- setResourceMapping([]);
- setDataUpload(false);
- };
-
- // Function for handling upload file event
- const UploadFileToFileStorage = async (file) => {
- if (!file) return;
- try {
- // setting loader
- setLoader("FILE_UPLOADING");
- let check;
- let fileDataToStore;
- let errorMsg;
- let errorLocationObject; // object containing the location and type of error
- let response;
- let callMapping = false;
- // Checking if the file follows name convention rules
- if (!validateNamingConvention(file, selectedFileType["namingConvention"], setToast, t)) {
- setLoader(false);
- return;
- }
-
- let schemaData;
- if (selectedFileType.id !== SHAPEFILE) {
- // Check if validation schema is present or not
- schemaData = getSchema(campaignType, selectedFileType.id, selectedSection.id, validationSchemas);
- if (!schemaData) {
- setToast({
- state: "error",
- message: t("ERROR_VALIDATION_SCHEMA_ABSENT"),
- });
- setLoader(false);
- return;
- }
- }
- let resourceMappingData = [];
- let additionalSheets = [];
- // Handling different filetypes
- switch (selectedFileType.id) {
- case EXCEL:
- // let response = handleExcelFile(file,schemaData);
- try {
- response = await handleExcelFile(
- file,
- schemaData,
- hierarchy,
- selectedFileType,
- {},
- setUploadedFileError,
- t,
- campaignData,
- state?.CommonConstants?.find((item) => item?.name === "readMeSheetName")?.value
- );
- check = response.check;
- errorMsg = response.errorMsg;
- errorLocationObject = response.errors;
- fileDataToStore = response.fileDataToStore;
- resourceMappingData = response?.tempResourceMappingData || [];
- additionalSheets = response?.additionalSheets;
- if (check === true) {
- if (response?.toast) setToast(response.toast);
- else setToast({ state: "success", message: t("FILE_UPLOADED_SUCCESSFULLY") });
- } else if (response.toast) {
- setToast(response.toast);
- } else {
- setToast({ state: "error", message: t("ERROR_UPLOADED_FILE") });
- }
- if (response.interruptUpload) {
- setLoader(false);
- return;
- }
- } catch (error) {
- console.error("Excel parsing error", error.message);
- setToast({ state: "error", message: t("ERROR_UPLOADED_FILE") });
- handleValidationErrorResponse(t("ERROR_UPLOADED_FILE"));
- return;
- }
- break;
- case GEOJSON:
- try {
- response = await handleGeojsonFile(file, schemaData, setUploadedFileError, t);
- file = new File([file], file.name, { type: "application/geo+json" });
- if (response.check === false && response.stopUpload) {
- setLoader(false);
- setToast(response.toast);
- return;
- }
- check = response.check;
- errorMsg = response.error;
- fileDataToStore = response.fileDataToStore;
- callMapping = true;
- } catch (error) {
- // console.error("Geojson parsing error", error.message);
- setToast({ state: "error", message: t("ERROR_UPLOADED_FILE") });
- handleValidationErrorResponse(t("ERROR_UPLOADED_FILE"));
- return;
- }
- break;
- case SHAPEFILE:
- try {
- response = await handleShapefiles(file, schemaData, setUploadedFileError, selectedFileType, setToast, t);
- file = new File([file], file.name, { type: "application/octet-stream" });
- check = response.check;
- errorMsg = response.error;
- fileDataToStore = response.fileDataToStore;
- callMapping = true;
- } catch (error) {
- console.error("Shapefile parsing error", error.message);
- setToast({ state: "error", message: t("ERROR_UPLOADED_FILE") });
- handleValidationErrorResponse(t("ERROR_UPLOADED_FILE"));
- return;
- }
- break;
- default:
- setToast({
- state: "error",
- message: t("ERROR_UNKNOWN_FILETYPE"),
- });
- setLoader(false);
- return;
- }
- let filestoreId;
- if (!errorMsg && !callMapping) {
- try {
- const filestoreResponse = await Digit.UploadServices.Filestorage(FILE_STORE, file, Digit.ULBService.getCurrentTenantId());
- if (filestoreResponse?.data?.files?.length > 0) {
- filestoreId = filestoreResponse?.data?.files[0]?.fileStoreId;
- } else {
- errorMsg = t("ERROR_UPLOADING_FILE");
- setToast({ state: "error", message: t("ERROR_UPLOADING_FILE") });
- setFileData((previous) => ({ ...previous, error: errorMsg }));
- setUploadedFileError(errorMsg);
- }
- } catch (errorData) {
- console.error(errorData.message);
- errorMsg = t("ERROR_UPLOADING_FILE");
- setToast({ state: "error", message: t("ERROR_UPLOADING_FILE") });
- setUploadedFileError(errorMsg);
- handleValidationErrorResponse(t("ERROR_UPLOADING_FILE"));
- return;
- }
- }
-
- if (selectedFileType.id === EXCEL) {
- resourceMappingData = resourceMappingData.map((item) => ({ ...item, filestoreId }));
- }
- const uuid = uuidv4();
- // creating a fileObject to save all the data collectively
- let fileObject = {
- id: uuid,
- templateIdentifier: `${selectedSection.id}`,
- fileName: file.name,
- section: selectedSection.id,
- fileType: selectedFileType.id,
- data: fileDataToStore,
- file,
- error: errorMsg ? errorMsg : null,
- filestoreId,
- resourceMapping: resourceMappingData,
- active: true,
- additionalSheets,
- errorLocationObject, // contains location and type of error
- };
- setFileDataList((prevFileDataList) => {
- let temp = _.cloneDeep(prevFileDataList);
- if (!temp) return temp;
- let index = prevFileDataList?.findIndex((item) => item.active && item.templateIdentifier === selectedSection.id);
- if (index !== -1)
- temp[index] = { ...temp[index], resourceMapping: temp[index]?.resourceMapping.map((e) => ({ active: false, ...e })), active: false };
- temp.push(fileObject);
- return temp;
- });
- setFileData(fileObject);
- if (errorMsg === undefined && callMapping) {
- setModal("spatial-data-property-mapping");
- }
- setDataPresent(true);
- setLoader(false);
- } catch (error) {
- console.error(error.message);
- console.error("File Upload error", error?.message);
- setUploadedFileError("ERROR_UPLOADING_FILE");
- setLoader(false);
- }
- };
-
- // Reupload the selected file
- const reuplaodFile = () => {
- setResourceMapping([]);
- setFileData(undefined);
- setDataPresent(false);
- setUploadedFileError(null);
- setDataUpload(false);
- setSelectedFileType(null);
- closeModal();
- };
-
- const convertAndCombineFileData = () => {
- let combinedData = fileData?.data ? Object.entries(fileData.data)?.map(([key, value]) => ({ sheetName: key, data: value })) : [];
- if (fileData?.additionalSheets) {
- for (const sheet of fileData.additionalSheets) {
- if (sheet?.data && sheet.sheetName) {
- const index = sheet?.position < combinedData.length && sheet.position !== -1 ? sheet.position : combinedData.length;
- combinedData.splice(index, 0, sheet);
- }
- }
- }
- return combinedData;
- };
-
- // Function for creating blob out of data
- const dataToBlob = async () => {
- try {
- let blob;
- const schema = getSchema(campaignType, selectedFileType.id, selectedSection.id, validationSchemas);
- const filteredReadMeData = findReadMe(state?.ReadMeData, campaignType, selectedFileType.id, selectedSection.id);
- let combinedData = convertAndCombineFileData();
- const readMeSheetName = state?.CommonConstants?.find((item) => item?.name === "readMeSheetName")?.value;
- switch (fileData.fileType) {
- case EXCEL:
- if (fileData?.errorLocationObject?.length !== 0)
- blob = await prepareExcelFileBlobWithErrors(
- combinedData,
- fileData.errorLocationObject,
- schema,
- hierarchy,
- filteredReadMeData,
- readMeSheetName,
- t
- );
- else blob = fileData.file;
- break;
- case SHAPEFILE:
- case GEOJSON:
- if (fileData?.data) {
- const result = convertToSheetArray(Digit.Utils.microplan.convertGeojsonToExcelSingleSheet(fileData?.data?.features, fileData?.section));
-
- if (fileData?.errorLocationObject?.length !== 0)
- blob = await prepareExcelFileBlobWithErrors(
- result,
- fileData.errorLocationObject,
- schema,
- hierarchy,
- filteredReadMeData,
- readMeSheetName,
- t
- );
- }
- break;
- }
- return blob;
- } catch (error) {
- console.error("Error generating blob:", error);
- return;
- }
- };
-
- // Download the selected file
- const downloadFile = async () => {
- setLoader("LOADING");
- try {
- await delay(100);
- let blob = await dataToBlob();
- if (blob) {
- // Crating a url object for the blob
- const url = URL.createObjectURL(blob);
- const link = document.createElement("a");
- link.href = url;
-
- // Forming a name for downloaded file
- let fileNameParts = fileData.fileName.split(".");
- fileNameParts.pop();
- fileNameParts.push("xlsx");
- fileNameParts.join(".");
-
- //Downloading the file
- link.download = fileNameParts.join(".");
- link.click();
- URL.revokeObjectURL(url);
- } else {
- let downloadUrl = await Digit.UploadServices.Filefetch([fileData.filestoreId], Digit.ULBService.getCurrentTenantId());
- const link = document.createElement("a");
- link.href = downloadUrl;
- // Forming a name for downloaded file
- let fileNameParts = fileData.fileName.split(".");
- fileNameParts.pop();
- fileNameParts.push("xlsx");
- fileNameParts.join(".");
- link.download = fileNameParts; // Replace with the desired file name and extension
- document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
- }
- } catch (error) {
- console.error(error.message);
- setToast({
- state: "error",
- message: t("ERROR_UNKNOWN_ERROR"),
- });
- }
- setLoader(false);
- };
-
- // delete the selected file
- const deleteFile = () => {
- setResourceMapping([]);
- setFileDataList((previous) => {
- let temp = _.cloneDeep(previous);
- if (!temp) return temp;
- let index = temp?.findIndex((item) => {
- return item.id === fileData.id;
- });
- if (index !== -1)
- temp[index] = { ...temp[index], resourceMapping: temp[index]?.resourceMapping.map((e) => ({ active: false, ...e })), active: false };
- return temp;
- });
- setFileData(undefined);
- setDataPresent(false);
- setUploadedFileError(null);
- setDataUpload(false);
- setSelectedFileType(null);
- closeModal();
- };
-
- // Function for handling the validations for geojson and shapefiles after mapping of properties
- const validationForMappingAndDataSaving = async () => {
- try {
- setLoader("LOADING");
- const schemaData = getSchema(campaignType, selectedFileType.id, selectedSection.id, validationSchemas);
- let error;
- if (!checkForSchemaData(schemaData)) return;
- const { data, valid, errors } = computeMappedDataAndItsValidations(schemaData);
- error = errors;
- if (!valid) return;
- let filestoreId;
- if (!error) {
- filestoreId = await saveFileToFileStore();
- }
- let resourceMappingData;
- if (filestoreId) {
- resourceMappingData = resourceMapping.map((item) => {
- return { ...item, filestoreId };
- });
- }
- setResourceMapping([]);
-
- let boundaryDataAgainstBoundaryCode = (await boundaryDataGeneration(schemaData, campaignData, t)) || {};
- const mappedToList = resourceMappingData.map((item) => item.mappedTo);
- if (hierarchy.every((item) => !mappedToList.includes(t(item)))) {
- data.features.forEach((feature) => {
- const boundaryCode = feature.properties.boundaryCode;
- let additionalDetails = {};
- for (let i = 0; i < hierarchy.length; i++) {
- if (boundaryDataAgainstBoundaryCode[boundaryCode]?.[i] || boundaryDataAgainstBoundaryCode[boundaryCode]?.[i] === "") {
- additionalDetails[hierarchy[i]] = boundaryDataAgainstBoundaryCode[boundaryCode][i];
- } else {
- additionalDetails[hierarchy[i]] = "";
- }
- }
- feature.properties = { ...additionalDetails, ...feature.properties };
- });
- }
-
- let fileObject = _.cloneDeep(fileData);
- fileObject = { ...fileData, data, resourceMapping: resourceMappingData, error: error ? error : null, filestoreId };
- setFileData(fileObject);
- setFileDataList((prevFileDataList) => {
- let temp = _.cloneDeep(prevFileDataList);
- if (!temp) return temp;
- let index = prevFileDataList?.findIndex((item) => item.id === fileData.id);
- if (index !== -1) temp[index] = fileObject;
- // temp.push(fileObject);
- return temp;
- });
-
- setToast({ state: "success", message: t("FILE_UPLOADED_SUCCESSFULLY") });
- setLoader(false);
- } catch (error) {
- console.error(error.message);
- setUploadedFileError(t("ERROR_UPLOADING_FILE"));
- setToast({ state: "error", message: t("ERROR_UPLOADING_FILE") });
- setLoader(false);
- handleValidationErrorResponse("ERROR_UPLOADING_FILE");
- }
- };
- const saveFileToFileStore = async () => {
- try {
- const filestoreResponse = await Digit.UploadServices.Filestorage(FILE_STORE, fileData.file, Digit.ULBService.getCurrentTenantId());
- if (filestoreResponse?.data?.files?.length > 0) {
- return filestoreResponse?.data?.files[0]?.fileStoreId;
- }
- error = t("ERROR_UPLOADING_FILE");
- setToast({ state: "error", message: t("ERROR_UPLOADING_FILE") });
- setResourceMapping([]);
- setUploadedFileError(error);
- } catch (errorData) {
- console.error("Error while uploading file to filestore: ", errorData?.message);
- let error = t("ERROR_UPLOADING_FILE");
- handleValidationErrorResponse(error);
- setResourceMapping([]);
- return;
- }
- };
- const computeMappedDataAndItsValidations = (schemaData) => {
- const data = computeGeojsonWithMappedProperties();
- const response = geojsonPropertiesValidation(data, schemaData.schema, fileData?.section, t);
- if (!response.valid) {
- handleValidationErrorResponse(response.message, response.errors);
- return { data: data, errors: response.errors, valid: response.valid };
- }
- return { data: data, valid: response.valid };
- };
-
- const handleValidationErrorResponse = (error, errorLocationObject = {}) => {
- const fileObject = fileData;
- if (fileObject) {
- fileObject.error = [error];
- if (errorLocationObject) fileObject.errorLocationObject = errorLocationObject;
- setFileData((previous) => ({ ...previous, error, errorLocationObject }));
- setFileDataList((prevFileDataList) => {
- let temp = _.cloneDeep(prevFileDataList);
- if (!temp) return temp;
- let index = prevFileDataList?.findIndex((item) => item.id === fileData.id);
- temp[index] = fileObject;
- return temp;
- });
- setToast({ state: "error", message: t("ERROR_UPLOADED_FILE") });
- if (error) setUploadedFileError(error);
- }
- setLoader(false);
- };
-
- const checkForSchemaData = (schemaData) => {
- if (resourceMapping?.length === 0) {
- setToast({ state: "warning", message: t("WARNING_INCOMPLETE_MAPPING") });
- setLoader(false);
- return false;
- }
-
- if (!schemaData || !schemaData.schema || !schemaData.schema["Properties"]) {
- setToast({ state: "error", message: t("ERROR_VALIDATION_SCHEMA_ABSENT") });
- setLoader(false);
- return;
- }
-
- let columns = [];
- if (schemaData?.doHierarchyCheckInUploadedData) {
- columns.push(...hierarchy);
- }
- columns.push(
- ...Object.entries(schemaData?.schema?.Properties || {}).reduce((acc, [key, value]) => {
- if (value?.isRequired) {
- acc.push(key);
- }
- return acc;
- }, [])
- );
-
- const resourceMappingLength = resourceMapping.filter((e) => !!e?.mappedFrom && columns.includes(e?.mappedTo)).length;
- if (resourceMappingLength !== columns?.length) {
- setToast({ state: "warning", message: t("WARNING_INCOMPLETE_MAPPING") });
- setLoader(false);
- return false;
- }
- setModal("none");
- return true;
- };
-
- const computeGeojsonWithMappedProperties = () => {
- const schemaData = getSchema(campaignType, selectedFileType.id, selectedSection.id, validationSchemas);
- let schemaKeys;
- if (schemaData?.schema?.["Properties"]) schemaKeys = hierarchy.concat(Object.keys(schemaData.schema["Properties"]));
- // Sorting the resourceMapping list inorder to maintain the column sequence
- const sortedSecondList = Digit.Utils.microplan.sortSecondListBasedOnFirstListOrder(schemaKeys, resourceMapping);
- // Creating a object with input data with MDMS keys
- const newFeatures = fileData.data["features"].map((item) => {
- let newProperties = {};
-
- sortedSecondList.forEach((e) => {
- newProperties[e["mappedTo"]] = item["properties"][e["mappedFrom"]];
- });
- item["properties"] = newProperties;
- return item;
- });
- let data = fileData.data;
- data["features"] = newFeatures;
- return data;
- };
-
- // Handler for checing file extension and showing errors in case it is wrong
- const onTypeErrorWhileFileUpload = () => {
- switch (selectedFileType.id) {
- case EXCEL:
- setToast({ state: "error", message: t("ERROR_EXCEL_EXTENSION") });
- break;
- case GEOJSON:
- setToast({ state: "error", message: t("ERROR_GEOJSON_EXTENSION") });
- break;
- case SHAPEFILE:
- setToast({ state: "error", message: t("ERROR_SHAPE_FILE_EXTENSION") });
- break;
- }
- };
-
- // Cancle mapping and uplaod in case of geojson and shapefiles
- const cancelUpload = () => {
- setFileDataList((previous) => {
- let temp = previous?.filter((item) => item.id !== fileData?.id);
- return temp;
- });
- setFileData(undefined);
- setDataPresent(false);
- setUploadedFileError(null);
- setDataUpload(false);
- setSelectedFileType(null);
- closeModal();
- };
-
- const openDataPreview = () => {
- let data;
- switch (fileData.fileType) {
- case EXCEL:
- data = fileData.data;
- break;
- case SHAPEFILE:
- case GEOJSON:
- if (!fileData || !fileData.data) {
- setToast({
- state: "error",
- message: t("ERROR_DATA_NOT_PRESENT"),
- });
- return;
- }
- data = Digit.Utils.microplan.convertGeojsonToExcelSingleSheet(fileData?.data?.features, fileData?.section);
- break;
- }
- if (!data || Object.keys(data).length === 0) {
- setToast({
- state: "error",
- message: t("ERROR_DATA_NOT_PRESENT"),
- });
- return;
- }
- setPreviewUploadedData(data);
- };
-
- if (isCampaignLoading || ishierarchyLoading) {
- return (
-
-
-
- );
- }
-
- return (
- <>
-
-
-
- {!dataPresent ? (
- dataUpload ? (
-
- e.id === selectedSection.id)[0]}
- selectedSection={selectedSection}
- selectedFileType={selectedFileType}
- UploadFileToFileStorage={UploadFileToFileStorage}
- onTypeError={onTypeErrorWhileFileUpload}
- downloadTemplateHandler={downloadTemplateHandler}
- showDownloadTemplate={showDownloadTemplate}
- />
-
- ) : (
-
{sectionComponents}
- )
- ) : (
-
- {selectedSection != null && fileData !== null && (
- {
- setModal("reupload-conformation");
- }}
- DownloadFile={downloadFile}
- DeleteFile={() => {
- setModal("delete-conformation");
- }}
- error={uploadedFileError}
- openDataPreview={openDataPreview}
- downloadTemplateHandler={downloadTemplateHandler}
- showDownloadTemplate={showDownloadTemplate}
- />
- )}
-
- )}
- {!dataPresent && dataUpload && (
-
{
- setModal("upload-guidelines");
- }}
- t={t}
- />
- )}
-
-
-
{sectionOptions}
-
-
-
- {modal === "upload-modal" && (
-
{
- closeModal();
- setSelectedFileType(null);
- }}
- LeftButtonHandler={() => UploadFileClickHandler(false)}
- RightButtonHandler={() => UploadFileClickHandler(true)}
- sections={sections}
- popupModuleActionBarStyles={{
- flex: 1,
- justifyContent: "space-between",
- padding: "1rem",
- gap: "1rem",
- }}
- footerLeftButtonBody={}
- footerRightButtonBody={}
- header={
-
- }
- bodyText={t(`INSTRUCTIONS_DOWNLOAD_TEMPLATE_FOR_${selectedSection.code}_${selectedFileType.code}`)}
- />
- )}
- {modal === "delete-conformation" && (
- }
- actionCancelLabel={t("YES")}
- actionCancelOnSubmit={deleteFile}
- actionSaveLabel={t("NO")}
- actionSaveOnSubmit={closeModal}
- >
-
-
{t("INSTRUCTIONS_DELETE_FILE_CONFIRMATION")}
-
-
- )}
- {modal === "reupload-conformation" && (
- }
- actionCancelLabel={t("YES")}
- actionCancelOnSubmit={reuplaodFile}
- actionSaveLabel={t("NO")}
- actionSaveOnSubmit={closeModal}
- >
-
-
{t("INSTRUCTIONS_REUPLOAD_FILE_CONFIRMATION")}
-
-
- )}
- {modal === "spatial-data-property-mapping" && (
- }
- actionSaveOnSubmit={validationForMappingAndDataSaving}
- actionSaveLabel={t("COMPLETE_MAPPING")}
- headerBarEnd={}
- >
-
-
{t("INSTRUCTION_SPATIAL_DATA_PROPERTY_MAPPING")}
-
-
-
- )}
- {modal === "upload-guidelines" && (
-
- }
- headerBarEnd={}
- >
-
-
- )}
- {loader && }
-
- {previewUploadedData && (
-
- setPreviewUploadedData(undefined)}
- onDownload={downloadFile}
- />
-
- )}
-
-
- >
- );
-};
-
-export default Upload;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/UploadHelperComponents.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/UploadHelperComponents.js
deleted file mode 100644
index 5a520c4a1bd..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/UploadHelperComponents.js
+++ /dev/null
@@ -1,299 +0,0 @@
-import React, { useState, useEffect } from "react";
-import { useTranslation } from "react-i18next";
-import * as Icons from "@egovernments/digit-ui-svg-components";
-import { FileUploader } from "react-drag-drop-files";
-import { InfoButton, InfoCard } from "@egovernments/digit-ui-components";
-import { PRIMARY_THEME_COLOR } from "../configs/constants";
-
-// Component for rendering individual section option
-export const UploadSection = ({ item, selected, setSelectedSection, uploadDone }) => {
- const { t } = useTranslation();
- // Handle click on section option
- const handleClick = () => {
- setSelectedSection(item);
- };
-
- return (
-
-
-
-
-
{t(item.code)}
- {uploadDone && (
-
-
-
- )}
-
- );
-};
-
-export const UploadInstructions = ({ setModal, t }) => {
- return (
-
- {t("REFER")}
-
- {t("INFORMATION_DESCRIPTION_LINK")}
-
- ,
- ]}
- />
- );
-};
-
-// Component for rendering individual upload option
-export const UploadComponents = ({ item, selected, uploadOptions, selectedFileType, selectFileTypeHandler }) => {
- const { t } = useTranslation();
- const title = item.code;
-
- // Component for rendering individual upload option container
- const UploadOptionContainer = ({ item, selectedFileType, selectFileTypeHandler }) => {
- const [isHovered, setIsHovered] = useState(false);
-
- const handleMouseEnter = () => {
- setIsHovered(true);
- };
-
- const handleMouseLeave = () => {
- setIsHovered(false);
- };
-
- return (
-
-
-
{t(item.code)}
-
- {selectedFileType.id === item.id && (
-
- )}
- {selectedFileType.id === item.id ? t("SELECTED") : t("SELECT")}
-
-
- );
- };
-
- return (
-
-
-
-
{t(`HEADING_UPLOAD_DATA_${title}`)}
-
-
-
{t(`INSTRUCTIONS_DATA_UPLOAD_OPTIONS_${title}`)}
-
-
- {uploadOptions?.map((item) => (
-
- ))}
-
-
- );
-};
-
-// Component for uploading file
-export const FileUploadComponent = ({
- selectedSection,
- selectedFileType,
- UploadFileToFileStorage,
- section,
- onTypeError,
- downloadTemplateHandler,
- showDownloadTemplate,
-}) => {
- if (!selectedSection || !selectedFileType) return ;
- const { t } = useTranslation();
- let types;
- section["UploadFileTypes"].forEach((item) => {
- if (item.id === selectedFileType.id) types = item.fileExtension;
- });
- return (
-
-
-
-
{t(`HEADING_FILE_UPLOAD_${selectedSection.code}_${selectedFileType.code}`)}
- {showDownloadTemplate() && (
-
-
-
-
- {t("DOWNLOAD_TEMPLATE")}
-
- )}
-
-
{t(`INSTRUCTIONS_FILE_UPLOAD_FROM_TEMPLATE_${selectedSection.code}`)}
-
-
-
-
- {t(`INSTRUCTIONS_UPLOAD_${selectedFileType.code}`)}
{t("INSTRUCTIONS_UPLOAD_BROWSE_FILES")}
-
-
-
-
-
- );
-};
-
-// Component to display uploaded file
-export const UploadedFile = ({
- selectedSection,
- selectedFileType,
- file,
- ReuplaodFile,
- DownloadFile,
- DeleteFile,
- error,
- openDataPreview,
- downloadTemplateHandler,
- showDownloadTemplate,
-}) => {
- const { t } = useTranslation();
- const [errorList, setErrorList] = useState([]);
- useEffect(() => {
- let tempErrorList = [];
- if (file?.errorLocationObject) {
- for (const [sheetName, values] of Object.entries(file?.errorLocationObject)) {
- for (const [row, columns] of Object.entries(values)) {
- for (const [column, errors] of Object.entries(columns)) {
- for (const error of errors) {
- let convertedError;
- if (typeof error === "object") {
- let { error: actualError, ...otherProperties } = error;
- convertedError = t(actualError, otherProperties?.values);
- } else {
- convertedError = t(error);
- }
- tempErrorList.push(
- t("ERROR_UPLOAD_DATA_LOCATION_AND_MESSAGE", {
- rowNumber: Number(row) + 1,
- columnName: t(column),
- error: convertedError,
- sheetName: sheetName,
- })
- );
- }
- }
- }
- }
- }
- if (tempErrorList.length !== 0) {
- setErrorList(tempErrorList);
- }
- }, [file]);
- return (
-
-
-
-
{t(`HEADING_FILE_UPLOAD_${selectedSection.code}_${selectedFileType.code}`)}
- {showDownloadTemplate() && (
-
-
-
-
- {t("DOWNLOAD_TEMPLATE")}
-
- )}
-
-
{t(`INSTRUCTIONS_FILE_UPLOAD_FROM_TEMPLATE_${selectedSection.code}`)}
-
-
-
-
-
-
-
{file.fileName}
-
-
-
-
- {t("Reupload")}
-
-
-
- {t("Download")}
-
-
-
- {t("DELETE")}
-
-
-
-
- {error && Array.isArray(error) && (
-
,
-
- {error?.map((item) => {
- if (item !== "ERROR_REFER_UPLOAD_PREVIEW_TO_SEE_THE_ERRORS") {
- return
{t(item)}
;
- }
- return null;
- })}
- {errorList.length !== 0 && errorList.map((item) =>
{item}
)}
-
,
- ]}
- />
- )}
-
- );
-};
-
-// Uplaod GuideLines
-export const UploadGuideLines = ({ uploadGuideLines, t }) => {
- const formMsgFromObject = (item) => {
- if (!item?.hasLink) {
- return t(item?.name);
- }
- return (
- <>
- {t(item?.name)} {t(item?.linkName)}{" "}
- >
- );
- };
- return (
-
- {uploadGuideLines?.map((item, index) => (
-
-
- {t(index + 1)}.
-
-
- {formMsgFromObject(item)}
-
-
- ))}
-
- );
-};
-
-export const CustomIcon = (props) => {
- if (!props.Icon) return null;
- return ;
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/ZoomControl.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/ZoomControl.js
deleted file mode 100644
index 5a0cdabf735..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/ZoomControl.js
+++ /dev/null
@@ -1,29 +0,0 @@
-import React, { memo, useCallback } from "react";
-import { useTranslation } from "react-i18next";
-
-const ZoomControl = memo(({ map, t }) => {
- if (!map) return {t("LOADING_MAP")}
;
-
- const zoomIn = useCallback(() => {
- map.zoomIn();
- }, [map]);
-
- const zoomOut = useCallback(() => {
- map.zoomOut();
- }, [map]);
-
- return (
-
- );
-});
-
-export default ZoomControl;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/resourceMapping.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/resourceMapping.js
deleted file mode 100644
index df1eb78c135..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/components/resourceMapping.js
+++ /dev/null
@@ -1,187 +0,0 @@
-import { Dropdown } from "@egovernments/digit-ui-components";
-import { Table } from "@egovernments/digit-ui-react-components";
-import { PaginationFirst, PaginationLast, PaginationNext, PaginationPrevious } from "@egovernments/digit-ui-svg-components";
-import React, { useState, useEffect, useMemo, useRef, useCallback } from "react";
-const SCROLL_OFFSET = 100;
-
-export const SpatialDataPropertyMapping = ({ uploadedData, resourceMapping, setResourceMapping, schema, setToast, hierarchy, close, t }) => {
- // If no data is uploaded, display a message
- if (!uploadedData) return {t("NO_DATA_TO_DO_MAPPING")}
;
-
- const itemRefs = useRef([]);
- const [expandedIndex, setExpandedIndex] = useState(null);
- // State to track the render cycle count
- const [renderCycle, setRenderCycle] = useState(0);
- const scrollContainerRef = useRef(null);
-
- // Effect to reset the render cycle count whenever the expandedIndex changes
- useEffect(() => {
- if (expandedIndex !== null) {
- setRenderCycle(0);
- }
- }, [expandedIndex]);
-
- // Effect to handle scrolling to the expanded item after the DOM has updated
- useEffect(() => {
- if (renderCycle < 3) {
- // Increment render cycle count to ensure multiple render checks
- setRenderCycle((prev) => prev + 1);
- } else if (expandedIndex !== null && itemRefs.current[expandedIndex]) {
- try {
- const parentElement = itemRefs.current[expandedIndex];
- const childElement = itemRefs.current[expandedIndex].children[1];
-
- if (parentElement) {
- const scrollContainer = scrollContainerRef.current;
- const parentRect = parentElement.getBoundingClientRect();
- const containerRect = scrollContainer.getBoundingClientRect();
-
- // Calculate the offset from the top of the container
- const offset = parentRect.top - containerRect.top;
- // Scroll the container to the target position
- scrollContainer.scrollTo({
- top: scrollContainer.scrollTop + offset - SCROLL_OFFSET,
- behavior: "smooth",
- });
- }
-
- if (childElement) {
- // Focus the child element if it exists
- childElement.focus();
- }
- } catch (error) {
- console.error("Error scrolling to element:", error);
- }
- }
- }, [renderCycle, expandedIndex]);
-
- // Effect to observe DOM changes in the expanded item and trigger render cycle
- useEffect(() => {
- if (expandedIndex !== null) {
- const observer = new MutationObserver(() => {
- setRenderCycle((prev) => prev + 1);
- });
-
- if (itemRefs.current[expandedIndex]) {
- observer.observe(itemRefs.current[expandedIndex], { childList: true, subtree: true });
- }
-
- return () => observer.disconnect();
- }
- }, [expandedIndex]);
-
- // State variables
- const [userColumns, setUserColumns] = useState([]);
- const [templateColumns, setTemplateColumns] = useState([]);
-
- // Fetch template columns when schema changes
- useEffect(() => {
- if (!schema || !schema["schema"] || !schema.schema["Properties"])
- return setToast({ state: "error", message: t("ERROR_VALIDATION_SCHEMA_ABSENT") });
-
- const columns = Object.keys(schema.schema["Properties"]);
- if (columns) {
- const newTemplateColumns = schema && !schema.doHierarchyCheckInUploadedData ? columns : [...hierarchy, ...columns];
- setTemplateColumns(newTemplateColumns);
- }
- }, [schema]);
-
- // Update user columns when uploaded data changes
- useEffect(() => {
- const userUploadedColumns = new Set();
- uploadedData?.["features"]?.forEach((item) => {
- Object.keys(item["properties"]).forEach((key) => userUploadedColumns.add(key));
- });
-
- //field level validations
- for (const item of userUploadedColumns) {
- if (item.length < 2) {
- setToast({ state: "error", message: t("ERROR_FIELD_LENGTH") });
- close();
- }
- }
- setUserColumns((preUserColumns) => [...preUserColumns, ...userUploadedColumns]);
- }, [uploadedData]);
-
- // Dropdown component for selecting user columns
- const DropDownUserColumnSelect = ({ id, index }) => {
- const [selectedOption, setSelectedOption] = useState("");
- useEffect(() => {
- const obj = resourceMapping.find((item) => item["mappedTo"] === id);
- if (obj) setSelectedOption({ code: obj["mappedFrom"] });
- else setSelectedOption();
- }, [id, resourceMapping]);
-
- const handleSelectChange = (event) => {
- const newValue = event.code;
- setSelectedOption(event);
- setResourceMapping((previous) => {
- const revisedData = previous.filter((item) => !(item["mappedTo"] === id || item["mappedFrom"] === newValue));
- return [...revisedData, { mappedTo: id, mappedFrom: newValue }];
- });
- };
-
- const toggleExpand = (index) => {
- setExpandedIndex(index === expandedIndex ? null : index);
- };
-
- return (
- {
- itemRefs.current[index] = el;
- }}
- onClick={() => toggleExpand(index)}
- onKeyDown={() => toggleExpand(index)}
- >
- ({ code: item }))}
- selected={selectedOption}
- optionKey="code"
- select={handleSelectChange}
- style={{ width: "100%", backgroundColor: "rgb(0,0,0,0)" }}
- showToolTip={true}
- />
-
- );
- };
-
- const tableColumns = useMemo(
- () => [
- {
- Header: t("COLUMNS_IN_TEMPLATE"),
- accessor: "COLUMNS_IN_TEMPLATE",
- },
- {
- Header: t("COLUMNS_IN_USER_UPLOAD"),
- accessor: "COLUMNS_IN_USER_UPLOAD",
- Cell: ({ cell: { value }, row: { index } }) =>
- useMemo(() => , [value, index]),
- },
- ],
- [userColumns, setResourceMapping, resourceMapping, t, itemRefs]
- );
- const data = useMemo(() => templateColumns.map((item) => ({ COLUMNS_IN_TEMPLATE: t(item), COLUMNS_IN_USER_UPLOAD: item })), [templateColumns]);
- return (
-
-
{
- return { style: {} };
- }}
- getHeaderProps={(cellInfo) => {
- return { style: {} };
- }}
- />
-
- );
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/configs/UICustomizations.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/configs/UICustomizations.js
deleted file mode 100644
index 8f7fd717aba..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/configs/UICustomizations.js
+++ /dev/null
@@ -1,324 +0,0 @@
-import _ from "lodash";
-
-//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 || {};
-
-const businessServiceMap = {
- "muster roll": "MR",
-};
-
-const inboxModuleNameMap = {
- "muster-roll-approval": "muster-roll-service",
-};
-
-function filterUniqueByKey(arr, key) {
- const uniqueValues = new Set();
- const result = [];
-
- arr.forEach((obj) => {
- const value = obj[key];
- if (!uniqueValues.has(value)) {
- uniqueValues.add(value);
- result.push(obj);
- }
- });
-
- return result;
-}
-
-const epochTimeForTomorrow12 = () => {
- const now = new Date();
-
- // Create a new Date object for tomorrow at 12:00 PM
- const tomorrowNoon = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 12, 0, 0, 0);
-
- // Format the date as "YYYY-MM-DD"
- const year = tomorrowNoon.getFullYear();
- const month = String(tomorrowNoon.getMonth() + 1).padStart(2, "0"); // Months are 0-indexed
- const day = String(tomorrowNoon.getDate()).padStart(2, "0");
-
- return Digit.Utils.date.convertDateToEpoch(`${year}-${month}-${day}`);
-};
-
-function cleanObject(obj) {
- for (const key in obj) {
- if (Object.hasOwn(obj, key)) {
- if (Array.isArray(obj[key])) {
- if (obj[key].length === 0) {
- delete obj[key];
- }
- } else if (
- obj[key] === undefined ||
- obj[key] === null ||
- obj[key] === false ||
- obj[key] === "" || // Check for empty string
- (typeof obj[key] === "object" && Object.keys(obj[key]).length === 0)
- ) {
- delete obj[key];
- }
- }
- }
- return obj;
-}
-
-export const UICustomizations = {
- businessServiceMap,
- updatePayload: (applicationDetails, data, action, businessService) => {
- if (businessService === businessServiceMap.estimate) {
- const workflow = {
- comment: data.comments,
- documents: data?.documents?.map((document) => {
- return {
- documentType: action?.action + " DOC",
- fileName: document?.[1]?.file?.name,
- fileStoreId: document?.[1]?.fileStoreId?.fileStoreId,
- documentUid: document?.[1]?.fileStoreId?.fileStoreId,
- tenantId: document?.[1]?.fileStoreId?.tenantId,
- };
- }),
- assignees: data?.assignees?.uuid ? [data?.assignees?.uuid] : null,
- action: action.action,
- };
- //filtering out the data
- Object.keys(workflow).forEach((key, index) => {
- if (!workflow[key] || workflow[key]?.length === 0) delete workflow[key];
- });
-
- return {
- estimate: applicationDetails,
- workflow,
- };
- }
- if (businessService === businessServiceMap.contract) {
- const workflow = {
- comment: data?.comments,
- documents: data?.documents?.map((document) => {
- return {
- documentType: action?.action + " DOC",
- fileName: document?.[1]?.file?.name,
- fileStoreId: document?.[1]?.fileStoreId?.fileStoreId,
- documentUid: document?.[1]?.fileStoreId?.fileStoreId,
- tenantId: document?.[1]?.fileStoreId?.tenantId,
- };
- }),
- assignees: data?.assignees?.uuid ? [data?.assignees?.uuid] : null,
- action: action.action,
- };
- //filtering out the data
- Object.keys(workflow).forEach((key, index) => {
- if (!workflow[key] || workflow[key]?.length === 0) delete workflow[key];
- });
-
- return {
- contract: applicationDetails,
- workflow,
- };
- }
- if (businessService === businessServiceMap?.["muster roll"]) {
- const workflow = {
- comment: data?.comments,
- documents: data?.documents?.map((document) => {
- return {
- documentType: action?.action + " DOC",
- fileName: document?.[1]?.file?.name,
- fileStoreId: document?.[1]?.fileStoreId?.fileStoreId,
- documentUid: document?.[1]?.fileStoreId?.fileStoreId,
- tenantId: document?.[1]?.fileStoreId?.tenantId,
- };
- }),
- assignees: data?.assignees?.uuid ? [data?.assignees?.uuid] : null,
- action: action.action,
- };
- //filtering out the data
- Object.keys(workflow).forEach((key, index) => {
- if (!workflow[key] || workflow[key]?.length === 0) delete workflow[key];
- });
-
- return {
- musterRoll: applicationDetails,
- workflow,
- };
- }
- if (businessService === businessServiceMap?.["works.purchase"]) {
- const workflow = {
- comment: data.comments,
- documents: data?.documents?.map((document) => {
- return {
- documentType: action?.action + " DOC",
- fileName: document?.[1]?.file?.name,
- fileStoreId: document?.[1]?.fileStoreId?.fileStoreId,
- documentUid: document?.[1]?.fileStoreId?.fileStoreId,
- tenantId: document?.[1]?.fileStoreId?.tenantId,
- };
- }),
- assignees: data?.assignees?.uuid ? [data?.assignees?.uuid] : null,
- action: action.action,
- };
- //filtering out the data
- Object.keys(workflow).forEach((key, index) => {
- if (!workflow[key] || workflow[key]?.length === 0) delete workflow[key];
- });
-
- const additionalFieldsToSet = {
- 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 },
- workflow,
- };
- }
- },
- enableModalSubmit: (businessService, action, setModalSubmit, data) => {
- if (businessService === businessServiceMap?.["muster roll"] && action.action === "APPROVE") {
- setModalSubmit(data?.acceptTerms);
- }
- },
- enableHrmsSearch: (businessService, action) => {
- if (businessService === businessServiceMap.estimate) {
- return action.action.includes("TECHNICALSANCTION") || action.action.includes("VERIFYANDFORWARD");
- }
- if (businessService === businessServiceMap.contract) {
- return action.action.includes("VERIFY_AND_FORWARD");
- }
- if (businessService === businessServiceMap?.["muster roll"]) {
- return action.action.includes("VERIFY");
- }
- if (businessService === businessServiceMap?.["works.purchase"]) {
- return action.action.includes("VERIFY_AND_FORWARD");
- }
- return false;
- },
- getBusinessService: (moduleCode) => {
- if (moduleCode?.includes("estimate")) {
- return businessServiceMap?.estimate;
- } else if (moduleCode?.includes("contract")) {
- return businessServiceMap?.contract;
- } else if (moduleCode?.includes("muster roll")) {
- return businessServiceMap?.["muster roll"];
- } else if (moduleCode?.includes("works.purchase")) {
- return businessServiceMap?.["works.purchase"];
- } else if (moduleCode?.includes("works.wages")) {
- return businessServiceMap?.["works.wages"];
- } else if (moduleCode?.includes("works.supervision")) {
- return businessServiceMap?.["works.supervision"];
- } else {
- return businessServiceMap;
- }
- },
- getInboxModuleName: (moduleCode) => {
- if (moduleCode?.includes("estimate")) {
- return inboxModuleNameMap?.estimate;
- } else if (moduleCode?.includes("contract")) {
- return inboxModuleNameMap?.contracts;
- } else if (moduleCode?.includes("attendence")) {
- return inboxModuleNameMap?.attendencemgmt;
- } else {
- return inboxModuleNameMap;
- }
- },
- SearchCampaign: {
- preProcess: (data, additionalDetails) => {
- const { campaignName = "", endDate = "", projectType = "", startDate = "" } = data?.state?.searchForm || {};
- data.body.CampaignDetails = {};
- data.body.CampaignDetails.pagination = data?.state?.tableForm;
- data.body.CampaignDetails.tenantId = Digit.ULBService.getCurrentTenantId();
- // data.body.CampaignDetails.boundaryCode = boundaryCode;
- data.body.CampaignDetails.createdBy = Digit.UserService.getUser().info.uuid;
- data.body.CampaignDetails.campaignName = campaignName;
- data.body.CampaignDetails.status = ["drafted"];
- if (startDate) {
- data.body.CampaignDetails.startDate = Digit.Utils.date.convertDateToEpoch(startDate);
- } else {
- data.body.CampaignDetails.startDate = epochTimeForTomorrow12();
- }
- if (endDate) {
- data.body.CampaignDetails.endDate = Digit.Utils.date.convertDateToEpoch(endDate);
- }
- data.body.CampaignDetails.projectType = projectType?.[0]?.code;
-
- cleanObject(data.body.CampaignDetails);
-
- return data;
- },
- populateProjectType: () => {
- const tenantId = Digit.ULBService.getCurrentTenantId();
-
- return {
- url: "/egov-mdms-service/v1/_search",
- params: { tenantId },
- body: {
- MdmsCriteria: {
- tenantId,
- moduleDetails: [
- {
- moduleName: "HCM-PROJECT-TYPES",
- masterDetails: [
- {
- name: "projectTypes",
- },
- ],
- },
- ],
- },
- },
- changeQueryName: "projectType",
- config: {
- enabled: true,
- select: (data) => {
- const dropdownData = filterUniqueByKey(data?.MdmsRes?.["HCM-PROJECT-TYPES"]?.projectTypes, "code").map((row) => {
- return {
- ...row,
- i18nKey: Digit.Utils.locale.getTransformedLocale(`CAMPAIGN_TYPE_${row.code}`),
- };
- });
- return dropdownData;
- },
- },
- };
- },
- customValidationCheck: (data) => {
- //checking if both to and from date are present then they should be startDate<=endDate
- const { startDate, endDate } = data;
- const startDateEpoch = Digit.Utils.date.convertDateToEpoch(startDate);
- const endDateEpoch = Digit.Utils.date.convertDateToEpoch(endDate);
-
- if (startDate && endDate && startDateEpoch > endDateEpoch) {
- return { warning: true, label: "ES_COMMON_ENTER_DATE_RANGE" };
- }
- return false;
- },
- additionalCustomizations: (row, key, column, value, t, searchResult) => {
- if (key === "CAMPAIGN_DATE") {
- return `${Digit.DateUtils.ConvertEpochToDate(value)} - ${Digit.DateUtils.ConvertEpochToDate(row?.endDate)}`;
- }
- },
- },
- SearchMicroplan: {
- preProcess: (data, additionalDetails) => {
- const { name, status } = data?.state?.searchForm || {};
-
- data.body.PlanConfigurationSearchCriteria = {};
- data.body.PlanConfigurationSearchCriteria.limit = data?.state?.tableForm?.limit;
- // data.body.PlanConfigurationSearchCriteria.limit = 10
- data.body.PlanConfigurationSearchCriteria.offset = data?.state?.tableForm?.offset;
- data.body.PlanConfigurationSearchCriteria.name = name;
- data.body.PlanConfigurationSearchCriteria.tenantId = Digit.ULBService.getCurrentTenantId();
- data.body.PlanConfigurationSearchCriteria.userUuid = Digit.UserService.getUser().info.uuid;
- // delete data.body.PlanConfigurationSearchCriteria.pagination
- data.body.PlanConfigurationSearchCriteria.status = status?.status;
- cleanObject(data.body.PlanConfigurationSearchCriteria);
- return data;
- },
- additionalCustomizations: (row, key, column, value, t, searchResult) => {
- if (key === "CAMPAIGN_DATE") {
- return `${Digit.DateUtils.ConvertEpochToDate(value)} - ${Digit.DateUtils.ConvertEpochToDate(row?.CampaignDetails?.endDate)}`;
- }
- },
- },
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/configs/constants.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/configs/constants.js
deleted file mode 100644
index c9f5af95d46..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/configs/constants.js
+++ /dev/null
@@ -1,36 +0,0 @@
-export const LOCALITY = "Locality";
-
-export const EXCEL = "Excel";
-
-export const GEOJSON = "GeoJSON";
-
-export const SHAPEFILE = "Shapefile";
-
-export const commonColumn = "boundaryCode";
-
-export const ACCEPT_HEADERS = {
- GeoJSON: "application/geo+json",
- Shapefile: "application/shapefile",
- Excel: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
-};
-
-// Define the colors of the gradient for choropleth mapping
-export const MapChoroplethGradientColors = [
- { percent: 0, color: "#edd1cf" },
- { percent: 100, color: "#b52626" },
-];
-
-export const PRIMARY_THEME_COLOR = "#C84C0E";
-
-export const BOUNDARY_DATA_SHEET = "MICROPLAN_BOUNDARY_DATA_SHEET";
-export const FACILITY_DATA_SHEET = "MICROPLAN_FACILITY_DATA_SHEET";
-
-export const FILE_STORE = "microplan";
-
-export const SHEET_PASSWORD = "eGov_sheet_password";
-
-export const SHEET_COLUMN_WIDTH = 40;
-
-export const SCHEMA_PROPERTIES_PREFIX = "DISPLAY";
-
-export const UNPROTECT_TILL_ROW = "10000";
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/configs/timeLineOptions.json b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/configs/timeLineOptions.json
deleted file mode 100644
index 768e323ef86..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/configs/timeLineOptions.json
+++ /dev/null
@@ -1,40 +0,0 @@
-{
- "timeLineOptions": [
- {
- "id": 0,
- "name": "MICROPLAN_DETAILS",
- "component": "MicroplanDetails",
- "checkForCompleteness": true
- },
- {
- "id": 1,
- "name": "UPLOAD_DATA",
- "component": "Upload",
- "checkForCompleteness": true
- },
- {
- "id": 2,
- "name": "HYPOTHESIS",
- "component": "Hypothesis",
- "checkForCompleteness": true
- },
- {
- "id": 3,
- "name": "FORMULA_CONFIGURATION",
- "component": "RuleEngine",
- "checkForCompleteness": true
- },
- {
- "id": 4,
- "name": "MAPPING",
- "component": "Mapping",
- "checkForCompleteness": false
- },
- {
- "id": 5,
- "name": "MICROPLAN_GENERATION",
- "component": "MicroplanPreview",
- "checkForCompleteness": false
- }
- ]
-}
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/configs/tourSteps.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/configs/tourSteps.js
deleted file mode 100644
index 241f8ec64ec..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/configs/tourSteps.js
+++ /dev/null
@@ -1,193 +0,0 @@
-export const tourSteps = (t) => {
- return {
- microplanDetails: {
- name: "microplanDetails",
- run: true,
- steps: [
- {
- content: t("HELP_MICROPLAN_DETAILS_CAMPAIGN_DETAILS"),
- target: ".microplan-campaign-detials",
- disableBeacon: true,
- placement: "bottom",
- title: "",
- disableScrolling: true,
- disableOverlay :true,
- },
- {
- content: t("HELP_MICROPLAN_DETAILS_MICROPLAN_NAME"),
- target: ".microplan-name",
- disableBeacon: true,
- placement: "bottom",
- title: "",
- disableScrolling: true,
- disableOverlay :true,
- },
- ],
- tourActive: true,
- },
- upload: {
- name: "upload",
- run: true,
- steps: [
- {
- content: t("HELP_UPLOAD_FILETYPE_OPTION_CONTAINER"),
- target: ".upload-option-container",
- disableBeacon: true,
- placement: "top-end",
- title: "",
- disableScrolling: true,
- disableOverlay :true,
- },
- ],
- tourActive: true,
- },
- hypothesis: {
- name: "hypothesis",
- run: true,
- steps: [
- {
- content: t("HELP_HYPOTHESIS_INTERACTABLE_SECTION"),
- target: ".hypothesis-help",
- disableBeacon: true,
- placement: "right-start",
- title: "",
- disableScrolling: true,
- disableOverlay :true,
- },
- // {
- // content:
- // t("HELP_RULE_ENGINE_INPUT"),
- // target: ".last-container .key",
- // disableBeacon: true,
- // placement: "top-start",
- // title: "",
- // },
- // {
- // content:
- // t("HELP_HYPOTHESIS_DELETE_BUTTON"),
- // target: ".last-containe .delete-button-help-locator",
- // disableBeacon: true,
- // placement: "top-start",
- // title: "",
- // },
- {
- content: t("HELP_HYPOTHESIS_ADD_BUTTON"),
- target: ".add-button-help",
- disableBeacon: true,
- placement: "top-start",
- title: "",
- disableOverlay :true,
- },
- ],
- tourActive: true,
- },
- ruleEngine: {
- name: "ruleEngine",
- run: true,
- steps: [
- {
- content: t("HELP_RULE_ENGINE_INTERACTABLE_SECTION"),
- target: ".rule-engine-help",
- disableBeacon: true,
- placement: "right-start",
- title: "",
- disableScrolling: true,
- disableOverlay :true,
- },
- {
- content: t("HELP_RULE_ENGINE_INPUT"),
- target: ".user-input-section .interactable-section .select-and-input-wrapper-first .input",
- disableBeacon: true,
- placement: "top-end",
- title: "",
- disableOverlay :true,
- },
- {
- content: t("HELP_RULE_ENGINE_DELETE_BUTTON"),
- target: ".select-and-input-wrapper-first .delete-button",
- disableBeacon: true,
- placement: "left-start",
- title: "",
- disableOverlay :true,
- },
- {
- content: t("HELP_RULE_ENGINE_ADD_BUTTON"),
- target: ".add-button-help",
- disableBeacon: true,
- placement: "top-start",
- title: "",
- disableOverlay :true,
- },
- ],
- tourActive: true,
- },
- mapping: {
- name: "mapping",
- run: true,
- steps: [
- {
- content: t("HELP_MAPPING_BOUNDARY_SELECTION"),
- target: ".filter-by-boundary .button-primary",
- disableBeacon: true,
- placement: "right-end",
- title: "",
- disableScrolling: true,
- disableOverlay :true,
- },
- {
- content: t("HELP_MAPPING_BASE_MAP"),
- target: ".base-map-selector .icon-first",
- disableBeacon: true,
- placement: "left-start",
- title: "",
- disableScrolling: true,
- disableOverlay :true,
- },
- {
- content: t("HELP_MAPPING_FILTER"),
- target: ".filter-icon p",
- disableBeacon: true,
- placement: "left-start",
- title: "",
- disableScrolling: true,
- disableOverlay :true,
- },
- {
- content: t("HELP_MAPPING_VIRTUALIZATION"),
- target: ".virtualization-icon p",
- disableBeacon: true,
- placement: "left-start",
- title: "",
- disableScrolling: true,
- disableOverlay :true,
- },
- {
- content: t("HELP_MAPPING_MAP_GEOMETRIES"),
- target: ".map-container",
- disableBeacon: true,
- placement: "top-end",
- title: "",
- disableScrolling: true,
- disableOverlay :true,
- },
- ],
- tourActive: true,
- },
- microplanPreview: {
- name: "microplanPreview",
- run: true,
- steps: [
- {
- content: t("HELP_MICROPLAN_DETAILS_EDIT_ROWS"),
- target: ".preview-container",
- disableBeacon: true,
- placement: "top-end",
- title: "",
- disableOverlay :true,
- disableScrolling: true,
- },
- ],
- tourActive: true,
- },
- };
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/hooks/index.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/hooks/index.js
deleted file mode 100644
index 1241d678738..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/hooks/index.js
+++ /dev/null
@@ -1,42 +0,0 @@
-import utils from "../utils";
-import useCreatePlanConfig from "./useCreatePlanConfig";
-import useSearchPlanConfig from "./useSearchPlanConfig";
-import useUpdatePlanConfig from "./useUpdatePlanConfig";
-import useSavedMicroplans from "./useSavedMicroplans";
-import useSearchCampaign from "./useSearchCampaign";
-import { useGenerateIdCampaign } from "./useGenerateIdCampaign";
-const UserService = {};
-
-const microplan = {
- useCreatePlanConfig,
- useSearchPlanConfig,
- useUpdatePlanConfig,
- useSavedMicroplans,
- useSearchCampaign,
- useGenerateIdCampaign,
-};
-
-const contracts = {};
-
-const Hooks = {
- attendance: {
- update: () => {},
- },
- microplan,
- contracts,
-};
-
-const Utils = {
- browser: {
- sample: () => {},
- },
- microplan: {
- ...utils,
- },
-};
-
-export const CustomisedHooks = {
- Hooks,
- UserService,
- Utils,
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/hooks/useCreatePlanConfig.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/hooks/useCreatePlanConfig.js
deleted file mode 100644
index 6afb891b15b..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/hooks/useCreatePlanConfig.js
+++ /dev/null
@@ -1,8 +0,0 @@
-import { useMutation } from "react-query";
-import CreatePlanConfig from "../services/CreatePlanConfig";
-
-const useCreatePlanConfig = () => {
- return useMutation(data => CreatePlanConfig(data))
-}
-
-export default useCreatePlanConfig;
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/hooks/useGenerateIdCampaign.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/hooks/useGenerateIdCampaign.js
deleted file mode 100644
index f315dda5ff8..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/hooks/useGenerateIdCampaign.js
+++ /dev/null
@@ -1,26 +0,0 @@
-export const useGenerateIdCampaign = ({ type, hierarchyType, filters, campaignId, config = {} }) => {
- const updatedFilters = filters?.map(({ type, ...rest }) => ({
- ...rest,
- boundaryType: type,
- }));
- const reqCriteria = {
- url: `/project-factory/v1/data/_generate`,
- changeQueryName: `${type}${hierarchyType}${filters}`,
- params: {
- tenantId: Digit.ULBService.getCurrentTenantId(),
- type: type,
- forceUpdate: true,
- hierarchyType: hierarchyType,
- campaignId: campaignId,
- },
- body: type === "boundary" ? (updatedFilters === undefined ? { Filters: null } : { Filters: { boundaries: updatedFilters } }) : {},
- config: {
- ...config,
- cacheTime: 0,
- staleTime: 0,
- },
- };
- const { data: Data, refetch, isLoading } = Digit.Hooks.useCustomAPIHook(reqCriteria);
-
- return { isLoading: isLoading, data: Data?.GeneratedResource?.[0]?.id, refetch };
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/hooks/useNumberFormatter.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/hooks/useNumberFormatter.js
deleted file mode 100644
index 15e423d59e0..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/hooks/useNumberFormatter.js
+++ /dev/null
@@ -1,21 +0,0 @@
-import { useTranslation } from "react-i18next";
-
-export const useNumberFormatter = (FormatMapping) => {
- const { i18n } = useTranslation();
-
- const formatNumber = (value, options) => {
- try {
- const currentLanguage = i18n.language;
- const fallbackLanguage = i18n.options.fallbackLng[0]; // Get the first language in the fallback list
- const locale = FormatMapping?.[currentLanguage] || FormatMapping?.[fallbackLanguage] || currentLanguage || "";
- return new Intl.NumberFormat(locale, options).format(value);
- } catch (error) {
- console.error("Error formatting number:", error);
- return value;
- }
- };
-
- return { formatNumber };
-};
-
-export default useNumberFormatter;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/hooks/useSavedMicroplans.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/hooks/useSavedMicroplans.js
deleted file mode 100644
index 23c1259c6c4..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/hooks/useSavedMicroplans.js
+++ /dev/null
@@ -1,23 +0,0 @@
-import { useQuery } from "react-query";
-import SearchSavedPlans from "../services/searchSavedPlans";
-
-const useSavedMicroplans = (reqCriteria) => {
- const { body, config, params, state, url } = reqCriteria;
- const { isLoading, data, isFetching, refetch } = useQuery(["SAVED_MICROPLANS", url], () => SearchSavedPlans(body), {
- ...config,
- cacheTime: 0,
- staleTime: 0,
- onError: (err) => console.error("Error fetching saved microplans:", err),
- });
-
- return {
- isLoading,
- isFetching,
- data,
- refetch,
- revalidate: () => {},
- };
-};
-
-// () => SearchSavedPlans(data)
-export default useSavedMicroplans;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/hooks/useSearchCampaign.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/hooks/useSearchCampaign.js
deleted file mode 100644
index e2644f00ca9..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/hooks/useSearchCampaign.js
+++ /dev/null
@@ -1,8 +0,0 @@
-import { useQuery } from "react-query";
-import SearchCampaignConfig from "../services/SearchCampaignConfig";
-
-const useSearchCampaign = (data, config = {}) => {
- return useQuery(["SEARCH_CAMPAIGN",data], () => SearchCampaignConfig(data), { ...config });
-};
-
-export default useSearchCampaign;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/hooks/useSearchPlanConfig.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/hooks/useSearchPlanConfig.js
deleted file mode 100644
index 003fdaa4f51..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/hooks/useSearchPlanConfig.js
+++ /dev/null
@@ -1,8 +0,0 @@
-import { useMutation } from "react-query";
-import SearchPlanConfig from "../services/SearchPlanConfig";
-
-const useSearchPlanConfig = (data, config = {}) => {
- return useQuery([data?.tenantId, data?.id, data?.name, data?.executionPlanId, data?.userUuid, data?.offset, data?.limit], () => SearchPlanConfig(data), { ...config });
-};
-
-export default useSearchPlanConfig;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/hooks/useUpdatePlanConfig.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/hooks/useUpdatePlanConfig.js
deleted file mode 100644
index 17b16145a08..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/hooks/useUpdatePlanConfig.js
+++ /dev/null
@@ -1,8 +0,0 @@
-import { useMutation } from "react-query";
-import UpdatePlanConfig from "../services/UpdatePlanConfig";
-
-const useUpdatePlanConfig = () => {
- return useMutation(data => UpdatePlanConfig(data))
-}
-
-export default useUpdatePlanConfig;
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/icons/Svg.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/icons/Svg.js
deleted file mode 100644
index 03f82f59456..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/icons/Svg.js
+++ /dev/null
@@ -1,217 +0,0 @@
-import React from "react";
-
-export const PopulationSvg = (style) => {
- return `
-
- `;
-};
-
-export const HelpOutlineIcon = ({ className = "", fill = "", style = {} }) => (
-
-);
-
-export const DefaultMapMarkerSvg = (style) => {
- return ``;
-};
-
-
-export const WarehouseMarker = ({
- className = "",
- fill = "white",
- fillBackground = "#42BBFF",
- style = {},
- width = "3.125rem",
- height = "3.125rem",
-}) => {
- return `
-
- `;
-};
-
-export const Warehouse = ({ className = "", fill = "white", fillBackground = "#42BBFF", style = {}, width = "1.5rem", height = "1.5rem" }) => {
- return (
-
- );
-};
-
-export const Church = ({ className = "", fill = "white", fillBackground = "#064466", style = {}, width = "1.5rem", height = "1.5rem" }) => {
- return (
-
- );
-};
-
-export const School = ({ className = "", fill = "white", fillBackground = "#FF7B42", style = {}, width = "1.5rem", height = "1.5rem" }) => {
- return (
-
- );
-};
-
-export const HealthFacility = ({ className = "", fill = "white", fillBackground = "#0C9219", style = {}, width = "1.5rem", height = "1.5rem" , onClick=null}) => {
- return (
-
- );
-};
-
-export const ChurchMarker = ({ className = "", fill = "white", fillBackground = "#064466", style = {}, width = "3.125rem", height = "3.125rem" }) => {
- return `
-
-`;
-};
-
-export const SchoolMarker = ({ className = "", fill = "white", fillBackground = "#FF7B42", style = {}, width = "3.125rem", height = "3.125rem" }) => {
- return `
-
-`;
-};
-
-export const HealthFacilityMarker = ({
- className = "",
- fill = "white",
- fillBackground = "#0C9219",
- style = {},
- width = "3.125rem",
- height = "3.125rem",
-}) => {
- return `
-
-`;
-};
-
-
-
-
-
-export const PlusWithSurroundingCircle = ({ className = "", fill = "white", fillBackground = "#FF7B42", style = {}, width = "1rem", height = "1rem" ,onClick=null }) => {
- return (
-
- );
-};
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/pages/employee/CreateMicroplan.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/pages/employee/CreateMicroplan.js
deleted file mode 100644
index 3885795450c..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/pages/employee/CreateMicroplan.js
+++ /dev/null
@@ -1,288 +0,0 @@
-import React, { useState, useEffect, useCallback, Fragment } from "react";
-import { useTranslation } from "react-i18next";
-import { timeLineOptions } from "../../configs/timeLineOptions.json";
-import Upload from "../../components/Upload";
-import Hypothesis from "../../components/Hypothesis";
-import RuleEngine from "../../components/RuleEngine";
-import Mapping from "../../components/Mapping";
-import Navigator from "../../components/Nagivator";
-import { Toast } from "@egovernments/digit-ui-components";
-import MicroplanPreview from "../../components/MicroplanPreview";
-import MicroplanDetails from "../../components/MicroplanDetails";
-
-export const components = {
- MicroplanDetails,
- Upload,
- Hypothesis,
- RuleEngine,
- Mapping,
- MicroplanPreview,
-};
-
-import MicroplanCreatedScreen from "../../components/MicroplanCreatedScreen";
-import { LoaderWithGap, Tutorial } from "@egovernments/digit-ui-react-components";
-import { useMyContext } from "../../utils/context";
-import { updateSessionUtils } from "../../utils/updateSessionUtils";
-import { render } from "react-dom";
-
-// Main component for creating a microplan
-const CreateMicroplan = () => {
- // Fetching data using custom MDMS hook
- const { id: campaignId = "" } = Digit.Hooks.useQueryParams();
- const { mutate: CreateMutate } = Digit.Hooks.microplan.useCreatePlanConfig();
- const { mutate: UpdateMutate } = Digit.Hooks.microplan.useUpdatePlanConfig();
- const [toRender, setToRender] = useState("navigator");
- const { t } = useTranslation();
-
- // States
- const [microplanData, setMicroplanData] = useState();
- const [operatorsObject, setOperatorsObject] = useState([]);
- const [toast, setToast] = useState();
- const [checkForCompleteness, setCheckForCompletion] = useState([]);
- const [loaderActivation, setLoaderActivation] = useState(false);
- const { state } = useMyContext();
-
- //fetch campaign data
- const { id = "" } = Digit.Hooks.useQueryParams();
- const { isLoading: isCampaignLoading, data: campaignData } = Digit.Hooks.microplan.useSearchCampaign(
- {
- CampaignDetails: {
- tenantId: Digit.ULBService.getCurrentTenantId(),
- ids: [id],
- },
- },
- {
- enabled: !!id,
- }
- );
- // to save microplan helper data to ssn
- useEffect(() => {
- if (campaignData) Digit.SessionStorage.set("microplanHelperData", { ...Digit.SessionStorage.get("microplanHelperData"), campaignData });
- }, [campaignData]);
-
- const campaignType = campaignData?.projectType;
-
- // request body for boundary hierarchy api
- const reqCriteria = {
- url: `/boundary-service/boundary-hierarchy-definition/_search`,
- params: {},
- body: {
- BoundaryTypeHierarchySearchCriteria: {
- tenantId: Digit.ULBService.getStateId(),
- hierarchyType: campaignData?.hierarchyType,
- },
- },
- config: {
- enabled: !!campaignData?.hierarchyType,
- select: (data) => {
- return data?.BoundaryHierarchy?.[0]?.boundaryHierarchy?.map((item) => item?.boundaryType) || {};
- },
- },
- };
- const { isLoading: ishierarchyLoading, data: hierarchyData } = Digit.Hooks.useCustomAPIHook(reqCriteria);
-
- // useEffect to initialise the data from MDMS
- useEffect(() => {
- let temp;
- if (!state || !state.UIConfiguration) return;
- const UIConfiguration = state?.UIConfiguration || {};
- if (UIConfiguration) temp = UIConfiguration.find((item) => item.name === "ruleConfigure");
- if (!temp?.ruleConfigureOperators) return;
- setOperatorsObject(temp.ruleConfigureOperators);
- }, []);
-
- // useEffect to store data in session storage
- useEffect(() => {
- if (!microplanData) return;
- Digit.SessionStorage.set("microplanData", microplanData);
- }, [microplanData]);
-
- // useEffect to store data in session storage
- useEffect(() => {
- const data = Digit.SessionStorage.get("microplanData");
- if (data?.microplanStatus === "GENERATED") setToRender("success-screen");
- let statusData = {};
- let toCheckCompletenesData = [];
- timeLineOptions.forEach((item) => {
- statusData[item.name] = false;
- if (item?.checkForCompleteness) toCheckCompletenesData.push(item.name);
- });
- if (data && data?.status) {
- if (Object.keys(data?.status) === 0) setMicroplanData({ ...data, status: statusData });
- else setMicroplanData({ ...data });
- }
- setCheckForCompletion(toCheckCompletenesData);
- }, []);
-
- // An addon function to pass to Navigator
- const nextEventAddon = useCallback(
- async (currentPage, checkDataCompletion, setCheckDataCompletion) => {
- if (!microplanData) {
- setCheckDataCompletion("perform-action");
- return;
- }
- setMicroplanData((previous) => ({
- ...previous,
- status: { ...previous?.status, [currentPage?.name]: checkDataCompletion === "valid" },
- }));
-
- setCheckDataCompletion("false");
- let body = Digit.Utils.microplan.mapDataForApi(
- microplanData,
- operatorsObject,
- microplanData?.microplanDetails?.name,
- campaignId,
- "DRAFT",
- microplanData?.planConfigurationId ? "update" : "create"
- );
- if (!Digit.Utils.microplan.planConfigRequestBodyValidator(body, state, campaignType)) {
- setCheckDataCompletion("perform-action");
- return;
- }
- setLoaderActivation(true);
- try {
- if (!microplanData?.planConfigurationId) {
- await createPlanConfiguration(body, setCheckDataCompletion, setLoaderActivation, state);
- } else if (microplanData?.planConfigurationId) {
- await updatePlanConfiguration(body, setCheckDataCompletion, setLoaderActivation, state);
- }
- } catch (error) {
- console.error("Failed to create/update plan configuration:", error);
- }
- },
- [microplanData, UpdateMutate, CreateMutate]
- );
-
- const createPlanConfiguration = async (body, setCheckDataCompletion, setLoaderActivation, state) => {
- await CreateMutate(body, {
- onSuccess: async (data) => {
- const readMeConstant = state?.CommonConstants?.find((item) => item?.name === "readMeSheetName");
- const additionalProps = {
- hierarchyData: hierarchyData,
- t,
- campaignType,
- campaignData,
- readMeSheetName: readMeConstant ? readMeConstant.value : undefined,
- };
- const computedSession = await updateSessionUtils.computeSessionObject(data?.PlanConfiguration[0], state, additionalProps);
- if (computedSession) {
- computedSession.microplanStatus = "DRAFT";
- setMicroplanData(computedSession);
- } else {
- console.error("Failed to compute session data.");
- }
- setLoaderActivation(false);
- setCheckDataCompletion("perform-action");
- },
- onError: (error, variables) => {
- setToast({
- message: t("ERROR_DATA_NOT_SAVED"),
- state: "error",
- transitionTime: 10000,
- });
- setTimeout(() => {
- setLoaderActivation(false);
- setCheckDataCompletion("false");
- }, 2000);
- },
- });
- };
-
- const updatePlanConfiguration = async (body, setCheckDataCompletion, setLoaderActivation, state) => {
- body.PlanConfiguration["id"] = microplanData?.planConfigurationId;
- body.PlanConfiguration["auditDetails"] = microplanData?.auditDetails;
- await UpdateMutate(body, {
- onSuccess: async (data) => {
- const readMeConstant = state?.CommonConstants?.find((item) => item?.name === "readMeSheetName");
- const additionalProps = {
- hierarchyData: hierarchyData,
- t,
- campaignType,
- campaignData,
- readMeSheetName: readMeConstant ? readMeConstant.value : undefined,
- };
- const computedSession = await updateSessionUtils.computeSessionObject(data?.PlanConfiguration[0], state, additionalProps);
- if (computedSession) {
- computedSession.microplanStatus = "DRAFT";
- setMicroplanData(computedSession);
- } else {
- console.error("Failed to compute session data.");
- }
- setLoaderActivation(false);
- setCheckDataCompletion("perform-action");
- },
- onError: (error, variables) => {
- setToast({
- message: t("ERROR_DATA_NOT_SAVED"),
- state: "error",
- transitionTime: 10000,
- });
- setTimeout(() => {
- setLoaderActivation(false);
- setCheckDataCompletion("false");
- }, 2000);
- },
- });
- };
-
- const setCurrentPageExternally = useCallback(
- (props) => {
- switch (props.method) {
- case "set": {
- let currentPage;
- const data = Digit.SessionStorage.get("microplanData");
- if (data?.currentPage) currentPage = data.currentPage;
- if (currentPage && props?.setCurrentPage && timeLineOptions.find((item) => item.id === currentPage?.id)) {
- props.setCurrentPage(currentPage);
- return true;
- }
- break;
- }
- case "save": {
- if (props.currentPage) {
- setMicroplanData((previous) => ({ ...previous, currentPage: props.currentPage }));
- }
- break;
- }
- }
- },
- [microplanData, setMicroplanData, Navigator]
- );
-
- const completeNavigation = useCallback(() => {
- setToRender("success-screen");
- }, [setToRender]);
-
- return (
- <>
-
- {toRender === "navigator" && (
-
- )}
- {toRender === "success-screen" && }
-
- {toast && (
- setToast(undefined)}
- />
- )}
- {loaderActivation && }
- >
- );
-};
-
-export default CreateMicroplan;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/pages/employee/Guidelines.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/pages/employee/Guidelines.js
deleted file mode 100644
index 7534c1b2af1..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/pages/employee/Guidelines.js
+++ /dev/null
@@ -1,54 +0,0 @@
-import React, { Fragment } from "react";
-import { useTranslation } from "react-i18next";
-import { Link } from "react-router-dom";
-import { ArrowForward } from "@egovernments/digit-ui-svg-components";
-import { Button } from "@egovernments/digit-ui-react-components";
-import { useHistory } from "react-router-dom";
-import { ActionBar } from "@egovernments/digit-ui-components";
-
-const Guidelines = ({ path }) => {
- const { t } = useTranslation();
- const history = useHistory()
- // Keeping inline style for now because design for this screen is not given yet
- const { id = "" } = Digit.Hooks.useQueryParams();
- const onNextClick = ()=>{
- history.push(`/${window.contextPath}/employee/microplanning/create-microplan?id=${id}`);
- }
- return (
- <>
-
-
- {t("CREATE_MICROPLAN_GUIDELINES")}
-
-
- {/* Action bar */}
-
- {/* Next/Submit button */}
-
-
-
-
- >
- );
-};
-
-export default Guidelines;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/pages/employee/SavedMicroplans.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/pages/employee/SavedMicroplans.js
deleted file mode 100644
index bbb0aef7628..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/pages/employee/SavedMicroplans.js
+++ /dev/null
@@ -1,200 +0,0 @@
-import React, { useState } from "react";
-import { useTranslation } from "react-i18next";
-import { Header, InboxSearchComposerV2, Loader } from "@egovernments/digit-ui-react-components";
-import { useHistory } from "react-router-dom";
-import { updateSessionUtils } from "../../utils/updateSessionUtils";
-import { useMyContext } from "../../utils/context";
-
-const configs = {
- label: "SAVED_MICROPLANS",
- type: "search",
- apiDetails: {
- serviceName: "/plan-service/config/_search",
- requestParam: {},
- requestBody: {},
- minParametersForSearchForm: 0,
- masterName: "commonUiConfig",
- moduleName: "SearchMicroplan",
- tableFormJsonPath: "requestBody.PlanConfigurationSearchCriteria.pagination",
- searchFormJsonPath: "requestBody.PlanConfigurationSearchCriteria",
- },
- sections: {
- search: {
- uiConfig: {
- type: "search",
- typeMobile: "filter",
- headerLabel: "SAVED_MICROPLANS",
- headerStyle: null,
- primaryLabel: "ES_COMMON_SEARCH",
- secondaryLabel: "ES_COMMON_CLEAR_SEARCH",
- minReqFields: 0,
- // "showFormInstruction": "TQM_SEARCH_HINT",
- defaultValues: {
- name: "",
- status: "",
- },
- fields: [
- {
- label: "MICROPLAN_NAME",
- type: "text",
- isMandatory: false,
- disable: false,
- populators: {
- name: "name",
- style: {
- marginBottom: "0px",
- },
- },
- },
- {
- label: "MICROPLAN_STATUS",
- type: "dropdown",
- isMandatory: false,
- disable: false,
- populators: {
- name: "status",
- optionsKey: "status",
- optionsCustomStyle: {
- top: "2.3rem",
- },
- mdmsConfig: {
- masterName: "MicroplanStatus",
- moduleName: "hcm-microplanning",
- localePrefix: "MICROPLAN_STATUS",
- },
- },
- },
- ],
- },
- label: "",
- children: {},
- show: true,
- // "labelMobile": "TQM_INBOX_SEARCH"
- },
- searchResult: {
- uiConfig: {
- columns: [
- {
- label: "MICROPLAN_NAME",
- jsonPath: "name",
- },
- {
- label: "MICROPLAN_STATUS",
- jsonPath: "status",
- prefix: "MICROPLAN_STATUS_COLUMN_",
- translate: true,
- },
- {
- label: "CAMPAIGNS_ASSIGNED",
- jsonPath: "CampaignDetails.campaignName",
- },
- {
- label: "CAMPAIGN_DATE",
- jsonPath: "CampaignDetails.startDate",
- additionalCustomization: true,
- },
- ],
- showActionBarMobileCard: true,
- actionButtonLabelMobileCard: "TQM_VIEW_RESULTS",
- enableGlobalSearch: false,
- enableColumnSort: true,
- resultsJsonPath: "PlanConfiguration",
- tableClassName: "table pqm-table",
- noColumnBorder: true,
- rowClassName: "table-row-mdms table-row-mdms-hover",
- },
- children: {},
- show: true,
- },
- },
- additionalSections: {},
- persistFormData: true,
- showAsRemovableTagsInMobile: false,
- customHookName: "microplan.useSavedMicroplans",
-};
-
-const SavedMicroplans = () => {
- const [showLoader, setShowLoader] = useState(false);
- const { state } = useMyContext();
- const history = useHistory();
- const { t } = useTranslation();
-
- const fetchHierarchyData = async (hierarchyType) => {
- const response = await Digit.CustomService.getResponse({
- url: "/boundary-service/boundary-hierarchy-definition/_search",
- useCache: false,
- method: "POST",
- userService: false,
- body: {
- BoundaryTypeHierarchySearchCriteria: {
- tenantId: Digit.ULBService.getStateId(),
- hierarchyType,
- },
- },
- });
- if (response?.BoundaryHierarchy?.length) {
- return response.BoundaryHierarchy[0].boundaryHierarchy.map((item) => item.boundaryType);
- }
- console.error("Invalid response structure");
- };
-
- const computeAdditionalProps = (row, state, t, hierarchyData) => {
- const campaignDetails = row?.original?.CampaignDetails;
- const readMeSheetName = state?.CommonConstants?.find((item) => item?.name === "readMeSheetName")?.value;
- return {
- hierarchyData,
- t,
- campaignType: campaignDetails?.projectType,
- campaignData: campaignDetails,
- readMeSheetName,
- };
- };
-
- const onClickRow = (row) => {
- const handleClick = async () => {
- setShowLoader(true);
- try {
- const campaignType = row?.original?.CampaignDetails?.projectType;
- const hierarchyData = await fetchHierarchyData(row?.original?.CampaignDetails?.hierarchyType);
- const additionalProps = computeAdditionalProps(row, state, t, hierarchyData);
-
- // Compute the session object based on the row?.original data and then re-route
- const computedSession = await updateSessionUtils.computeSessionObject(row.original, state, additionalProps);
- Digit.SessionStorage.set("microplanData", computedSession);
-
- setShowLoader(false);
- history.push(`/${window.contextPath}/employee/microplanning/create-microplan?id=${row?.original?.executionPlanId}`);
- } catch (error) {
- console.error(`Failed to process the request: ${error.message}`);
- setShowLoader(false);
- }
- };
-
- handleClick();
- };
-
- const savedMircoplanSession = Digit.Hooks.useSessionStorage("SAVED_MICROPLAN_SESSION", {});
-
- if (showLoader) {
- return ;
- }
-
- return (
-
-
-
-
-
-
- );
-};
-
-export default SavedMicroplans;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/pages/employee/SelectCampaign.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/pages/employee/SelectCampaign.js
deleted file mode 100644
index 8f2131eefdd..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/pages/employee/SelectCampaign.js
+++ /dev/null
@@ -1,226 +0,0 @@
-import React, { useEffect, useMemo } from "react";
-import { useTranslation } from "react-i18next";
-import { Header, InboxSearchComposer, InboxSearchComposerV2, Loader } from "@egovernments/digit-ui-react-components";
-import { useHistory, useParams } from "react-router-dom";
-
-const configs = {
- label: "SELECT_CAMPAIGN",
- type: "search",
- apiDetails: {
- serviceName: "/project-factory/v1/project-type/search",
- requestParam: {},
- requestBody: {},
- minParametersForSearchForm: 0,
- masterName: "commonUiConfig",
- moduleName: "SearchCampaign",
- tableFormJsonPath: "requestBody.CampaignDetails.pagination",
- searchFormJsonPath: "requestBody.CampaignDetails",
- },
- sections: {
- search: {
- uiConfig: {
- type: "search",
- // typeMobile: "filter",
- headerLabel: "SELECT_CAMPAIGN",
- headerStyle: null,
- primaryLabel: "ES_COMMON_SEARCH",
- secondaryLabel: "ES_COMMON_CLEAR_SEARCH",
- minReqFields: 1,
- // "showFormInstruction": "TQM_SEARCH_HINT",
- defaultValues: {
- campaignName: "",
- projectType: "",
- startDate: "",
- endDate: "",
- boundaryCode: "",
- },
- fields: [
- {
- label: "CAMPAIGN_NAME",
- type: "text",
- isMandatory: false,
- disable: false,
- populators: {
- name: "campaignName",
- style: {
- marginBottom: "0px",
- },
- error: "ERR_MIN_LENGTH_CAMPAIGN_NAME",
- validationErrorStyles: {
- marginTop: "0.3rem",
- },
- validation: {
- minLength: 2,
- },
- },
- },
- // {
- // label: "CAMPAIGN_TYPE",
- // type: "dropdown",
- // isMandatory: false,
- // disable: false,
- // populators: {
- // name: "projectType",
- // optionsKey: "name",
- // optionsCustomStyle: {
- // top: "2.3rem",
- // },
- // mdmsConfig: {
- // masterName: "projectTypes",
- // moduleName: "HCM-PROJECT-TYPES",
- // localePrefix: "CAMPAIGN_TYPE",
- // },
- // },
- // },
- {
- label: "CAMPAIGN_TYPE",
- type: "apidropdown",
- isMandatory: false,
- disable: false,
- populators: {
- name: "projectType",
- optionsKey: "i18nKey",
- optionsCustomStyle: {
- top: "2.3rem",
- },
- allowMultiSelect: false,
- masterName: "commonUiConfig",
- moduleName: "SearchCampaign",
- customfn: "populateProjectType",
- },
- },
- {
- label: "CAMPAIGN_START_DATE",
- type: "date",
- isMandatory: false,
- key: "startDate",
- disable: false,
- preProcess: {
- updateDependent: ["populators.max"],
- },
- populators: {
- name: "startDate",
- style: {
- marginBottom: "0px",
- },
- error: "DATE_VALIDATION_MSG",
- },
- },
- {
- label: "CAMPAIGN_END_DATE",
- type: "date",
- isMandatory: false,
- disable: false,
- key: "endDate",
- preProcess: {
- updateDependent: ["populators.max"],
- },
- populators: {
- name: "endDate",
- error: "DATE_VALIDATION_MSG",
- min: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString().slice(0, 10),
- style: {
- marginBottom: "0px",
- },
- },
- },
- // {
- // label: "CAMPAIGN_BOUNDARY",
- // type: "text",
- // isMandatory: false,
- // disable: false,
- // populators: {
- // name: "boundaryCode",
- // style: {
- // marginBottom: "0px",
- // },
- // },
- // },
- ],
- },
- label: "",
- children: {},
- show: true,
- // "labelMobile": "TQM_INBOX_SEARCH"
- },
- searchResult: {
- uiConfig: {
- columns: [
- {
- label: "CAMPAIGN_NAME",
- jsonPath: "campaignName",
- // "additionalCustomization": true
- },
- {
- label: "CAMPAIGN_TYPE",
- jsonPath: "projectType",
- // "additionalCustomization": false,
- prefix: "CAMPAIGN_TYPE_",
- translate: true,
- },
- {
- label: "CAMPAIGN_BOUNDARY_CAMP",
- jsonPath: "boundaryCode",
- // "additionalCustomization": false,
- prefix: "CAMPAIGN_BOUNDARY_",
- translate: true,
- },
- {
- label: "CAMPAIGN_BENEFICIARY_TYPE",
- jsonPath: "additionalDetails.beneficiaryType",
- prefix: "CAMPAIGN_BENEFICIARY_TYPE_",
- translate: true,
- },
- {
- label: "CAMPAIGN_DATE",
- jsonPath: "startDate",
- additionalCustomization: true,
- },
- ],
- showActionBarMobileCard: true,
- actionButtonLabelMobileCard: "TQM_VIEW_RESULTS",
- enableGlobalSearch: false,
- enableColumnSort: true,
- resultsJsonPath: "CampaignDetails",
- tableClassName: "table pqm-table",
- rowClassName: "table-row-mdms table-row-mdms-hover",
- noColumnBorder: true,
- },
- children: {},
- show: true,
- },
- },
- additionalSections: {},
- persistFormData: true,
- showAsRemovableTagsInMobile: false,
-};
-const SelectCampaign = () => {
- const { t } = useTranslation();
- const history = useHistory();
-
- const onClickRow = (row) => {
- // history.push(`/${window.contextPath}/employee/microplanning/help-guidelines?id=${row?.original?.id}`);
- history.push(`/${window.contextPath}/employee/microplanning/create-microplan?id=${row?.original?.id}`);
- };
-
- const SelectCampaignSession = Digit.Hooks.useSessionStorage("SELECT_CAMPAIGN_SESSION", {});
-
- return (
-
-
-
-
-
-
- );
-};
-
-export default SelectCampaign;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/pages/employee/index.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/pages/employee/index.js
deleted file mode 100644
index 6f58779637a..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/pages/employee/index.js
+++ /dev/null
@@ -1,128 +0,0 @@
-import React, { useEffect } from "react";
-import { Switch, useLocation } from "react-router-dom";
-import { useTranslation } from "react-i18next";
-import { PrivateRoute, AppContainer, BreadCrumb, Loader } from "@egovernments/digit-ui-react-components";
-import MicroplanningHeader from "../../components/MicroplanningHeader";
-import Guidelines from "./Guidelines";
-import CreateMicroplan from "./CreateMicroplan";
-import SavedMicroplans from "./SavedMicroplans";
-import SelectCampaign from "./SelectCampaign";
-import { useMyContext } from "../../utils/context";
-
-const MicroplanningBreadCrumb = ({ location, defaultPath }) => {
- const { t } = useTranslation();
- const pathVar = location.pathname.replace(`${defaultPath}/`, "").split("?")?.[0];
- const { masterName, moduleName, uniqueIdentifier } = Digit.Hooks.useQueryParams();
-
- const crumbs = [
- {
- path: `/${window?.contextPath}/employee`,
- content: t("Home"),
- show: true,
- },
- // {
- // content: t(`UPLOAD`) ,
- // show: pathVar.includes("upload")?true: false,
- // },
- // {
- // content: t(`HYPOTHESIS`) ,
- // show: pathVar.includes("hypothesis")?true: false,
- // },
- // {
- // content: t(`RULE_ENGINE`) ,
- // show: pathVar.includes("rule-engine")?true: false,
- // },
- {
- content: t(`CREATE_MICROPLAN`),
- show: pathVar.includes("create-microplan"),
- },
- {
- content: t(`SAVED_MICROPLANS_TEXT`),
- show: pathVar.includes("saved-microplan"),
- },
- {
- content: t(`CREATE_MICROPLAN`),
- show: pathVar.includes("select-campaign"),
- },
- ];
- return ;
-};
-
-const App = ({ path }) => {
- const { dispatch } = useMyContext();
-
- const location = useLocation();
- const MDMSCreateSession = Digit.Hooks.useSessionStorage("MDMS_add", {});
- const [sessionFormData, setSessionFormData, clearSessionFormData] = MDMSCreateSession;
-
- const MDMSViewSession = Digit.Hooks.useSessionStorage("MDMS_view", {});
- const [sessionFormDataView, setSessionFormDataView, clearSessionFormDataView] = MDMSViewSession;
-
- const { isLoading: isLoadingMdmsBaseData, data } = Digit.Hooks.useCustomMDMS(
- Digit.ULBService.getCurrentTenantId(),
- "hcm-microplanning",
- [
- { name: "UploadConfiguration" },
- { name: "UIConfiguration" },
- { name: "Schemas" },
- { name: "RuleConfigureOutput" },
- { name: "Resources" },
- { name: "HypothesisAssumptions" },
- { name: "BaseMapLayers" },
- { name: "MicroplanPreviewAggregates" },
- { name: "AutoFilledRuleConfigurations" },
- { name: "MapFilters" },
- { name: "HierarchyConfigurations" },
- { name: "NumberFormatMappingForTranslation" },
- { name: "UploadGuidelines" },
- { name: "ReadMeData" },
- { name: "CommonConstants" },
- ],
- {
- select: (data) => {
- dispatch({
- type: "SETINITDATA",
- state: {
- ...data?.["hcm-microplanning"],
- },
- });
- },
- }
- );
-
- //destroying session
- useEffect(() => {
- const pathVar = location.pathname.replace(`${path}/`, "").split("?")?.[0];
- Digit.Utils.microplan.destroySessionHelper(pathVar, ["create-microplan"], "microplanData");
- Digit.Utils.microplan.destroySessionHelper(pathVar, ["create-microplan"], "microplanHelperData");
- Digit.Utils.microplan.destroySessionHelper(pathVar, ["select-campaign"], "SELECT_CAMPAIGN_SESSION");
- Digit.Utils.microplan.destroySessionHelper(pathVar, ["saved-microplans"], "SAVED_MICROPLAN_SESSION");
- }, [location]);
-
- if (isLoadingMdmsBaseData) {
- return ;
- }
-
- return (
-
-
-
-
-
-
-
- {/* } />
- } />
- } /> */}
- } />
-
- } />
- } />
- } />
-
-
-
- );
-};
-
-export default App;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/services/CreatePlanConfig.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/services/CreatePlanConfig.js
deleted file mode 100644
index cabc9b67b56..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/services/CreatePlanConfig.js
+++ /dev/null
@@ -1,19 +0,0 @@
-const CreatePlanConfig = async (body) => {
- try {
- const response = await Digit.CustomService.getResponse({
- url: "/plan-service/config/_create",
- useCache: false,
- method: "POST",
- userService: true,
- body,
- });
- return response;
- } catch (error) {
- if (error?.response?.data?.Errors) {
- throw new Error(error.response.data.Errors[0].message);
- }
- throw new Error("An unknown error occurred");
- }
-};
-
-export default CreatePlanConfig;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/services/Search.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/services/Search.js
deleted file mode 100644
index 83d4fb5fc72..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/services/Search.js
+++ /dev/null
@@ -1,181 +0,0 @@
-import _ from "lodash";
-
-const createProjectsArray = (t, project, searchParams, headerLocale) => {
- let totalProjects = {
- searchedProject: {},
- subProjects: [],
- };
- let basicDetails = {};
- let totalProjectsLength = project.length;
- // for(let projectIndex = 0; projectIndex < totalProjectsLength; projectIndex++) {
- let currentProject = project[0];
- const headerDetails = {
- title: " ",
- asSectionHeader: true,
- values: [
- { title: "WORKS_PROJECT_ID", value: currentProject?.projectNumber || "NA" },
- { title: "ES_COMMON_PROPOSAL_DATE", value: Digit.Utils.pt.convertEpochToDate(currentProject?.additionalDetails?.dateOfProposal) || "NA" },
- { title: "WORKS_PROJECT_NAME", value: currentProject?.name || "NA" },
- { title: "PROJECT_PROJECT_DESC", value: currentProject?.description || "NA" },
- ],
- };
-
- const projectDetails = {
- title: "WORKS_PROJECT_DETAILS",
- asSectionHeader: true,
- values: [
- { title: "PROJECT_LOR", value: currentProject?.referenceID || "NA" },
- {
- title: "WORKS_PROJECT_TYPE",
- value: currentProject?.projectType ? t(`COMMON_MASTERS_${Digit.Utils.locale.getTransformedLocale(currentProject?.projectType)}`) : "NA",
- },
- {
- title: "PROJECT_TARGET_DEMOGRAPHY",
- value: currentProject?.additionalDetails?.targetDemography
- ? t(`COMMON_MASTERS_${currentProject?.additionalDetails?.targetDemography}`)
- : "NA",
- },
- {
- title: "PROJECT_ESTIMATED_COST",
- value: currentProject?.additionalDetails?.estimatedCostInRs
- ? `₹ ${Digit.Utils.dss.formatterWithoutRound(currentProject?.additionalDetails?.estimatedCostInRs, "number")}`
- : "NA",
- },
- ],
- };
-
- const locationDetails = {
- title: "WORKS_LOCATION_DETAILS",
- asSectionHeader: true,
- values: [
- {
- title: "WORKS_GEO_LOCATION",
- value:
- currentProject?.address?.latitude || currentProject?.address?.longitude
- ? `${currentProject?.address?.latitude}, ${currentProject?.address?.longitude}`
- : "NA",
- },
- {
- title: "WORKS_CITY",
- value: currentProject?.address?.city ? t(`TENANT_TENANTS_${Digit.Utils.locale.getTransformedLocale(currentProject?.address?.city)}`) : "NA",
- }, //will check with Backend
- { title: "WORKS_WARD", value: currentProject?.address?.boundary ? t(`${headerLocale}_ADMIN_${currentProject?.address?.boundary}`) : "NA" }, ///backend to update this
- {
- title: "WORKS_LOCALITY",
- value: currentProject?.additionalDetails?.locality ? t(`${headerLocale}_ADMIN_${currentProject?.additionalDetails?.locality}`) : "NA",
- },
- ],
- };
-
- // const financialDetails = {
- // title: "WORKS_FINANCIAL_DETAILS",
- // asSectionHeader: false,
- // values: [
- // { title: "WORKS_HEAD_OF_ACCOUNTS", value: currentProject?.additionalDetails?.fund ? t(`COMMON_MASTERS_FUND_${currentProject?.additionalDetails?.fund}`) : "NA" },
- // ],
- // };
-
- let documentDetails = {
- title: "",
- asSectionHeader: true,
- additionalDetails: {
- documents: [
- {
- title: "WORKS_RELEVANT_DOCUMENTS",
- BS: "Works",
- values: currentProject?.documents?.map((document) => {
- if (document?.status !== "INACTIVE") {
- return {
- title: document?.documentType === "OTHERS" ? document?.additionalDetails?.otherCategoryName : t(`PROJECT_${document?.documentType}`),
- documentType: document?.documentType,
- documentUid: document?.fileStore,
- fileStoreId: document?.fileStore,
- };
- }
- return {};
- }),
- },
- ],
- },
- };
-
- //filter any empty object
- documentDetails.additionalDetails.documents[0].values = documentDetails?.additionalDetails?.documents?.[0]?.values?.filter((value) => {
- if (value?.title) {
- return value;
- }
- });
-
- // if(currentProject?.projectNumber === searchParams?.Projects?.[0]?.projectNumber) {
- basicDetails = {
- projectID: currentProject?.projectNumber,
- projectProposalDate: Digit.Utils.pt.convertEpochToDate(currentProject?.additionalDetails?.dateOfProposal) || "NA",
- projectName: currentProject?.name || "NA",
- projectDesc: currentProject?.description || "NA",
- projectHasSubProject: totalProjectsLength > 1 ? "COMMON_YES" : "COMMON_NO",
- projectParentProjectID: currentProject?.ancestors?.[0]?.projectNumber || "NA",
- uuid: currentProject?.id,
- address: currentProject?.address,
- ward: currentProject?.address?.boundary,
- locality: currentProject?.additionalDetails?.locality,
- };
- totalProjects.searchedProject = {
- basicDetails,
- headerDetails,
- projectDetails,
- locationDetails,
- documentDetails,
- };
- // }
- // }
- return totalProjects;
-};
-
-export const Search = {
- viewProjectDetailsScreen: async (
- t,
- tenantId,
- searchParams,
- filters = { limit: 10, offset: 0, includeAncestors: true, includeDescendants: true },
- headerLocale
- ) => {
- const response = await Digit.WorksService?.searchProject(tenantId, searchParams, filters);
-
- let projectDetails = {
- searchedProject: {
- basicDetails: {},
- details: {
- projectDetails: [],
- },
- },
- };
-
- if (response?.Project) {
- let projects = createProjectsArray(t, response?.Project, searchParams, headerLocale);
-
- //searched Project details
- projectDetails.searchedProject["basicDetails"] = projects?.searchedProject?.basicDetails;
- projectDetails.searchedProject["details"]["projectDetails"] = {
- applicationDetails: [
- projects?.searchedProject?.headerDetails,
- projects?.searchedProject?.projectDetails,
- projects?.searchedProject?.locationDetails,
- projects?.searchedProject?.documentDetails,
- ],
- }; //rest categories will come here
- }
-
- return {
- projectDetails: response?.Project ? projectDetails : [],
- response: response?.Project,
- processInstancesDetails: [],
- workflowDetails: [],
- applicationData: {},
- isNoDataFound: response?.Project?.length === 0,
- };
- },
- searchEstimate: async (tenantId, filters) => {
- const response = await Digit.WorksService?.estimateSearch({ tenantId, filters });
- return response?.estimates;
- },
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/services/SearchCampaignConfig.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/services/SearchCampaignConfig.js
deleted file mode 100644
index bb6a9f26916..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/services/SearchCampaignConfig.js
+++ /dev/null
@@ -1,22 +0,0 @@
-const SearchCampaignConfig = async (body) => {
- try {
- const response = await Digit.CustomService.getResponse({
- url: "/project-factory/v1/project-type/search",
- useCache: false,
- method: "POST",
- userService: false,
- body,
- });
- if (response?.CampaignDetails?.length === 0) {
- throw new Error("Campaign not found with the given id");
- }
- return response?.CampaignDetails?.[0];
- } catch (error) {
- if (error?.response?.data?.Errors) {
- throw new Error(error.response.data.Errors[0].message);
- }
- throw new Error("An unknown error occurred");
- }
-};
-
-export default SearchCampaignConfig;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/services/SearchPlanConfig.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/services/SearchPlanConfig.js
deleted file mode 100644
index 1fe11f206a7..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/services/SearchPlanConfig.js
+++ /dev/null
@@ -1,19 +0,0 @@
-const SearchPlanConfig = async (body) => {
- try {
- const response = await Digit.CustomService.getResponse({
- url: "/plan-service/config/_search",
- useCache: false,
- method: "POST",
- userService: true,
- body,
- });
- return response;
- } catch (error) {
- if (error?.response?.data?.Errors) {
- throw new Error(error.response.data.Errors[0].message);
- }
- throw new Error("An unknown error occurred");
- }
-};
-
-export default SearchPlanConfig;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/services/UpdatePlanConfig.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/services/UpdatePlanConfig.js
deleted file mode 100644
index d1623cbd167..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/services/UpdatePlanConfig.js
+++ /dev/null
@@ -1,18 +0,0 @@
-const UpdatePlanConfig = async (body) => {
- try {
- const response = await Digit.CustomService.getResponse({
- url: "/plan-service/config/_update",
- useCache: false,
- method: "POST",
- userService: true,
- body,
- });
- return response;
- } catch (error) {
- if (error?.response?.data?.Errors) {
- throw new Error(error.response.data.Errors[0].message);
- }
- throw new Error("An unknown error occurred");
- }
-};
-export default UpdatePlanConfig;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/services/searchSavedPlans.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/services/searchSavedPlans.js
deleted file mode 100644
index ba4342526a8..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/services/searchSavedPlans.js
+++ /dev/null
@@ -1,67 +0,0 @@
-function mergeArrays(array1, key1, array2, key2) {
- const mergedArray = [];
-
- // Create a map of values from array2 using key2
- const map = new Map();
- array2.forEach((item) => {
- map.set(item[key2], item);
- });
-
- // Iterate over array1 and merge with matching items from array2
- array1.forEach((item) => {
- const matchingItem = map.get(item[key1]);
- if (matchingItem) {
- // Merge properties from both items and append to 'CampaignDetails'
- const mergedItem = { ...item, CampaignDetails: { ...matchingItem } };
- mergedArray.push(mergedItem);
- } else {
- // No matching item found in array2, add array1 item with empty 'CampaignDetails'
- const mergedItem = { ...item, CampaignDetails: {} };
- mergedArray.push(mergedItem);
- }
- });
- return mergedArray;
-}
-
-const SearchSavedPlans = async (body) => {
- try {
- //here get response from both apis and process data and return
- const responsePlan = await Digit.CustomService.getResponse({
- url: "/plan-service/config/_search",
- useCache: false,
- method: "POST",
- userService: false,
- body,
- });
-
- const { PlanConfiguration } = responsePlan;
- if (!PlanConfiguration || PlanConfiguration.length === 0) return [];
-
- const executionPlanIds = PlanConfiguration?.map((row) => row?.executionPlanId)?.filter((item) => item);
- const CampaignDetails = {
- tenantId: Digit.ULBService.getCurrentTenantId(),
- ids: executionPlanIds,
- };
-
- const responseCampaign = await Digit.CustomService.getResponse({
- url: "/project-factory/v1/project-type/search",
- useCache: false,
- method: "POST",
- userService: false,
- body: {
- CampaignDetails,
- },
- });
- const finalResult = {
- PlanConfiguration: mergeArrays(responsePlan?.PlanConfiguration, "executionPlanId", responseCampaign?.CampaignDetails, "id"),
- };
- return finalResult;
- } catch (error) {
- if (error?.response?.data?.Errors) {
- throw new Error(error.response.data.Errors[0].message);
- }
- throw new Error("An unknown error occurred");
- }
-};
-
-export default SearchSavedPlans;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/context.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/context.js
deleted file mode 100644
index 5e6c18f699e..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/context.js
+++ /dev/null
@@ -1,31 +0,0 @@
-import React,{useContext,createContext,useReducer} from "react"
-
-const MyContext = createContext()
-const initialState = {
-
-}
-
-const reducer = (state=initialState,action) => {
- switch (action.type) {
- case "SETINITDATA":
- return {...state,...action.state}
- default:
- return state;
- }
-}
-
-export const useMyContext = () => {
-
- return useContext(MyContext)
-}
-
-export const ProviderContext = ({children}) => {
-
- const [state,dispatch] = useReducer(reducer,initialState)
-
- return (
-
- {children}
-
- )
-}
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/createTemplate.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/createTemplate.js
deleted file mode 100644
index a3f79c2358e..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/createTemplate.js
+++ /dev/null
@@ -1,485 +0,0 @@
-import { BOUNDARY_DATA_SHEET, FACILITY_DATA_SHEET, SCHEMA_PROPERTIES_PREFIX, commonColumn } from "../configs/constants";
-
-export const fetchBoundaryData = async (tenantId, hierarchyType, codes) => {
- // request for boundary relation api
- const reqCriteria = {
- url: "/boundary-service/boundary-relationships/_search",
- params: { tenantId, hierarchyType, codes, includeChildren: true },
- body: {},
- };
- let response;
- try {
- response = (await Digit.CustomService.getResponse(reqCriteria))?.TenantBoundary?.[0]?.boundary || {};
- } catch (error) {
- console.error("Error in fetching boundary Data: ", error.message);
- }
- return response;
-};
-
-export const getFacilities = async (params, body) => {
- // request for boundary relation api
- const reqCriteria = {
- url: "/facility/v1/_search",
- params: params,
- body: body,
- };
- let response;
- try {
- response = (await Digit.CustomService.getResponse(reqCriteria))?.Facilities || {};
- } catch (error) {
- if (error.response) {
- throw new Error(`Failed to fetch facility data: ${error.response.data.message}`);
- }
- if (error.request) {
- // Network error
- throw new Error("Network error while fetching facility data");
- }
- // Other errors
- throw new Error(`Error while fetching facility data: ${error.message}`);
- }
- return response;
-};
-
-// export const fetchColumnsFromMdms = (schema)=>{
-// return
-// }
-
-/**
- *
- * @param {*} xlsxData
- * @param {*} boundaryData
- * @returns xlsxData with boundary data added
- */
-export const addBoundaryData = (xlsxData, boundaryData, hierarchyType) => {
- // Return the original data if there is no boundary data to add
- if (!boundaryData) return xlsxData;
-
- // Initialize the array to hold new data
- let newXlsxData = [];
-
- // Recursive function to convert boundary data into sheet format
- const convertBoundaryDataToSheets = (boundaryData, currentBoundaryPredecessor = [], hierarchyAccumulator = [], dataAccumulator = []) => {
- // Return if boundary data is not valid or not an array
- if (!boundaryData || !Array.isArray(boundaryData)) return;
-
- // Clone the current boundary predecessor to avoid modifying the original data
- const rowData = [...currentBoundaryPredecessor];
- // Clone the data accumulator to preserve the accumulated data
- let tempDataAccumulator = [...dataAccumulator];
- // Use a set to accumulate unique hierarchy levels
- let tempHierarchyAccumulator = new Set(hierarchyAccumulator);
-
- // Iterate over each item in the boundary data array
- for (const item of boundaryData) {
- if (item?.code) {
- // Create a new row with the current item's code
- const tempRow = [...rowData, item?.code];
- let response;
- // Add the current item's boundary type to the hierarchy
- tempHierarchyAccumulator.add(item.boundaryType);
-
- // If the current item has children, recursively process them
- if (item.children)
- response = convertBoundaryDataToSheets(item.children, tempRow, tempHierarchyAccumulator, [...tempDataAccumulator, tempRow]);
-
- // Update the accumulators with the response from the recursive call
- if (response) {
- tempDataAccumulator = response.tempDataAccumulator;
- tempHierarchyAccumulator = response.tempHierarchyAccumulator;
- }
- }
- }
-
- // Return the accumulated data and hierarchy
- return { tempDataAccumulator, tempHierarchyAccumulator };
- };
-
- // Convert the boundary data into sheet format and extract the sorted data and hierarchy
- let { tempDataAccumulator: sortedBoundaryDataForXlsxSheet, tempHierarchyAccumulator: hierarchy } = convertBoundaryDataToSheets(boundaryData);
-
- // Add the hierarchy as the first row of the sheet
- hierarchy = [...hierarchy].map((item) => `${hierarchyType}_${Digit.Utils.microplan.transformIntoLocalisationCode(item)}`);
- sortedBoundaryDataForXlsxSheet = [[...hierarchy], ...sortedBoundaryDataForXlsxSheet];
-
- // Determine the maximum row length to ensure all rows have the same length
- const topIndex = Math.max(...sortedBoundaryDataForXlsxSheet.map((row) => row.length)) - 1;
-
- // Ensure all rows are of the same length by filling them with empty strings
- sortedBoundaryDataForXlsxSheet = sortedBoundaryDataForXlsxSheet.map((item, index) => {
- let newItem = item;
- if (index !== 0) {
- if (!newItem) {
- newItem = [];
- }
- const itemLength = newItem.length;
- while (newItem.length <= topIndex) {
- newItem.push("");
- }
- newItem.push(newItem[itemLength - 1]);
- } else {
- newItem.push(commonColumn);
- }
-
- return newItem;
- });
-
- // Add the new sheet data to the original data
- newXlsxData = [...xlsxData, ...newXlsxData, { sheetName: BOUNDARY_DATA_SHEET, data: sortedBoundaryDataForXlsxSheet }];
-
- // Return the updated data
- return newXlsxData;
-};
-
-const fillDataWithBlanks = (data, tillRow) => {
- while (data.length < tillRow) {
- data.push([]);
- }
-
- const maxLength = Math.max(...data.map((row) => row.length));
- return data.map((row) => [...row, ...new Array(maxLength - row.length).fill("")]);
-};
-const generateLocalisationKeyForSchemaProperties = (code) => {
- if (!code) return code;
- return `${SCHEMA_PROPERTIES_PREFIX}_${code}`;
-};
-/**
- *
- * @param {array} xlsxData , xlsx data
- * @param {object} schema , schema to refer to
- * @returns {Array of Object} , xlsxData with schema data added
- *
- * adds schema data to sheets
- */
-const addSchemaData = (xlsxData, schema, extraColumnsToAdd) => {
- if (!schema) return xlsxData;
- let columnSchema = schema.schema?.Properties || {};
- const newXlsxData = [];
- const columnList = [[], [], [], []]; // Initialize columnList with four empty arrays
-
- for (const [key, value] of Object.entries(columnSchema)) {
- if (key === commonColumn) continue;
-
- columnList[0].push(generateLocalisationKeyForSchemaProperties(key)); // Add key to the first array
-
- // columnList[1].push(value.type || ""); // Add type to the second array
-
- // columnList[2].push(value.isRequired ? "MANDATORY" : "OPTIONAL"); // Add requirement status to the third array
-
- // columnList[3].push(value.pattern || ""); // Add pattern to the fourth array
- }
-
- if (extraColumnsToAdd) columnList[0].push(...extraColumnsToAdd);
-
- for (let { sheetName, data } of xlsxData) {
- data = fillDataWithBlanks(data, 4);
- columnList.forEach((item, index) => {
- // Append the new items to the row
- if (data[index]) {
- data[index] = [...data[index], ...item];
- } else {
- data[index] = [...item];
- }
- });
-
- newXlsxData.push({ sheetName, data });
- }
-
- return newXlsxData;
-};
-
-/**
- *
- * @param {Array of Object} xlsxData
- * @param {string} hierarchyLevelName
- */
-const devideXlsxDataHierarchyLevelWise = (xlsxData, hierarchyLevelName) => {
- if (!hierarchyLevelName) return xlsxData; // Return original data if no hierarchy level name
-
- const result = []; // Initialize result array
-
- // Iterate over each sheet in the xlsxData
- for (const sheet of xlsxData) {
- const sheetData = sheet.data;
- const hierarchyLevelIndex = sheetData[0].indexOf(hierarchyLevelName);
-
- // If hierarchy level name not found, skip this sheet
- if (hierarchyLevelIndex === -1) {
- result.push(sheet);
- continue;
- }
-
- const { sheetsMap, danglingDataMap } = processSheetData(sheetData, hierarchyLevelIndex);
-
- // Combine danglingDataMap with sheetsMap
- for (const key of Object.keys(danglingDataMap)) {
- if (sheetsMap[key]) {
- sheetsMap[key].data = [sheetData[0], ...danglingDataMap[key], ...sheetsMap[key].data.slice(1)];
- } else {
- sheetsMap[key] = {
- sheetName: key,
- data: [...danglingDataMap[key], sheetData[0]],
- };
- }
- }
-
- // Add sheetsMap values to result
- result.push(...Object.values(sheetsMap));
- }
-
- return result.length > 0 ? result : xlsxData; // Return result or original data if result is empty
-};
-
-// Function to process sheet data and return sheetsMap and danglingDataMap
-const processSheetData = (sheetData, hierarchyLevelIndex) => {
- const sheetsMap = {};
- const danglingDataMap = {};
- let emptyHierarchyRow = [];
- let lastWasEmpty = true;
-
- // Iterate through sheet data starting from the second row (skipping header)
- for (let i = 1; i < sheetData.length; i++) {
- const row = sheetData[i];
- const hierarchyValue = row[hierarchyLevelIndex];
-
- if (emptyHierarchyRow.length && hierarchyValue !== "") {
- danglingDataMap[hierarchyValue] = emptyHierarchyRow;
- }
-
- if (hierarchyValue === "" && lastWasEmpty) {
- emptyHierarchyRow.push(row);
- } else {
- emptyHierarchyRow = [];
- }
-
- if (!sheetsMap[hierarchyValue] && hierarchyValue !== "") {
- sheetsMap[hierarchyValue] = {
- sheetName: hierarchyValue,
- data: [sheetData[0]],
- };
- }
-
- if (hierarchyValue === row[hierarchyLevelIndex] && hierarchyValue !== "") {
- sheetsMap[hierarchyValue].data.push(row);
- }
-
- lastWasEmpty = hierarchyValue === "";
- }
-
- return { sheetsMap, danglingDataMap };
-};
-
-export const filterBoundaries = (boundaryData, boundaryFilters) => {
- if (!boundaryFilters) return boundaryData;
- // Define a helper function to recursively filter boundaries
- function filterRecursive(boundary) {
- // Find the filter that matches the current boundary
- const filter = boundaryFilters?.find((f) => f.code === boundary.code && f.type === boundary.boundaryType);
-
- // If no filter is found, return the boundary with its children filtered recursively
- if (!filter) {
- return {
- ...boundary,
- children: boundary.children.map(filterRecursive),
- };
- }
-
- // If the boundary has no children, handle the case where includeAllChildren is false
- if (!boundary.children.length) {
- // Return the boundary with an empty children array
- return {
- ...boundary,
- children: [],
- };
- }
-
- // If includeAllChildren is true, return the boundary with all children
- if (filter.includeAllChildren) {
- return {
- ...boundary,
- children: boundary.children.map(filterRecursive),
- };
- }
-
- // Filter children based on the filters
- const filteredChildren = boundary.children
- .filter((child) => boundaryFilters.some((f) => f.code === child.code && f.type === child.boundaryType))
- .map(filterRecursive);
-
- // Return the boundary with filtered children
- return {
- ...boundary,
- children: filteredChildren,
- };
- }
-
- // Map through the boundary data and apply the recursive filter function to each boundary
- const filteredData = boundaryData.map(filterRecursive);
- return filteredData;
-};
-
-/**
- * Retrieves all facilities for a given tenant ID.
- * @param tenantId The ID of the tenant.
- * @returns An array of facilities.
- */
-async function getAllFacilities(tenantId) {
- // Retrieve all facilities for the given tenant ID
- const facilitySearchBody = {
- Facility: { isPermanent: true },
- };
-
- const facilitySearchParams = {
- limit: 50,
- offset: 0,
- tenantId: tenantId,
- };
-
- const searchedFacilities = [];
- let searchAgain = true;
-
- while (searchAgain) {
- const response = await getFacilities(facilitySearchParams, facilitySearchBody);
- if (response) {
- searchAgain = response.length >= 50;
- searchedFacilities.push(...response);
- facilitySearchParams.offset += 50;
- } else searchAgain = false;
- }
-
- return searchedFacilities;
-}
-
-const addFacilitySheet = (xlsxData, mapping, facilities, schema, t) => {
- if (!mapping) return xlsxData;
- // Create header row
- const headers = Object.keys(mapping);
-
- // Create data rows
- const dataRow = [];
- for (const facility of facilities) {
- facility.isPermanent = facility.isPermanent ? t("PERMAENENT") : t("TEMPORARY");
- dataRow.push(headers.map((header) => facility[mapping[header]]));
- }
- headers.push(commonColumn);
- const additionalCols = [];
- if (schema?.schema?.Properties) {
- const properties = Object.keys(schema.schema.Properties);
- for (const col of properties) {
- if (!headers.includes(col)) {
- additionalCols.push(col);
- }
- }
- }
- headers.push(...additionalCols);
- // Combine headers and data rows
- const arrayOfArrays = [headers.map((item) => generateLocalisationKeyForSchemaProperties(item)), ...dataRow];
-
- const facilitySheet = {
- sheetName: FACILITY_DATA_SHEET,
- data: arrayOfArrays,
- };
- const updatedXlsxData = [facilitySheet, ...xlsxData];
- return updatedXlsxData;
-};
-
-const addReadMeSheet = (xlsxData, readMeData, readMeSheetName) => {
- if (!readMeSheetName) return xlsxData;
- const data = readMeData.reduce((acc, item) => {
- if (item?.header) {
- acc.push([item.header], ...(item.points || []).map((item) => [item]), [], [], [], []);
- }
- return acc;
- }, []);
-
- const readMeSheet = {
- sheetName: readMeSheetName,
- data: [["MICROPLAN_TEMPLATE_README_MAIN_HEADER"], [], [], [], ...data],
- };
- xlsxData.unshift(readMeSheet);
- return xlsxData;
-};
-
-/**
- * @param {Object} options
- * @param {boolean} options.hierarchyLevelWiseSheets
- * @param {string} options.hierarchyLevelName
- * @param {boolean} options.addFacilityData
- * @param {Object} options.schema
- * @param {Object[]} options.boundaries
- * @param {string} options.tenantId
- * @param {string} options.hierarchyType
- * @param {Object} options.readMeData
- * @param {string} options.readMeSheetName
- * @param {string} options.t // Assuming t is some context or translation object
- */
-export const createTemplate = async ({
- hierarchyLevelWiseSheets = true,
- hierarchyLevelName,
- addFacilityData = false,
- schema,
- boundaries,
- tenantId,
- hierarchyType,
- readMeData,
- readMeSheetName,
- t,
-}) => {
- // Fetch or retrieve boundary data
- const filteredBoundaries = await fetchFilteredBoundaries(boundaries, tenantId, hierarchyType);
-
- // Initialize xlsxData array
- let xlsxData = [];
-
- // Add boundary data to xlsxData
- xlsxData = addBoundaryData(xlsxData, filteredBoundaries, hierarchyType);
-
- // Handle hierarchy level sheets
- if (hierarchyLevelWiseSheets) {
- xlsxData = devideXlsxDataHierarchyLevelWise(xlsxData, hierarchyLevelName);
- }
-
- // Handle facility data addition
- if (addFacilityData) {
- xlsxData = await addFacilityDataToSheets(xlsxData, schema, tenantId, t);
- } else {
- // If no facility data, add schema data directly
- xlsxData = addSchemaData(xlsxData, schema);
- }
-
- // Add readme sheet data if provided
- xlsxData = addReadMeSheet(xlsxData, readMeData, readMeSheetName);
-
- return xlsxData;
-};
-
-// Function to fetch filtered boundaries
-const fetchFilteredBoundaries = async (boundaries, tenantId, hierarchyType) => {
- const rootBoundary = boundaries?.find((boundary) => boundary.isRoot);
- const sessionData = Digit.SessionStorage.get("microplanHelperData") || {};
- let boundaryData = sessionData.filteredBoundaries;
-
- if (!boundaryData) {
- boundaryData = await fetchBoundaryData(tenantId, hierarchyType, rootBoundary?.code);
- const filteredBoundaries = await filterBoundaries(boundaryData, boundaries);
- Digit.SessionStorage.set("microplanHelperData", {
- ...sessionData,
- filteredBoundaries: filteredBoundaries,
- });
- return filteredBoundaries;
- }
- return boundaryData;
-};
-
-// Function to add facility data to sheets
-const addFacilityDataToSheets = async (xlsxData, schema, tenantId, t) => {
- const facilities = await getAllFacilities(tenantId);
- if (schema?.template?.facilitySchemaApiMapping) {
- return addFacilitySheet(xlsxData, schema.template.facilitySchemaApiMapping, facilities, schema, t);
- }
- // If no specific facility schema mapping, add default facility data
- const facilitySheet = {
- sheetName: FACILITY_DATA_SHEET,
- data: [],
- };
- return addSchemaData([facilitySheet], schema);
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/excelUtils.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/excelUtils.js
deleted file mode 100644
index b50b2ad48a6..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/excelUtils.js
+++ /dev/null
@@ -1,150 +0,0 @@
-import { SHEET_PASSWORD, UNPROTECT_TILL_ROW } from "../configs/constants";
-
-export function updateFontNameToRoboto(worksheet) {
- worksheet.eachRow({ includeEmpty: true }, (row) => {
- row.eachCell({ includeEmpty: true }, (cell) => {
- // Preserve existing font properties
- const existingFont = cell.font || {};
-
- // Update only the font name to Roboto
- cell.font = {
- ...existingFont, // Spread existing properties
- name: "Roboto", // Update the font name
- };
- });
- });
-}
-
-export const freezeWorkbookValues = async (workbook) => {
- workbook.eachSheet((worksheet) => {
- worksheet.eachRow((row) => {
- row.eachCell((cell) => {
- // Lock each cell
- cell.protection = {
- locked: true,
- };
- });
- });
- // Protect the worksheet
- worksheet.protect(SHEET_PASSWORD, {
- selectLockedCells: true,
- selectUnlockedCells: true,
- });
- });
-
- return workbook;
-};
-
-export const unfreezeColumnsByHeader = async (workbook, headers) => {
- workbook.eachSheet((worksheet) => {
- const headerRow = worksheet.getRow(1); // Assuming headers are in the first row
- const columnsToUnfreeze = [];
-
- headerRow.eachCell((cell, colNumber) => {
- if (headers.includes(cell.value)) {
- columnsToUnfreeze.push(colNumber);
- }
- });
-
- worksheet.eachRow((row, rowNumber) => {
- if (rowNumber === 1) return;
- columnsToUnfreeze.forEach((colNumber) => {
- const cell = row.getCell(colNumber);
- cell.protection = {
- locked: false,
- };
- });
- });
-
- // Re-protect the worksheet after modifying cell protection
- worksheet.protect(SHEET_PASSWORD, {
- selectLockedCells: true,
- selectUnlockedCells: true,
- });
- });
-
- return workbook;
-};
-
-export const freezeSheetValues = async (workbook, sheetName) => {
- const worksheet = workbook.getWorksheet(sheetName);
- if (worksheet) {
- worksheet.eachRow((row) => {
- row.eachCell((cell) => {
- // Lock each cell
- cell.protection = {
- locked: true,
- };
- });
- });
- // Protect the worksheet
- worksheet.protect(SHEET_PASSWORD, {
- selectLockedCells: true,
- selectUnlockedCells: true,
- });
- }
-
- return workbook;
-};
-
-export const freezeCellsWithData = async (workbook, sheetName) => {
- const worksheet = workbook.getWorksheet(sheetName);
- if (worksheet) {
- worksheet.eachRow((row) => {
- row.eachCell((cell) => {
- if (cell.value) {
- // Check if the cell has data
- cell.protection = {
- locked: true,
- };
- } else {
- cell.protection = {
- locked: false,
- };
- }
- });
- });
- // Protect the worksheet
- worksheet.protect(SHEET_PASSWORD, {
- selectLockedCells: true,
- selectUnlockedCells: true,
- });
- }
-
- return workbook;
-};
-export const performUnfreezeCells = async (workbook, sheetName) => {
- const sheet = workbook.getWorksheet(sheetName);
-
- let lastFilledColumn = 1;
- sheet.getRow(1).eachCell((cell, colNumber) => {
- if (cell.value !== undefined && cell.value !== null && cell.value !== "") {
- lastFilledColumn = colNumber;
- }
- });
-
- for (let row = 1; row <= parseInt(UNPROTECT_TILL_ROW); row++) {
- for (let col = 1; col <= lastFilledColumn; col++) {
- const cell = sheet.getCell(row, col);
- if (!cell.value && cell.value !== 0) {
- cell.protection = { locked: false };
- }
- }
- }
- sheet.protect(SHEET_PASSWORD, { selectLockedCells: true, selectUnlockedCells: true });
-};
-
-export const hideUniqueIdentifierColumn = async (workbook, sheetName, column) => {
- const sheet = workbook.getWorksheet(sheetName);
- for (const item of column) {
- let colIndex;
- sheet.getRow(1).eachCell((cell, colNumber) => {
- if (cell.value === item) {
- colIndex = colNumber;
- }
- });
- if (column && sheet.getColumn(colIndex)) {
- sheet.getColumn(colIndex).hidden = true;
- }
- }
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/excelValidations.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/excelValidations.js
deleted file mode 100644
index 0d2a344a8f1..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/excelValidations.js
+++ /dev/null
@@ -1,199 +0,0 @@
-import Ajv from "ajv";
-const ajv = new Ajv({ allErrors: true });
-ajv.addKeyword("isRequired");
-ajv.addKeyword("isLocationDataColumns");
-ajv.addKeyword("isRuleConfigureInputs");
-ajv.addKeyword("isFilterPropertyOfMapSection");
-ajv.addKeyword("isVisualizationPropertyOfMapSection");
-ajv.addKeyword("toShowInMicroplanPreview");
-
-// Function responsible for excel data validation with respect to the template/schema provided
-const translateSchema = (schemaData) => {
- const required = Object.entries(schemaData?.Properties || {}).reduce((acc, [key, value]) => {
- if (value?.isRequired) {
- acc.push(key);
- }
- return acc;
- }, []);
-
- return { required, properties: schemaData.Properties };
-};
-
-const createSchema = (properties, required) => {
- return {
- type: "object",
- patternProperties: {
- ".*": {
- type: "array",
- items: {
- type: "object",
- properties: properties,
- required: required,
- additionalProperties: true,
- },
- },
- },
- minProperties: 1,
- additionalProperties: false,
- };
-};
-
-const extractLocationDataColumns = (schemaData) => {
- return Object.entries(schemaData?.Properties || {}).reduce((acc, [key, value]) => {
- if (value?.isLocationDataColumns) {
- acc.push(key);
- }
- return acc;
- }, []);
-};
-
-const setNestedError = (errors, path, error) => {
- if (!path.length) return;
-
- let current = errors;
- for (let i = 0; i < path.length - 1; i++) {
- if (!current[path[i]]) {
- current[path[i]] = {};
- }
- current = current[path[i]];
- }
-
- if (!current[path[path.length - 1]]) {
- current[path[path.length - 1]] = [];
- }
-
- current[path[path.length - 1]] = [...new Set([...current[path[path.length - 1]], error])];
-};
-
-const formatErrors = (validateExcelErrors, locationDataColumns, t) => {
- const errors = {};
- let hasDataErrors = "false"; // true, false, missing_properties, unknown
- const missingColumnsList = new Set();
- let errorMessages = {};
-
- validateExcelErrors.forEach((error) => {
- let tempErrorStore = "";
- let instancePathTypeGlobal;
-
- switch (error.keyword) {
- case "additionalProperties":
- tempErrorStore = "ERROR_ADDITIONAL_PROPERTIES";
- hasDataErrors = "true";
- break;
- case "type":
- {
- const instancePathType = error.instancePath.split("/");
- const neededType = error.params?.type;
- instancePathTypeGlobal = instancePathType;
- tempErrorStore = locationDataColumns.includes(instancePathType[instancePathType.length - 1])
- ? "ERROR_INCORRECT_LOCATION_COORDINATES"
- : neededType === "number"
- ? "ERROR_MUST_BE_A_NUMBER"
- : "ERROR_MUST_BE_A_STRING";
- hasDataErrors = "true";
- }
- break;
- case "required":
- {
- const missing = error.params.missingProperty;
- const instancePathType = error.instancePath.split("/");
- instancePathTypeGlobal = [...instancePathType, missing];
- tempErrorStore = "ERROR_MANDATORY_FIELDS_CANT_BE_EMPTY";
- missingColumnsList.add(missing);
- hasDataErrors = "true";
- }
- break;
- case "maximum":
- case "minimum":
- {
- const instancePathMinMax = error.instancePath.split("/");
- instancePathTypeGlobal = instancePathMinMax;
- tempErrorStore = locationDataColumns.includes(instancePathMinMax[instancePathTypeGlobal.length - 1])
- ? "ERROR_INCORRECT_LOCATION_COORDINATES"
- : "ERROR_DATA_EXCEEDS_LIMIT_CONSTRAINTS";
- hasDataErrors = "true";
- }
- break;
- case "pattern":
- tempErrorStore = "ERROR_VALUE_NOT_ALLOWED";
- hasDataErrors = "true";
- break;
- case "minProperties":
- hasDataErrors = "minProperties";
- break;
- case "enum":
- {
- const instancePathType = error.instancePath.split("/");
- instancePathTypeGlobal = instancePathType;
- tempErrorStore = {
- error: "ERROR_UPLOAD_DATA_ENUM",
- values: { allowedValues: error.params?.allowedValues?.map((item) => t(item)).join(", ") },
- };
- hasDataErrors = "true";
- }
- break;
- default:
- hasDataErrors = "unknown";
- }
-
- if (tempErrorStore && instancePathTypeGlobal) {
- setNestedError(errors, instancePathTypeGlobal.slice(1, 4), tempErrorStore);
- }
-
- switch (hasDataErrors) {
- case "true":
- errorMessages = { dataError: "ERROR_REFER_UPLOAD_PREVIEW_TO_SEE_THE_ERRORS" };
- break;
- case "minProperties":
- errorMessages = { minProperties: "ERROR_UPLOADED_DATA_IS_EMPTY" };
- break;
- case "unknown":
- errorMessages = { unknown: "ERROR_UNKNOWN" };
- break;
- case "false":
- break;
- }
- });
-
- return {
- valid: !hasDataErrors,
- message: errorMessages ? [...new Set(Object.values(errorMessages))] : [],
- errors,
- missingColumnsList,
- };
-};
-
-export const excelValidations = (data, schemaData, t) => {
- const { required, properties } = translateSchema(schemaData);
- const schema = createSchema(properties, required);
- const validateExcel = ajv.compile(schema);
- const valid = validateExcel(data);
- const locationDataColumns = extractLocationDataColumns(schemaData);
-
- if (!valid) {
- const validationResult = formatErrors(validateExcel.errors, locationDataColumns, t);
- ajv.removeSchema();
- return validationResult;
- }
-
- ajv.removeSchema();
- return { valid };
-};
-
-export const checkForErrorInUploadedFileExcel = async (fileInJson, schemaData, t) => {
- try {
- const valid = excelValidations(fileInJson, schemaData, t);
- if (valid.valid) {
- return { valid: true };
- }
- return {
- valid: false,
- message: valid.message,
- errors: valid.errors,
- missingProperties: valid.missingColumnsList,
- };
- } catch (error) {
- console.error("Error in excel validations: ", error?.message);
- return { valid: false, message: ["ERROR_PARSING_FILE"] };
- }
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/exceltojson.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/exceltojson.js
deleted file mode 100644
index f2d4f277ba6..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/exceltojson.js
+++ /dev/null
@@ -1,99 +0,0 @@
-import ExcelJS from "exceljs";
-
-// input is a xlsx blob
-// options {header}
-// header: true -> have seperate header so data will be in key: value pair
-export const parseXlsxToJsonMultipleSheets = async (file, options = {}) => {
- return new Promise((resolve, reject) => {
- const reader = new FileReader();
-
- reader.onload = async (event) => {
- try {
- const arrayBuffer = event.target.result;
- const workbook = await loadWorkbook(arrayBuffer);
- const jsonData = processWorkbook(workbook, options);
- resolve(jsonData);
- } catch (error) {
- console.error(error);
- resolve({ error: true });
- }
- };
-
- reader.onerror = (error) => {
- console.error(error);
- resolve({ error: true, details: error });
- };
-
- reader.readAsArrayBuffer(file);
- });
-};
-
-const loadWorkbook = async (arrayBuffer) => {
- const workbook = new ExcelJS.Workbook();
- await workbook.xlsx.load(arrayBuffer);
- return workbook;
-};
-
-const processWorkbook = (workbook, options) => {
- const jsonData = {};
- workbook.eachSheet((worksheet) => {
- const jsonSheetData = processSheet(worksheet, options);
- if (jsonSheetData.length !== 0 && jsonSheetData?.[0].length !== 0) {
- jsonData[worksheet.name] = jsonSheetData;
- }
- });
- return jsonData;
-};
-
-const processSheet = (worksheet, options) => {
- const jsonSheetData = [];
- let headers = [];
-
- worksheet.eachRow({ includeEmpty: true }, (row, rowNumber) => {
- const rowData = cleanRowData(row.values);
- if (options.header && rowNumber === 1) {
- headers = rowData;
- } else if (options.header && headers.length > 0) {
- jsonSheetData.push(mapRowToHeaders(rowData, headers));
- } else {
- jsonSheetData.push(rowData);
- }
- });
-
- removeTrailingEmptyRows(jsonSheetData);
- return jsonSheetData;
-};
-
-const cleanRowData = (rowData) => {
- return rowData.slice(1).map((cell) => (typeof cell === "string" ? cell.trim() : cell));
-};
-
-const mapRowToHeaders = (rowData, headers) => {
- const rowObject = {};
- headers.forEach((header, index) => {
- rowObject[header] = rowData[index];
- });
- return rowObject;
-};
-
-const removeTrailingEmptyRows = (data) => {
- while (data.length > 0) {
- const lastRow = data[data.length - 1];
- const isEmptyRow = checkIfRowIsEmpty(lastRow);
- if (isEmptyRow) {
- data.pop();
- } else {
- break;
- }
- }
-};
-
-const checkIfRowIsEmpty = (row) => {
- if (Array.isArray(row)) {
- return row.filter((item) => item !== "").length === 0;
- }
- if (typeof row === "object" && row !== null) {
- return Object.values(row).filter((item) => item !== "").length === 0;
- }
- return false;
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/geojsonValidations.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/geojsonValidations.js
deleted file mode 100644
index 42a465740b5..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/geojsonValidations.js
+++ /dev/null
@@ -1,234 +0,0 @@
-import gjv from "geojson-validation";
-import Ajv from "ajv";
-const ajv = new Ajv({ allErrors: true });
-ajv.addKeyword("isRequired");
-ajv.addKeyword("isLocationDataColumns");
-ajv.addKeyword("isRuleConfigureInputs");
-ajv.addKeyword("isFilterPropertyOfMapSection");
-ajv.addKeyword("isVisualizationPropertyOfMapSection");
-ajv.addKeyword("toShowInMicroplanPreview");
-
-//the postion must be valid point on the earth, x between -180 and 180
-gjv.define("Position", (position) => {
- let errors = [];
- if (position[0] < -180 || position[0] > 180) {
- errors.push("Location Coordinates Error: the x must be between -180 and 180");
- }
- if (position[1] < -90 || position[1] > 90) {
- errors.push("Location Coordinates Error: the y must be between -90 and 90");
- }
- return errors;
-});
-
-// Main functino for geojson validation that includes structural and property validations
-export const geojsonValidations = (data, schemaData, t) => {
- const valid = geojsonStructureValidation(data);
- return valid.valid ? { valid: true } : { valid: false, message: valid.message || ["ERROR_INVALID_GEOJSON"] };
-};
-
-// Funciton responsible for structural verification of geojson data
-export const geojsonStructureValidation = (data) => {
- let valid = true;
- const trace = {};
- for (let i = 0; i < data["features"].length; i++) {
- const check = gjv.valid(data["features"][i]);
- valid = valid && check;
- const errors = gjv.isFeature(data["features"][i], true);
- // check if the location coordinates are according to the provided guidlines
- if (errors.some((str) => str.includes("Location Coordinates Error:"))) return { valid: false, message: ["ERROR_INCORRECT_LOCATION_COORDINATES"] };
- if (!check) trace[i] = [errors];
- // let error;
- // Object.keys(data["features"][i]["properties"]).forEach((j) => {
- // if (j.length > 10) error = { valid: false, trace, message: ["ERROR_FIELD_NAME"] };
- // return j;
- // });
- // if (error) return error;
- }
- return { valid, trace };
-};
-
-const geometryValidation = (data) => {
- let firstType;
- for (const feature of data.features) {
- if (!feature.geometry || !feature.geometry.type) {
- return false; // Missing geometry or geometry type
- }
- if (!firstType) {
- firstType = feature.geometry.type;
- } else {
- // Check if the current geometry type matches the first one
- if (feature.geometry.type !== firstType) {
- return false; // Different geometry types found
- }
- }
- }
- return true;
-};
-
-// Function responsible for property verification of geojson data
-export const geojsonPropertiesValidation = (data, schemaData, name, t) => {
- const translate = () => {
- const required = Object.entries(schemaData?.Properties || {}).reduce((acc, [key, value]) => {
- if (value?.isRequired) {
- acc.push(key);
- }
- return acc;
- }, []);
-
- // const properties = prepareProperties(schemaData.Properties, t);
- return { required, properties: schemaData.Properties };
- };
- const { required, properties } = translate();
- const schema = {
- type: "object",
- properties: {
- type: { const: "FeatureCollection" },
- },
- patternProperties: {
- "^features$": {
- type: "array",
- items: {
- type: "object",
- patternProperties: {
- "^properties$": {
- type: "object",
- patternProperties: properties,
- required: required,
- additionalProperties: true,
- },
- },
- },
- },
- },
- additionalProperties: true,
- };
- const validateGeojson = ajv.compile(schema);
- const valid = validateGeojson(data);
- const errors = {};
- let hasDataErrors = "false"; // true, false, missing_properties, unknown
- const missingColumnsList = new Set();
- let errorMessages = [];
- if (!valid) {
- for (let i = 0; i < validateGeojson.errors.length; i++) {
- let tempErrorStore = "";
- let instancePathTypeGlobal = validateGeojson.errors[i].instancePath.split("/");
- switch (validateGeojson.errors[i].keyword) {
- case "additionalProperties": {
- tempErrorStore = "ERROR_ADDITIONAL_PROPERTIES";
- hasDataErrors = "true";
- break;
- }
- case "type":
- {
- const instancePathType = validateGeojson.errors[i].instancePath.split("/");
- const neededType = validateGeojson.errors[i].params?.type;
- instancePathTypeGlobal = instancePathType;
- tempErrorStore = neededType === "number" ? "ERROR_MUST_BE_A_NUMBER" : "ERROR_MUST_BE_A_STRING";
- hasDataErrors = "true";
- }
- break;
- case "const": {
- if (validateGeojson.errors[i].params.allowedValue === "FeatureCollection") tempErrorStore = "ERROR_FEATURECOLLECTION";
- hasDataErrors = "true";
- break;
- }
- case "required": {
- const missing = validateGeojson.errors[i].params.missingProperty;
- const instancePathType = validateGeojson.errors[i].instancePath.split("/");
- instancePathTypeGlobal = [...instancePathType, missing];
- tempErrorStore = "ERROR_MANDATORY_FIELDS_CANT_BE_EMPTY";
- missingColumnsList.add(missing);
- // hasDataErrors = "missing_properties";
- hasDataErrors = "true";
- break;
- }
- case "pattern":
- tempErrorStore = "ERROR_VALUE_NOT_ALLOWED";
- hasDataErrors = "true";
- break;
- case "minProperties": {
- hasDataErrors = "minProperties";
- break;
- }
- case "enum": {
- const instancePathType = validateGeojson.errors[i].instancePath.split("/");
- instancePathTypeGlobal = instancePathType;
- tempErrorStore = {
- error: "ERROR_UPLOAD_DATA_ENUM",
- values: { allowedValues: validateGeojson.errors[i]?.params?.allowedValues?.map((item) => t(item)).join(", ") },
- };
- hasDataErrors = "true";
- break;
- }
- default:
- hasDataErrors = "unknown";
- break;
- }
- if (tempErrorStore)
- errors[name] = {
- ...(errors[name] ? errors[name] : {}),
- [instancePathTypeGlobal[2]]: {
- ...(errors?.[name]?.[instancePathTypeGlobal[2]] ? errors?.[name]?.[instancePathTypeGlobal[2]] : {}),
- [instancePathTypeGlobal[4]]: [
- ...new Set(
- ...(errors?.[name]?.[instancePathTypeGlobal[2]]?.[instancePathTypeGlobal[4]]
- ? errors?.[name]?.[instancePathTypeGlobal[2]]?.[instancePathTypeGlobal[4]]
- : [])
- ),
- tempErrorStore,
- ],
- },
- };
-
- switch (hasDataErrors) {
- case "true":
- errorMessages = { ...errorMessages, dataError: t("ERROR_REFER_UPLOAD_PREVIEW_TO_SEE_THE_ERRORS") };
- break;
- case "unknown":
- errorMessages = { ...errorMessages, unkown: t("ERROR_UNKNOWN") };
- break;
- case "missing_properties":
- errorMessages = {
- ...errorMessages,
- missingProperty: t("ERROR_MISSING_PROPERTY", { properties: [...missingColumnsList].map((item) => t(item)).join(", ") }),
- };
- break;
- case "false":
- break;
- }
- }
-
- ajv.removeSchema();
- return {
- valid: !hasDataErrors,
- message: errorMessages ? [...new Set(Object.values(errorMessages))] : [],
- errors,
- validationError: validateGeojson.errors,
- };
- }
- ajv.removeSchema();
- if (!geometryValidation(data)) return { valid: false, message: t("ERROR_MULTIPLE_GEOMETRY_TYPES") };
- return { valid: true };
-};
-
-////////////////////////////
-// // Might be needed
-// function filterOutWordAndLocalise(inputString, operation) {
-// // Define a regular expression to match the string parts
-// var regex = /(\w+)/g; // Matches one or more word characters
-
-// // Replace each match using the provided function
-// var replacedString = inputString.replace(regex, function (match) {
-// // Apply the function to each matched string part
-// return operation(match);
-// });
-
-// return replacedString;
-// }
-// const prepareProperties = (properties, t) => {
-// let newProperties = {};
-// Object.keys(properties).forEach((item) => (newProperties[filterOutWordAndLocalise(item, t)] = properties[item]));
-// return newProperties;
-// };
-
-////////////////////////////
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/index.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/index.js
deleted file mode 100644
index 0d21a93ca46..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/index.js
+++ /dev/null
@@ -1,478 +0,0 @@
-import _ from "lodash";
-import { findChildren, findParent } from "../utils/processHierarchyAndData";
-import { EXCEL, LOCALITY, commonColumn } from "../configs/constants";
-
-const formatDates = (value, type) => {
- let newValue = value;
- if (type !== "EPOC" && (!newValue || Number.isNaN(Number(newValue)))) {
- newValue = new Date();
- }
- switch (type) {
- case "date":
- return new Date(newValue)?.toISOString?.()?.split?.("T")?.[0];
- case "datetime":
- return new Date(newValue).toISOString();
- case "EPOC":
- return String(new Date(newValue)?.getTime());
- }
-};
-
-// get schema for validation
-const getSchema = (campaignType, type, section, schemas) => {
- if (!campaignType || !type || !section || !schemas) return {};
- return schemas.find((schema) => {
- if (!schema.campaignType) {
- return schema.type === type && schema.section === section;
- }
- return schema.campaignType === campaignType && schema.type === type && schema.section === section;
- });
-};
-
-// Sorting 2 lists, The first list is a list of string and second one is list of Objects
-const sortSecondListBasedOnFirstListOrder = (firstList, secondList) => {
- if (!firstList) return [];
- // Create a map to store the indices of elements in the first list
- const indexMap = {};
- firstList.forEach((value, index) => {
- indexMap[value] = index;
- });
-
- // Sort the second list based on the order of elements in the first list
- secondList.sort((objecta, objectb) => {
- // Get the mappedTo values of each object
- const mappedToA = objecta.mappedTo;
- const mappedToB = objectb.mappedTo;
-
- // Get the indices of mappedTo values in the first list
- const indexA = indexMap[mappedToA];
- const indexB = indexMap[mappedToB];
-
- // Compare the indices
- return indexA - indexB;
- });
-
- return secondList;
-};
-
-const computeGeojsonWithMappedProperties = ({ campaignType, fileType, templateIdentifier, validationSchemas }) => {
- const schemaData = getSchema(campaignType, fileType, templateIdentifier, validationSchemas);
- let schemaKeys;
- if (schemaData?.schema?.["Properties"]) schemaKeys = hierarchy.concat(Object.keys(schemaData.schema["Properties"]));
- // Sorting the resourceMapping list inorder to maintain the column sequence
- const sortedSecondList = sortSecondListBasedOnFirstListOrder(schemaKeys, resourceMapping);
- // Creating a object with input data with MDMS keys
- const newFeatures = fileData.data["features"].map((item) => {
- const newProperties = sortedSecondList.reduce(
- (acc, e) => ({
- ...acc,
- [e["mappedTo"]]: item["properties"][e["mappedFrom"]],
- }),
- {}
- );
- item["properties"] = newProperties;
- return item;
- });
- const data = fileData.data;
- data["features"] = newFeatures;
- return data;
-};
-
-const destroySessionHelper = (currentPath, pathList, sessionName) => {
- if (!pathList.includes(currentPath)) {
- sessionStorage.removeItem(`Digit.${sessionName}`);
- }
-};
-
-const convertGeojsonToExcelSingleSheet = (InputData, fileName) => {
- if (!InputData || !Array.isArray(InputData) || InputData.length === 0) {
- return null;
- }
-
- // Extract keys from the first feature's properties
- const keys = Object.keys(InputData?.[0]?.properties);
-
- if (!keys || keys.length === 0) {
- return null;
- }
-
- // Extract corresponding values for each feature
- const values = InputData?.map((feature) => {
- return keys.map((key) => feature.properties[key]);
- });
-
- // Group keys and values into the desired format
- return { [fileName]: [keys, ...values] };
-};
-
-const areObjectsEqual = (obj1, obj2) => {
- return obj1.name === obj2.name && obj1.code === obj2.code;
-};
-
-const computeDifferences = (data1, data2) => {
- const removed = {};
- const added = {};
-
- for (const key in data1) {
- if (Object.hasOwn(data2, key)) {
- removed[key] = data1[key].filter((item1) => !data2[key].some((item2) => areObjectsEqual(item1, item2)));
- added[key] = data2[key].filter((item2) => !data1[key].some((item1) => areObjectsEqual(item1, item2)));
- } else {
- removed[key] = data1[key];
- added[key] = [];
- }
- }
-
- for (const key in data2) {
- if (!data1.hasOwnProperty(key)) {
- added[key] = data2[key];
- removed[key] = [];
- }
- }
-
- return { removed, added };
-};
-
-const extractNames = (data) => {
- return Object.values(data)
- .flatMap((items) => items)
- .filter((item) => item.name)
- .map((item) => item.name);
-};
-// function that handles dropdown selection. used in: mapping and microplan preview
-const handleSelection = (e, boundaryType, boundarySelections, hierarchy, setBoundarySelections, boundaryData, setIsLoading) => {
- setIsLoading(true);
- if (!e || !boundaryType) return;
- const selections = e.map((item) => item?.[1]);
- const newComputedSelection = { ...boundarySelections, [boundaryType]: selections };
- const { removed, added } = computeDifferences(boundarySelections, newComputedSelection);
- // for(const item in removed){
- if (removed && Object.keys(removed).length !== 0 && Object.values(removed)?.flatMap((item) => item).length !== 0) {
- const filteredRemoved = extractNames(removed);
- const children = Object.values(findChildren(filteredRemoved, Object.values(boundaryData)?.[0]?.hierarchicalData))?.map((item) => item?.name);
- for (const key in newComputedSelection) {
- newComputedSelection[key] = newComputedSelection[key].filter((item) => !children.includes(item?.name));
- }
- }
- setBoundarySelections(newComputedSelection);
-};
-
-// Preventing default action when we scroll on input[number] is that it increments or decrements the number
-const inputScrollPrevention = (e) => {
- e.target.addEventListener("wheel", (e) => e.preventDefault(), { passive: false });
-};
-
-const mapDataForApi = (data, Operators, microplanName, campaignId, status, reqType = "update") => {
- const files = extractFiles(data, reqType);
- const resourceMapping = extractResourceMapping(data, reqType);
- const assumptions = extractAssumptions(data, reqType);
- const operations = extractOperations(data, Operators, reqType);
-
- return createApiRequestBody(status, microplanName, campaignId, files, assumptions, operations, resourceMapping);
-};
-
-const extractFiles = (data, reqType) => {
- const files = [];
- if (data && data.upload) {
- Object.values(data.upload).forEach((item) => {
- if (isValidFile(item, reqType)) {
- files.push(mapFile(item));
- }
- });
- }
- return files;
-};
-
-const isValidFile = (item, reqType) => {
- if (!item || item.error || !item.filestoreId) return false;
- if (reqType === "create" && !item.active) return false;
- return true;
-};
-
-const mapFile = (item) => ({
- active: item.active,
- filestoreId: item.filestoreId,
- inputFileType: item.fileType,
- templateIdentifier: item.section,
- id: item.fileId,
-});
-
-const extractResourceMapping = (data, reqType) => {
- let resourceMapping = [];
- if (data && data.upload) {
- Object.values(data.upload).forEach((item) => {
- if (isValidResourceMapping(item, reqType)) {
- resourceMapping.push(item.resourceMapping);
- }
- });
- resourceMapping = resourceMapping.flat();
- }
- return resourceMapping;
-};
-
-const isValidResourceMapping = (item, reqType) => {
- if (reqType === "create" && item.resourceMapping && item.resourceMapping.every((i) => i.active === false)) return false;
- if (!item || !item.resourceMapping || item.error || !Array.isArray(item.resourceMapping)) return false;
- if (!item.resourceMapping.every((i) => i.mappedFrom && i.mappedTo)) return false;
- return true;
-};
-
-const extractAssumptions = (data, reqType) => {
- if (!data || !data.hypothesis) return [];
- return data.hypothesis.reduce((acc, item) => {
- if (isValidAssumption(item, reqType)) {
- acc.push({ ...item });
- }
- return acc;
- }, []);
-};
-
-const isValidAssumption = (item, reqType) => {
- if (reqType === "create" && !item.active) return false;
- if (!item.key || !item.value) return false;
- return true;
-};
-
-const extractOperations = (data, Operators, reqType) => {
- if (!data || !data.ruleEngine) return [];
- return data.ruleEngine.reduce((acc, item) => {
- if (isValidOperation(item, reqType)) {
- acc.push(mapOperation(item, Operators));
- }
- return acc;
- }, []);
-};
-
-const isValidOperation = (item, reqType) => {
- if (reqType === "create" && !item.active) return false;
- if (!item.active && !item.input) return true;
- if (!item.active && !item.operator && !item.output && !item.input && !item.assumptionValue) return false;
- return true;
-};
-
-const mapOperation = (item, Operators) => {
- const data = { ...item };
- const operator = Operators.find((e) => e.name === data.operator);
- if (operator && operator.code) data.operator = operator.code;
- if (data.oldInput) data.input = data.oldInput;
- return data;
-};
-
-const createApiRequestBody = (status, microplanName, campaignId, files, assumptions, operations, resourceMapping) => ({
- PlanConfiguration: {
- status,
- tenantId: Digit.ULBService.getStateId(),
- name: microplanName,
- executionPlanId: campaignId,
- files,
- assumptions,
- operations,
- resourceMapping,
- },
-});
-
-const addResourcesToFilteredDataToShow = (previewData, resources, hypothesisAssumptionsList, formulaConfiguration, userEditedResources, t) => {
- // Clone the preview data to avoid mutating the original data
- const data = _.cloneDeep(previewData);
-
- // Helper function to check for user-edited data
- const checkUserEditedData = (commonColumnData, resourceName) => {
- if (userEditedResources && userEditedResources[commonColumnData]) {
- return userEditedResources[commonColumnData][resourceName];
- }
- };
-
- // Ensure the previewData has at least one row and the first row is an array
- if (!Array.isArray(data) || !Array.isArray(data[0])) {
- return [];
- }
-
- // Identify the index of the common column
- const conmmonColumnIndex = data[0].indexOf(commonColumn);
- if (conmmonColumnIndex === -1) {
- return [];
- }
-
- // Ensure resources is a valid array
- if (!Array.isArray(resources)) {
- return data;
- }
-
- // Process each row of the data
- const combinedData = data.map((item, index) => {
- if (!Array.isArray(item)) {
- return item;
- }
-
- if (index === 0) {
- // Add resource names to the header row
- resources.forEach((e) => item.push(e));
- return item;
- }
-
- // Process each resource for the current row
- resources.forEach((resourceName, resourceIndex) => {
- let savedData = checkUserEditedData(item[conmmonColumnIndex], resourceName);
- if (savedData !== undefined) {
- item.push(savedData);
- } else {
- let calculations = calculateResource(resourceName, item, formulaConfiguration, previewData[0], hypothesisAssumptionsList, t);
- if (calculations !== null) calculations = Math.round(calculations);
- item.push(calculations !== null && calculations !== undefined ? calculations : undefined);
- }
- });
-
- return item;
- });
-
- return combinedData;
-};
-
-const calculateResource = (resourceName, rowData, formulaConfiguration, headers, hypothesisAssumptionsList, t) => {
- let formula = formulaConfiguration?.find((item) => item?.active && item?.output === resourceName);
- if (!formula) return null;
-
- // Finding Input
- // check for Uploaded Data
- const inputValue = findInputValue(formula, rowData, formulaConfiguration, headers, hypothesisAssumptionsList, t);
- if (inputValue === undefined || inputValue === null) return null;
- const assumptionValue = hypothesisAssumptionsList?.find((item) => item?.active && item?.key === formula?.assumptionValue)?.value;
- if (assumptionValue === undefined) return null;
-
- return findResult(inputValue, assumptionValue, formula?.operator);
-};
-
-// function to find input value, it calls calculateResource fucntion recurcively until it get a proper value
-const findInputValue = (formula, rowData, formulaConfiguration, headers, hypothesisAssumptionsList, t) => {
- const inputIndex = headers?.indexOf(formula?.input);
- if (inputIndex === -1 || !rowData[inputIndex]) {
- // let tempFormula = formulaConfiguration.find((item) => item?.output === formula?.input);
- return calculateResource(formula?.input, rowData, formulaConfiguration, headers, hypothesisAssumptionsList, t);
- } else return rowData[inputIndex];
-};
-
-const findResult = (inputValue, assumptionValue, operator) => {
- switch (operator) {
- case "DEVIDED_BY":
- if (assumptionValue === 0) return;
- return inputValue / assumptionValue;
- case "MULTIPLIED_BY":
- return inputValue * assumptionValue;
- case "ADDITION":
- return inputValue + assumptionValue;
- case "SUBSTRACTION":
- return inputValue - assumptionValue;
- case "RAISE_TO":
- return inputValue ** assumptionValue;
- default:
- return;
- }
-};
-
-const fetchData = (state, campaignType) => {
- let hypothesis = [];
- let rulesOutputs = [];
- let uploadList = [];
-
- hypothesis = state?.HypothesisAssumptions?.find((item) => item.campaignType === campaignType)?.assumptions;
- rulesOutputs = state?.RuleConfigureOutput?.find((item) => item.campaignType === campaignType)?.data;
- uploadList = state?.UploadConfiguration?.reduce((acc, item) => {
- if (item.required) acc.push(item.id);
- return acc;
- }, []);
- return { hypothesisList: hypothesis, rulesOutputs, uploadList };
-};
-const hypothesisCheck = (hypothesis, validList) => {
- if (hypothesis && Array.isArray(hypothesis) && hypothesis.length !== 0 && validList && Array.isArray(validList) && validList.length !== 0) {
- return hypothesis.filter((item) => item.active).every((item) => validList.includes(item.key));
- }
- return false;
-};
-const ruleOutputCheck = (rules, ruleOuputList) => {
- if (
- rules &&
- Array.isArray(rules) &&
- rules.filter((item) => item.active).length !== 0 &&
- ruleOuputList &&
- Array.isArray(ruleOuputList) &&
- ruleOuputList.length !== 0
- ) {
- return rules.filter((item) => item.active).every((item) => ruleOuputList.includes(item.output));
- }
- return false;
-};
-const emptyRuleCheck = (rules) => {
- return !rules || rules.filter((item) => item.active && Object.values(item)?.filter((e) => e === "").length !== 0).length === 0;
-};
-const ruleHypothesisCheck = (rules, ruleHypothesis) => {
- if (rules && Array.isArray(rules) && rules.length !== 0 && ruleHypothesis && Array.isArray(ruleHypothesis) && ruleHypothesis.length !== 0) {
- return rules.filter((item) => item.active).every((item) => ruleHypothesis.includes(item.assumptionValue));
- }
- return false;
-};
-const uploadCheck = (uploads, uploadList) => {
- if (uploads && Array.isArray(uploads) && uploads.length !== 0 && uploadList && Array.isArray(uploadList) && uploadList.length !== 0) {
- return uploads.some((item) => uploadList.includes(item.templateIdentifier) && item.active);
- }
- return false;
-};
-const planConfigRequestBodyValidator = (data, state, campaignType) => {
- if (!data || !campaignType || !state) return false;
-
- const { hypothesisList, rulesOutputs, uploadList } = fetchData(state, campaignType);
- let checks =
- // microplan name check
- (!data || !data.name) &&
- hypothesisCheck(data?.PlanConfiguration?.assumptions, hypothesisList) &&
- emptyRuleCheck(data?.PlanConfiguration?.operations) &&
- ruleOutputCheck(data?.PlanConfiguration?.operations, rulesOutputs) &&
- ruleHypothesisCheck(
- data?.PlanConfiguration?.operations,
- data?.PlanConfiguration?.assumptions?.filter((item) => item.active)?.map((item) => item.key)
- ) &&
- uploadCheck(data?.PlanConfiguration?.files, uploadList);
- return checks;
- // if()
-};
-
-const processDropdownForNestedMultiSelect = (dropDownOptions) => {
- if (!dropDownOptions) return dropDownOptions;
- const result = dropDownOptions.reduce((acc, item) => {
- const { parent, ...rest } = item;
-
- // Find the group by parentBoundaryType
- let group = acc.find((g) => g.name === parent?.name);
-
- // If not found, create a new group
- if (!group) {
- group = { name: parent?.name, options: [] };
- acc.push(group);
- }
-
- // Add the item to the options of the found/created group
- group.options.push(rest);
-
- return acc;
- }, []);
- return result;
-};
-
-const transformIntoLocalisationCode = (code) => {
- return code?.toUpperCase();
-};
-
-export default {
- formatDates,
- computeGeojsonWithMappedProperties,
- destroySessionHelper,
- mapDataForApi,
- inputScrollPrevention,
- handleSelection,
- convertGeojsonToExcelSingleSheet,
- sortSecondListBasedOnFirstListOrder,
- addResourcesToFilteredDataToShow,
- calculateResource,
- planConfigRequestBodyValidator,
- getSchema,
- processDropdownForNestedMultiSelect,
- transformIntoLocalisationCode,
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/jsonToExcelBlob.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/jsonToExcelBlob.js
deleted file mode 100644
index ae470038a91..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/jsonToExcelBlob.js
+++ /dev/null
@@ -1,72 +0,0 @@
-import ExcelJS from "exceljs";
-import { SHEET_COLUMN_WIDTH } from "../configs/constants";
-
-export const convertJsonToXlsx = async (jsonData, columnWithStyle, returnWorkbook = false) => {
- const workbook = new ExcelJS.Workbook();
-
- for (const [sheetName, data] of Object.entries(jsonData)) {
- const worksheet = workbook.addWorksheet(sheetName);
- populateWorksheet(worksheet, data, columnWithStyle);
- }
-
- if (returnWorkbook) return workbook;
- return await writeWorkbookToBuffer(workbook);
-};
-
-const populateWorksheet = (worksheet, data, columnWithStyle) => {
- data.forEach((row, rowIndex) => {
- const newRow = worksheet.addRow(row);
- if (columnWithStyle?.errorColumn && rowIndex > 0) {
- applyStyleToColumn(newRow, data[0], columnWithStyle);
- }
- });
-
- styleHeaderRow(worksheet);
- setColumnWidths(worksheet);
-};
-
-/**
- * Applies a specified style to a column in a given row of a spreadsheet.
- *
- * @param {Object} newRow - The row object where the style will be applied.
- * @param {Array} headerRow - The header row array containing column names.
- * @param {Object} columnWithStyle - An object containing the column name and the style to be applied.
- * @param {string} columnWithStyle.errorColumn - The name of the column where the style should be applied.
- * @param {Object} columnWithStyle.style - The style properties to be applied to the cell.
- */
-const applyStyleToColumn = (newRow, headerRow, columnWithStyle) => {
- const errorColumnIndex = headerRow.indexOf(columnWithStyle.errorColumn);
- if (errorColumnIndex !== -1) {
- const columnIndex = errorColumnIndex + 1;
- const newCell = newRow.getCell(columnIndex);
- if (columnWithStyle.style && newCell) {
- for (const key in columnWithStyle.style) {
- newCell[key] = columnWithStyle.style[key];
- }
- }
- }
-};
-
-const styleHeaderRow = (worksheet) => {
- const headerRow = worksheet.getRow(1);
- if (headerRow) {
- headerRow.font = { bold: true };
- }
-};
-
-const setColumnWidths = (worksheet) => {
- // Iterate over all rows in the worksheet
- worksheet.eachRow((worksheetRow, rowNumber) => {
- worksheetRow.eachCell((cell, colNumber) => {
- // Update column width based on the length of the cell's text
- const currentWidth = worksheet.getColumn(colNumber).width || SHEET_COLUMN_WIDTH; // Default width or current width
- const newWidth = Math.max(currentWidth, cell.value.toString().length + 2); // Add padding
- worksheet.getColumn(colNumber).width = newWidth;
- });
- });
-};
-
-export const writeWorkbookToBuffer = async (workbook) => {
- const buffer = await workbook.xlsx.writeBuffer({ compression: true });
- return new Blob([buffer], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/mappingUtils.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/mappingUtils.js
deleted file mode 100644
index f742ffd5e47..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/mappingUtils.js
+++ /dev/null
@@ -1,760 +0,0 @@
-import L from "leaflet";
-import "leaflet/dist/leaflet.css";
-import { processHierarchyAndData, findChildren, calculateAggregateForTree } from "../utils/processHierarchyAndData";
-import { EXCEL, GEOJSON, SHAPEFILE, MapChoroplethGradientColors } from "../configs/constants";
-import { PopulationSvg } from "../icons/Svg";
-import chroma from "chroma-js";
-import * as MicroplanIconCollection from "../icons/Svg";
-import * as DigitSvgs from "@egovernments/digit-ui-svg-components";
-
-const IconCollection = { ...MicroplanIconCollection, ...DigitSvgs };
-
-export const generatePreviewUrl = (baseMapUrl, center = [0, 0], zoom = 5) => {
- const lon = Math.floor(((center[1] + 180) / 360) * Math.pow(0, zoom));
- const lat = Math.floor(
- ((1 - Math.log(Math.tan((center[0] * Math.PI) / 180) + 1 / Math.cos((center[0] * Math.PI) / 180)) / Math.PI) / 2) * Math.pow(2, zoom)
- );
- if (baseMapUrl) {
- return baseMapUrl.replace("{z}", zoom).replace("{x}", lat).replace("{y}", lon);
- }
- // Return a default preview URL or handle this case as needed
- return "default-preview-url.jpg"; // todo
-};
-
-// get schema for validation
-export const getSchema = (campaignType, type, section, schemas) => {
- return schemas.find((schema) => {
- if (!schema.campaignType) {
- return schema.type === type && schema.section === section;
- }
- return schema.campaignType === campaignType && schema.type === type && schema.section === section;
- });
-};
-
-export const calculateAggregateForTreeMicroplanWrapper = (entity) => {
- if (!entity || typeof entity !== "object") return {};
- let newObject = {};
- for (let [key, value] of Object.entries(entity)) {
- if (!value?.["hierarchicalData"]) continue;
- let aggregatedTree = calculateAggregateForTree(value?.["hierarchicalData"]);
- newObject[key] = { ...value, hierarchicalData: aggregatedTree };
- }
- return newObject;
-};
-
-export const extractGeoData = (
- campaignType,
- microplanData,
- filterDataOrigin,
- validationSchemas,
- setToast,
- setDataAvailability,
- hierarchy,
- setBoundaryData,
- setFilterData,
- setFilterProperties,
- setFilterSelections,
- setFilterPropertyNames,
- state,
- setChoroplethProperties,
- setDataCompleteness,
- t
-) => {
- if (!hierarchy) return;
-
- const initializeDataAvailability = (microplanData) => (microplanData?.upload ? "initialStage" : undefined);
-
- const checkFileActivity = (fileData) => fileData.active;
-
- const checkFileSection = (fileData, filterDataOrigin) =>
- filterDataOrigin?.boundriesDataOrigin?.includes(fileData?.section) || filterDataOrigin?.layerDataOrigin?.includes(fileData?.section);
-
- const getFileValidationSchema = (campaignType, fileData, validationSchemas) =>
- getSchema(campaignType, fileData?.fileType, fileData?.section, validationSchemas);
-
- const updateDataAvailabilityCheck = (dataAvailabilityCheck, condition, partialState) =>
- condition ? partialState : dataAvailabilityCheck === "initialStage" ? "false" : partialState;
-
- const handleFileDataError = (dataAvailabilityCheck, fileData) =>
- fileData?.error ? updateDataAvailabilityCheck(dataAvailabilityCheck, true, "partial") : dataAvailabilityCheck;
-
- const addResourcesToFilteredData = (data, resources, hypothesisAssumptionsList, formulaConfiguration, microplanData, t) =>
- Digit.Utils.microplan.addResourcesToFilteredDataToShow(
- data,
- resources,
- hypothesisAssumptionsList,
- formulaConfiguration,
- microplanData?.microplanPreview?.userEditedResources || [],
- t
- );
-
- const processFileData = (
- fileData,
- schema,
- filterDataOrigin,
- virtualizationPropertiesCollector,
- filterPropertiesCollector,
- filterPropertieNameCollector,
- resources,
- hypothesisAssumptionsList,
- formulaConfiguration,
- t
- ) => {
- const properties = Object.entries(schema?.schema?.Properties || {});
- const latLngColumns = [];
- const filterProperty = [];
-
- for (const [key, value] of properties) {
- if (value?.isLocationDataColumns) latLngColumns.push(t(key));
- if (filterDataOrigin?.layerDataOrigin?.includes(fileData?.section) && value?.isFilterPropertyOfMapSection) filterProperty.push(key);
- if (value?.isVisualizationPropertyOfMapSection && filterDataOrigin?.boundriesDataOrigin?.includes(fileData?.section))
- virtualizationPropertiesCollector.add(key);
- }
-
- filterProperty.forEach((property) => filterPropertieNameCollector.add(property));
-
- return { latLngColumns, filterProperty };
- };
-
- const processExcelFile = (fileData, latLngColumns, resources, formulaConfiguration, hypothesisAssumptionsList, schema, t) => {
- let dataAvailabilityCheck = "true";
- const columnList = Object.values(fileData?.data)?.[0]?.[0];
- const check = latLngColumns.every((colName) => columnList.includes(t(colName)));
-
- if (!check) dataAvailabilityCheck = "partial";
-
- let dataWithResources = Object.values(fileData?.data);
- if (resources && formulaConfiguration && hypothesisAssumptionsList && schema?.showResourcesInMappingSection) {
- dataWithResources = dataWithResources.map((item) =>
- addResourcesToFilteredData(item, resources, hypothesisAssumptionsList, formulaConfiguration, microplanData, t)
- );
- }
-
- const hasLocationData = dataWithResources.some((item) => item.some((row) => row.includes("lat") && row.includes("long")));
-
- const convertedData = dataWithResources.map((item) =>
- item.map((row, rowIndex) => {
- if (rowIndex === 0) {
- if (row.indexOf("features") === -1) row.push("feature");
- return row;
- }
- const latIndex = item[0].findIndex((cell) => cell === "lat");
- const lonIndex = item[0].findIndex((cell) => cell === "long");
- const properties = item[0].reduce((acc, cell, index) => ({ ...acc, [cell]: row[index] }), {});
- const feature =
- latIndex !== -1 && lonIndex !== -1
- ? {
- type: "Feature",
- properties,
- geometry: {
- type: "Point",
- coordinates: [row[lonIndex], row[latIndex]],
- },
- }
- : null;
- row.push(feature);
- return row;
- })
- );
-
- return { dataAvailabilityCheck, hasLocationData, convertedData };
- };
-
- const processGeoJsonFile = (fileData, filterProperty, resources, formulaConfiguration, hypothesisAssumptionsList, t) => {
- const dataAvailabilityCheck = "true";
- const keys = [...Object.keys(fileData?.data.features[0].properties), "feature"];
- const values = fileData?.data.features.map((feature) => keys.map((key) => (key === "feature" ? feature : feature.properties[key] || null)));
-
- const dataWithResources = [[...keys, ...resources], ...values];
- const processedDataWithResources = dataWithResources.map((item, index) => {
- if (index === 0) return item;
- const newProperties = keys.reduce((acc, key, i) => (key !== "feature" ? { ...acc, [key]: item[i] } : acc), {});
- item[item.length - 1] = { ...item[item.length - 1], properties: newProperties };
- return item;
- });
-
- return { dataAvailabilityCheck, dataWithResources: processedDataWithResources };
- };
-
- const updateFilterPropertiesCollector = (fileData, filterProperty, filterPropertiesCollector) => {
- filterProperty.forEach((item) => {
- Object.values(fileData?.data).forEach((data) => {
- const filterPropertyIndex = data[0].indexOf(item);
- if (filterPropertyIndex !== -1) data.slice(1).forEach((e) => filterPropertiesCollector.add(e[filterPropertyIndex]));
- });
- });
- };
-
- const setAvailabilityAndToastMessages = (dataAvailabilityCheck, combineList, files, setToast, t) => {
- if (dataAvailabilityCheck === "true") {
- const sectionWiseCheck = combineList.every((item) => Object.keys(files).includes(item));
- if (!sectionWiseCheck) dataAvailabilityCheck = "partial";
- }
-
- if (dataAvailabilityCheck === "initialStage" && (combineList.length === 0 || Object.keys(files).length === 0)) dataAvailabilityCheck = "false";
-
- const toastMessages = {
- false: { state: "warning", message: t("MAPPING_NO_DATA_TO_SHOW") },
- partial: { state: "warning", message: t("MAPPING_PARTIAL_DATA_TO_SHOW") },
- undefined: { state: "error", message: t("MAPPING_NO_DATA_TO_SHOW") },
- };
-
- setToast(toastMessages[dataAvailabilityCheck]);
- return dataAvailabilityCheck;
- };
-
- const setFinalDataAndProperties = (
- dataAvailabilityCheck,
- setBoundary,
- setFilter,
- setBoundaryData,
- setFilterData,
- setFilterProperties,
- setFilterSelections,
- setFilterPropertyNames,
- filterPropertiesCollector,
- filterPropertieNameCollector,
- virtualizationPropertiesCollector,
- setChoroplethProperties,
- resources
- ) => {
- setDataCompleteness(dataAvailabilityCheck);
- setBoundary = calculateAggregateForTreeMicroplanWrapper(setBoundary);
- setFilter = calculateAggregateForTreeMicroplanWrapper(setFilter);
- setBoundaryData((previous) => ({ ...previous, ...setBoundary }));
- setFilterData((previous) => ({ ...previous, ...setFilter }));
- setFilterProperties([...filterPropertiesCollector]);
- setFilterSelections([...filterPropertiesCollector]);
- setFilterPropertyNames([...filterPropertieNameCollector]);
- const tempVirtualizationPropertiesCollectorArray = [...virtualizationPropertiesCollector];
- if (tempVirtualizationPropertiesCollectorArray.length !== 0)
- setChoroplethProperties([...tempVirtualizationPropertiesCollectorArray, ...(resources || [])]);
- };
-
- let setBoundary = {};
- let setFilter = {};
- const virtualizationPropertiesCollector = new Set();
- const filterPropertiesCollector = new Set();
- const filterPropertieNameCollector = new Set();
- const resources = state?.Resources?.find((item) => item.campaignType === campaignType)?.data;
- const hypothesisAssumptionsList = microplanData?.hypothesis;
- const formulaConfiguration = microplanData?.ruleEngine;
-
- let dataAvailabilityCheck = initializeDataAvailability(microplanData);
- if (!dataAvailabilityCheck) return setToast({ state: "error", message: t("MAPPING_NO_DATA_TO_SHOW") });
-
- const files = _.cloneDeep(microplanData.upload);
- for (const fileData of files) {
- if (!checkFileActivity(fileData) || !checkFileSection(fileData, filterDataOrigin)) {
- dataAvailabilityCheck = "false";
- continue;
- }
-
- if (!fileData?.fileType || !fileData?.section) continue;
-
- const schema = getFileValidationSchema(campaignType, fileData, validationSchemas);
- dataAvailabilityCheck = handleFileDataError(dataAvailabilityCheck, fileData);
-
- const { latLngColumns, filterProperty } = processFileData(
- fileData,
- schema,
- filterDataOrigin,
- virtualizationPropertiesCollector,
- filterPropertiesCollector,
- filterPropertieNameCollector,
- resources,
- hypothesisAssumptionsList,
- formulaConfiguration,
- t
- );
-
- if (fileData?.data && Object.keys(fileData?.data).length > 0) {
- switch (fileData?.fileType) {
- case EXCEL:
- const { dataAvailabilityCheck: excelDataAvailabilityCheck, hasLocationData, convertedData } = processExcelFile(
- fileData,
- latLngColumns,
- resources,
- formulaConfiguration,
- hypothesisAssumptionsList,
- schema,
- t
- );
- dataAvailabilityCheck = excelDataAvailabilityCheck;
- if (hasLocationData) updateFilterPropertiesCollector(fileData, filterProperty, filterPropertiesCollector);
- const { hierarchyLists: excelHierarchyLists, hierarchicalData: excelHierarchicalData } = processHierarchyAndData(hierarchy, convertedData);
- if (filterDataOrigin?.boundriesDataOrigin?.includes(fileData.section))
- setBoundary = { ...setBoundary, [fileData.section]: { hierarchyLists: excelHierarchyLists, hierarchicalData: excelHierarchicalData } };
- else if (filterDataOrigin?.layerDataOrigin?.includes(fileData.section))
- setFilter = { ...setFilter, [fileData.section]: { hierarchyLists: excelHierarchyLists, hierarchicalData: excelHierarchicalData } };
- break;
- case GEOJSON:
- case SHAPEFILE:
- const { dataAvailabilityCheck: geoJsonDataAvailabilityCheck, dataWithResources } = processGeoJsonFile(
- fileData,
- filterProperty,
- resources,
- formulaConfiguration,
- hypothesisAssumptionsList,
- t
- );
- dataAvailabilityCheck = geoJsonDataAvailabilityCheck;
- const { hierarchyLists: geoJsonHierarchyLists, hierarchicalData: geoJsonHierarchicalData } = processHierarchyAndData(hierarchy, [
- dataWithResources,
- ]);
- if (filterDataOrigin?.boundriesDataOrigin?.includes(fileData.section))
- setBoundary = {
- ...setBoundary,
- [fileData.section]: { hierarchyLists: geoJsonHierarchyLists, hierarchicalData: geoJsonHierarchicalData },
- };
- else if (filterDataOrigin?.layerDataOrigin?.includes(fileData.section))
- setFilter = { ...setFilter, [fileData.section]: { hierarchyLists: geoJsonHierarchyLists, hierarchicalData: geoJsonHierarchicalData } };
- break;
- default:
- break;
- }
- }
- }
-
- const combineList = [...(filterDataOrigin?.boundriesDataOrigin || []), ...(filterDataOrigin?.layerDataOrigin || [])];
- dataAvailabilityCheck = setAvailabilityAndToastMessages(dataAvailabilityCheck, combineList, files, setToast, t);
-
- setFinalDataAndProperties(
- dataAvailabilityCheck,
- setBoundary,
- setFilter,
- setBoundaryData,
- setFilterData,
- setFilterProperties,
- setFilterSelections,
- setFilterPropertyNames,
- filterPropertiesCollector,
- filterPropertieNameCollector,
- virtualizationPropertiesCollector,
- setChoroplethProperties,
- resources
- );
-};
-
-//prepare geojson to show on the map
-export const prepareGeojson = (boundaryData, selection, style = {}) => {
- if (!boundaryData || Object.keys(boundaryData).length === 0) return [];
- let geojsonRawFeatures = [];
- if (selection === "ALL") {
- for (let data of Object.values(boundaryData)) {
- const templist = fetchFeatures(data?.hierarchicalData, selection, [], style);
- if (templist?.length !== 0) geojsonRawFeatures = [...geojsonRawFeatures, ...templist];
- }
- } else if (Array.isArray(selection)) {
- for (let data of Object.values(boundaryData)) {
- const templist = fetchFeatures(data?.hierarchicalData, selection, [], style);
- if (templist?.length !== 0) geojsonRawFeatures = [...geojsonRawFeatures, ...templist];
- }
- }
-
- return geojsonRawFeatures.filter(Boolean);
-};
-export const fetchFeatures = (data, parameter = "ALL", outputList = [], addOn = {}) => {
- let tempStorage = [];
- if (parameter === "ALL") {
- // outputList(Object.values(data).flatMap(item=>item?.data?.feature))
- for (let [entityKey, entityValue] of Object.entries(data)) {
- if (entityValue?.data?.feature) {
- let feature = entityValue.data.feature;
- feature.properties["name"] = entityKey;
- feature.properties["addOn"] = addOn;
- if (entityValue?.children) tempStorage = [...tempStorage, feature, ...fetchFeatures(entityValue?.children, parameter, outputList, addOn)];
- else tempStorage = [...tempStorage, feature];
- } else {
- tempStorage = [...tempStorage, ...fetchFeatures(entityValue?.children, parameter, outputList, addOn)];
- }
- }
- return tempStorage;
- }
- if (Array.isArray(parameter)) {
- for (let [entityKey, entityValue] of Object.entries(data)) {
- if (parameter.includes(entityKey) && entityValue && entityValue.data && entityValue.data.feature) {
- let feature = entityValue.data.feature;
- feature.properties["name"] = entityKey;
- feature.properties["addOn"] = addOn;
- if (entityValue?.children) tempStorage = [...tempStorage, feature, ...fetchFeatures(entityValue?.children, parameter, outputList, addOn)];
- else tempStorage = [...tempStorage, feature];
- }
- if (entityValue?.children) tempStorage = [...tempStorage, ...fetchFeatures(entityValue?.children, parameter, outputList, addOn)];
- }
- return tempStorage;
- }
-};
-
-export const addChoroplethProperties = (geojson, choroplethProperty, filteredSelection) => {
- // Calculate min and max values of the property
- const values = geojson.map((feature) => feature.properties[choroplethProperty]).filter((item) => !!item || item === 0) || [];
- if (!values || values.length === 0) return [];
- const convertedValues = values.map((item) => (!isNaN(item) ? item : 0));
- const minValue = Math.min(...convertedValues);
- const maxValue = Math.max(...convertedValues);
-
- // Create a new geojson object
- const newGeojson = geojson.map((feature) => {
- const newFeature = { ...feature, properties: { ...feature.properties, addOn: { ...feature.properties.addOn } } };
- let color;
-
- if (choroplethProperty) {
- color = interpolateColor(newFeature.properties[choroplethProperty], minValue, maxValue, MapChoroplethGradientColors);
- }
-
- newFeature.properties.addOn.fillColor = color;
- newFeature.properties.addOn.color = "rgba(0, 0, 0, 1)";
- if (!filteredSelection || filteredSelection.length === 0 || filteredSelection.includes(newFeature.properties.name)) {
- newFeature.properties.addOn.fillOpacity = 1;
- } else {
- newFeature.properties.addOn.fillOpacity = 0.4;
- newFeature.properties.addOn.opacity = 0.7;
- }
-
- return newFeature;
- });
- return newGeojson;
-};
-
-/**
- * filterGeojsons : json
- * filterSelection : array
- * MapFilters :
- */
-export const addFilterProperties = (filterGeojsons, filterSelections, filterPropertyNames, iconMapping) => {
- try {
- if (!filterGeojsons || !iconMapping || !filterSelections) return [];
- let newFilterGeojson = [];
- filterGeojsons.forEach((item) => {
- if (filterPropertyNames && filterPropertyNames.length !== 0 && item.properties) {
- let icon;
- filterPropertyNames.forEach((name) => {
- if (item.properties[name]) {
- let temp = item.properties[name];
- if (!filterSelections.includes(temp)) return;
- temp = iconMapping?.find((e) => e?.name == temp)?.icon?.marker;
- let DynamicIcon = IconCollection?.[temp];
- if (typeof DynamicIcon === "function") {
- icon = L.divIcon({
- className: "custom-svg-icon",
- html: DynamicIcon({}),
- iconAnchor: [25, 50],
- });
- newFilterGeojson.push({ ...item, properties: { ...item?.properties, addOn: { ...item?.properties?.addOn, icon: icon } } });
- } else {
- icon = DefaultMapMarker({});
- newFilterGeojson.push({ ...item, properties: { ...item?.properties, addOn: { ...item?.properties?.addOn, icon: icon } } });
- }
- }
- });
- }
- return item;
- });
- return newFilterGeojson;
- } catch (error) {
- console.error(error.message);
- }
-};
-
-/**
- * map: map
- * geojson: geojson
- * t: translator
- */
-
-export const addGeojsonToMap = (map, geojson, t) => {
- try {
- if (!map || !geojson) return false;
- const geojsonLayer = L.geoJSON(geojson, {
- style: (feature) => {
- if (Object.keys(feature.properties.addOn).length !== 0) {
- return feature.properties.addOn;
- }
- return {
- weight: 2,
- opacity: 1,
- color: "rgba(176, 176, 176, 1)",
- fillColor: "rgb(0,0,0,0)",
- // fillColor: choroplethProperty ? color : "rgb(0,0,0,0)",
- fillOpacity: 0,
- // fillOpacity: choroplethProperty ? (feature?.properties?.style?.fillOpacity ? feature.properties.style.fillOpacity : 0.7) : 0,
- };
- },
- pointToLayer: (feature, latlng) => {
- if (feature.properties.addOn.icon) {
- let icon = feature.properties.addOn.icon;
- if (icon) {
- return L.marker(latlng, {
- icon: icon,
- });
- }
- }
- return L.marker(latlng, {
- icon: MapMarker(feature.properties.addOn),
- });
- },
- onEachFeature: (feature, layer) => {
- let popupContent;
- popupContent = "";
- popupContent += "
";
- popupContent += `${feature.properties["name"]}
`;
- for (let prop in feature.properties) {
- if (prop !== "name" && prop !== "addOn" && prop !== "feature") {
- let data = feature.properties[prop] ? feature.properties[prop] : t("NO_DATA");
- popupContent +=
- "" +
- t(prop) +
- " | " +
- data +
- " |
";
- }
- }
- popupContent += "
";
- layer.bindPopup(popupContent, {
- minWidth: "28rem",
- padding: "0",
- });
- // Adjust map here when pop up closes
- layer.on("popupclose", () => {
- map.fitBounds(geojsonLayer.getBounds());
- });
- layer.on({
- mouseover: (e) => {
- const layer = e.target;
- if (layer.feature.properties.addOn && !layer.feature.properties.addOn.child) {
- return;
- }
- if (layer.setStyle)
- layer.setStyle({
- weight: 2.7,
- opacity: 1,
- color: "rgba(255, 255, 255, 1)",
- });
- // layer.openPopup();
- },
- mouseout: (e) => {
- const layer = e.target;
- if (layer.feature.properties.addOn && !layer.feature.properties.addOn.child) {
- return;
- }
- if (layer.setStyle) {
- if (layer.feature.properties.addOn && Object.keys(layer.feature.properties.addOn).length !== 0)
- layer.setStyle({
- ...layer.feature.properties.addOn,
- });
- else
- layer.setStyle({
- weight: 2,
- color: "rgba(176, 176, 176, 1)",
- });
- }
- // layer.closePopup();
- },
- });
- },
- });
- geojsonLayer.addTo(map);
- return geojsonLayer;
- } catch (error) {
- console.error(error.message);
- }
-};
-
-export const interpolateColor = (value, minValue, maxValue, colors) => {
- // Handle case where min and max values are the same
- if (minValue === maxValue) {
- // Return a default color or handle the case as needed
- return colors[0].color;
- }
-
- // Normalize the value to a percentage between 0 and 100
- const percent = !isNaN(value) ? ((value - minValue) / (maxValue - minValue)) * 100 : 0;
- // Find the two colors to interpolate between
- let lowerColor, upperColor;
- for (let i = 0; i < colors.length - 1; i++) {
- if (!isNaN(percent) && percent >= colors[i].percent && percent <= colors[i + 1].percent) {
- lowerColor = colors[i];
- upperColor = colors[i + 1];
- break;
- }
- }
- // Interpolate between the two colors
- const t = (percent - lowerColor.percent) / (upperColor.percent - lowerColor.percent);
- return chroma.mix(lowerColor.color, upperColor.color, t, "lab").hex();
-};
-
-// Find bounds for multiple geojson together
-export const findBounds = (data, buffer = 0.1) => {
- if (!Array.isArray(data) || data.length === 0) {
- return null;
- }
-
- // Initialize variables to store bounds
- var minLat = Number.MAX_VALUE;
- var maxLat = -Number.MAX_VALUE;
- var minLng = Number.MAX_VALUE;
- var maxLng = -Number.MAX_VALUE;
-
- // Iterate through the data to find bounds
- data.forEach(function (feature) {
- if (!feature || !feature.geometry || !feature.geometry.type || !feature.geometry.coordinates) {
- return null;
- }
-
- var coords = feature.geometry.coordinates;
- var geometryType = feature.geometry.type;
-
- switch (geometryType) {
- case "Point":
- var coord = coords;
- var lat = coord[1];
- var lng = coord[0];
- minLat = Math.min(minLat, lat);
- maxLat = Math.max(maxLat, lat);
- minLng = Math.min(minLng, lng);
- maxLng = Math.max(maxLng, lng);
- break;
- case "MultiPoint":
- coords.forEach(function (coord) {
- var lat = coord[1];
- var lng = coord[0];
- minLat = Math.min(minLat, lat);
- maxLat = Math.max(maxLat, lat);
- minLng = Math.min(minLng, lng);
- maxLng = Math.max(maxLng, lng);
- });
- break;
- case "LineString":
- case "MultiLineString":
- case "Polygon":
- case "MultiPolygon":
- coords.forEach(function (polygons) {
- if ((geometryType === "Polygon" || geometryType === "MultiPolygon") && Array.isArray(polygons[0][0])) {
- polygons.forEach(function (coordinates) {
- coordinates.forEach(function (coord) {
- if (!Array.isArray(coord) || coord.length !== 2 || typeof coord[0] !== "number" || typeof coord[1] !== "number") {
- return null;
- }
-
- var lat = coord[1];
- var lng = coord[0];
- minLat = Math.min(minLat, lat);
- maxLat = Math.max(maxLat, lat);
- minLng = Math.min(minLng, lng);
- maxLng = Math.max(maxLng, lng);
- });
- });
- } else {
- polygons.forEach(function (coord) {
- if (!Array.isArray(coord) || coord.length !== 2 || typeof coord[0] !== "number" || typeof coord[1] !== "number") {
- return null;
- }
-
- var lat = coord[1];
- var lng = coord[0];
- minLat = Math.min(minLat, lat);
- maxLat = Math.max(maxLat, lat);
- minLng = Math.min(minLng, lng);
- maxLng = Math.max(maxLng, lng);
- });
- }
- });
- break;
- default:
- return null;
- }
- });
-
- // Check if valid bounds found
- if (minLat === Number.MAX_VALUE || maxLat === -Number.MAX_VALUE || minLng === Number.MAX_VALUE || maxLng === -Number.MAX_VALUE) {
- return null;
- }
- // Apply buffer to bounds
- minLat -= buffer;
- maxLat += buffer;
- minLng -= buffer;
- maxLng += buffer;
-
- // Set bounds for the Leaflet map
- var bounds = [
- [minLat, minLng],
- [maxLat, maxLng],
- ];
-
- return bounds;
-};
-
-export const filterBoundarySelection = (boundaryData, boundarySelections) => {
- if (Object.keys(boundaryData).length === 0 || Object.keys(boundarySelections).length === 0) return [];
- let selectionList = [];
- Object.values(boundarySelections).forEach((item) => (selectionList = [...selectionList, ...item.map((e) => e.name)]));
- let childrenList = [];
- const set1 = new Set(selectionList);
- selectionList = selectionList.filter((item) => {
- const children = findChildren([item], Object.values(boundaryData)?.[0]?.hierarchicalData);
- if (children) {
- let childrenKeyList = getAllKeys(children);
- childrenList = [...childrenList, ...childrenKeyList];
- const nonePresent = childrenKeyList.every((item) => !set1.has(item));
- const allPresent = childrenKeyList.every((item) => set1.has(item));
- return nonePresent ? true : allPresent ? true : false;
- }
- return true;
- });
- return { filteredSelection: selectionList, childrenList };
-};
-
-// Recursive function to extract all keys
-export const getAllKeys = (obj, keys = []) => {
- for (let [key, value] of Object.entries(obj)) {
- keys.push(key);
- if (value.children) {
- getAllKeys(value.children, keys);
- }
- }
- return keys;
-};
-
-// Remove all layers from the map
-export const removeAllLayers = (map, layer) => {
- if (!map) return;
- layer.forEach((layer) => {
- map.removeLayer(layer);
- });
-};
-// Map-Marker
-export const MapMarker = (style = {}) => {
- return L.divIcon({
- className: "custom-svg-icon",
- html: PopulationSvg(style),
- iconAnchor: [25, 50],
- });
-};
-export const DefaultMapMarker = (style = {}) => {
- return L.divIcon({
- className: "custom-svg-icon",
- html: IconCollection.DefaultMapMarkerSvg(style),
- iconAnchor: [25, 50],
- });
-};
-
-export const disableMapInteractions = (map) => {
- if (!map) return;
- map.dragging.disable();
- map.scrollWheelZoom.disable();
- map.touchZoom.disable();
- map.doubleClickZoom.disable();
- map.boxZoom.disable();
- map.keyboard.disable();
-};
-
-export const enableMapInteractions = (map) => {
- if (!map) return;
- map.dragging.enable();
- map.scrollWheelZoom.enable();
- map.touchZoom.enable();
- map.doubleClickZoom.enable();
- map.boxZoom.enable();
- map.keyboard.enable();
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/microplanPreviewUtils.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/microplanPreviewUtils.js
deleted file mode 100644
index ff5cd55208f..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/microplanPreviewUtils.js
+++ /dev/null
@@ -1,413 +0,0 @@
-import { EXCEL, GEOJSON, SHAPEFILE, commonColumn } from "../configs/constants";
-
-export const calculateAggregateValue = (aggregateName, dataToShow) => {
- if (!aggregateName || !dataToShow || dataToShow.length === 0) return;
- let aggregateNameList = aggregateName;
- if (typeof aggregateName !== "object") aggregateNameList = { name: aggregateName, entities: [aggregateName] };
- let aggregateData = 0;
- if (aggregateNameList)
- for (const item of aggregateNameList.entities) {
- const columnIndex = dataToShow?.[0].indexOf(item);
- dataToShow.slice(1).forEach((e) => {
- if (e?.[columnIndex]) aggregateData = aggregateData + Number(e[columnIndex]);
- });
- }
- return aggregateData;
-};
-
-export const fetchMicroplanData = (microplanData, campaignType, validationSchemas) => {
- if (!microplanData) return [];
-
- let combinesDataList = [];
- // Check if microplanData and its upload property exist
- if (microplanData?.upload) {
- let files = microplanData?.upload;
- // Loop through each file in the microplan upload
- for (let fileData of files) {
- const schema = getSchema(campaignType, fileData.fileType, fileData.templateIdentifier, validationSchemas);
-
- // Check if the file is not part of boundary or layer data origins
- if (!fileData.active || !fileData.fileType || !fileData?.section) continue; // Skip files with errors or missing properties
-
- // Check if file contains latitude and longitude columns
- if (fileData?.data) {
- // Check file type and update data availability accordingly
- switch (fileData?.fileType) {
- case EXCEL: {
- // extract dada
- const mergedData = schema?.template?.hierarchyLevelWiseSheets ? Object.values(fileData?.data).flat() : Object.values(fileData?.data)?.[0];
-
- let commonColumnIndex = mergedData?.[0]?.indexOf(commonColumn);
-
- let uniqueEntries;
- if (commonColumnIndex !== undefined)
- uniqueEntries = schema?.template?.hierarchyLevelWiseSheets
- ? Array.from(new Map(mergedData.map((entry) => [entry[commonColumnIndex], entry])).values())
- : mergedData;
- if (uniqueEntries) combinesDataList.push(uniqueEntries);
- break;
- }
- case GEOJSON:
- case SHAPEFILE: {
- // Extract keys from the first feature's properties
- let keys = Object.keys(fileData?.data.features[0].properties);
-
- // Extract corresponding values for each feature
- const values = fileData?.data?.features.map((feature) => {
- // list with features added to it
- const temp = keys.map((key) => {
- // if (feature.properties[key] === "") {
- // return null;
- // }
- return feature.properties[key];
- });
- return temp;
- });
-
- let data = [keys, ...values];
- combinesDataList.push(data);
- }
- }
- }
- }
- }
- return combinesDataList;
-};
-
-// get schema for validation
-export const getSchema = (campaignType, type, section, schemas) => {
- return schemas.find((schema) =>
- schema.campaignType
- ? schema.campaignType === campaignType && schema.type === type && schema.section === section
- : schema.type === type && schema.section === section
- );
-};
-
-export const fetchMicroplanPreviewData = (campaignType, microplanData, validationSchemas, hierarchy) => {
- try {
- const filteredSchemaColumns = getFilteredSchemaColumnsList(campaignType, microplanData, validationSchemas, hierarchy);
- const fetchedData = fetchMicroplanData(microplanData, campaignType, validationSchemas);
- const dataAfterJoins = performDataJoins(fetchedData, filteredSchemaColumns);
- return dataAfterJoins;
- } catch (error) {
- console.error("Error in fetch microplan data: ", error.message);
- }
-};
-
-const getFilteredSchemaColumnsList = (campaignType, microplanData, validationSchemas, hierarchy) => {
- let filteredSchemaColumns = getRequiredColumnsFromSchema(campaignType, microplanData, validationSchemas) || [];
- if (hierarchy) {
- filteredSchemaColumns = [...hierarchy, commonColumn, ...filteredSchemaColumns.filter((e) => e !== commonColumn)];
- }
- return filteredSchemaColumns;
-};
-
-const performDataJoins = (fetchedData, filteredSchemaColumns) => {
- return fetchedData.reduce((accumulator, currentData, index) => {
- if (index === 0) {
- return innerJoinLists(currentData, null, commonColumn, filteredSchemaColumns);
- }
- return innerJoinLists(accumulator, currentData, commonColumn, filteredSchemaColumns);
- }, null);
-};
-
-export const filterObjects = (arr1, arr2) => {
- if (!arr1 || !arr2) return [];
- // Create a new array to store the filtered objects
- let filteredArray = [];
-
- // Iterate through the first array
- arr1.forEach((obj1) => {
- // Find the corresponding object in the second array
- let obj2 = _.cloneDeep(arr2.find((item) => item.key === obj1.key));
-
- // If the object with the same key is found in the second array and their values are the same
- if (obj2 && obj1.value !== obj2.value) {
- // Push the object to the filtered array
- obj1.oldValue = obj2.value;
- filteredArray.push(obj1);
- }
- });
-
- return filteredArray;
-};
-
-export const useHypothesis = (tempHypothesisList, hypothesisAssumptionsList) => {
- // Handles the change in hypothesis value
- const valueChangeHandler = (e, setTempHypothesisList, boundarySelections, setToast, t) => {
- // Checks it the boundary filters at at root level ( given constraints )
- if (Object.keys(boundarySelections).length !== 0 && Object.values(boundarySelections)?.every((item) => item?.length !== 0))
- return setToast({ state: "error", message: t("HYPOTHESIS_CAN_BE_ONLY_APPLIED_ON_ADMIN_LEVEL_ZORO") });
-
- // validating user input
- if (e?.newValue.includes("+") || e?.newValue.includes("e")) return;
- if ((e?.newValue < 0 || e.newValue > 10000000000) && e?.newValue !== "") return;
- let value;
- const decimalIndex = e.newValue.indexOf(".");
- if (decimalIndex !== -1) {
- const numDecimals = e.newValue.length - decimalIndex - 1;
- if (numDecimals <= 2) {
- value = e.newValue;
- } else if (numDecimals > 2) {
- value = e.newValue.substring(0, decimalIndex + 3);
- }
- } else value = parseFloat(e.newValue);
- value = !isNaN(value) ? value : "";
-
- // update the state with user input
- let newhypothesisEntityIndex = hypothesisAssumptionsList.findIndex((item) => item?.id === e?.item?.id);
- let unprocessedHypothesisList = _.cloneDeep(tempHypothesisList);
- if (newhypothesisEntityIndex !== -1) unprocessedHypothesisList[newhypothesisEntityIndex].value = value;
- setTempHypothesisList(unprocessedHypothesisList);
- };
-
- return {
- valueChangeHandler,
- };
-};
-
-const validateRequestBody = (body, state, campaignType, setLoaderActivation, setToast, setCheckDataCompletion, navigationEvent, t) => {
- if (!Digit.Utils.microplan.planConfigRequestBodyValidator(body, state, campaignType)) {
- setLoaderActivation(false);
- if (navigationEvent.name === "next") {
- setToast({
- message: t("ERROR_DATA_NOT_SAVED"),
- state: "error",
- });
- setCheckDataCompletion("false");
- } else {
- setCheckDataCompletion("perform-action");
- }
- return false;
- }
- return true;
-};
-
-const handleApiSuccess = (data, updateData, setLoaderActivation, setMicroplanData, status) => {
- updateData();
- setLoaderActivation(false);
- setMicroplanData((previous) => ({ ...previous, microplanStatus: status }));
-};
-
-const handleApiError = (error, variables, setLoaderActivation, setToast, status, cancleNavigation, updateData, t) => {
- setLoaderActivation(false);
- setToast({
- message: t("ERROR_DATA_NOT_SAVED"),
- state: "error",
- });
- if (status === "GENERATED") {
- cancleNavigation();
- } else {
- updateData();
- }
-};
-
-const constructRequestBody = (microplanData, operatorsObject, MicroplanName, campaignId, status) => {
- const body = Digit.Utils.microplan.mapDataForApi(microplanData, operatorsObject, MicroplanName, campaignId, status);
- body.PlanConfiguration["id"] = microplanData?.planConfigurationId;
- body.PlanConfiguration["auditDetails"] = microplanData?.auditDetails;
- return body;
-};
-
-export const updateHyothesisAPICall = async (
- microplanData,
- setMicroplanData,
- operatorsObject,
- MicroplanName,
- campaignId,
- UpdateMutate,
- setToast,
- updateData,
- setLoaderActivation,
- status,
- cancleNavigation,
- state,
- campaignType,
- navigationEvent,
- setCheckDataCompletion,
- t
-) => {
- try {
- const body = constructRequestBody(microplanData, operatorsObject, MicroplanName, campaignId, status);
- const isValid = validateRequestBody(body, state, campaignType, setLoaderActivation, setToast, setCheckDataCompletion, navigationEvent, t);
- if (!isValid) return;
-
- await UpdateMutate(body, {
- onSuccess: (data) => handleApiSuccess(data, updateData, setLoaderActivation, setMicroplanData, status),
- onError: (error, variables) => handleApiError(error, variables, setLoaderActivation, setToast, status, cancleNavigation, updateData, t),
- });
- } catch (error) {
- setLoaderActivation(false);
- setToast({
- message: t("ERROR_DATA_NOT_SAVED"),
- state: "error",
- });
- }
-};
-
-// get schema for validation
-export const getRequiredColumnsFromSchema = (campaignType, microplanData, schemas) => {
- if (!schemas || !microplanData || !microplanData?.upload || !campaignType) return [];
- const sortData = [];
- if (microplanData?.upload) {
- for (const value of microplanData.upload) {
- if (value.active && value?.error === null) {
- sortData.push({ section: value.section, fileType: value?.fileType });
- }
- }
- }
- const filteredSchemas =
- schemas?.filter((schema) => {
- if (schema.campaignType) {
- return schema.campaignType === campaignType && sortData.some((entry) => entry.section === schema.section && entry.fileType === schema.type);
- }
- return sortData.some((entry) => entry.section === schema.section && entry.fileType === schema.type);
- }) || [];
-
- let finalData = [];
- let tempdata;
-
- tempdata = filteredSchemas
- ?.flatMap((item) =>
- Object.entries(item?.schema?.Properties || {}).reduce((acc, [key, value]) => {
- if (value?.isRuleConfigureInputs && value?.toShowInMicroplanPreview) {
- acc.push(key);
- }
- return acc;
- }, [])
- )
- .filter((item) => !!item);
- finalData = [...finalData, ...tempdata];
-
- tempdata = filteredSchemas
- ?.flatMap((item) =>
- Object.entries(item?.schema?.Properties || {}).reduce((acc, [key, value]) => {
- if (value?.toShowInMicroplanPreview) acc.push(key);
- return acc;
- }, [])
- )
- .filter((item) => !!item);
- finalData = [...finalData, ...tempdata];
- return [...new Set(finalData)];
-};
-
-/**
- * Combines two datasets based on a common column, duplicating rows from data1 for each matching row in data2.
- * The final dataset's columns and their order are determined by listOfColumnsNeededInFinalData.
- * If data2 is not provided, rows from data1 are included with null values for missing columns.
- */
-export const innerJoinLists = (data1, data2, commonColumnName, listOfColumnsNeededInFinalData) => {
- // Error handling: Check if data1 array is provided
- if (!Array.isArray(data1)) {
- throw new Error("The first data input must be an array.");
- }
-
- // Error handling: Check if common column name is provided
- if (typeof commonColumnName !== "string") {
- throw new Error("Common column name must be a string.");
- }
-
- // Error handling: Check if listOfColumnsNeededInFinalData is provided and is an array
- if (!Array.isArray(listOfColumnsNeededInFinalData)) {
- throw new Error("listOfColumnsNeededInFinalData must be an array.");
- }
-
- // Find the index of the common column in the first dataset
- const commonColumnIndex1 = data1[0].indexOf(commonColumnName);
-
- // Error handling: Check if common column exists in the first dataset
- if (commonColumnIndex1 === -1) {
- throw new Error(`Common column "${commonColumnName}" not found in the first dataset.`);
- }
-
- let commonColumnIndex2 = -1;
- const data2Map = new Map();
- if (data2) {
- // Find the index of the common column in the second dataset
- commonColumnIndex2 = data2[0].indexOf(commonColumnName);
-
- // Error handling: Check if common column exists in the second dataset
- if (commonColumnIndex2 === -1) {
- throw new Error(`Common column "${commonColumnName}" not found in the second dataset.`);
- }
-
- // Create a map for the second dataset for quick lookup by the common column value
- for (let i = 1; i < data2.length; i++) {
- const row = data2[i];
- const commonValue = row[commonColumnIndex2];
- if (!data2Map.has(commonValue)) {
- data2Map.set(commonValue, []);
- }
- data2Map.get(commonValue).push(row);
- }
- }
-
- // Determine the headers for the final combined dataset based on listOfColumnsNeededInFinalData
- const combinedHeaders = listOfColumnsNeededInFinalData.filter((header) => data1[0].includes(header) || data2?.[0].includes(header));
-
- // Combine rows
- const combinedData = [combinedHeaders];
- const addedCommonValues = new Set();
- for (let i = 1; i < data1.length; i++) {
- const row1 = data1[i];
- const commonValue = row1[commonColumnIndex1];
- const rows2 = data2 ? data2Map.get(commonValue) || [[null]] : [[null]]; // Handle missing common values with a placeholder array of null
-
- // Check if rows2 is the placeholder array
- const isPlaceholderArray = rows2.length === 1 && rows2[0].every((value) => value === null);
-
- // Create combined rows for each row in data2
- if (isPlaceholderArray) {
- // If no corresponding row found in data2, use row from data1 with null values for missing columns
- const combinedRow = combinedHeaders.map((header) => {
- const index1 = data1[0].indexOf(header);
- return index1 !== -1 ? row1[index1] : null;
- });
- combinedData.push(combinedRow);
- } else {
- // If corresponding rows found in data2, combine each row from data2 with row from data1
- rows2.forEach((row2) => {
- const combinedRow = combinedHeaders.map((header) => {
- const index1 = data1[0].indexOf(header);
- const index2 = data2 ? data2[0].indexOf(header) : -1;
- return index1 !== -1 ? row1[index1] : index2 !== -1 ? row2[index2] : null;
- });
- combinedData.push(combinedRow);
- });
- }
- addedCommonValues.add(commonValue);
- }
- // Add rows from data2 that do not have a matching row in data1
- if (data2) {
- for (let i = 1; i < data2.length; i++) {
- const row2 = data2[i];
- const commonValue = row2[commonColumnIndex2];
- if (!addedCommonValues.has(commonValue)) {
- const combinedRow = combinedHeaders.map((header) => {
- // const index1 = data1[0].indexOf(header);
- const index2 = data2[0].indexOf(header);
- return index2 !== -1 ? row2[index2] : null;
- });
- combinedData.push(combinedRow);
- }
- }
- }
-
- return combinedData;
-};
-
-// function to filter the microplan data with respect to the hierarchy selected by the user
-export const filterMicroplanDataToShowWithHierarchySelection = (data, selections, hierarchy, hierarchyIndex = 0) => {
- if (!selections || selections?.length === 0) return data;
- if (hierarchyIndex >= hierarchy?.length) return data;
- const filteredHirarchyLevelList = selections?.[hierarchy?.[hierarchyIndex]]?.map((item) => item?.name);
- if (!filteredHirarchyLevelList || filteredHirarchyLevelList?.length === 0) return data;
- const columnDataIndexForHierarchyLevel = data?.[0]?.indexOf(hierarchy?.[hierarchyIndex]);
- if (columnDataIndexForHierarchyLevel === -1) return data;
- const levelFilteredData = data.filter((item, index) => {
- if (index === 0) return true;
- if (item?.[columnDataIndexForHierarchyLevel] && filteredHirarchyLevelList.includes(item?.[columnDataIndexForHierarchyLevel])) return true;
- return false;
- });
- return filterMicroplanDataToShowWithHierarchySelection(levelFilteredData, selections, hierarchy, hierarchyIndex + 1);
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/processHierarchyAndData.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/processHierarchyAndData.js
deleted file mode 100644
index 09e24a4658e..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/processHierarchyAndData.js
+++ /dev/null
@@ -1,351 +0,0 @@
-export const processHierarchyAndData = (hierarchy, allData) => {
- const hierarchyLists = {};
- let hierarchicalData = {};
- try {
- // Process hierarchy
- hierarchy.forEach((item) => {
- hierarchyLists[item.boundaryType] = [];
- });
-
- // Process all sets of data
- allData.forEach((data) => {
- const dataHierarchicalData = {};
-
- // Process data for this set
- data.slice(1).forEach((row) => {
- // Exclude the header row
- let currentNode = dataHierarchicalData;
- let parent = null;
- hierarchy.forEach((item, index) => {
- const boundaryType = item.boundaryType;
- const dataIndex = data?.[0].indexOf(boundaryType);
- if (dataIndex === -1) return;
- const cellValue = row[dataIndex];
- if (!cellValue) return;
- // Populate hierarchy lists
- if (!hierarchyLists[boundaryType].includes(cellValue) && cellValue !== null && cellValue !== "" && cellValue !== undefined) {
- hierarchyLists[boundaryType].push(cellValue);
- }
-
- // Populate hierarchical data
- if (!currentNode[cellValue]) {
- currentNode[cellValue] = {
- name: cellValue,
- boundaryType: boundaryType,
- children: {},
- data: null,
- };
- }
-
- // Assign row data to the correct hierarchical level
- if (cellValue) {
- if (index === hierarchy.length - 1) {
- currentNode[cellValue].data = createDataObject(data[0], row);
- } else if (index + 1 < hierarchy.length) {
- let nextHierarchyList = hierarchy.slice(index + 1);
- let check = true;
- nextHierarchyList.forEach((e) => {
- const boundaryType = e.boundaryType;
- const dataIndex = data?.[0].indexOf(boundaryType);
- if (dataIndex === -1) return;
- check = check && !row[dataIndex];
- });
- if (check) currentNode[cellValue].data = createDataObject(data[0], row);
- }
- }
- currentNode = currentNode[cellValue].children;
- });
- });
-
- // Merge dataHierarchicalData into hierarchicalData
- hierarchicalData = mergeHierarchicalData(hierarchicalData, dataHierarchicalData);
- });
-
- // Remove null element from children of each province
- Object.values(hierarchicalData).forEach((country) => {
- if (country.children[null]) {
- country.data = country.children[null].data;
- country.children[null] = undefined;
- }
- });
- } catch (error) {
- console.error("Error in processing hierarchy and uploaded data: ", error.message);
- // Return empty objects in case of error
- return { hierarchyLists: {}, hierarchicalData: {} };
- }
-
- return { hierarchyLists, hierarchicalData };
-};
-
-// Function to merge two hierarchical data objects
-const mergeHierarchicalData = (data1, data2) => {
- for (const [key, value] of Object.entries(data2)) {
- if (!data1[key]) {
- if (!value.data) value.data = {};
- data1[key] = value || {};
- } else {
- data1[key].data = value.data; // Merge data
- mergeHierarchicalData(data1[key].children, value.children); // Recursively merge children
- }
- if (data1[key].data?.feature) {
- const { feature, ...temp } = value.data ? _.cloneDeep(value.data) : {};
- data1[key].data.feature.properties = { ...data1[key].data?.feature?.properties, ...temp };
- }
- }
- return data1;
-};
-
-// Function to create a data object with key-value pairs from headers and row data
-const createDataObject = (headers, row) => {
- const dataObject = {};
- headers.forEach((header, index) => {
- dataObject[header] = row[index];
- });
- return dataObject;
-};
-
-// Find parent in hierarchy
-export const findParent = (name, hierarchy, parent, accumulator = []) => {
- if (!name || !hierarchy) return null;
- for (let key in hierarchy) {
- if (hierarchy[key]?.name == name) {
- accumulator.push(parent);
- }
- if (hierarchy[key]?.children) {
- let response = findParent(name, hierarchy[key]?.children, hierarchy[key], accumulator);
- if (response)
- response.forEach((item) => {
- if (!accumulator.includes(item)) {
- accumulator.push(item);
- }
- });
- } else {
- return accumulator;
- }
- }
- return accumulator;
-};
-
-/**
- *
- * @param {Array of parents} parents
- * @param {hierarchycal Object data} hierarchy
- * @returns An Array containing all the cummulative children
- */
-export const findChildren = (parents, hierarchy) => {
- const hierarchyTraveller = (parents, hierarchy, accumulator = {}) => {
- let tempData = [];
- if (accumulator && Object.keys(accumulator).length !== 0)
- tempData = {
- ...accumulator,
- ...hierarchy.reduce((data, item) => {
- if (parents.includes(item?.name) && item?.children) {
- for (const key in item.children) {
- if (!data[key]) {
- data[key] = item.children[key];
- }
- }
- }
- return data;
- }, {}),
- };
- else
- tempData = hierarchy.reduce((data, item) => {
- if (parents.includes(item?.name) && item?.children) {
- for (const key in item.children) {
- if (!data[key]) {
- data[key] = item.children[key];
- }
- }
- }
- return data;
- }, {});
- for (let parent of hierarchy) {
- if (parent?.children) tempData = hierarchyTraveller(parents, Object.values(parent?.children), tempData);
- }
- return tempData;
- };
- return hierarchyTraveller(parents, Object.values(hierarchy), {});
-};
-
-// Fetched data from tree
-export const fetchDropdownValues = (boundaryData, hierarchy, boundarySelections, changedBoundaryType) => {
- if (
- !hierarchy ||
- !boundaryData ||
- !boundarySelections ||
- hierarchy.length === 0 ||
- Object.keys(hierarchy).length === 0 ||
- Object.keys(boundaryData).length === 0
- )
- return [];
- let TempHierarchy = _.cloneDeep(hierarchy);
- if (!boundarySelections || Object.values(boundarySelections)?.every((item) => item?.length === 0)) {
- for (let i in TempHierarchy) {
- if (i === "0") {
- TempHierarchy[0].dropDownOptions = findByBoundaryType(
- TempHierarchy?.[0]?.boundaryType,
- Object.values(boundaryData)?.[0]?.hierarchicalData
- ).map((data, index) => ({
- name: data,
- code: data,
- boundaryType: TempHierarchy?.[0]?.boundaryType,
- parentBoundaryType: undefined,
- }));
- } else TempHierarchy[i].dropDownOptions = [];
- }
- } else {
- const currentHierarchy = findCurrentFilteredHierarchy(Object.values(boundaryData)?.[0]?.hierarchicalData, boundarySelections, TempHierarchy);
- let currentDropdownIndex = 0;
- hierarchy.forEach((e, index) => {
- if (e && e?.boundaryType == changedBoundaryType) {
- // && boundarySelections && boundarySelections[e.boundaryType] && boundarySelections[e.boundaryType].length !== 0) {
- currentDropdownIndex = index;
- }
- });
- Object.entries(boundarySelections)?.forEach(([key, value]) => {
- let currentindex = hierarchy.findIndex((e) => e?.boundaryType === key);
- if (currentDropdownIndex !== currentindex) return;
- let childIndex = hierarchy.findIndex((e) => e?.parentBoundaryType === key);
- if (childIndex == -1) return;
- if (TempHierarchy?.[childIndex]) {
- let newDropDownValuesForChild = [];
- for (const element of value) {
- let tempStore = Object.values(findChildren([element.name], currentHierarchy)).map((value) => ({
- name: value?.name,
- code: value?.name,
- parent: element,
- boundaryType: TempHierarchy[childIndex]?.boundaryType,
- parentBoundaryType: TempHierarchy[childIndex]?.parentBoundaryType,
- }));
- if (tempStore) newDropDownValuesForChild.push(...tempStore);
- }
- // if (TempHierarchy[childIndex].dropDownOptions)
- // TempHierarchy[childIndex].dropDownOptions = [...TempHierarchy[childIndex].dropDownOptions, ...newDropDownValuesForChild];
- TempHierarchy[childIndex].dropDownOptions = newDropDownValuesForChild;
- }
- });
- }
- return TempHierarchy;
-};
-
-const findByBoundaryType = (boundaryType, hierarchy) => {
- for (let [key, value] of Object.entries(hierarchy)) {
- if (value?.boundaryType === boundaryType) return Object.keys(hierarchy).filter(Boolean);
- if (value?.children) return findByBoundaryType(boundaryType, value?.children);
- return [];
- }
- return [];
-};
-
-// makes a tree with the boundary selections as there might be duplicates in different branches that are not yet selected
-const findCurrentFilteredHierarchy = (hierarchyTree, boundarySelections, hierarchy) => {
- const newtree = constructNewHierarchyTree(hierarchy, hierarchyTree, boundarySelections);
- return newtree;
-};
-
-const constructNewHierarchyTree = (hierarchy, oldTree, boundarySelection, level = 0) => {
- // let newTree = { ...oldTree }; // Initialize a new hierarchy tree
- let newTree = {}; // Initialize a new hierarchy tree
- if (!hierarchy?.[level]) return;
- const levelName = hierarchy[level].boundaryType;
-
- // Get the selections for this level from the boundary selection object
- const selections = boundarySelection[levelName] || [];
- // If there are selections for this level
- if (selections.length > 0) {
- // Construct the new hierarchy tree based on selections
- for (const selection of selections) {
- const { name } = selection;
- // If the selection exists in the existing hierarchy tree
- if (oldTree[name]) {
- // Add the selected division to the new hierarchy tree
- newTree[name] = { ...oldTree[name] };
- // If there are children, recursively construct the children
- if (oldTree[name].children) {
- oldTree[name].children;
- const nonNullObject = Object.entries(oldTree[name].children).reduce((acc, [key, value]) => {
- if (value.name !== null) {
- acc[key] = value;
- }
- return acc;
- }, {});
- newTree[name].children = constructNewHierarchyTree(hierarchy, nonNullObject, boundarySelection, level + 1);
- }
- }
- }
- } else {
- const nonNullObject = Object.entries(oldTree).reduce((acc, [key, value]) => {
- if (value.name !== null) {
- acc[key] = value;
- }
- return acc;
- }, {});
- newTree = nonNullObject;
- }
-
- return newTree;
-};
-
-// Recursively calculates aggregate values for numerical properties within the `data` objects of each node in a hierarchical tree structure.
-// Updates the `properties` object within the `feature` object of each node with the aggregate values, if present.
-export const calculateAggregateForTree = (tree) => {
- try {
- function calculateAggregate(node) {
- if (!node.children || Object.keys(node.children).length === 0) {
- // if the node has no children, return a new node with its own data
- return { ...node, data: { ...node.data } };
- }
-
- // Recursively calculate aggregate values for each child
- const newChildren = {};
-
- for (const childKey in node.children) {
- const child = node.children[childKey];
- const newChild = calculateAggregate(child);
- newChildren[childKey] = newChild;
- }
-
- // Aggregate numerical values dynamically
- const aggregate = {};
- for (const childKey in newChildren) {
- const child = newChildren[childKey];
- for (const prop in child.data) {
- if (typeof child.data[prop] === "number") {
- aggregate[prop] = (aggregate[prop] || 0) + child.data[prop];
- }
- }
- }
-
- // Create a new node with updated data
- const newNode = {
- ...node,
- data: { ...node.data, ...aggregate },
- children: newChildren,
- };
-
- // Update properties in the feature object
- if (newNode.data.feature) {
- newNode.data.feature.properties = { ...newNode.data.feature.properties, ...aggregate };
- }
-
- return newNode;
- }
-
- const newTree = {};
-
- // Iterate over each node object
- for (const nodeKey in tree) {
- const node = tree[nodeKey];
- // Calculate aggregate values for the current node
- const newNode = calculateAggregate(node);
- // Add the updated node to the new tree
- newTree[nodeKey] = newNode;
- }
-
- return newTree;
- } catch (error) {
- console.error("Failed to calculate treenode aggregates");
- return {};
- }
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/updateSessionUtils.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/updateSessionUtils.js
deleted file mode 100644
index 129ec488b43..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/updateSessionUtils.js
+++ /dev/null
@@ -1,486 +0,0 @@
-import { Request } from "@egovernments/digit-ui-libraries";
-import { parseXlsxToJsonMultipleSheetsForSessionUtil } from "../utils/exceltojson";
-import JSZip from "jszip";
-import * as XLSX from "xlsx";
-import axios from "axios";
-import shp from "shpjs";
-import { EXCEL, GEOJSON, SHAPEFILE, ACCEPT_HEADERS, LOCALITY, commonColumn } from "../configs/constants";
-import { addBoundaryData, fetchBoundaryData, filterBoundaries } from "./createTemplate";
-import { handleExcelFile } from "./uploadUtils";
-
-function handleExcelArrayBuffer(arrayBuffer, file) {
- return new Promise((resolve, reject) => {
- try {
- // Read the response as an array buffer
- // const arrayBuffer = response.arrayBuffer();
-
- // Convert the array buffer to binary string
- const data = new Uint8Array(arrayBuffer);
- const binaryString = String.fromCharCode.apply(null, data);
-
- // Parse the binary string into a workbook
- const workbook = XLSX.read(binaryString, { type: "binary" });
-
- // Assuming there's only one sheet in the workbook
- const sheetName = workbook.SheetNames[0];
- const sheet = workbook.Sheets[sheetName];
-
- // Convert the sheet to JSON object
- const jsonData = XLSX.utils.sheet_to_json(sheet);
-
- resolve(jsonData);
- } catch (error) {
- reject(error);
- }
- });
-}
-
-function shpToGeoJSON(shpBuffer, file) {
- return new Promise((resolve, reject) => {
- try {
- shp(shpBuffer)
- .then((geojson) => {
- resolve({ jsonData: geojson, file });
- })
- .catch((error) => reject(error));
- } catch (error) {
- reject(error);
- }
- });
-}
-
-function parseGeoJSONResponse(arrayBuffer, file) {
- return new Promise((resolve, reject) => {
- try {
- const decoder = new TextDecoder("utf-8");
- const jsonString = decoder.decode(arrayBuffer);
- const jsonData = JSON.parse(jsonString);
- resolve({ jsonData, file });
- } catch (error) {
- reject(error);
- }
- });
-}
-
-// Function to read blob data and parse it into JSON
-function parseBlobToJSON(blob, file) {
- return new Promise((resolve, reject) => {
- const reader = new FileReader();
-
- reader.onload = function (event) {
- const data = new Uint8Array(event.target.result);
- const workbook = XLSX.read(data, { type: "array" });
- const jsonData = {};
-
- workbook.SheetNames.forEach((sheetName) => {
- const sheetData = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName]);
- jsonData[sheetName] = sheetData;
- });
-
- resolve({ jsonData, file });
- };
-
- reader.onerror = function () {
- reject(new Error("Error reading the blob data"));
- };
-
- reader.readAsArrayBuffer(blob);
- });
-}
-
-export const updateSessionUtils = {
- computeSessionObject: async (row, state, additionalProps) => {
- const sessionObj = {};
- const setCurrentPage = () => {
- sessionObj.currentPage = {
- id: 0,
- name: "MICROPLAN_DETAILS",
- component: "MicroplanDetails",
- checkForCompleteness: true,
- };
- };
-
- //currently hardcoded
- const setMicroplanStatus = () => {
- sessionObj.status = {
- MICROPLAN_DETAILS: true,
- UPLOAD_DATA: true,
- HYPOTHESIS: true,
- FORMULA_CONFIGURATION: true,
- };
- };
-
- const setMicroplanDetails = () => {
- if (row.name) {
- sessionObj.microplanDetails = {
- name: row?.name,
- };
- }
- };
-
- const setMicroplanHypothesis = () => {
- if (row.assumptions.length > 0) {
- sessionObj.hypothesis = row.assumptions?.filter((item) => item?.active);
- }
- };
-
- const sortRules = (rules) => {
- // Step 1: Identify all unique rule outputs
- const allOutputs = [...new Set(rules.map((rule) => rule.output))];
-
- // Step 2: Build input-output relationships
- const inputOutputMap = new Map(); // Map to store input -> output relationship
- rules.forEach((rule) => {
- const { input, output } = rule;
- if (!inputOutputMap.has(input)) {
- inputOutputMap.set(input, []);
- }
- inputOutputMap.get(input).push(output);
- });
-
- // Step 3: Sort the output list based on dependencies
- const sortedOutputList = [];
- const visited = new Set();
-
- const dfs = (output) => {
- if (!visited.has(output)) {
- visited.add(output);
- if (inputOutputMap.has(output)) {
- inputOutputMap.get(output).forEach((input) => {
- dfs(input);
- });
- }
- sortedOutputList.push(output);
- }
- };
-
- // Sort outputs based on dependencies
- allOutputs.forEach((output) => {
- dfs(output);
- });
-
- // Reverse to get outputs in the correct order (outputs first)
- sortedOutputList.reverse();
-
- // Step 4: Arrange rules based on sorted output list
- const sortedRules = [];
- const ruleMap = new Map(rules.map((rule) => [rule.id, rule]));
-
- sortedOutputList.forEach((output) => {
- rules
- .filter((rule) => rule.output === output)
- .forEach((rule) => {
- sortedRules.push(rule);
- });
- });
-
- return sortedRules;
- };
-
- const setMicroplanRuleEngine = () => {
- const rulesList = state.UIConfiguration?.filter((item) => item.name === "ruleConfigure")?.[0]?.ruleConfigureOperators;
- let sortedRules = sortRules(row.operations);
- if (row.operations.length > 0) {
- sessionObj.ruleEngine = sortedRules?.map((item) => {
- return {
- ...item,
- operator: rulesList.filter((rule) => rule.code === item.operator)?.[0]?.name,
- };
- });
- }
- };
-
- const setDraftValues = () => {
- sessionObj.planConfigurationId = row?.id;
- sessionObj.auditDetails = row.auditDetails;
- };
-
- const fetchBoundaryDataWrapper = async (schemaData) => {
- let boundaryDataAgainstBoundaryCode = {};
- // if (!schemaData?.doHierarchyCheckInUploadedData) {
- try {
- const rootBoundary = additionalProps.campaignData?.boundaries?.filter((boundary) => boundary.isRoot); // Retrieve session storage data once and store it in a variable
- const sessionData = Digit.SessionStorage.get("microplanHelperData") || {};
- let boundaryData = sessionData.filteredBoundaries;
- let filteredBoundaries;
- if (!boundaryData) {
- // Only fetch boundary data if not present in session storage
- boundaryData = await fetchBoundaryData(
- await Digit.ULBService.getCurrentTenantId(),
- additionalProps.campaignData?.hierarchyType,
- rootBoundary?.[0]?.code
- );
- filteredBoundaries = await filterBoundaries(boundaryData, additionalProps.campaignData?.boundaries);
-
- // Update the session storage with the new filtered boundaries
- Digit.SessionStorage.set("microplanHelperData", {
- ...sessionData,
- filteredBoundaries: filteredBoundaries,
- });
- } else {
- filteredBoundaries = boundaryData;
- }
- const xlsxData = addBoundaryData([], filteredBoundaries, additionalProps.campaignData?.hierarchyType)?.[0]?.data;
- xlsxData.forEach((item, i) => {
- if (i === 0) return;
- let boundaryCodeIndex = xlsxData?.[0]?.indexOf(commonColumn);
- if (boundaryCodeIndex >= item.length) {
- // If boundaryCodeIndex is out of bounds, return the item as is
- boundaryDataAgainstBoundaryCode[item[boundaryCodeIndex]] = item.slice().map(additionalProps.t);
- } else {
- // Otherwise, remove the element at boundaryCodeIndex
- boundaryDataAgainstBoundaryCode[item[boundaryCodeIndex]] = item
- .slice(0, boundaryCodeIndex)
- .concat(item.slice(boundaryCodeIndex + 1))
- .map(additionalProps.t);
- }
- });
- } catch (error) {
- console.error(error?.message);
- }
- // }
- return boundaryDataAgainstBoundaryCode;
- };
-
- const handleGeoJson = async (file, result, upload, translatedData, active, processedData, shapefileOrigin = false) => {
- if (!file) {
- console.error(`${shapefileOrigin ? "Shapefile" : "Geojson"} file is undefined`);
- return upload;
- }
-
- const { inputFileType, templateIdentifier, filestoreId, id: fileId } = file || {};
- let uploadObject = createUploadObject(templateIdentifier, inputFileType, fileId, filestoreId, shapefileOrigin ? ".zip" : ".geojson", active);
-
- const schema = findSchema(inputFileType, templateIdentifier, additionalProps?.campaignType);
- if (!schema) {
- console.error("Schema got undefined while handling geojson at handleGeoJson");
- return [...upload, uploadObject];
- }
-
- await handleGeoJsonSpecific(schema, uploadObject, templateIdentifier, result, translatedData, filestoreId, processedData);
- upload.push(uploadObject);
- return upload;
- };
-
- const handleExcel = (file, result, upload, translatedData, active) => {
- if (!file) {
- console.error("Excel file is undefined");
- return upload;
- }
-
- const { inputFileType, templateIdentifier, filestoreId, id: fileId } = file || {};
- let uploadObject = createUploadObject(templateIdentifier, inputFileType, fileId, filestoreId, ".xlsx", active),
- schema = findSchema(inputFileType, templateIdentifier, additionalProps.campaignType);
- if (!schema) {
- console.error("Schema got undefined while handling excel at handleExcel");
- return [...upload, uploadObject];
- }
-
- uploadObject.data = result; //resultAfterMapping?.tempFileDataToStore;
- upload.push(uploadObject);
- return upload;
- };
-
- const createUploadObject = (templateIdentifier, inputFileType, fileId, filestoreId, extension, active) => ({
- id: fileId,
- templateIdentifier,
- section: templateIdentifier,
- fileName: `${templateIdentifier}${extension}`,
- fileType: inputFileType,
- file: null,
- fileId: fileId,
- filestoreId: filestoreId,
- error: null,
- resourceMapping: row?.resourceMapping?.filter((resourse) => resourse.filestoreId === filestoreId).map((item) => ({ ...item, filestoreId })),
- data: {},
- active,
- });
-
- const findSchema = (inputFileType, templateIdentifier, campaignType) => {
- return state?.Schemas?.find(
- (schema) =>
- schema.type === inputFileType && schema.section === templateIdentifier && (!schema.campaignType || schema.campaignType === campaignType)
- );
- };
-
- const handleGeoJsonSpecific = async (schema, upload, templateIdentifier, result, translatedData, filestoreId, processedData) => {
- let schemaKeys;
- if (schema?.schema?.["Properties"]) {
- schemaKeys = additionalProps.hierarchyData?.concat(Object.keys(schema.schema["Properties"]));
- }
- upload.data = result;
- if (processedData) return;
- const mappedToList = upload?.resourceMapping.map((item) => item.mappedTo);
- let sortedSecondList = Digit.Utils.microplan.sortSecondListBasedOnFirstListOrder(schemaKeys, upload?.resourceMapping);
- const newFeatures = result["features"].map((item) => {
- let newProperties = {};
- sortedSecondList
- ?.filter((resourse) => resourse.filestoreId === filestoreId)
- .forEach((e) => {
- newProperties[e["mappedTo"]] = item["properties"][e["mappedFrom"]];
- });
- item["properties"] = newProperties;
- return item;
- });
- upload.data.features = newFeatures;
- if (
- additionalProps.hierarchyData?.every(
- (item) =>
- !mappedToList.includes(`${additionalProps.campaignData?.hierarchyType}_${Digit.Utils.microplan.transformIntoLocalisationCode(item)}`)
- )
- ) {
- let boundaryDataAgainstBoundaryCode = await fetchBoundaryDataWrapper(schema);
- upload.data.features.forEach((feature) => {
- const boundaryCode = feature.properties.boundaryCode;
- let additionalDetails = {};
- for (let i = 0; i < additionalProps.hierarchyData?.length; i++) {
- if (boundaryDataAgainstBoundaryCode[boundaryCode]?.[i] || boundaryDataAgainstBoundaryCode[boundaryCode]?.[i] === "") {
- additionalDetails[additionalProps.hierarchyData?.[i]] = boundaryDataAgainstBoundaryCode[boundaryCode][i];
- } else {
- additionalDetails[additionalProps.hierarchyData?.[i]] = "";
- }
- }
- feature.properties = { ...additionalDetails, ...feature.properties };
- });
- }
- };
-
- const fetchFiles = async () => {
- const files = row?.files;
- if (!files || files.length === 0) {
- return [];
- }
-
- const promises = [];
- let storedData = [];
- for (const { filestoreId, inputFileType, templateIdentifier, id, active } of files) {
- if (!active) continue;
- const schemaData = findSchema(inputFileType, templateIdentifier, additionalProps?.campaignType);
- if (!schemaData) {
- console.error("Schema got undefined while handling geojson at handleGeoJson");
- return [...upload, uploadObject];
- }
- const boundaryDataAgainstBoundaryCode = {};
- let fileData = {
- filestoreId,
- inputFileType,
- templateIdentifier,
- id,
- };
- let dataInSsn = Digit.SessionStorage.get("microplanData")?.upload?.find((item) => item.active && item.id === id);
- if (dataInSsn && dataInSsn.filestoreId === filestoreId) {
- storedData.push({ file: fileData, jsonData: dataInSsn?.data, processedData: true, translatedData: false, active });
- } else {
- const promiseToAttach = axios
- .get("/filestore/v1/files/id", {
- responseType: "arraybuffer",
- headers: {
- "Content-Type": "application/json",
- Accept: ACCEPT_HEADERS[inputFileType],
- "auth-token": Digit.UserService.getUser()?.["access_token"],
- },
- params: {
- tenantId: Digit.ULBService.getCurrentTenantId(),
- fileStoreId: filestoreId,
- },
- })
- .then(async (res) => {
- if (inputFileType === EXCEL) {
- try {
- const file = new Blob([res.data], { type: ACCEPT_HEADERS[inputFileType] });
- const response = await handleExcelFile(
- file,
- schemaData,
- additionalProps.hierarchyData.map(
- (item) => `${additionalProps.campaignData?.hierarchyType}_${Digit.Utils.microplan.transformIntoLocalisationCode(item)}`
- ),
- { id: inputFileType },
- boundaryDataAgainstBoundaryCode,
- () => {},
- additionalProps.t,
- additionalProps.campaignData,
- additionalProps.readMeSheetName
- );
- let fileData = {
- filestoreId,
- inputFileType,
- templateIdentifier,
- id,
- };
-
- return { jsonData: response.fileDataToStore, file: fileData, translatedData: true, active };
- } catch (error) {
- console.error(error);
- }
- } else if (inputFileType === GEOJSON) {
- let response = await parseGeoJSONResponse(res.data, {
- filestoreId,
- inputFileType,
- templateIdentifier,
- id,
- });
- return { ...response, translatedData: true, active };
- } else if (inputFileType === SHAPEFILE) {
- const geoJson = await shpToGeoJSON(res.data, {
- filestoreId,
- inputFileType,
- templateIdentifier,
- id,
- });
- return { ...geoJson, translatedData: true, active };
- }
- });
- promises.push(promiseToAttach);
- }
- }
-
- const resolvedPromises = await Promise.all(promises);
- let result = storedData;
- if (resolvedPromises) result = [...storedData, ...resolvedPromises];
- return result;
- };
- const setMicroplanUpload = async (filesResponse) => {
- //here based on files response set data in session
- if (filesResponse.length === 0) {
- return {};
- }
- //populate this object based on the files and return
- let upload = [];
-
- await filesResponse.forEach(async ({ jsonData, file, translatedData, active, processedData }, idx) => {
- switch (file?.inputFileType) {
- case "Shapefile":
- upload = await handleGeoJson(file, jsonData, upload, translatedData, active, processedData, true);
- break;
- case "Excel":
- upload = handleExcel(file, jsonData, upload, translatedData, active);
- break;
- case "GeoJSON":
- upload = await handleGeoJson(file, jsonData, upload, translatedData, active, processedData);
- break;
- default:
- break;
- }
- });
- //here basically parse the files data from filestore parse it and populate upload object based on file type -> excel,shape,geojson
- return upload;
- };
-
- try {
- setCurrentPage();
- setMicroplanStatus();
- setMicroplanDetails();
- setMicroplanHypothesis();
- setMicroplanRuleEngine();
- setDraftValues();
- // calling fucntion to cache filtered boundary data
- await fetchBoundaryDataWrapper({});
- const filesResponse = await fetchFiles();
- const upload = await setMicroplanUpload(filesResponse);
- sessionObj.upload = upload;
- return sessionObj;
- } catch (error) {
- console.error(error.message);
- }
- },
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/uploadUtils.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/uploadUtils.js
deleted file mode 100644
index 066f47c47f3..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/hcm-microplanning/src/utils/uploadUtils.js
+++ /dev/null
@@ -1,880 +0,0 @@
-import ExcelJS from "exceljs";
-import {
- freezeSheetValues,
- freezeWorkbookValues,
- hideUniqueIdentifierColumn,
- performUnfreezeCells,
- unfreezeColumnsByHeader,
- updateFontNameToRoboto,
-} from "../utils/excelUtils";
-import { addBoundaryData, createTemplate, fetchBoundaryData, filterBoundaries } from "../utils/createTemplate";
-import { BOUNDARY_DATA_SHEET, EXCEL, FACILITY_DATA_SHEET, SCHEMA_PROPERTIES_PREFIX, SHEET_COLUMN_WIDTH, commonColumn } from "../configs/constants";
-import shp from "shpjs";
-import JSZip from "jszip";
-import { checkForErrorInUploadedFileExcel } from "../utils/excelValidations";
-import { convertJsonToXlsx } from "../utils/jsonToExcelBlob";
-import { parseXlsxToJsonMultipleSheets } from "../utils/exceltojson";
-import { geojsonValidations } from "../utils/geojsonValidations";
-
-// Function for checking the uploaded file for nameing conventions
-export const validateNamingConvention = (file, namingConvention, setToast, t) => {
- try {
- let processedConvention = namingConvention.replace("$", ".[^.]*$");
- const regx = new RegExp(processedConvention);
-
- if (regx && !regx.test(file.name)) {
- setToast({
- state: "error",
- message: t("ERROR_NAMING_CONVENSION"),
- });
- return false;
- }
- return true;
- } catch (error) {
- console.error(error.message);
- setToast({
- state: "error",
- message: t("ERROR_UNKNOWN"),
- });
- }
-};
-
-// Function for reading ancd checking geojson data
-export const readGeojson = async (file, t) => {
- return new Promise((resolve, reject) => {
- if (!file) return resolve({ valid: false, toast: { state: "error", message: t("ERROR_PARSING_FILE") } });
-
- const reader = new FileReader();
- reader.onload = (e) => {
- try {
- const geoJSONData = JSON.parse(e.target.result);
- const trimmedGeoJSONData = trimJSON(geoJSONData);
- resolve({ valid: true, geojsonData: trimmedGeoJSONData });
- } catch (error) {
- resolve({ valid: false, toast: { state: "error", message: t("ERROR_INCORRECT_FORMAT") } });
- }
- };
- reader.onerror = (error) => {
- resolve({ valid: false, toast: { state: "error", message: t("ERROR_CORRUPTED_FILE") } });
- };
-
- reader.readAsText(file);
- });
-};
-
-// Function to recursively trim leading and trailing spaces from string values in a JSON object
-export const trimJSON = (jsonObject) => {
- if (typeof jsonObject !== "object") {
- return jsonObject; // If not an object, return as is
- }
-
- if (Array.isArray(jsonObject)) {
- return jsonObject.map((item) => trimJSON(item)); // If it's an array, recursively trim each item
- }
-
- const trimmedObject = {};
- for (const key in jsonObject) {
- if (Object.hasOwn(jsonObject, key)) {
- const value = jsonObject[key];
- // Trim string values, recursively trim objects
- trimmedObject[key.trim()] = typeof value === "string" ? value.trim() : typeof value === "object" ? trimJSON(value) : value;
- }
- }
- return trimmedObject;
-};
-// Function for reading and validating shape file data
-export const readAndValidateShapeFiles = async (file, t, namingConvention) => {
- return new Promise((resolve, reject) => {
- const readAndValidate = async () => {
- if (!file) {
- resolve({ valid: false, toast: { state: "error", message: t("ERROR_PARSING_FILE") } });
- }
- const fileRegex = new RegExp(namingConvention.replace("$", ".*$"));
- // File Size Check
- const fileSizeInBytes = file.size;
- const maxSizeInBytes = 2 * 1024 * 1024 * 1024; // 2 GB
-
- // Check if file size is within limit
- if (fileSizeInBytes > maxSizeInBytes)
- resolve({ valid: false, message: t("ERROR_FILE_SIZE"), toast: { state: "error", message: t("ERROR_FILE_SIZE") } });
-
- try {
- const zip = await JSZip.loadAsync(file);
- const isEPSG4326 = await checkProjection(zip);
- if (!isEPSG4326) {
- resolve({ valid: false, message: t("ERROR_WRONG_PRJ"), toast: { state: "error", message: t("ERROR_WRONG_PRJ") } });
- }
- const files = Object.keys(zip.files);
- const allFilesMatchRegex = files.every((fl) => {
- return fileRegex.test(fl);
- });
- let regx = new RegExp(namingConvention.replace("$", "\\.shp$"));
- const shpFile = zip.file(regx)[0];
- regx = new RegExp(namingConvention.replace("$", "\\.shx$"));
- const shxFile = zip.file(regx)[0];
- regx = new RegExp(namingConvention.replace("$", "\\.dbf$"));
- const dbfFile = zip.file(regx)[0];
-
- let geojson;
- if (shpFile && dbfFile) {
- const shpArrayBuffer = await shpFile.async("arraybuffer");
- const dbfArrayBuffer = await dbfFile.async("arraybuffer");
-
- geojson = shp.combine([shp.parseShp(shpArrayBuffer), shp.parseDbf(dbfArrayBuffer)]);
- }
- if (shpFile && dbfFile && shxFile && allFilesMatchRegex) resolve({ valid: true, data: geojson });
- else if (!allFilesMatchRegex)
- resolve({
- valid: false,
- message: [t("ERROR_CONTENT_NAMING_CONVENSION")],
- toast: { state: "error", data: geojson, message: t("ERROR_CONTENT_NAMING_CONVENSION") },
- });
- else if (!shpFile)
- resolve({ valid: false, message: [t("ERROR_SHP_MISSING")], toast: { state: "error", data: geojson, message: t("ERROR_SHP_MISSING") } });
- else if (!dbfFile)
- resolve({ valid: false, message: [t("ERROR_DBF_MISSING")], toast: { state: "error", data: geojson, message: t("ERROR_DBF_MISSING") } });
- else if (!shxFile)
- resolve({ valid: false, message: [t("ERROR_SHX_MISSING")], toast: { state: "error", data: geojson, message: t("ERROR_SHX_MISSING") } });
- } catch (error) {
- resolve({ valid: false, toast: { state: "error", message: t("ERROR_PARSING_FILE") } });
- }
- };
- readAndValidate();
- });
-};
-
-// Function for projections check in case of shapefile data
-export const checkProjection = async (zip) => {
- const prjFile = zip.file(/.prj$/i)[0];
- if (!prjFile) {
- return "absent";
- }
-
- const prjText = await prjFile.async("text");
-
- if (prjText.includes("GEOGCS") && prjText.includes("WGS_1984") && prjText.includes("DATUM") && prjText.includes("D_WGS_1984")) {
- return "EPSG:4326";
- }
- return false;
-};
-
-// find readMe as per campaign, template identifier and file type
-export const findReadMe = (readMeCollection, campaignType, type, section) => {
- if (!readMeCollection) return readMeCollection;
- return (
- readMeCollection.find(
- (readMe) => readMe.fileType === type && readMe.templateIdentifier === section && (!readMe.campaignType || readMe.campaignType === campaignType)
- )?.data || {}
- );
-};
-
-// Function to handle the template download
-export const downloadTemplate = async ({
- campaignType,
- type,
- section,
- setToast,
- campaignData,
- hierarchyType,
- Schemas,
- HierarchyConfigurations,
- setLoader,
- hierarchy,
- readMeData,
- readMeSheetName,
- t,
-}) => {
- try {
- setLoader("LOADING");
- await delay(100);
- // Find the template based on the provided parameters
- const schema = getSchema(campaignType, type, section, Schemas);
- const hierarchyLevelName = HierarchyConfigurations?.find((item) => item.name === "devideBoundaryDataBy")?.value;
- const filteredReadMeData = findReadMe(readMeData, campaignType, type, section);
- let template = await createTemplate({
- hierarchyLevelWiseSheets: schema?.template?.hierarchyLevelWiseSheets,
- hierarchyLevelName,
- addFacilityData: schema?.template?.includeFacilityData,
- schema,
- boundaries: campaignData?.boundaries,
- tenantId: Digit.ULBService.getCurrentTenantId(),
- hierarchyType,
- readMeData: filteredReadMeData,
- readMeSheetName,
- t,
- });
- const translatedTemplate = translateTemplate(template, t);
-
- // Create a new workbook
- const workbook = new ExcelJS.Workbook();
-
- formatTemplate(translatedTemplate, workbook);
-
- // Color headers
- colorHeaders(
- workbook,
- [...hierarchy.map((item) => t(item)), t(commonColumn)],
- schema?.schema?.Properties ? Object.keys(schema.schema.Properties).map((item) => t(generateLocalisationKeyForSchemaProperties(item))) : [],
- []
- );
-
- formatAndColorReadMeFile(
- workbook,
- filteredReadMeData?.map((item) => item?.header),
- readMeSheetName
- );
-
- // protextData
- await protectData({
- workbook,
- hierarchyLevelWiseSheets: schema?.template?.hierarchyLevelWiseSheets,
- addFacilityData: schema?.template?.includeFacilityData,
- schema,
- t,
- });
-
- // Write the workbook to a buffer
- workbook.xlsx.writeBuffer({ compression: true }).then((buffer) => {
- // Create a Blob from the buffer
- const blob = new Blob([buffer], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
- // Create a URL for the Blob
- const url = URL.createObjectURL(blob);
- // Create a link element and simulate click to trigger download
- const link = document.createElement("a");
- link.href = url;
- link.download = `${t(section)}.xlsx`;
- link.click();
- // Revoke the URL to release the Blob
- URL.revokeObjectURL(url);
- setLoader(false);
- });
- } catch (error) {
- setLoader(false);
- console.error(error?.message);
- setToast({ state: "error", message: t("ERROR_DOWNLOADING_TEMPLATE") });
- }
-};
-
-export const formatAndColorReadMeFile = (workbook, headerSet, readMeSheetName) => {
- const readMeSheet = workbook.getWorksheet(readMeSheetName);
- if (!readMeSheet) return;
- setAndFormatHeaders(readMeSheet);
- formatWorksheet(readMeSheet, headerSet);
-};
-
-export function setAndFormatHeaders(worksheet) {
- const row = worksheet.getRow(1);
- // Color the header cell
- row.eachCell((cell) => {
- cell.fill = {
- type: "pattern",
- pattern: "solid",
- fgColor: { argb: "f25449" }, // Header cell color
- };
- cell.alignment = { vertical: "middle", horizontal: "center", wrapText: true }; // Center align and wrap text
- cell.font = { bold: true };
- });
-}
-export function formatWorksheet(worksheet, headerSet) {
- // Add the data rows with text wrapping
- const lineHeight = 15; // Set an approximate line height
- const maxCharactersPerLine = 100; // Set a maximum number of characters per line for wrapping
-
- worksheet.eachRow((row) => {
- row.eachCell({ includeEmpty: true }, (cell) => {
- cell.alignment = { vertical: "middle", horizontal: "left", wrapText: true }; // Apply text wrapping
- // Calculate the required row height based on content length
- const numberOfLines = Math.ceil(cell?.value.length / maxCharactersPerLine);
- row.height = numberOfLines * lineHeight;
-
- // Make the header text bold
- if (headerSet?.includes(cell.value)) {
- cell.font = { bold: true };
- }
- });
- });
- worksheet.getColumn(1).width = 130;
-}
-
-export const protectData = async ({ workbook, hierarchyLevelWiseSheets = true, addFacilityData = false, schema, t }) => {
- if (hierarchyLevelWiseSheets) {
- if (addFacilityData) {
- await freezeSheetValues(workbook, t(BOUNDARY_DATA_SHEET));
- await performUnfreezeCells(workbook, t(FACILITY_DATA_SHEET));
- if (schema?.template?.propertiesToHide && Array.isArray(schema.template.propertiesToHide)) {
- let tempPropertiesToHide = schema?.template?.propertiesToHide.map((item) => t(generateLocalisationKeyForSchemaProperties(item)));
- await hideUniqueIdentifierColumn(workbook, t(FACILITY_DATA_SHEET), tempPropertiesToHide);
- }
- if (schema?.template?.facilitySchemaApiMapping) {
- } else {
- }
- } else {
- await freezeWorkbookValues(workbook);
- await unfreezeColumnsByHeader(
- workbook,
- schema?.schema?.Properties ? Object.keys(schema.schema.Properties).map((item) => t(generateLocalisationKeyForSchemaProperties(item))) : []
- );
- }
- } else {
- // total boundary Data in one sheet
- if (addFacilityData) {
- await freezeSheetValues(workbook, t(BOUNDARY_DATA_SHEET));
- await performUnfreezeCells(workbook, t(FACILITY_DATA_SHEET));
- if (schema?.template?.propertiesToHide && Array.isArray(schema.template.propertiesToHide)) {
- let tempPropertiesToHide = schema?.template?.propertiesToHide.map((item) => t(generateLocalisationKeyForSchemaProperties(item)));
- await hideUniqueIdentifierColumn(workbook, t(FACILITY_DATA_SHEET), tempPropertiesToHide);
- }
-
- if (schema?.template?.facilitySchemaApiMapping) {
- } else {
- }
- } else {
- await freezeWorkbookValues(workbook);
- await unfreezeColumnsByHeader(
- workbook,
- schema?.schema?.Properties ? Object.keys(schema.schema.Properties).map((item) => t(generateLocalisationKeyForSchemaProperties(item))) : []
- );
- }
- }
-};
-
-export const colorHeaders = async (workbook, headerList1, headerList2, headerList3) => {
- try {
- // Iterate through each sheet
- workbook.eachSheet((sheet, sheetId) => {
- // Get the first row
- const firstRow = sheet.getRow(1);
-
- // Iterate through each cell in the first row
- firstRow.eachCell((cell, colNumber) => {
- const cellValue = cell.value.toString();
-
- // Check conditions and set colors
- if (headerList1?.includes(cellValue)) {
- cell.fill = {
- type: "pattern",
- pattern: "solid",
- fgColor: { argb: "ff9248" },
- };
- } else if (headerList2?.includes(cellValue)) {
- cell.fill = {
- type: "pattern",
- pattern: "solid",
- fgColor: { argb: "93C47D" },
- };
- } else if (headerList3?.includes(cellValue)) {
- cell.fill = {
- type: "pattern",
- pattern: "solid",
- fgColor: { argb: "CCCC00" },
- };
- }
- });
- });
- } catch (error) {
- console.error("Error coloring headers:", error);
- }
-};
-
-export const formatTemplate = (template, workbook) => {
- template.forEach(({ sheetName, data }) => {
- // Create a new worksheet with properties
- const worksheet = workbook.addWorksheet(sheetName);
- data?.forEach((row, index) => {
- const worksheetRow = worksheet.addRow(row);
-
- // Apply fill color to each cell in the first row and make cells bold
- if (index === 0) {
- worksheetRow.eachCell((cell, colNumber) => {
- // Set font to bold
- cell.font = { bold: true };
-
- // Enable text wrapping
- cell.alignment = { wrapText: true };
- // Update column width based on the length of the cell's text
- const currentWidth = worksheet.getColumn(colNumber).width || SHEET_COLUMN_WIDTH; // Default width or current width
- const newWidth = Math.max(currentWidth, cell.value.toString().length + 2); // Add padding
- worksheet.getColumn(colNumber).width = newWidth;
- });
- }
- });
- updateFontNameToRoboto(worksheet);
- });
-};
-
-export const translateTemplate = (template, t) => {
- // Initialize an array to hold the transformed result
- const transformedResult = [];
-
- // Iterate over each sheet in the divided data
- for (const sheet of template) {
- const sheetData = sheet.data;
-
- // Find the index of the boundaryCode column in the header row
- const boundaryCodeIndex = sheetData[0].indexOf(commonColumn);
-
- const sheetName = t(sheet.sheetName);
- const transformedSheet = {
- sheetName: sheetName.length > 31 ? sheetName.slice(0, 31) : sheetName,
- data: [],
- };
-
- // Iterate over each row in the sheet data
- for (const [rowIndex, row] of sheetData.entries()) {
- // Transform each entity in the row using the transformFunction
- const transformedRow = row.map((entity, index) => {
- // Skip transformation for the boundaryCode column
- if ((index === boundaryCodeIndex && rowIndex !== 0) || typeof entity === "number") {
- return entity;
- }
- return t(entity);
- });
- transformedSheet.data.push(transformedRow);
- }
-
- // Add the transformed sheet to the transformed result
- transformedResult.push(transformedSheet);
- }
-
- return transformedResult;
-};
-
-// get schema for validation
-export const getSchema = (campaignType, type, section, schemas) => {
- return schemas.find((schema) => {
- if (!schema.campaignType) {
- return schema.type === type && schema.section === section;
- }
- return schema.campaignType === campaignType && schema.type === type && schema.section === section;
- });
-};
-
-// Performs resource mapping and data filtering for Excel files based on provided schema data, hierarchy, and file data.
-export const resourceMappingAndDataFilteringForExcelFiles = (schemaData, hierarchy, selectedFileType, fileDataToStore, t) => {
- const resourceMappingData = [];
- const newFileData = {};
- if (selectedFileType.id === EXCEL && fileDataToStore) {
- // Extract all unique column names from fileDataToStore and then doing thir resource mapping
- const columnForMapping = new Set(Object.values(fileDataToStore).flatMap((value) => value?.[0] || []));
- if (schemaData?.schema?.["Properties"]) {
- const schemaKeys = Object.keys(schemaData.schema["Properties"])
- .map((item) => generateLocalisationKeyForSchemaProperties(item))
- .concat([...hierarchy, commonColumn]);
- schemaKeys.forEach((item) => {
- if (columnForMapping.has(t(item))) {
- resourceMappingData.push({
- mappedFrom: t(item),
- mappedTo: revertLocalisationKey(item),
- });
- }
- });
- }
-
- // Filtering the columns with respect to the resource mapping and removing the columns that are not needed
- Object.entries(fileDataToStore).forEach(([key, value]) => {
- const data = [];
- const headers = [];
- const toRemove = [];
- if (value && value.length > 0) {
- value[0].forEach((item, index) => {
- const mappedTo = resourceMappingData.find((e) => e.mappedFrom === item)?.mappedTo;
- if (!mappedTo) {
- toRemove.push(index);
- return;
- }
- headers.push(mappedTo);
- return;
- });
- for (let i = 1; i < value?.length; i++) {
- let temp = [];
- for (let j = 0; j < value[i].length; j++) {
- if (!toRemove.includes(j)) {
- temp.push(value[i][j]);
- }
- }
- data.push(temp);
- }
- }
- newFileData[key] = [headers, ...data];
- });
- }
- return { tempResourceMappingData: resourceMappingData, tempFileDataToStore: newFileData };
-};
-export const revertLocalisationKey = (localisedCode) => {
- if (!localisedCode || !localisedCode.startsWith(SCHEMA_PROPERTIES_PREFIX + "_")) {
- return localisedCode;
- }
- return localisedCode.substring(SCHEMA_PROPERTIES_PREFIX.length + 1);
-};
-export const prepareExcelFileBlobWithErrors = async (data, errors, schema, hierarchy, readMeData, readMeSheetName, t) => {
- let tempData = [...data];
- // Process each dataset within the data object
- const processedData = {};
- const schemaCols = schema?.schema?.Properties ? Object.keys(schema.schema.Properties) : [];
- for (const sheet of tempData) {
- const dataset = [...sheet.data];
-
- // Add the 'error' column to the header
- dataset[0] = dataset[0].map((item) => {
- if (item !== commonColumn && schemaCols.includes(item)) {
- return t(generateLocalisationKeyForSchemaProperties(item));
- }
- return t(item);
- });
- if (sheet.sheetName !== t(BOUNDARY_DATA_SHEET) && sheet.sheetName !== t(readMeSheetName)) {
- // Process each data row
- if (errors) {
- dataset[0].push(t("MICROPLAN_ERROR_STATUS_COLUMN"), t("MICROPLAN_ERROR_COLUMN"));
- let headerCount = 0;
- for (let i = 1; i < dataset.length; i++) {
- const row = dataset[i];
- if (i === 1 && row) {
- headerCount = row.length;
- }
-
- if (headerCount > row.length) {
- row.push(...Array(headerCount - row.length).fill(""));
- }
-
- // Check if there are errors for the given commonColumnData
- const errorInfo = errors?.[sheet.sheetName]?.[i - 1];
- if (errorInfo) {
- let rowDataAddOn = Object.entries(errorInfo)
- .map(([key, value]) => {
- return `${t(key)}: ${value.map((item) => t(item)).join(", ")}`;
- })
- .join(". ");
- row.push(t("MICROPLAN_ERROR_STATUS_INVALID"), rowDataAddOn);
- } else {
- row.push("");
- }
- }
- }
- }
- processedData[sheet.sheetName] = dataset;
- }
- const errorColumns = ["MICROPLAN_ERROR_STATUS_COLUMN", "MICROPLAN_ERROR_COLUMN"];
- const style = {
- font: { color: { argb: "B91900" } },
- border: {
- top: { style: "thin", color: { argb: "B91900" } },
- left: { style: "thin", color: { argb: "B91900" } },
- bottom: { style: "thin", color: { argb: "B91900" } },
- right: { style: "thin", color: { argb: "B91900" } },
- },
- };
- const workbook = await convertToWorkBook(processedData, { errorColumns, style });
- colorHeaders(
- workbook,
- [...hierarchy.map((item) => t(item)), t(commonColumn)],
- schema?.schema?.Properties ? Object.keys(schema.schema.Properties).map((item) => t(generateLocalisationKeyForSchemaProperties(item))) : [],
- [t("MICROPLAN_ERROR_STATUS_COLUMN"), t("MICROPLAN_ERROR_COLUMN")]
- );
-
- formatAndColorReadMeFile(
- workbook,
- readMeData?.map((item) => item?.header),
- readMeSheetName
- );
-
- // protextData
- await protectData({
- workbook,
- hierarchyLevelWiseSheets: schema?.template?.hierarchyLevelWiseSheets,
- addFacilityData: schema?.template?.includeFacilityData,
- schema,
- t,
- });
- return await workbook.xlsx.writeBuffer({ compression: true }).then((buffer) => {
- // Create a Blob from the buffer
- return new Blob([buffer], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
- });
- // return xlsxBlob;
-};
-export const convertToWorkBook = async (jsonData, columnWithStyle) => {
- const workbook = new ExcelJS.Workbook();
-
- // Iterate over each sheet in jsonData
- for (const [sheetName, data] of Object.entries(jsonData)) {
- // Create a new worksheet
- const worksheet = workbook.addWorksheet(sheetName);
-
- // Convert data to worksheet
- for (const row of data) {
- const newRow = worksheet.addRow(row);
- const rowHasData = row?.filter((item) => item !== "").length !== 0;
- // Apply red font color to the errorColumn if it exists
- if (rowHasData && columnWithStyle?.errorColumns) {
- for (const errorColumn of columnWithStyle?.errorColumns) {
- const errorColumnIndex = data[0].indexOf(errorColumn);
- if (errorColumnIndex !== -1) {
- const columnIndex = errorColumnIndex + 1;
- if (columnIndex > 0) {
- const newCell = newRow.getCell(columnIndex);
- if (columnWithStyle.style && newCell) for (const key in columnWithStyle.style) newCell[key] = columnWithStyle.style[key];
- }
- }
- }
- }
- }
-
- // Make the first row bold
- if (worksheet.getRow(1)) {
- worksheet.getRow(1).font = { bold: true };
- }
-
- // Set column widths
- const columnCount = data?.[0]?.length || 0;
- const wscols = Array(columnCount).fill({ width: 30 });
- wscols.forEach((col, colIndex) => {
- worksheet.getColumn(colIndex + 1).width = col.width;
- });
- }
- return workbook;
-};
-export const boundaryDataGeneration = async (schemaData, campaignData, t) => {
- let boundaryDataAgainstBoundaryCode = {};
- if (schemaData && !schemaData.doHierarchyCheckInUploadedData) {
- try {
- const rootBoundary = campaignData?.boundaries?.filter((boundary) => boundary.isRoot); // Retrieve session storage data once and store it in a variable
- const sessionData = Digit.SessionStorage.get("microplanHelperData") || {};
- let boundaryData = sessionData.filteredBoundaries;
- let filteredBoundaries;
- if (!boundaryData) {
- // Only fetch boundary data if not present in session storage
- boundaryData = await fetchBoundaryData(Digit.ULBService.getCurrentTenantId(), campaignData?.hierarchyType, rootBoundary?.[0]?.code);
- filteredBoundaries = filterBoundaries(boundaryData, campaignData?.boundaries);
-
- // Update the session storage with the new filtered boundaries
- Digit.SessionStorage.set("microplanHelperData", {
- ...sessionData,
- filteredBoundaries: filteredBoundaries,
- });
- } else {
- filteredBoundaries = boundaryData;
- }
- const xlsxData = addBoundaryData([], filteredBoundaries, campaignData?.hierarchyType)?.[0]?.data;
- xlsxData.forEach((item, i) => {
- if (i === 0) return;
- let boundaryCodeIndex = xlsxData?.[0]?.indexOf(commonColumn);
- if (boundaryCodeIndex >= item.length) {
- // If boundaryCodeIndex is out of bounds, return the item as is
- boundaryDataAgainstBoundaryCode[item[boundaryCodeIndex]] = item.slice().map(t);
- } else {
- // Otherwise, remove the element at boundaryCodeIndex
- boundaryDataAgainstBoundaryCode[item[boundaryCodeIndex]] = item
- .slice(0, boundaryCodeIndex)
- .concat(item.slice(boundaryCodeIndex + 1))
- .map(t);
- }
- });
- return boundaryDataAgainstBoundaryCode;
- } catch (error) {
- console.error(error?.message);
- }
- }
-};
-
-export const handleExcelFile = async (
- file,
- schemaData,
- hierarchy,
- selectedFileType,
- boundaryDataAgainstBoundaryCode,
- setUploadedFileError,
- t,
- campaignData,
- readMeSheetName
-) => {
- try {
- // Converting the file to preserve the sequence of columns so that it can be stored
- let fileDataToStore = await parseXlsxToJsonMultipleSheets(file, { header: 0 });
- const additionalSheets = [];
- if (fileDataToStore[t(BOUNDARY_DATA_SHEET)]) {
- additionalSheets.push({ sheetName: t(BOUNDARY_DATA_SHEET), data: fileDataToStore[t(BOUNDARY_DATA_SHEET)], position: -1 });
- delete fileDataToStore[t(BOUNDARY_DATA_SHEET)];
- }
- if (fileDataToStore[t(readMeSheetName)]) {
- additionalSheets.push({ sheetName: t(readMeSheetName), data: fileDataToStore[t(readMeSheetName)], position: 0 });
- delete fileDataToStore[t(readMeSheetName)];
- }
- let { tempResourceMappingData, tempFileDataToStore } = resourceMappingAndDataFilteringForExcelFiles(
- schemaData,
- hierarchy,
- selectedFileType,
- fileDataToStore,
- t
- );
- fileDataToStore = await convertJsonToXlsx(tempFileDataToStore);
- // Converting the input file to json format
- let result = await parseXlsxToJsonMultipleSheets(fileDataToStore, { header: 1 });
- if (result?.error) {
- return {
- check: false,
- interruptUpload: true,
- error: result.error,
- fileDataToStore: {},
- toast: { state: "error", message: t("ERROR_CORRUPTED_FILE") },
- };
- }
- let extraColumns = [commonColumn];
- // checking if the hierarchy and common column is present the uploaded data
- extraColumns = [...hierarchy, commonColumn];
- let data = Object.values(tempFileDataToStore);
- let errorMsg;
- let errors; // object containing the location and type of error
- let toast;
- let hierarchyDataPresent = true;
- let latLngColumns =
- Object.entries(schemaData?.schema?.Properties || {}).reduce((acc, [key, value]) => {
- if (value?.isLocationDataColumns) {
- acc.push(key);
- }
- return acc;
- }, []) || [];
- data.forEach((item) => {
- const keys = item[0];
- if (keys?.length !== 0) {
- if (!extraColumns?.every((e) => keys.includes(e))) {
- if (schemaData && !schemaData.doHierarchyCheckInUploadedData) {
- hierarchyDataPresent = false;
- } else {
- errorMsg = {
- check: false,
- interruptUpload: true,
- error: t("ERROR_BOUNDARY_DATA_COLUMNS_ABSENT"),
- fileDataToStore: {},
- toast: { state: "error", message: t("ERROR_BOUNDARY_DATA_COLUMNS_ABSENT") },
- };
- }
- }
- if (!latLngColumns?.every((e) => keys.includes(e))) {
- toast = { state: "warning", message: t("ERROR_UPLOAD_EXCEL_LOCATION_DATA_MISSING") };
- }
- }
- });
- if (errorMsg && !errorMsg?.check) return errorMsg;
- // Running Validations for uploaded file
- let response = await checkForErrorInUploadedFileExcel(result, schemaData.schema, t);
- if (!response.valid) setUploadedFileError(response.message);
- errorMsg = response.message;
- errors = response.errors;
- const missingProperties = response.missingProperties;
- let check = response.valid;
- try {
- if (
- schemaData &&
- !schemaData.doHierarchyCheckInUploadedData &&
- !hierarchyDataPresent &&
- boundaryDataAgainstBoundaryCode &&
- (!missingProperties || [...missingProperties]?.includes(commonColumn))
- ) {
- let tempBoundaryDataAgainstBoundaryCode = (await boundaryDataGeneration(schemaData, campaignData, t)) || {};
- for (const sheet in tempFileDataToStore) {
- const commonColumnIndex = tempFileDataToStore[sheet]?.[0]?.indexOf(commonColumn);
- if (commonColumnIndex !== -1) {
- const dataCollector = [];
- for (let index = 0; index < tempFileDataToStore[sheet].length; index++) {
- let row = tempFileDataToStore[sheet][index];
- const commonColumnValues = row[commonColumnIndex]?.split(",").map((item) => item.trim());
- if (!commonColumnValues) {
- dataCollector.push([...new Array(hierarchy.length).fill(""), ...row]);
- continue;
- }
- for (const value of commonColumnValues) {
- const newRowData = [...row];
- newRowData[commonColumnIndex] = value;
- dataCollector.push([
- ...(tempBoundaryDataAgainstBoundaryCode[value]
- ? tempBoundaryDataAgainstBoundaryCode[value]
- : index !== 0
- ? new Array(hierarchy.length).fill("")
- : []),
- ...newRowData,
- ]);
- }
- }
- tempFileDataToStore[sheet] = dataCollector;
- }
-
- tempFileDataToStore[sheet][0] = [...hierarchy, ...tempFileDataToStore[sheet][0]];
- }
- }
- } catch (error) {
- console.error("Error in boundary adding operaiton: ", error);
- }
- tempFileDataToStore = addMissingPropertiesToFileData(tempFileDataToStore, missingProperties);
- return { check, errors, errorMsg, fileDataToStore: tempFileDataToStore, tempResourceMappingData, toast, additionalSheets };
- } catch (error) {
- console.error("Error in handling Excel file:", error.message);
- }
-};
-export const addMissingPropertiesToFileData = (data, missingProperties) => {
- if (!data || !missingProperties) return data;
- let tempData = {};
- Object.entries(data).forEach(([key, value], index) => {
- const filteredMissingProperties = [...missingProperties]?.reduce((acc, item) => {
- if (!value?.[0]?.includes(item)) {
- acc.push(item);
- }
- return acc;
- }, []);
- const newTempHeaders = value?.[0].length !== 0 ? [...value[0], ...filteredMissingProperties] : [...filteredMissingProperties];
- tempData[key] = [newTempHeaders, ...value.slice(1)];
- });
- return tempData;
-};
-
-export const handleGeojsonFile = async (file, schemaData, setUploadedFileError, t) => {
- // Reading and checking geojson data
- const data = await readGeojson(file, t);
- if (!data.valid) {
- return { check: false, stopUpload: true, toast: data.toast };
- }
-
- // Running geojson validaiton on uploaded file
- let response = geojsonValidations(data.geojsonData, schemaData.schema, t);
- if (!response.valid) setUploadedFileError(response.message);
- let check = response.valid;
- let error = response.message;
- let fileDataToStore = data.geojsonData;
- return { check, error, fileDataToStore };
-};
-
-const generateLocalisationKeyForSchemaProperties = (code) => {
- if (!code) return code;
- return `${SCHEMA_PROPERTIES_PREFIX}_${code}`;
-};
-export const handleShapefiles = async (file, schemaData, setUploadedFileError, selectedFileType, setToast, t) => {
- // Reading and validating the uploaded geojson file
- let response = await readAndValidateShapeFiles(file, t, selectedFileType["namingConvention"]);
- if (!response.valid) {
- setUploadedFileError(response.message);
- setToast(response.toast);
- }
- let check = response.valid;
- let error = response.message;
- let fileDataToStore = response.data;
- return { check, error, fileDataToStore };
-};
-
-export const convertToSheetArray = (data) => {
- if (!data) return [];
- const convertedSheetData = [];
- for (const [key, value] of Object.entries(data)) {
- convertedSheetData.push({ sheetName: key, data: value });
- }
- return convertedSheetData;
-};
-
-//find guideline
-export const findGuideLine = (campaignType, type, section, guidelineArray) => {
- if (!guidelineArray) return guidelineArray;
- return guidelineArray.find(
- (guideline) =>
- guideline.fileType === type && guideline.templateIdentifier === section && (!guideline.campaignType || guideline.campaignType === campaignType)
- )?.guidelines;
-};
-
-// Utility function to introduce a delay
-export const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/AttendanceActionModal.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/AttendanceActionModal.js
deleted file mode 100644
index a2c50215207..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/AttendanceActionModal.js
+++ /dev/null
@@ -1,133 +0,0 @@
-import React, { useState, useEffect } from "react";
-import _ from "lodash";
-import { Loader, Modal, FormComposer } from "@egovernments/digit-ui-react-components";
-import { configAttendanceApproveModal, configAttendanceRejectModal, configAttendanceCheckModal } from "../config";
-
-
-const Heading = (props) => {
- return {props.label}
;
-};
-
-const Close = () => (
-
-);
-
-const CloseBtn = (props) => {
- return (
-
-
-
- );
-};
-
-const AttendanceActionModal = ({ t, action, tenantId, state, id, closeModal, submitAction, actionData, applicationData, businessService, moduleCode,applicationDetails,workflowDetails, saveAttendanceState}) => {
- const [config, setConfig] = useState({});
-
- const userUuid = Digit.UserService.getUser()?.info.uuid;
- const { isLoading, data:employeeData } = Digit.Hooks.hrms.useHRMSSearch(
- { uuids : userUuid }, tenantId
- );
-
- const empData = employeeData?.Employees[0]
- const empDepartment = empData?.assignments?.[0].department
- const empDesignation = empData?.assignments?.[0].designation
- const empName = empData?.user?.name
-
- useEffect(() => {
- const selectedAction = action?.action
- switch(selectedAction) {
- case "VERIFY":
- submitBasedOnAction(action, 'Verify muster roll')
- break;
- case "REJECT":
- setConfig(
- configAttendanceRejectModal({
- t,
- action,
- empDepartment,
- empDesignation,
- empName
- })
- )
- break;
- case "APPROVE":
- setConfig(
- configAttendanceApproveModal({
- t,
- action
- })
- )
- break;
- case "RESUBMIT":
- submitBasedOnAction(action, 'Resubmit muster roll')
- break;
- case "SAVE":
- submitBasedOnAction(action, 'Verify muster roll')
- break;
- default:
- break
- }
- }, [employeeData]);
-
- function onSubmit (data) {
- submitBasedOnAction(action, data?.comments)
- }
-
- const submitBasedOnAction = (action, comments) => {
- let musterRoll = { tenantId, id: applicationDetails?.applicationDetails?.[0]?.applicationData?.id}
- let workflow = { action: action?.action, comments: (comments || `${action?.action} done`), assignees: [] }
-
- const selectedAction = action?.action
- switch(selectedAction) {
- case "SAVE":
- musterRoll.individualEntries = saveAttendanceState?.updatePayload
- workflow.action = 'VERIFY'
- break;
- case "RESUBMIT":
- musterRoll.additionalDetails = { computeAttendance : true }
- break;
- default:
- break;
- }
- const dataTobeSubmitted = {musterRoll, workflow}
- submitAction(dataTobeSubmitted)
- }
-
- const cardStyle = () => {
- if(config.label.heading === "Processing Details") {
- return {
- "padding" : "0px"
- }
- }
- return {}
- }
-
- return action && config?.form ? (
- }
- headerBarEnd={}
- actionCancelLabel={t(config.label.cancel)}
- actionCancelOnSubmit={closeModal}
- actionSaveLabel={t(config.label.submit)}
- actionSaveOnSubmit={() => {}}
- formId="modal-action"
- >
-
-
- ) : (
-
- );
-}
-
-export default AttendanceActionModal
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/BPAActionModal.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/BPAActionModal.js
deleted file mode 100644
index 269bbefa1dd..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/BPAActionModal.js
+++ /dev/null
@@ -1,283 +0,0 @@
-import { Loader, Modal, FormComposer } from "@egovernments/digit-ui-react-components";
-import React, { useState, useEffect } from "react";
-import { useQueryClient } from "react-query";
-import { configBPAApproverApplication } from "../config";
-import * as predefinedConfig from "../config";
-
-const Heading = (props) => {
- return {props.label}
;
-};
-
-const Close = () => (
-
-);
-
-const CloseBtn = (props) => {
- return (
-
-
-
- );
-};
-
-const ActionModal = ({ t, action, tenantId, state, id, closeModal, submitAction, actionData, applicationDetails, applicationData, businessService, moduleCode,workflowDetails }) => {
- const mutation1 = Digit.Hooks.obps.useObpsAPI(
- applicationData?.landInfo?.address?.city ? applicationData?.landInfo?.address?.city : tenantId,
- false
- );
- const { data: approverData, isLoading: PTALoading } = Digit.Hooks.useEmployeeSearch(
- tenantId,
- {
- roles: workflowDetails?.data?.initialActionState?.nextActions?.filter(ele=>ele?.action==action?.action)?.[0]?.assigneeRoles?.map(role=>({code:role})),
- isActive: true,
- },
- { enabled: !action?.isTerminateState }
- );
-
- const queryClient = useQueryClient();
- const [config, setConfig] = useState({});
- const [defaultValues, setDefaultValues] = useState({});
- const [approvers, setApprovers] = useState([]);
- const [selectedApprover, setSelectedApprover] = useState({});
- const [file, setFile] = useState(null);
- const [uploadedFile, setUploadedFile] = useState(null);
- const [error, setError] = useState(null);
- const [selectedFinancialYear, setSelectedFinancialYear] = useState(null);
- const mobileView = Digit.Utils.browser.isMobile() ? true : false;
-
- useEffect(() => {
- setApprovers(approverData?.Employees?.map((employee) => ({ uuid: employee?.uuid, name: employee?.user?.name })));
- }, [approverData]);
-
- function selectFile(e) {
- setFile(e.target.files[0]);
- }
-
- useEffect(() => {
- (async () => {
- setError(null);
- if (file) {
- const allowedFileTypesRegex = /(.*?)(jpg|jpeg|png|image|pdf)$/i
- if (file.size >= 5242880) {
- setError(t("CS_MAXIMUM_UPLOAD_SIZE_EXCEEDED"));
- } else if (file?.type && !allowedFileTypesRegex.test(file?.type)) {
- setError(t(`NOT_SUPPORTED_FILE_TYPE`))
- } else {
- try {
- const response = await Digit.UploadServices.Filestorage("OBPS", file, Digit.ULBService.getStateId() || tenantId?.split(".")[0]);
- if (response?.data?.files?.length > 0) {
- setUploadedFile(response?.data?.files[0]?.fileStoreId);
- } else {
- setError(t("CS_FILE_UPLOAD_ERROR"));
- }
- } catch (err) {
- setError(t("CS_FILE_UPLOAD_ERROR"));
- }
- }
- }
- })();
- }, [file]);
-
- const getInspectionDocs = (docs) => {
- let refinedDocs = [];
- docs && docs.map((doc,ind) => {
- refinedDocs.push({
- "documentType":(doc.documentType+"_"+doc.documentType.split("_")[1]).replaceAll("_","."),
- "fileStoreId":doc.fileStoreId,
- "fileStore":doc.fileStoreId,
- "fileName":"",
- "dropDownValues": {
- "value": (doc.documentType+"_"+doc.documentType.split("_")[1]).replaceAll("_","."),
- }
- })
- })
- return refinedDocs;
- }
-
- const getQuestion = (data) => {
- let refinedQues = [];
- var i;
- for(i=0; i {
- let formdata = [], inspectionOb = [];
-
- if (data?.additionalDetails?.fieldinspection_pending?.length > 0) {
- inspectionOb = data?.additionalDetails?.fieldinspection_pending
- }
-
- if(data.status == "FIELDINSPECTION_INPROGRESS") {
- formdata = JSON.parse(sessionStorage.getItem("INSPECTION_DATA"));
- formdata?.length > 0 && formdata.map((ob,ind) => {
- inspectionOb.push({
- docs: getInspectionDocs(ob.Documents),
- date: ob.InspectionDate,
- questions: getQuestion(ob),
- time: ob?.InspectionTime,
- })
- })
- inspectionOb = inspectionOb.filter((ob) => ob.docs && ob.docs.length>0);
- } else {
- sessionStorage.removeItem("INSPECTION_DATA")
- }
-
- let fieldinspection_pending = [ ...inspectionOb];
- return fieldinspection_pending;
- }
-
- const getDocuments = (applicationData) => {
- let documentsformdata = JSON.parse(sessionStorage.getItem("BPA_DOCUMENTS"));
- let documentList = [];
- documentsformdata.map(doc => {
- if(doc?.uploadedDocuments?.[0]?.values?.length > 0) documentList = [...documentList, ...doc?.uploadedDocuments?.[0]?.values];
- if(doc?.newUploadedDocs?.length > 0) documentList = [...documentList, ...doc?.newUploadedDocs]
- });
- return documentList;
- }
-
- const getPendingApprovals = () => {
- const approvals = Digit.SessionStorage.get("OBPS_APPROVAL_CHECKS");
- const newApprovals = Digit.SessionStorage.get("OBPS_NEW_APPROVALS");
- let result = approvals?.reduce((acc, approval) => approval?.checked ? acc.push(approval?.label) && acc : acc, []);
- result = result?.concat(newApprovals !== null?newApprovals.filter(ob => ob.label !== "").map(approval => approval?.label):[]);
- return result;
- }
-
- function submit(data) {
- let workflow = { action: action?.action, comments: data?.comments, businessService, moduleName: moduleCode };
- applicationData = {
- ...applicationData,
- documents: getDocuments(applicationData),
- additionalDetails: {...applicationData?.additionalDetails, fieldinspection_pending:getfeildInspection(applicationData), pendingapproval: getPendingApprovals() },
- workflow:{
- action: action?.action,
- comment: data?.comments?.length > 0 ? data?.comments : null,
- comments: data?.comments?.length > 0 ? data?.comments : null,
- assignee: !selectedApprover?.uuid ? null : [selectedApprover?.uuid],
- assignes: !selectedApprover?.uuid ? null : [selectedApprover?.uuid],
- varificationDocuments: uploadedFile
- ? [
- {
- documentType: action?.action + " DOC",
- fileName: file?.name,
- fileStoreId: uploadedFile,
- },
- ]
- : null,
- },
- action: action?.action,
- comment: data?.comments,
- assignee: !selectedApprover?.uuid ? null : [selectedApprover?.uuid],
- wfDocuments: uploadedFile
- ? [
- {
- documentType: action?.action + " DOC",
- fileName: file?.name,
- fileStoreId: uploadedFile,
- },
- ]
- : null,
- };
-
- const nocDetails = applicationDetails?.nocData?.map(noc => {
- const uploadedDocuments = Digit.SessionStorage.get(noc?.nocType) || [];
- return {
- Noc: {
- ...noc,
- documents: [
- ...(noc?.documents?noc?.documents:[]),
- ...(uploadedDocuments?uploadedDocuments:[])
- ]
- }
- }
- })
-
- let nocData = [];
- if (nocDetails) {
- nocDetails.map(noc => {
- if (
- noc?.Noc?.applicationStatus?.toUpperCase() != "APPROVED" &&
- noc?.Noc?.applicationStatus?.toUpperCase() != "AUTO_APPROVED" &&
- noc?.Noc?.applicationStatus?.toUpperCase() != "REJECTED" &&
- noc?.Noc?.applicationStatus?.toUpperCase() != "AUTO_REJECTED" &&
- noc?.Noc?.applicationStatus?.toUpperCase() != "VOIDED"
- ) {
- nocData.push(noc);
- }
- })
- }
-
- submitAction({
- BPA:applicationData
- }, nocData?.length > 0 ? nocData : false, {isStakeholder: false, bpa: true});
- }
-
-
- useEffect(() => {
- if (action) {
- setConfig(
- configBPAApproverApplication({
- t,
- action,
- approvers,
- selectedApprover,
- setSelectedApprover,
- selectFile,
- uploadedFile,
- setUploadedFile,
- businessService,
- assigneeLabel: "WF_ASSIGNEE_NAME_LABEL",
- error
- })
- );
- }
- }, [action, approvers, selectedFinancialYear, uploadedFile, error]);
-
- return action && config.form ? (
- }
- headerBarEnd={}
- actionCancelLabel={t(config.label.cancel)}
- actionCancelOnSubmit={closeModal}
- actionSaveLabel={t(config.label.submit)}
- actionSaveOnSubmit={() => { }}
- formId="modal-action"
- isOBPSFlow={true}
- popupStyles={mobileView?{width:"720px"}:{}}
- style={!mobileView?{minHeight: "45px", height: "auto", width:"107px",paddingLeft:"0px",paddingRight:"0px"}:{minHeight: "45px", height: "auto",width:"44%"}}
- popupModuleMianStyles={mobileView?{paddingLeft:"5px"}: {}}
- >
- {PTALoading ? (
-
- ) : (
-
- )}
-
- ) : (
-
- );
-};
-
-export default ActionModal;
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/BPAREGActionModal.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/BPAREGActionModal.js
deleted file mode 100644
index dc0bfe07776..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/BPAREGActionModal.js
+++ /dev/null
@@ -1,153 +0,0 @@
-import { Loader, Modal, FormComposer } from "@egovernments/digit-ui-react-components";
-import React, { useState, useEffect } from "react";
-import { configBPAREGApproverApplication } from "../config";
-import * as predefinedConfig from "../config";
-
-const Heading = (props) => {
- return {props.label}
;
-};
-
-const Close = () => (
-
-);
-
-const CloseBtn = (props) => {
- return (
-
-
-
- );
-};
-
-const ActionModal = ({ t, action, tenantId, state, id, closeModal, submitAction, actionData, applicationData, businessService, moduleCode }) => {
- const { data: approverData, isLoading: PTALoading } = Digit.Hooks.useEmployeeSearch(
- tenantId,
- {
- roles: action?.assigneeRoles?.map?.((e) => ({ code: e })),
- isActive: true,
- },
- { enabled: !action?.isTerminateState }
- );
-
- const [config, setConfig] = useState({});
- const [defaultValues, setDefaultValues] = useState({});
- const [approvers, setApprovers] = useState([]);
- const [selectedApprover, setSelectedApprover] = useState({});
- const [file, setFile] = useState(null);
- const [uploadedFile, setUploadedFile] = useState(null);
- const [error, setError] = useState(null);
- const mobileView = Digit.Utils.browser.isMobile() ? true : false;
-
- useEffect(() => {
- setApprovers(approverData?.Employees?.map((employee) => ({ uuid: employee?.uuid, name: employee?.user?.name })));
- }, [approverData]);
-
- function selectFile(e) {
- setFile(e.target.files[0]);
- }
-
- useEffect(() => {
- (async () => {
- setError(null);
- if (file) {
- const allowedFileTypesRegex = /(.*?)(jpg|jpeg|png|image|pdf)$/i
- if (file.size >= 5242880) {
- setError(t("CS_MAXIMUM_UPLOAD_SIZE_EXCEEDED"));
- } else if (file?.type && !allowedFileTypesRegex.test(file?.type)) {
- setError(t(`NOT_SUPPORTED_FILE_TYPE`))
- } else {
- try {
- const response = await Digit.UploadServices.Filestorage("OBPS", file, Digit.ULBService.getStateId() || tenantId?.split(".")[0]);
- if (response?.data?.files?.length > 0) {
- setUploadedFile(response?.data?.files[0]?.fileStoreId);
- } else {
- setError(t("CS_FILE_UPLOAD_ERROR"));
- }
- } catch (err) {
- setError(t("CS_FILE_UPLOAD_ERROR"));
- }
- }
- }
- })();
- }, [file]);
-
- function submit(data) {
- let workflow = { action: action?.action, comments: data?.comments, businessService, moduleName: moduleCode };
- applicationData = {
- ...applicationData,
- action: action?.action,
- comment: data?.comments,
- assignee: !selectedApprover?.uuid ? null : [selectedApprover?.uuid],
- wfDocuments: uploadedFile
- ? [
- {
- documentType: action?.action + " DOC",
- fileName: file?.name,
- fileStoreId: uploadedFile,
- },
- ]
- : null,
- };
- submitAction({
- Licenses: [applicationData],
- }, false, {isStakeholder: true, bpa: false});
- }
-
- useEffect(() => {
- if (action) {
- setConfig(
- configBPAREGApproverApplication({
- t,
- action,
- approvers,
- selectedApprover,
- setSelectedApprover,
- selectFile,
- uploadedFile,
- setUploadedFile,
- businessService,
- error
- })
- );
- }
- }, [action, approvers, uploadedFile, error]);
-
- return action && config.form ? (
- }
- headerBarEnd={}
- actionCancelLabel={t(config.label.cancel)}
- actionCancelOnSubmit={closeModal}
- actionSaveLabel={t(config.label.submit)}
- actionSaveOnSubmit={() => { }}
- formId="modal-action"
- isOBPSFlow={true}
- popupStyles={mobileView?{width:"720px"}:{}}
- style={!mobileView?{height: "45px", width:"107px",paddingLeft:"0px",paddingRight:"0px"}:{height:"45px",width:"44%"}}
- popupModuleMianStyles={mobileView?{paddingLeft:"5px"}: {}}
- >
- {PTALoading ? (
-
- ) : (
-
- )}
-
- ) : (
-
- );
-};
-
-export default ActionModal;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/ExpenditureActionModal.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/ExpenditureActionModal.js
deleted file mode 100644
index 95393b5ae05..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/ExpenditureActionModal.js
+++ /dev/null
@@ -1,190 +0,0 @@
-import { Loader, Modal, FormComposer, WorkflowModal } from "@egovernments/digit-ui-react-components";
-import React, { useState, useEffect, Fragment } from "react";
-import { configViewBillApproveModal, configViewBillRejectModal, configViewBillCheckModal } from "../config";
-import _ from "lodash";
-
-const Heading = (props) => {
- return {props.label}
;
-};
-
-const Close = () => (
-
-);
-
-const CloseBtn = (props) => {
- return (
-
-
-
- );
-};
-
-const ExpenditureActionModal = ({ t, action, tenantId, state, id, closeModal, submitAction, actionData, applicationData, businessService, moduleCode,applicationDetails,workflowDetails }) => {
-
- let { loiNumber, estimateNumber } = Digit.Hooks.useQueryParams();
- const [config, setConfig] = useState({});
- const [defaultValues, setDefaultValues] = useState({});
- const [approvers, setApprovers] = useState([]);
- const [selectedApprover, setSelectedApprover] = useState({});
-
- const [department, setDepartment] = useState([]);
- const [selectedDept,setSelectedDept] = useState({})
-
- const [designation, setDesignation] = useState([]);
- const [selectedDesignation,setSelectedDesignation] = useState({})
-
- const mdmsConfig = {
- moduleName: "common-masters",
- department : {
- masterName: "Department",
- localePrefix: "COMMON_MASTERS_DEPARTMENT",
- },
- designation : {
- masterName: "Designation",
- localePrefix: "COMMON_MASTERS_DESIGNATION",
- }
- }
-
- const { isLoading: mdmsLoading, data: mdmsData,isSuccess:mdmsSuccess } = Digit.Hooks.useCustomMDMS(
- Digit.ULBService.getStateId(),
- mdmsConfig?.moduleName,
- [{name : mdmsConfig?.designation?.masterName}, {name : mdmsConfig?.department?.masterName}, {name : mdmsConfig?.rejectReasons?.masterName}],
- {
- select: (data) => {
- let designationData = _.get(data, `${mdmsConfig?.moduleName}.${mdmsConfig?.designation?.masterName}`, []);
- designationData = designationData.filter((opt) => opt?.active).map((opt) => ({ ...opt, name: `${mdmsConfig?.designation?.localePrefix}_${opt.code}` }));
- designationData?.map(designation => {designation.i18nKey = designation?.name})
-
- let departmentData = _.get(data, `${mdmsConfig?.moduleName}.${mdmsConfig?.department?.masterName}`, []);
- departmentData = departmentData.filter((opt) => opt?.active).map((opt) => ({ ...opt, name: `${mdmsConfig?.department?.localePrefix}_${opt.code}` }));
- departmentData?.map(department => { department.i18nKey = department?.name})
-
- return {designationData, departmentData};
- },
- enabled: mdmsConfig?.moduleName ? true : false,
- }
- );
- useEffect(() => {
- setDepartment(mdmsData?.departmentData)
- setDesignation(mdmsData?.designationData)
- }, [mdmsData]);
-
-
-
- const { isLoading: approverLoading, isError, error, data: employeeDatav1 } = Digit.Hooks.hrms.useHRMSSearch({ designations: selectedDesignation?.code, departments: selectedDept?.code, roles: action?.assigneeRoles?.toString(), isActive: true }, Digit.ULBService.getCurrentTenantId(), null, null, { enabled: action?.action === "CHECK" || action?.action === "TECHNICALSANCATION"});
-
-
- employeeDatav1?.Employees.map(emp => emp.nameOfEmp = emp?.user?.name || "NA")
-
- useEffect(() => {
- setApprovers(employeeDatav1?.Employees?.length > 0 ? employeeDatav1?.Employees.filter(emp => emp?.nameOfEmp !== "NA") : [])
- }, [employeeDatav1])
-
- useEffect(() => {
-
- if(action?.action?.includes("CHECK")){
- setConfig(
- configViewBillCheckModal({
- t,
- action,
- businessService,
- approvers,
- selectedApprover,
- setSelectedApprover,
- designation,
- selectedDesignation,
- setSelectedDesignation,
- department,
- selectedDept,
- setSelectedDept,
- approverLoading
- })
- )
- }else if(action?.action?.includes("APPROVE")){
- setConfig(
- configViewBillApproveModal({
- t,
- action
- })
- )
- }
- else if(action?.action?.includes("REJECT")){
- setConfig(
- configViewBillRejectModal({
- t,
- action,
- })
- )
- }
- }, [approvers,designation,department]);
-
- const dummy_exp_response = {
- CHECK : {
- header: "Bill Forwarded Successfully",
- id: "Bill/2021-22/09/0001",
- info: "Bill ID",
- message: "Bill has been successfully created and forwarded for approval.",
- responseData:{},
- requestData:{},
- links : []
- },
- REJECT : {
- header: "Bill Rejected Successfully",
- id: "Bill/2021-22/09/0001",
- info: "Bill ID",
- message: "Bill has been Rejected.",
- responseData:{},
- requestData:{},
- links : []
- },
- APPROVE : {
- header: "Bill Approved Successfully",
- id: "Bill/2021-22/09/0001",
- info: "Bill ID",
- message: "Bill has been approved",
- responseData:{},
- requestData:{},
- links : []
- }
- }
-
-
- function submit (_data) {
- const workflow = {
- action: action?.action,
- comment: _data?.comments,
- response : dummy_exp_response,
- type : "bills",
- assignees: selectedApprover?.uuid ? [selectedApprover?.uuid] : undefined
- }
- submitAction({workflow});
- }
-
- const cardStyle = () => {
- if(config.label.heading === "Processing Details") {
- return {
- "padding" : "0px"
- }
- }
- return {}
- }
-
- return (
- <>
- {
- action && config?.form ?
-
- :
- mdmsLoading ?
- : null
- }
- >)
-}
-
-export default ExpenditureActionModal
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/FSMActionModal.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/FSMActionModal.js
deleted file mode 100644
index af0e0e8e701..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/FSMActionModal.js
+++ /dev/null
@@ -1,298 +0,0 @@
-import { Loader, Modal, FormComposer, Toast } from "@egovernments/digit-ui-react-components";
-import React, { useState, useEffect } from "react";
-import { useQueryClient } from "react-query";
-
-import { configAssignDso, configCompleteApplication, configReassignDSO, configAcceptDso, configRejectApplication } from "../config";
-
-const Heading = (props) => {
- return {props.label}
;
-};
-
-const Close = () => (
-
-);
-
-const CloseBtn = (props) => {
- return (
-
-
-
- );
-};
-
-const ActionModal = ({ t, action, tenantId, state, id, closeModal, submitAction, actionData }) => {
- const { data: dsoData, isLoading: isDsoLoading, isSuccess: isDsoSuccess, error: dsoError } = Digit.Hooks.fsm.useDsoSearch(tenantId);
- const { isLoading, isSuccess, isError, data: applicationData, error } = Digit.Hooks.fsm.useSearch(
- tenantId,
- { applicationNos: id },
- {
- staleTime: Infinity,
- select: (details) => {
- let { additionalDetails } = details;
-
- const parseTillObject = (str) => {
- if (typeof str === "object") return str;
- else return parseTillObject(JSON.parse(str));
- };
-
- additionalDetails = parseTillObject(additionalDetails);
- return { ...details, additionalDetails };
- },
- }
- );
- const client = useQueryClient();
- const stateCode = Digit.ULBService.getStateId();
- const { data: vehicleList, isLoading: isVehicleData, isSuccess: isVehicleDataLoaded } = Digit.Hooks.fsm.useMDMS(
- stateCode,
- "Vehicle",
- "VehicleType",
- { staleTime: Infinity }
- );
- const [dsoList, setDsoList] = useState([]);
- const [vehicleNoList, setVehicleNoList] = useState([]);
- const [config, setConfig] = useState({});
- const [dso, setDSO] = useState(null);
- const [vehicleNo, setVehicleNo] = useState(null);
- const [vehicleMenu, setVehicleMenu] = useState([]);
- const [vehicle, setVehicle] = useState(null);
- const [defaultValues, setDefautValue] = useState({
- capacity: vehicle?.capacity,
- wasteCollected: vehicle?.capacity,
- });
- // const [toastError, setToastError] = useState(false);
- const { data: Reason, isLoading: isReasonLoading } = Digit.Hooks.fsm.useMDMS(stateCode, "FSM", "Reason", { staleTime: Infinity }, [
- "ReassignReason",
- "RejectionReason",
- "DeclineReason",
- "CancelReason",
- ]);
-
- const [reassignReason, selectReassignReason] = useState(null);
- const [rejectionReason, setRejectionReason] = useState(null);
- const [declineReason, setDeclineReason] = useState(null);
- const [cancelReason, selectCancelReason] = useState(null);
-
- const [formValve, setFormValve] = useState(false);
-
- useEffect(() => {
- if (isSuccess && isVehicleDataLoaded) {
- const [vehicle] = vehicleList.filter((item) => item.code === applicationData.vehicleType);
- setVehicleMenu([vehicle]);
- setVehicle(vehicle);
- setDefautValue({
- capacity: vehicle?.capacity,
- wasteCollected: vehicle?.capacity,
- });
- }
- }, [isVehicleDataLoaded, isSuccess]);
-
- useEffect(() => {
- if (vehicle && isDsoSuccess) {
- const dsoList = dsoData.filter((dso) => dso.vehicles.find((dsoVehicle) => dsoVehicle.type === vehicle.code));
- setDsoList(dsoList);
- }
- }, [vehicle, isDsoSuccess]);
-
- useEffect(() => {
- if (isSuccess && isDsoSuccess && applicationData.dsoId) {
- const [dso] = dsoData.filter((dso) => dso.id === applicationData.dsoId);
- const vehicleNoList = dso.vehicles.filter((vehicle) => vehicle.type === applicationData.vehicleType);
- setVehicleNoList(vehicleNoList);
- }
- }, [isSuccess, isDsoSuccess]);
-
- useEffect(() => {
- reassignReason || (actionData && actionData[0] && actionData[0].comment?.length > 0) ? setFormValve(true) : setFormValve(false);
- }, [reassignReason]);
-
- useEffect(() => {
- setFormValve(rejectionReason ? true : false);
- }, [rejectionReason]);
-
- useEffect(() => {
- setFormValve(declineReason ? true : false);
- }, [declineReason]);
-
- useEffect(() => {
- setFormValve(cancelReason ? true : false);
- }, [cancelReason]);
-
- function selectDSO(dsoDetails) {
- setDSO(dsoDetails);
- }
-
- function selectVehicleNo(vehicleNo) {
- setVehicleNo(vehicleNo);
- }
-
- function selectVehicle(value) {
- setVehicle(value);
- setDefautValue({
- capacity: value?.capacity,
- wasteCollected: value?.capacity,
- });
- }
-
- function addCommentToWorkflow(state, workflow, data) {
- workflow.comments = data.comments ? state.code + "~" + data.comments : state.code;
- }
-
- function submit(data) {
- const workflow = { action: action };
-
- if (dso) applicationData.dsoId = dso.id;
- if (vehicleNo && action === "ACCEPT") applicationData.vehicleId = vehicleNo.id;
- if (vehicleNo && action === "DSO_ACCEPT") applicationData.vehicleId = vehicleNo.id;
- if (vehicle && action === "ASSIGN") applicationData.vehicleType = vehicle.code;
- if (data.date) applicationData.possibleServiceDate = new Date(`${data.date}`).getTime();
- if (data.desluged) applicationData.completedOn = new Date(data.desluged).getTime();
- if (data.wasteCollected) applicationData.wasteCollected = data.wasteCollected;
- if (reassignReason) addCommentToWorkflow(reassignReason, workflow, data);
- if (rejectionReason) addCommentToWorkflow(rejectionReason, workflow, data);
- if (declineReason) addCommentToWorkflow(declineReason, workflow, data);
- if (cancelReason) addCommentToWorkflow(cancelReason, workflow, data);
-
- submitAction({ fsm: applicationData, workflow });
- }
- useEffect(() => {
- switch (action) {
- case "DSO_ACCEPT":
- case "ACCEPT":
- setFormValve(vehicleNo ? true : false);
- return setConfig(
- configAcceptDso({
- t,
- dsoData,
- dso,
- vehicle,
- vehicleNo,
- vehicleNoList,
- selectVehicleNo,
- action,
- })
- );
-
- case "ASSIGN":
- case "GENERATE_DEMAND":
- case "FSM_GENERATE_DEMAND":
- setFormValve(dso && vehicle ? true : false);
- return setConfig(
- configAssignDso({
- t,
- dsoData,
- dso,
- selectDSO,
- vehicleMenu,
- vehicle,
- selectVehicle,
- action,
- })
- );
- case "REASSIGN":
- case "REASSING":
- case "FSM_REASSING":
- dso && vehicle && (reassignReason || (actionData && actionData[0] && actionData[0].comment?.length > 0))
- ? setFormValve(true)
- : setFormValve(false);
- return setConfig(
- configReassignDSO({
- t,
- dsoData,
- dso,
- selectDSO,
- vehicleMenu,
- vehicle,
- selectVehicle,
- reassignReasonMenu: Reason?.ReassignReason,
- reassignReason,
- selectReassignReason,
- action,
- showReassignReason: actionData && actionData[0] && actionData[0].comment?.length > 0 ? false : true,
- })
- );
- case "COMPLETE":
- case "COMPLETED":
- setFormValve(true);
- return setConfig(configCompleteApplication({ t, vehicle, applicationCreatedTime: applicationData?.auditDetails?.createdTime, action }));
- case "SUBMIT":
- case "FSM_SUBMIT":
- return history.push(`/${window?.contextPath}/employee/fsm/modify-application/` + applicationNumber);
- case "DECLINE":
- case "DSO_REJECT":
- //declinereason
- setFormValve(declineReason ? true : false);
- return setConfig(
- configRejectApplication({
- t,
- rejectMenu: Reason?.DeclineReason,
- setReason: setDeclineReason,
- reason: declineReason,
- action,
- })
- );
- case "REJECT":
- case "SENDBACK":
- // rejectionReason
- setFormValve(rejectionReason ? true : false);
- return setConfig(
- configRejectApplication({
- t,
- rejectMenu: Reason?.RejectionReason,
- setReason: setRejectionReason,
- reason: rejectionReason,
- action,
- })
- );
- case "CANCEL":
- ///cancellreason
- setFormValve(cancelReason ? true : false);
- return setConfig(
- configRejectApplication({
- t,
- rejectMenu: Reason?.CancelReason,
- setReason: selectCancelReason,
- reason: cancelReason,
- action,
- })
- );
-
- case "PAY":
- case "ADDITIONAL_PAY_REQUEST":
- case "FSM_PAY":
- return history.push(`/${window?.contextPath}/employee/payment/collect/FSM.TRIP_CHARGES/${applicationNumber}`);
- default:
- break;
- }
- }, [action, isDsoLoading, dso, vehicleMenu, rejectionReason, vehicleNo, vehicleNoList, Reason]);
-
- return action && config.form && !isDsoLoading && !isReasonLoading && isVehicleDataLoaded ? (
- }
- headerBarEnd={}
- actionCancelLabel={t(config.label.cancel)}
- actionCancelOnSubmit={closeModal}
- actionSaveLabel={t(config.label.submit)}
- actionSaveOnSubmit={() => {}}
- formId="modal-action"
- isDisabled={!formValve}
- >
-
- {/* {toastError && } */}
-
- ) : (
-
- );
-};
-
-export default ActionModal;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/NOCActionModal.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/NOCActionModal.js
deleted file mode 100644
index 09266ca1b7b..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/NOCActionModal.js
+++ /dev/null
@@ -1,169 +0,0 @@
-import { Loader, Modal, FormComposer } from "@egovernments/digit-ui-react-components";
-import React, { useState, useEffect } from "react";
-import { useQueryClient } from "react-query";
-import { useHistory } from "react-router-dom";
-import { configNOCApproverApplication } from "../config";
-import * as predefinedConfig from "../config";
-
-const Heading = (props) => {
- return {props.label}
;
-};
-
-const Close = () => (
-
-);
-
-const CloseBtn = (props) => {
- return (
-
-
-
- );
-};
-
-const ActionModal = ({ t, action, tenantId, state, id, closeModal, submitAction, actionData, applicationData, businessService, moduleCode }) => {
-
- const { data: approverData, isLoading: PTALoading } = Digit.Hooks.useEmployeeSearch(
- tenantId,
- {
- roles: action?.assigneeRoles?.map?.((e) => ({ code: e })),
- isActive: true,
- },
- { enabled: !action?.isTerminateState }
- );
-
- const queryClient = useQueryClient();
- const [config, setConfig] = useState({});
- const [defaultValues, setDefaultValues] = useState({});
- const [approvers, setApprovers] = useState([]);
- const [selectedApprover, setSelectedApprover] = useState({});
- const [file, setFile] = useState(null);
- const [uploadedFile, setUploadedFile] = useState(null);
- const [error, setError] = useState(null);
- const mobileView = Digit.Utils.browser.isMobile() ? true : false;
- const history = useHistory();
-
- useEffect(() => {
- setApprovers(approverData?.Employees?.map((employee) => ({ uuid: employee?.uuid, name: employee?.user?.name })));
- }, [approverData]);
-
- function selectFile(e) {
- setFile(e.target.files[0]);
- }
-
- useEffect(() => {
- (async () => {
- setError(null);
- if (file) {
- const allowedFileTypesRegex = /(.*?)(jpg|jpeg|png|image|pdf)$/i
- if (file.size >= 5242880) {
- setError(t("CS_MAXIMUM_UPLOAD_SIZE_EXCEEDED"));
- } else if (file?.type && !allowedFileTypesRegex.test(file?.type)) {
- setError(t(`NOT_SUPPORTED_FILE_TYPE`))
- } else {
- try {
- const response = await Digit.UploadServices.Filestorage("NOC", file, Digit.ULBService.getStateId() || tenantId?.split(".")[0]);
- if (response?.data?.files?.length > 0) {
- setUploadedFile(response?.data?.files[0]?.fileStoreId);
- } else {
- setError(t("CS_FILE_UPLOAD_ERROR"));
- }
- } catch (err) {
- setError(t("CS_FILE_UPLOAD_ERROR"));
- }
- }
- }
- })();
- }, [file]);
-
-
- function submit(data) {
- let enteredDocs = JSON.parse(sessionStorage.getItem("NewNOCDocs"));
- let newDocs = applicationData?.documents?.length > 0 ? [...applicationData?.documents] : [];
- enteredDocs.map((d,index) => {
- newDocs.push(d);
- })
- applicationData = {
- ...applicationData,
- workflow:{
- action: action?.action,
- comment: data?.comments ? data?.comments : null,
- assignee: !selectedApprover?.uuid ? null : [selectedApprover?.uuid],
- documents: uploadedFile
- ? [
- {
- documentType: action?.action + " DOC",
- fileName: file?.name,
- fileStoreId: uploadedFile,
- },
- ]
- : null,
- },
- documents: newDocs,
- };
-
-
- submitAction({
- Noc: applicationData,
- }, false, {isNoc: true});
- }
-
- useEffect(() => {
- if (action) {
- setConfig(
- configNOCApproverApplication({
- t,
- action,
- approvers,
- selectedApprover,
- setSelectedApprover,
- selectFile,
- uploadedFile,
- setUploadedFile,
- businessService,
- assigneeLabel: "WF_ASSIGNEE_NAME_LABEL",
- error
- })
- );
- }
- }, [action, approvers, uploadedFile, error]);
-
- return action && config.form ? (
- }
- headerBarEnd={}
- actionCancelLabel={t(config.label.cancel)}
- actionCancelOnSubmit={closeModal}
- actionSaveLabel={t(config.label.submit)}
- actionSaveOnSubmit={() => { }}
- formId="modal-action"
- isOBPSFlow={true}
- popupStyles={mobileView?{width:"720px"}:{}}
- style={!mobileView?{height: "45px", width:"107px",paddingLeft:"0px",paddingRight:"0px"}:{height:"45px",width:"44%"}}
- popupModuleMianStyles={mobileView?{paddingLeft:"5px"}: {}}
- >
- {PTALoading ? (
-
- ) : (
-
- )}
-
- ) : (
-
- );
-};
-
-export default ActionModal;
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/PTActionModal.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/PTActionModal.js
deleted file mode 100644
index 37b3d996177..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/PTActionModal.js
+++ /dev/null
@@ -1,190 +0,0 @@
-import { Loader, Modal, FormComposer } from "@egovernments/digit-ui-react-components";
-import React, { useState, useEffect } from "react";
-
-import { configPTApproverApplication, configPTAssessProperty } from "../config";
-import * as predefinedConfig from "../config";
-
-const Heading = (props) => {
- return {props.label}
;
-};
-
-const Close = () => (
-
-);
-
-const CloseBtn = (props) => {
- return (
-
-
-
- );
-};
-
-const ActionModal = ({ t, action, tenantId, state, id, closeModal, submitAction, actionData, applicationData, businessService, moduleCode }) => {
- const { data: approverData, isLoading: PTALoading } = Digit.Hooks.useEmployeeSearch(
- tenantId,
- {
- roles: action?.assigneeRoles?.map?.((e) => ({ code: e })),
- isActive: true,
- },
- { enabled: !action?.isTerminateState }
- );
- const { isLoading: financialYearsLoading, data: financialYearsData } = Digit.Hooks.pt.useMDMS(
- tenantId,
- businessService,
- "FINANCIAL_YEARLS",
- {},
- {
- details: {
- tenantId: Digit.ULBService.getStateId(),
- moduleDetails: [{ moduleName: "egf-master", masterDetails: [{ name: "FinancialYear", filter: "[?(@.module == 'PT')]" }] }],
- },
- }
- );
-
- const [config, setConfig] = useState({});
- const [defaultValues, setDefaultValues] = useState({});
- const [approvers, setApprovers] = useState([]);
- const [selectedApprover, setSelectedApprover] = useState(null);
- const [file, setFile] = useState(null);
- const [uploadedFile, setUploadedFile] = useState(null);
- const [error, setError] = useState(null);
- const [financialYears, setFinancialYears] = useState([]);
- const [selectedFinancialYear, setSelectedFinancialYear] = useState(null);
- const [disableActionSubmit, setDisableActionSubmit] = useState(false);
-
- useEffect(() => {
- if (financialYearsData && financialYearsData["egf-master"]) {
- setFinancialYears(financialYearsData["egf-master"]?.["FinancialYear"]);
- }
- }, [financialYearsData]);
-
- useEffect(() => {
- setApprovers(approverData?.Employees?.map((employee) => ({ uuid: employee?.uuid, name: employee?.user?.name })));
- }, [approverData]);
-
- function selectFile(e) {
- setFile(e.target.files[0]);
- }
-
- useEffect(() => {
- (async () => {
- setError(null);
- if (file) {
- if (file.size >= 5242880) {
- setError(t("CS_MAXIMUM_UPLOAD_SIZE_EXCEEDED"));
- } else {
- try {
- const response = await Digit.UploadServices.Filestorage("PT", file, Digit.ULBService.getStateId());
- if (response?.data?.files?.length > 0) {
- setUploadedFile(response?.data?.files[0]?.fileStoreId);
- } else {
- setError(t("CS_FILE_UPLOAD_ERROR"));
- }
- } catch (err) {
- setError(t("CS_FILE_UPLOAD_ERROR"));
- }
- }
- }
- })();
- }, [file]);
-
- function submit(data) {
- if (!action?.showFinancialYearsModal) {
- let workflow = { action: action?.action, comment: data?.comments, businessService, moduleName: moduleCode };
- workflow["assignes"] = action?.isTerminateState || !selectedApprover ? [] : [selectedApprover];
- if (uploadedFile)
- workflow["documents"] = [
- {
- documentType: action?.action + " DOC",
- fileName: file?.name,
- fileStoreId: uploadedFile,
- },
- ];
-
- submitAction({
- Property: {
- ...applicationData,
- workflow,
- },
- });
- } else {
- submitAction({
- customFunctionToExecute: action?.customFunctionToExecute,
- Assessment: {
- financialYear: selectedFinancialYear?.name,
- propertyId: applicationData?.propertyId,
- tenantId,
- source: applicationData?.source,
- channel: applicationData?.channel,
- assessmentDate: Date.now(),
- },
- });
- }
- }
-
- useEffect(() => {
- if (action) {
- if (action?.showFinancialYearsModal) {
- setConfig(
- configPTAssessProperty({
- t,
- action,
- financialYears,
- selectedFinancialYear,
- setSelectedFinancialYear,
- })
- );
- } else {
- setConfig(
- configPTApproverApplication({
- t,
- action,
- approvers,
- selectedApprover,
- setSelectedApprover,
- selectFile,
- uploadedFile,
- setUploadedFile,
- businessService,
- })
- );
- }
- }
- }, [action, approvers, financialYears, selectedFinancialYear, uploadedFile]);
-
- return action && config.form ? (
- }
- headerBarEnd={}
- actionCancelLabel={t(config.label.cancel)}
- actionCancelOnSubmit={closeModal}
- actionSaveLabel={t(config.label.submit)}
- actionSaveOnSubmit={() => {}}
- isDisabled={!action.showFinancialYearsModal ? PTALoading || (action?.docUploadRequired && !uploadedFile) : !selectedFinancialYear}
- formId="modal-action"
- >
- {financialYearsLoading ? (
-
- ) : (
-
- )}
-
- ) : (
-
- );
-};
-
-export default ActionModal;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/TLActionModal.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/TLActionModal.js
deleted file mode 100644
index f11658a987a..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/TLActionModal.js
+++ /dev/null
@@ -1,166 +0,0 @@
-import { Loader, Modal, FormComposer } from "@egovernments/digit-ui-react-components";
-import React, { useState, useEffect } from "react";
-
-import { configTLApproverApplication } from "../config";
-import * as predefinedConfig from "../config";
-
-const Heading = (props) => {
- return {props.label}
;
-};
-
-const Close = () => (
-
-);
-
-const CloseBtn = (props) => {
- return (
-
-
-
- );
-};
-
-const ActionModal = ({ t, action, tenantId, state, id, closeModal, submitAction, actionData, applicationData, businessService, moduleCode }) => {
- const { data: approverData, isLoading: PTALoading } = Digit.Hooks.useEmployeeSearch(
- tenantId,
- {
- roles: action?.assigneeRoles?.map?.((e) => ({ code: e })),
- isActive: true,
- },
- { enabled: !action?.isTerminateState }
- );
- const { isLoading: financialYearsLoading, data: financialYearsData } = Digit.Hooks.pt.useMDMS(
- tenantId,
- businessService,
- "FINANCIAL_YEARLS",
- {},
- {
- details: {
- tenantId: Digit.ULBService.getStateId(),
- moduleDetails: [{ moduleName: "egf-master", masterDetails: [{ name: "FinancialYear", filter: "[?(@.module == 'TL')]" }] }],
- },
- }
- );
-
- const [config, setConfig] = useState({});
- const [defaultValues, setDefaultValues] = useState({});
- const [approvers, setApprovers] = useState([]);
- const [selectedApprover, setSelectedApprover] = useState({});
- const [file, setFile] = useState(null);
- const [uploadedFile, setUploadedFile] = useState(null);
- const [error, setError] = useState(null);
- const [financialYears, setFinancialYears] = useState([]);
- const [selectedFinancialYear, setSelectedFinancialYear] = useState(null);
-
- useEffect(() => {
- if (financialYearsData && financialYearsData["egf-master"]) {
- setFinancialYears(financialYearsData["egf-master"]?.["FinancialYear"]);
- }
- }, [financialYearsData]);
-
- useEffect(() => {
- setApprovers(approverData?.Employees?.map((employee) => ({ uuid: employee?.uuid, name: employee?.user?.name })));
- }, [approverData]);
-
- function selectFile(e) {
- setFile(e.target.files[0]);
- }
-
- useEffect(() => {
- (async () => {
- setError(null);
- if (file) {
- if (file.size >= 5242880) {
- setError(t("CS_MAXIMUM_UPLOAD_SIZE_EXCEEDED"));
- } else {
- try {
- const response = await Digit.UploadServices.Filestorage("PT", file, Digit.ULBService.getStateId());
- if (response?.data?.files?.length > 0) {
- setUploadedFile(response?.data?.files[0]?.fileStoreId);
- } else {
- setError(t("CS_FILE_UPLOAD_ERROR"));
- }
- } catch (err) {
- setError(t("CS_FILE_UPLOAD_ERROR"));
- }
- }
- }
- })();
- }, [file]);
-
- function submit(data) {
- let workflow = { action: action?.action, comments: data?.comments, businessService, moduleName: moduleCode };
- applicationData = {
- ...applicationData,
- action: action?.action,
- comment: data?.comments,
- assignee: !selectedApprover?.uuid ? null : [selectedApprover?.uuid],
- // assignee: action?.isTerminateState ? [] : [selectedApprover?.uuid],
- wfDocuments: uploadedFile
- ? [
- {
- documentType: action?.action + " DOC",
- fileName: file?.name,
- fileStoreId: uploadedFile,
- },
- ]
- : null,
- };
- submitAction({
- Licenses: [applicationData],
- });
- }
-
- useEffect(() => {
- if (action) {
- setConfig(
- configTLApproverApplication({
- t,
- action,
- approvers,
- selectedApprover,
- setSelectedApprover,
- selectFile,
- uploadedFile,
- setUploadedFile,
- businessService,
- })
- );
- }
- }, [action, approvers, financialYears, selectedFinancialYear, uploadedFile]);
-
- return action && config.form ? (
- }
- headerBarEnd={}
- actionCancelLabel={t(config.label.cancel)}
- actionCancelOnSubmit={closeModal}
- actionSaveLabel={t(config.label.submit)}
- actionSaveOnSubmit={() => {}}
- // isDisabled={!action.showFinancialYearsModal ? PTALoading || (!action?.isTerminateState && !selectedApprover?.uuid) : !selectedFinancialYear}
- formId="modal-action"
- >
- {financialYearsLoading ? (
-
- ) : (
-
- )}
-
- ) : (
-
- );
-};
-
-export default ActionModal;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/WNSActionModal.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/WNSActionModal.js
deleted file mode 100644
index eb64a09804b..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/WNSActionModal.js
+++ /dev/null
@@ -1,261 +0,0 @@
-import { Loader, Modal, FormComposer } from "@egovernments/digit-ui-react-components";
-import React, { useState, useEffect } from "react";
-import { configWSApproverApplication, configWSDisConnectApplication } from "../config";
-import * as predefinedConfig from "../config";
-import cloneDeep from "lodash/cloneDeep";
-
-
-const Heading = (props) => {
- return {props.label}
;
-};
-
-const Close = () => (
-
-);
-
-const CloseBtn = (props) => {
- return (
-
-
-
- );
-};
-
-const convertDateToEpochNew = (dateString, dayStartOrEnd = "dayend") => {
- //example input format : "2018-10-02"
- try {
- const parts = dateString.match(/(\d{4})-(\d{1,2})-(\d{1,2})/);
- const DateObj = new Date(Date.UTC(parts[1], parts[3] - 1, parts[2]));
-
- DateObj.setMinutes(DateObj.getMinutes() + DateObj.getTimezoneOffset());
- if (dayStartOrEnd === "dayend") {
- DateObj.setHours(DateObj.getHours() + 24);
- DateObj.setSeconds(DateObj.getSeconds() - 1);
- }
- return DateObj.getTime();
- } catch (e) {
- return dateString;
- }
-};
-
-const ActionModal = ({ t, action, tenantId, state, id, closeModal, submitAction, actionData, applicationData, businessService, moduleCode }) => {
- const { data: approverData, isLoading: PTALoading } = Digit.Hooks.useEmployeeSearch(
- tenantId,
- {
- roles: action?.assigneeRoles?.map?.((e) => ({ code: e })),
- isActive: true,
- },
- { enabled: !action?.isTerminateState }
- );
-
- const [config, setConfig] = useState({});
- const [defaultValues, setDefaultValues] = useState({});
- const [approvers, setApprovers] = useState([]);
- const [selectedApprover, setSelectedApprover] = useState({});
- const [file, setFile] = useState(null);
- const [uploadedFile, setUploadedFile] = useState(null);
- const [error, setError] = useState(null);
-
- useEffect(() => {
- setApprovers(approverData?.Employees?.map((employee) => ({ uuid: employee?.uuid, name: employee?.user?.name })));
- }, [approverData]);
-
- function selectFile(e) {
- setFile(e.target.files[0]);
- }
-
- useEffect(() => {
- (async () => {
- setError(null);
- if (file) {
- const allowedFileTypesRegex = /(.*?)(jpg|jpeg|png|image|pdf)$/i
- if (file.size >= 5242880) {
- setError(t("CS_MAXIMUM_UPLOAD_SIZE_EXCEEDED"));
- } else if (file?.type && !allowedFileTypesRegex.test(file?.type)) {
- setError(t(`NOT_SUPPORTED_FILE_TYPE`))
- } else {
- try {
- const response = await Digit.UploadServices.Filestorage("WS", file, Digit.ULBService.getCurrentTenantId());
- if (response?.data?.files?.length > 0) {
- setUploadedFile(response?.data?.files[0]?.fileStoreId);
- } else {
- setError(t("CS_FILE_UPLOAD_ERROR"));
- }
- } catch (err) {
- console.error("Modal -> err ", err);
- setError(t("CS_FILE_UPLOAD_ERROR"));
- }
- }
- }
- })();
- }, [file]);
-
- function submit(data) {
- if(applicationData?.isBillAmend){
- const comments = data?.comments ? data.comments : null
-
- const additionalDetails = { ...applicationData?.billAmendmentDetails?.additionalDetails, comments }
- const amendment = {
- ...applicationData?.billAmendmentDetails,
- workflow:{
- businessId:applicationData?.billAmendmentDetails?.amendmentId,
- action:action?.action,
- tenantId:tenantId,
- businessService:"BS.AMENDMENT",
- moduleName:"BS"
- },
- additionalDetails,
- comment: data?.comments || "",
- wfDocuments: uploadedFile
- ? [
- {
- documentType: action?.action + " DOC",
- fileName: file?.name,
- fileStoreId: uploadedFile,
- },
- ]
- : null,
- processInstance: {
- action: action?.action,
- assignes: !selectedApprover?.uuid ? [] : [{ uuid: selectedApprover?.uuid }],
- comment: data?.comments || "",
- documents: uploadedFile
- ? [
- {
- documentType: action?.action + " DOC",
- fileName: file?.name,
- fileStoreId: uploadedFile,
- },
- ]
- : []
- }
- }
- //amendment?.additionalDetails?.comments = comments
- submitAction({AmendmentUpdate:amendment})
- return
- }
- let workflow = { action: action?.action, comments: data?.comments, businessService, moduleName: moduleCode };
- applicationData = {
- ...applicationData,
- action: action?.action,
- comment: data?.comments || "",
- assignee: !selectedApprover?.uuid ? [] : [selectedApprover?.uuid],
- assignes: !selectedApprover?.uuid ? [] : [{ uuid: selectedApprover?.uuid }],
- wfDocuments: uploadedFile
- ? [
- {
- documentType: action?.action + " DOC",
- fileName: file?.name,
- fileStoreId: uploadedFile,
- },
- ]
- : null,
- processInstance: {
- ...applicationData?.processInstance,
- action: action?.action,
- assignes: !selectedApprover?.uuid ? [] : [{ uuid: selectedApprover?.uuid }],
- comment: data?.comments || "",
- documents: uploadedFile
- ? [
- {
- documentType: action?.action + " DOC",
- fileName: file?.name,
- fileStoreId: uploadedFile,
- },
- ]
- : []
- }
- };
-
- if (data?.date) {
- const connectionExecutionDate = cloneDeep(data?.date);
- applicationData.connectionExecutionDate = convertDateToEpochNew(connectionExecutionDate)
- }
- if (applicationData?.processInstance?.businessService == "DisconnectWSConnection" || applicationData?.processInstance?.businessService == "DisconnectSWConnection"){
- applicationData?.serviceType == "WATER" ?
- submitAction({ WaterConnection: applicationData, disconnectRequest: true }) :
- submitAction({ SewerageConnection: applicationData, disconnectRequest: true })
- } else {
- const adhocRebateData = sessionStorage.getItem("Digit.ADHOC_ADD_REBATE_DATA");
- const parsedAdhocRebateData = adhocRebateData ? JSON.parse(adhocRebateData) : "";
- if (parsedAdhocRebateData?.value?.adhocPenalty) applicationData.additionalDetails.adhocPenalty = parseInt(parsedAdhocRebateData?.value?.adhocPenalty) || "";
- if (parsedAdhocRebateData?.value?.adhocPenaltyComment) applicationData.additionalDetails.adhocPenaltyComment = parsedAdhocRebateData?.value?.adhocPenaltyComment || "";
- if (parsedAdhocRebateData?.value?.adhocPenaltyReason) applicationData.additionalDetails.adhocPenaltyReason = parsedAdhocRebateData?.value?.adhocPenaltyReason || "";
- if (parsedAdhocRebateData?.value?.adhocRebate) applicationData.additionalDetails.adhocRebate = parseInt(parsedAdhocRebateData?.value?.adhocRebate) || "";
- if (parsedAdhocRebateData?.value?.adhocRebateComment) applicationData.additionalDetails.adhocRebateComment = parsedAdhocRebateData?.value?.adhocRebateComment || "";
- if (parsedAdhocRebateData?.value?.adhocRebateReason) applicationData.additionalDetails.adhocRebateReason = parsedAdhocRebateData?.value?.adhocRebateReason || "";
- applicationData?.serviceType == "WATER" ? submitAction({ WaterConnection: applicationData }) : submitAction({ SewerageConnection: applicationData });
- }
- }
-
- useEffect(() => {
- if (applicationData?.processInstance?.businessService == "DisconnectWSConnection" || applicationData?.processInstance?.businessService == "DisconnectSWConnection") {
- if (action) {
- setConfig(
- configWSDisConnectApplication({
- t,
- action,
- approvers,
- selectedApprover,
- setSelectedApprover,
- selectFile,
- uploadedFile,
- setUploadedFile,
- businessService,
- error
- })
- );
- }
- } else {
- if (action) {
- setConfig(
- configWSApproverApplication({
- t,
- action,
- approvers,
- selectedApprover,
- setSelectedApprover,
- selectFile,
- uploadedFile,
- setUploadedFile,
- businessService,
- error
- })
- );
- }
- }
- }, [action, approvers, uploadedFile, error]);
-
- return action && config.form ? (
- }
- headerBarEnd={}
- actionCancelLabel={t(config.label.cancel)}
- actionCancelOnSubmit={closeModal}
- actionSaveLabel={t(config.label.submit)}
- actionSaveOnSubmit={() => { }}
- formId="modal-action"
- >
- {PTALoading ? (
-
- ) : (
-
- )}
-
- ) : (
-
- );
-};
-
-export default ActionModal;
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/WorksActionModal.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/WorksActionModal.js
deleted file mode 100644
index dd19cf33a1e..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/WorksActionModal.js
+++ /dev/null
@@ -1,262 +0,0 @@
-import { Loader, Modal, FormComposer } from "@egovernments/digit-ui-react-components";
-import React, { useState, useEffect } from "react";
-import { configApproveModal, configRejectModal, configCheckModal } from "../config";
-
-import cloneDeep from "lodash/cloneDeep";
-
-
-const Heading = (props) => {
- return {props.label}
;
-};
-
-const Close = () => (
-
-);
-
-const CloseBtn = (props) => {
- return (
-
-
-
- );
-};
-
-const convertDateToEpochNew = (dateString, dayStartOrEnd = "dayend") => {
- //example input format : "2018-10-02"
- try {
- const parts = dateString.match(/(\d{4})-(\d{1,2})-(\d{1,2})/);
- const DateObj = new Date(Date.UTC(parts[1], parts[3] - 1, parts[2]));
-
- DateObj.setMinutes(DateObj.getMinutes() + DateObj.getTimezoneOffset());
- if (dayStartOrEnd === "dayend") {
- DateObj.setHours(DateObj.getHours() + 24);
- DateObj.setSeconds(DateObj.getSeconds() - 1);
- }
- return DateObj.getTime();
- } catch (e) {
- return dateString;
- }
-};
-
-
-const WorksActionModal = ({ t, action, tenantId, state, id, closeModal, submitAction, actionData, applicationData, businessService, moduleCode,applicationDetails,workflowDetails }) => {
- //here according to the action selected render appropriate modal
-
- // const { data: approverData, isLoading: PTALoading } = Digit.Hooks.useEmployeeSearch(
- // tenantId,
- // {
- // roles: action?.assigneeRoles?.map?.((e) => ({ code: e })),
- // isActive: true,
- // },
- // { enabled: !action?.isTerminateState }
- // );
- let { loiNumber, estimateNumber } = Digit.Hooks.useQueryParams();
- const [config, setConfig] = useState({});
- const [approvers, setApprovers] = useState([]);
- const [selectedApprover, setSelectedApprover] = useState({});
-
- const [department, setDepartment] = useState([]);
- const [selectedDept,setSelectedDept] = useState({})
-
- const [rejectionReason, setRejectionReason] = useState([]);
- const [selectedReason,setSelectedReason] = useState([])
-
- const [designation, setDesignation] = useState([]);
- const [selectedDesignation,setSelectedDesignation] = useState({})
-
- //get approverDept,designation,approver(hrms),rejectionReason
-
- const rejectReasons = [
- {
- name: "Estimate Details are incorrect"
- },
- {
- name: "Financial Details are incorrect"
- },
- {
- name: "Agreement Details are incorrect"
- },
- {
- name: "Vendor Details are incorrect"
- },
- {
- name: "Attachments provided are wrong"
- },
- {
- name: "Others"
- },
- ]
-
- const { isLoading: mdmsLoading, data: mdmsData,isSuccess:mdmsSuccess } = Digit.Hooks.useCustomMDMS(
- Digit.ULBService.getCurrentTenantId(),
- "common-masters",
- [
- {
- "name": "Designation"
- },
- {
- "name": "Department"
- }
- ]
- );
-
- mdmsData?.["common-masters"]?.Designation?.map(designation => {
- designation.i18nKey = `ES_COMMON_DESIGNATION_${designation?.name}`
- })
-
- mdmsData?.["common-masters"]?.Department?.map(department => {
- department.i18nKey = `ES_COMMON_${department?.code}`
- })
- // const { data: approverData, isLoading: approverLoading } = Digit.Hooks.useEmployeeSearch(
- // tenantId,
- // {
- // roles: action?.assigneeRoles?.map?.((e) => ({ code: e })),
- // isActive: true,
- // },
- // { enabled: !action?.isTerminateState }
- // );
-
-
- // const { isLoading: approverLoading, isError,isSuccess:approverSuccess, error, data: employeeDatav1 } = Digit.Hooks.hrms.useHRMSSearch({ Designation: selectedDesignation?.code, Department: selectedDept?.code }, Digit.ULBService.getCurrentTenantId(), null, null, { enabled: !!(selectedDept?.code && selectedDesignation?.code) });
- // employeeDatav1?.Employees.map(emp => emp.nameOfEmp = emp.user.name)
-
-
- // useEffect(() => {
-
- // setApprovers(approverData?.Employees?.map((employee) => ({ uuid: employee?.uuid, name: employee?.user?.name })));
- // }, [approverData]);
-
- useEffect(() => {
-
- //setApprovers(approverData?.Employees?.map((employee) => ({ uuid: employee?.uuid, name: employee?.user?.name })));
- //setApprovers(employeeDatav1?.Employees?.length > 0 ? employeeDatav1?.Employees : [])
- setDepartment(mdmsData?.["common-masters"]?.Department)
- setDesignation(mdmsData?.["common-masters"]?.Designation)
- setRejectionReason(rejectReasons)
- }, [mdmsData]);
-
-
-
- const { isLoading: approverLoading, isError, error, data: employeeDatav1 } = Digit.Hooks.hrms.useHRMSSearch({ designations: selectedDesignation?.code, departments: selectedDept?.code, roles: action?.assigneeRoles?.toString(), isActive: true }, Digit.ULBService.getCurrentTenantId(), null, null, { enabled: action?.action === "CHECK" || action?.action === "TECHNICALSANCATION"});
-
-
- employeeDatav1?.Employees.map(emp => emp.nameOfEmp = emp?.user?.name || "NA")
-
- useEffect(() => {
- setApprovers(employeeDatav1?.Employees?.length > 0 ? employeeDatav1?.Employees.filter(emp => emp?.nameOfEmp !== "NA") : [])
- }, [employeeDatav1])
-
-
- // if (employeeDatav1?.Employees?.length > 0) {
- // setApprovers(employeeDatav1?.Employees)
- // }
-
- useEffect(() => {
-
- if(action?.action?.includes("CHECK") || action?.action?.includes("TECHNICALSANCATION")){
- setConfig(
- configCheckModal({
- t,
- action,
- businessService,
- approvers,
- selectedApprover,
- setSelectedApprover,
- designation,
- selectedDesignation,
- setSelectedDesignation,
- department,
- selectedDept,
- setSelectedDept,
- approverLoading
- })
- )
- }else if(action?.action?.includes("APPROVE") || action?.action?.includes("ADMINSANCTION")){
- setConfig(
- configApproveModal({
- t,
- action
- })
- )
- }
- else if(action?.action?.includes("REJECT")){
- setConfig(
- configRejectModal({
- t,
- action,
- rejectReasons,
- selectedReason,
- setSelectedReason,
- loiNumber,
- department,
- estimateNumber
- })
- )
- }
- }, [approvers,designation,department]);
-
-
- function submit (_data) {
- //make the update object here and call submitAction
- //if the action is reject then you need to make a search call and get creater's uuid
- const workflow = {
- action: action?.action,
- comment: _data?.comments,
- assignees: selectedApprover?.uuid ? [selectedApprover?.uuid] : undefined
- }
-
- if(action?.action.includes("REJECT")) {
- workflow.assignee = [applicationData?.auditDetails?.createdBy]
- }
-
- Object.keys(workflow).forEach(key => {
- if (workflow[key] === undefined) {
- delete workflow[key];
- }
- });
- {estimateNumber ? submitAction({estimate:applicationData,workflow}) :
- submitAction({letterOfIndent:applicationData,workflow})}
-
- }
-
- // if(mdmsLoading || approverLoading ) {
- // return
- // }
-
-
-
-
-
- return action && config?.form ? (
- }
- headerBarEnd={}
- actionCancelLabel={t(config.label.cancel)}
- actionCancelOnSubmit={closeModal}
- actionSaveLabel={t(config.label.submit)}
- actionSaveOnSubmit={() => { }}
- formId="modal-action"
- >
- {mdmsLoading ? (
-
- ) : (
-
- )}
-
- ) : (
-
- );
-}
-
-export default WorksActionModal
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/index.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/index.js
deleted file mode 100644
index 56465790b8b..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/Modal/index.js
+++ /dev/null
@@ -1,49 +0,0 @@
-import React, { useState, useEffect } from "react";
-import FSMActionModal from "./FSMActionModal";
-import PTActionModal from "./PTActionModal";
-import TLActionModal from "./TLActionModal";
-import BPAREGActionModal from "./BPAREGActionModal";
-import BPAActionModal from "./BPAActionModal";
-import NOCActionModal from "./NOCActionModal";
-import WNSActionModal from "./WNSActionModal";
-import WorksActionModal from "./WorksActionModal";
-import AttendanceActionModal from "./AttendanceActionModal";
-import ExpenditureActionModal from "./ExpenditureActionModal";
-
-const ActionModal = (props) => {
- if (props?.businessService.includes("PT")) {
- return ;
- }
-
- if (props?.businessService.includes("NewTL") || props?.businessService.includes("TL") || props?.businessService.includes("EDITRENEWAL") || props?.businessService.includes("DIRECTRENEWAL")) {
- return ;
- }
-
- if (props?.moduleCode.includes("BPAREG")) {
- return ;
- }
-
- if (props?.moduleCode.includes("BPA")) {
- return ;
- }
-
- if (props?.moduleCode.includes("NOC")) {
- return ;
- }
-
- if (props?.moduleCode.includes("WS")) {
- return ;
- }
- if (props?.moduleCode.includes("works")) {
- return ;
- }
- if (props?.moduleCode.includes("AttendenceMgmt")) {
- return ;
- }
- if (props?.moduleCode.includes("Expenditure")) {
- return ;
- }
-
-};
-
-export default ActionModal;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/ApplicationDetailsActionBar.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/ApplicationDetailsActionBar.js
deleted file mode 100644
index 7ad3a0f95ce..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/ApplicationDetailsActionBar.js
+++ /dev/null
@@ -1,80 +0,0 @@
-import React, {useEffect, useRef} from "react";
-import { useTranslation } from "react-i18next";
-import { SubmitBar, ActionBar, Menu } from "@egovernments/digit-ui-react-components";
-
-function ApplicationDetailsActionBar({ workflowDetails, displayMenu, onActionSelect, setDisplayMenu, businessService, forcedActionPrefix,ActionBarStyle={},MenuStyle={}, saveAttendanceState }) {
- const { t } = useTranslation();
- let user = Digit.UserService.getUser();
- const menuRef = useRef();
- if (window.location.href.includes("/obps") || window.location.href.includes("/noc")) {
- const userInfos = sessionStorage.getItem("Digit.citizen.userRequestObject");
- const userInfo = userInfos ? JSON.parse(userInfos) : {};
- user = userInfo?.value;
- }
- const userRoles = user?.info?.roles?.map((e) => e.code);
- let isSingleButton = false;
- let isMenuBotton = false;
- let actions = workflowDetails?.data?.actionState?.nextActions?.filter((e) => {
- return userRoles.some((role) => e.roles?.includes(role)) || !e.roles;
- }) || workflowDetails?.data?.nextActions?.filter((e) => {
- return userRoles.some((role) => e.roles?.includes(role)) || !e.roles;
- });
-
- const closeMenu = () => {
- setDisplayMenu(false);
- }
- Digit.Hooks.useClickOutside(menuRef, closeMenu, displayMenu );
-
- if (((window.location.href.includes("/obps") || window.location.href.includes("/noc")) && actions?.length == 1) || (actions?.[0]?.redirectionUrl?.pathname.includes("/pt/property-details/")) && actions?.length == 1) {
- isMenuBotton = false;
- isSingleButton = true;
- } else if (actions?.length > 0) {
- isMenuBotton = true;
- isSingleButton = false;
- }
-
- if(saveAttendanceState?.displaySave) {
- isMenuBotton = false;
- isSingleButton = true;
- actions = [
- {
- action: "SAVE",
- state: "UPDATED"
- }
- ]
- }
-
- return (
-
- {!workflowDetails?.isLoading && isMenuBotton && !isSingleButton && (
-
- {displayMenu && (workflowDetails?.data?.actionState?.nextActions || workflowDetails?.data?.nextActions) ? (
-
- ) : null}
- setDisplayMenu(!displayMenu)} />
-
- )}
- {!workflowDetails?.isLoading && !isMenuBotton && isSingleButton && (
-
- { onActionSelect(actions?.[0] || {})}}>
- {t(`${forcedActionPrefix || `WF_EMPLOYEE_${businessService?.toUpperCase()}`}_${actions?.[0]?.action}`)}
-
-
- )}
-
- );
-}
-
-export default ApplicationDetailsActionBar;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/ApplicationDetailsContent.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/ApplicationDetailsContent.js
deleted file mode 100644
index 5596d7b694b..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/ApplicationDetailsContent.js
+++ /dev/null
@@ -1,484 +0,0 @@
-import {
- BreakLine,
- Card,
- CardSectionHeader,
- CardSubHeader,
- CheckPoint,
- CollapseAndExpandGroups,
- ConnectingCheckPoints,
- ViewImages,
- Loader,
- Row,
- StatusTable,
- Table,
-} from "@egovernments/digit-ui-react-components";
-import { values } from "lodash";
-import React, { Fragment, useCallback, useReducer, useState } from "react";
-import { useTranslation } from "react-i18next";
-import { Link } from "react-router-dom";
-import BPADocuments from "./BPADocuments";
-import InspectionReport from "./InspectionReport";
-import NOCDocuments from "./NOCDocuments";
-import PermissionCheck from "./PermissionCheck";
-import PropertyDocuments from "./PropertyDocuments";
-import PropertyEstimates from "./PropertyEstimates";
-import PropertyFloors from "./PropertyFloors";
-import PropertyOwners from "./PropertyOwners";
-import ScruntinyDetails from "./ScruntinyDetails";
-import SubOccupancyTable from "./SubOccupancyTable";
-import TLCaption from "./TLCaption";
-import TLTradeAccessories from "./TLTradeAccessories";
-import TLTradeUnits from "./TLTradeUnits";
-//import WSAdditonalDetails from "./WSAdditonalDetails";
-import WSFeeEstimation from "./WSFeeEstimation";
-//import WSInfoLabel from "../../../ws/src/pageComponents/WSInfoLabel";
-import DocumentsPreview from "./DocumentsPreview";
-import InfoDetails from "./InfoDetails";
-import ViewBreakup from "./ViewBreakup";
-import SubWorkTableDetails from "./SubWorkTableDetails";
-
-
-
-function ApplicationDetailsContent({
- applicationDetails,
- workflowDetails,
- isDataLoading,
- applicationData,
- businessService,
- timelineStatusPrefix,
- showTimeLine = true,
- statusAttribute = "status",
- paymentsList,
- oldValue,
- isInfoLabel = false,
- noBoxShadow = false,
- sectionHeadStyle = false,
- modify,
- setSaveAttendanceState
-}) {
- const { t } = useTranslation();
- const [localSearchParams, setLocalSearchParams] = useState(() => ({}));
-
-
- const handleDateRangeChange = useCallback((data) => {
- setLocalSearchParams(() => ({ ...data }));
- }, []);
-
- function OpenImage(imageSource, index, thumbnailsToShow) {
- window.open(thumbnailsToShow?.fullImage?.[0], "_blank");
- }
-
- const convertEpochToDateDMY = (dateEpoch) => {
- if (dateEpoch == null || dateEpoch == undefined || dateEpoch == "") {
- return "NA";
- }
- const dateFromApi = new Date(dateEpoch);
- let month = dateFromApi.getMonth() + 1;
- let day = dateFromApi.getDate();
- let year = dateFromApi.getFullYear();
- month = (month > 9 ? "" : "0") + month;
- day = (day > 9 ? "" : "0") + day;
- return `${day}/${month}/${year}`;
- };
- const getTimelineCaptions = (checkpoint) => {
- if (checkpoint.state === "OPEN" || (checkpoint.status === "INITIATED" && !window.location.href.includes("/obps/"))) {
- const caption = {
- date: convertEpochToDateDMY(applicationData?.auditDetails?.createdTime),
- source: applicationData?.channel || "",
- };
- return ;
- } else if (window.location.href.includes("/obps/") || window.location.href.includes("/noc/") || window.location.href.includes("/ws/")) {
- //From BE side assigneeMobileNumber is masked/unmasked with connectionHoldersMobileNumber and not assigneeMobileNumber
- const privacy = { uuid: checkpoint?.assignes?.[0]?.uuid, fieldName: ["connectionHoldersMobileNumber"], model: "WaterConnectionOwner" };
- const caption = {
- date: checkpoint?.auditDetails?.lastModified,
- name: checkpoint?.assignes?.[0]?.name,
- mobileNumber:
- applicationData?.processInstance?.assignes?.[0]?.uuid === checkpoint?.assignes?.[0]?.uuid &&
- applicationData?.processInstance?.assignes?.[0]?.mobileNumber
- ? applicationData?.processInstance?.assignes?.[0]?.mobileNumber
- : checkpoint?.assignes?.[0]?.mobileNumber,
- comment: t(checkpoint?.comment),
- wfComment: checkpoint.wfComment,
- thumbnailsToShow: checkpoint?.thumbnailsToShow,
- };
- return ;
- } else {
- const caption = {
- date: `${Digit.DateUtils?.ConvertTimestampToDate(checkpoint.auditDetails.lastModifiedEpoch)} ${Digit.DateUtils?.ConvertEpochToTimeInHours(
- checkpoint.auditDetails.lastModifiedEpoch
- )} ${Digit.DateUtils?.getDayfromTimeStamp(checkpoint.auditDetails.lastModifiedEpoch)}`,
- // name: checkpoint?.assigner?.name,
- name: checkpoint?.assignes?.[0]?.name,
- // mobileNumber: checkpoint?.assigner?.mobileNumber,
- wfComment: checkpoint?.wfComment,
- mobileNumber: checkpoint?.assignes?.[0]?.mobileNumber,
- };
-
- return ;
- }
- };
-
- const getTranslatedValues = (dataValue, isNotTranslated) => {
- if (dataValue) {
- return !isNotTranslated ? t(dataValue) : dataValue;
- } else {
- return t("NA");
- }
- };
-
- const checkLocation =
- window.location.href.includes("employee/tl") || window.location.href.includes("employee/obps") || window.location.href.includes("employee/noc");
- const isNocLocation = window.location.href.includes("employee/noc");
- const isBPALocation = window.location.href.includes("employee/obps");
- let isWS = window.location.href.includes("employee/ws") || window.location.href.includes("employee/works")|| window.location.href.includes("employee/project") || window.location.href.includes("employee/estimate") ;
-
-
-
- const getRowStyles = (tab="") => {
-
- if (window.location.href.includes("employee/obps") || window.location.href.includes("employee/noc")) {
- return { justifyContent: "space-between", fontSize: "16px", lineHeight: "19px", color: "#0B0C0C" };
- } else if (checkLocation) {
- return { justifyContent: "space-between", fontSize: "16px", lineHeight: "19px", color: "#0B0C0C" };
- }
- else if ( tab==="fieldSurvey") {
- return {
- justifyContent: "space-between", flexDirection:"column"
- }
- }
- else {
- return {};
- }
-
- };
- const getTextStyles = (tab="") => {
- if ( tab==="fieldSurvey" ) {
- return {
- marginTop:"1rem",
- marginBottom:"1rem"
- }
- }
- else {
- return {};
- }
-
- };
- const getLabelStyles = (tab = "") => {
- if ( tab === "fieldSurvey") {
- return {
- width:"100%"
- }
- }
- else {
- return {};
- }
-
- };
-
- const getTableStyles = () => {
- if (window.location.href.includes("employee/obps") || window.location.href.includes("employee/noc")) {
- return { position: "relative", marginTop: "19px" };
- } else if (checkLocation) {
- return { position: "relative", marginTop: "19px" };
- } else {
- return {};
- }
- };
-
- const getMainDivStyles = () => {
- if (
- window.location.href.includes("employee/obps") ||
- window.location.href.includes("employee/noc") ||
- window.location.href.includes("employee/ws") ||
- window.location.href.includes("employee/works") ||
- window.location.href.includes("employee/contracts")
- ) {
- return { lineHeight: "19px", maxWidth: "950px", minWidth: "280px" };
- } else if (checkLocation) {
- return { lineHeight: "19px", maxWidth: "600px", minWidth: "280px" };
- } else {
- return {};
- }
- };
-
- const getTextValue = (value) => {
- if (value?.skip) return value.value;
- else if (value?.isUnit) return value?.value ? `${getTranslatedValues(value?.value, value?.isNotTranslated)} ${t(value?.isUnit)}` : t("N/A");
- else if (value?.value === "Approved") return { `${getTranslatedValues(value?.value, value?.isNotTranslated)}`}
- else if (value?.value === "Rejected") return {t(value?.value)}
- else return value?.value ? getTranslatedValues(value?.value, value?.isNotTranslated) : t("N/A");
- };
-
- const getClickInfoDetails = () => {
- if (window.location.href.includes("disconnection") || window.location.href.includes("application")) {
- return "WS_DISCONNECTION_CLICK_ON_INFO_LABEL";
- } else {
- return "WS_CLICK_ON_INFO_LABEL";
- }
- };
-
- const getClickInfoDetails1 = () => {
- if (window.location.href.includes("disconnection") || window.location.href.includes("application")) {
- return "WS_DISCONNECTION_CLICK_ON_INFO1_LABEL";
- } else {
- return "";
- }
- };
-
- const getCardStyles = () => {
- let styles = { position: "relative" }
- if (noBoxShadow) styles = { ...styles, boxShadow: "none" };
- return styles;
- };
-
- return (
-
-
- {isInfoLabel ? (
-
- ) : null}
- {applicationDetails?.applicationDetails?.map((detail, index) => (
-
-
-
- {index === 0 && !detail.asSectionHeader ? (
-
{t(detail.title)}
- ) : (
-
-
- {isNocLocation ? `${t(detail.title)}` : t(detail.title)}
- {detail?.Component ? : null}
-
-
- )}
- {/* TODO, Later will move to classes */}
- {/* Here Render the table for adjustment amount details detail.isTable is true for that table*/}
- {/* {detail?.isTable && (
-
-
- {detail?.headers.map((header) => (
- {t(header)} |
- ))}
-
-
- {detail?.tableRows.map((row,index)=>{
- if(index===detail?.tableRows.length - 1){
- return <>
-
-
- {row.map(element => {t(element)} | )}
-
- >
- }
- return
- {row.map(element => {t(element)} | )}
-
})}
-
- )} */}
- {detail?.isTable &&
}
-
-
- {detail?.title &&
- !detail?.title.includes("NOC") &&
- detail?.values?.map((value, index) => {
- if (value.map === true && value.value !== "N/A") {
- return
} />;
- }
- if (value?.isLink == true) {
- return (
-
-
-
- {t(value?.title)}
-
-
-
- ) : isNocLocation || isBPALocation ? (
- `${t(value.title)}`
- ) : (
- t(value.title)
- )
- }
- text={
-
-
-
- {value?.value}
-
-
-
- }
- last={index === detail?.values?.length - 1}
- caption={value.caption}
- className="border-none"
- rowContainerStyle={getRowStyles()}
- />
- );
- }
- return (
- { }} />: getTextValue(value)}
- last={index === detail?.values?.length - 1}
- caption={value.caption}
- className="border-none"
- /* privacy object set to the Row Component */
- privacy={value?.privacy}
- // TODO, Later will move to classes
- rowContainerStyle={getRowStyles(detail?.tab)}
- textStyle={getTextStyles(detail?.tab)}
- labelStyle={getLabelStyles(detail?.tab)}
- />
- );
- })}
-
-
-
-
- {detail?.additionalDetails?.table
- ? detail?.additionalDetails?.table?.weekTable?.tableHeader && (
- <>
-
- {t(detail?.additionalDetails?.table?.weekTable?.tableHeader)}
-
- >
- )
- : null}
-
- {detail?.additionalDetails?.inspectionReport && (
-
- )}
- {applicationDetails?.applicationData?.additionalDetails?.fieldinspection_pending?.length > 0 && detail?.additionalDetails?.fiReport && (
-
- )}
- {/* {detail?.additionalDetails?.FIdocuments && detail?.additionalDetails?.values?.map((doc,index) => (
-
- {doc.isNotDuplicate &&
-
-
-
-
-
-
}
-
- )) } */}
- {detail?.additionalDetails?.floors && }
- {detail?.additionalDetails?.owners && }
- {detail?.additionalDetails?.units && }
- {detail?.additionalDetails?.accessories && }
- {detail?.additionalDetails?.permissions && workflowDetails?.data?.nextActions?.length > 0 && (
-
- )}
- {detail?.additionalDetails?.obpsDocuments && (
-
- )}
- {detail?.additionalDetails?.noc && (
-
- )}
- {detail?.additionalDetails?.scruntinyDetails && }
- {detail?.additionalDetails?.buildingExtractionDetails && }
- {detail?.additionalDetails?.subOccupancyTableDetails && (
-
- )}
- {detail?.additionalDetails?.documentsWithUrl && }
- {detail?.additionalDetails?.documents && }
- {detail?.additionalDetails?.taxHeadEstimatesCalculation && (
-
- )}
- {/* {detail?.isWaterConnectionDetails && } */}
- {detail?.additionalDetails?.redirectUrl && (
-
-
-
- {detail?.additionalDetails?.redirectUrl?.title}
-
-
-
- )}
- {detail?.additionalDetails?.estimationDetails && }
- {detail?.additionalDetails?.estimationDetails && }
-
-
- ))}
- {showTimeLine && workflowDetails?.data?.timeline?.length > 0 && (
-
- {workflowDetails?.breakLineRequired === undefined ? : workflowDetails?.breakLineRequired ? : null}
- {(workflowDetails?.isLoading || isDataLoading) && }
- {!workflowDetails?.isLoading && !isDataLoading && (
-
-
- {/* {t("ES_APPLICATION_DETAILS_APPLICATION_TIMELINE")} */}
- {t("WORKS_WORKFLOW_HISTORY")}
-
- {workflowDetails?.data?.timeline && workflowDetails?.data?.timeline?.length === 1 ? (
-
- ) : (
-
- {workflowDetails?.data?.timeline &&
- workflowDetails?.data?.timeline.map((checkpoint, index, arr) => {
- return (
-
-
-
- );
- })}
-
- )}
-
- )}
-
- )}
-
-
- );
-}
-
-export default ApplicationDetailsContent;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/ApplicationDetailsToast.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/ApplicationDetailsToast.js
deleted file mode 100644
index 9540495f32a..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/ApplicationDetailsToast.js
+++ /dev/null
@@ -1,74 +0,0 @@
-import React from "react";
-import { Toast } from "@egovernments/digit-ui-react-components";
-
-function ApplicationDetailsToast({ t, showToast, closeToast, businessService }) {
- if (businessService?.includes("NewTL") || businessService?.includes("TL") || businessService?.includes("EDITRENEWAL")) {
- let label = "";
- switch (showToast?.action?.action) {
- case "SENDBACK":
- label = showToast?.key === "error" ? showToast?.error?.message : t("TL_SENDBACK_CHECKLIST_MESSAGE_HEAD");
- break;
- case "FORWARD":
- label = showToast?.key === "error" ? showToast?.error?.message : t("TL_FORWARD_SUCCESS_MESSAGE_MAIN");
- break;
- case "APPROVE":
- label = showToast?.key === "error" ? showToast?.error?.message : t("TL_APPROVAL_CHECKLIST_MESSAGE_HEAD");
- break;
- case "SENDBACKTOCITIZEN":
- label = showToast?.key === "error" ? showToast?.error?.message : t("TL_SENDBACK_TOCITIZEN_CHECKLIST_MESSAGE_HEAD");
- break;
- case "REJECT":
- label = showToast?.key === "error" ? showToast?.error?.message : t("TL_APPROVAL_REJ_MESSAGE_HEAD");
- break;
- case "RESUBMIT":
- label = showToast?.key === "error" ? showToast?.error?.message : t("TL_APPLICATION_RESUBMIT_SUCCESS_MESSAGE_MAIN");
- break;
- case "CANCEL":
- label = showToast?.key === "error" ? showToast?.error?.message : t("TL_TL_CANCELLED_MESSAGE_HEAD");
- break;
- default:
- label = showToast?.key === "error" ? showToast?.error?.message : t(`ES_${businessService}_${showToast?.action?.action}_UPDATE_SUCCESS`);
- }
- return {showToast && };
- } else if (businessService?.includes("BPA") || businessService?.includes("BPA_LOW") || businessService?.includes("BPA_OC")) {
- const getMessage = (messages = []) => {
- let returnValue = messages[0];
- if(messages?.length == 2) returnValue = businessService?.includes("BPA_OC") ? t(messages[1]) : t(messages [0]);
- else returnValue = t(messages[0]);
- return returnValue;
- }
- let label = "";
- switch (showToast?.action?.action) {
- case "REVOCATE":
- label = showToast?.key === "error" ? showToast?.error?.message : getMessage(["BPA_APPROVAL_REVOCATED_MESSAGE_HEAD", "BPA_APPROVAL_OC_REVOCATED_MESSAGE_HEAD"]);
- break;
- case "VERIFY_AND_FORWARD":
- label = showToast?.key === "error" ? showToast?.error?.message : getMessage(["BPA_FORWARD_SUCCESS_MESSAGE_MAIN"]);
- break;
- case "SEND_BACK_TO_CITIZEN":
- label = showToast?.key === "error" ? showToast?.error?.message : getMessage(["BPA_SENDBACK_SUCCESS_MESSAGE_MAIN"]);
- break;
- case "APPROVE":
- label = showToast?.key === "error" ? showToast?.error?.message : getMessage(["BPA_APPROVAL_CHECKLIST_MESSAGE_HEAD"]);
- break;
- case "REJECT":
- label = showToast?.key === "error" ? showToast?.error?.message : getMessage(["BPA_APPROVAL_REJECTED_MESSAGE_HEAD", "BPA_OC_APPROVAL_REJECTED_MESSAGE_HEAD"]);
- break;
- case "FORWARD":
- label = showToast?.key === "error" ? showToast?.error?.message : getMessage(["BPA_FORWARD_SUCCESS_MESSAGE_MAIN"]);
- break;
- case "SEND_BACK_FOR_DOCUMENT_VERIFICATION":
- case "SEND_BACK_FOR_FIELD_INSPECTION":
- label = showToast?.key === "error" ? showToast?.error?.message : getMessage(["BPA_SENDBACK_SUCCESS_MESSAGE_MAIN"]);
- break;
- default:
- label = showToast?.key === "error" ? showToast?.error?.message : t(`ES_${businessService}_${showToast?.action?.action}_UPDATE_SUCCESS`);
- }
- return {showToast && };
- } else {
- const label = showToast?.key === "error" ? showToast?.error?.message : `ES_${businessService}_${showToast?.action?.action}_UPDATE_SUCCESS`;
- return {showToast && };
- }
-}
-
-export default ApplicationDetailsToast;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/ApplicationDetailsWarningPopup.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/ApplicationDetailsWarningPopup.js
deleted file mode 100644
index e95b9e038cd..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/ApplicationDetailsWarningPopup.js
+++ /dev/null
@@ -1,54 +0,0 @@
-import { Card, ButtonSelector, CardText, CardSubHeader, Modal, CardSectionHeader, Row } from "@egovernments/digit-ui-react-components";
-import React from "react";
-import { useTranslation } from "react-i18next";
-
-const Close = () => (
-
- );
-
-const CloseBtn = (props) => {
- return (
-
-
-
- );
- };
-
-function ApplicationDetailsWarningPopup({ action,workflowDetails,businessService,isWarningPop,closeWarningPopup }) {
-const { t } = useTranslation();
-const isMobile = window.Digit.Utils.browser.isMobile();
-return (
-
- {t("PT_DUES_ARE_PENDING")}}
- headerBarEnd={
- {
- closeWarningPopup();
- }}
- />
- }
- hideSubmit={true}
- isDisabled={false}
- popupStyles={isMobile ? {} : { width: "29%", marginTop: "auto" }}
- >
-
-
-
{t("PT_YOU_HAVE")} ₹{action?.AmountDueForPay} {t("PT_DUE_WARNING_MSG2")}
-
-
-
-
- window.location.assign(`${window.location.origin}${action?.redirectionUrl?.pathname}`)} style={{ marginLeft: "10px" }} />
-
-
-
- )
-
-)
-}
-
-export default ApplicationDetailsWarningPopup;
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/BPADocuments.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/BPADocuments.js
deleted file mode 100644
index 9a1febe081b..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/BPADocuments.js
+++ /dev/null
@@ -1,234 +0,0 @@
-import React, { useEffect, useState } from "react";
-import {
- CardLabel,
- Dropdown,
- LabelFieldPair,
- MultiUploadWrapper,
- CardSubHeader
-} from "@egovernments/digit-ui-react-components";
-import DocumentsPreview from "./DocumentsPreview";
-
-const BPADocuments = ({ t, formData, applicationData, docs, bpaActionsDetails }) => {
- const applicationStatus = applicationData?.status || "";
- const actions = bpaActionsDetails?.data?.nextActions || [];
- const stateId = Digit.ULBService.getStateId();
- const [documents, setDocuments] = useState(formData?.documents?.documents || []);
- const [error, setError] = useState(null);
- const [bpaTaxDocuments, setBpaTaxDocuments] = useState([]);
- const [enableSubmit, setEnableSubmit] = useState(true)
- const [checkRequiredFields, setCheckRequiredFields] = useState(false);
- const [checkEnablingDocs, setCheckEnablingDocs] = useState(false);
-
- const { isLoading: bpaDocsLoading, data: bpaDocs } = Digit.Hooks.obps.useMDMS(stateId, "BPA", ["DocTypeMapping"]);
- const { isLoading: commonDocsLoading, data: commonDocs } = Digit.Hooks.obps.useMDMS(stateId, "common-masters", ["DocumentType"]);
-
- useEffect(() => {
- let filtredBpaDocs = [];
- if (bpaDocs?.BPA?.DocTypeMapping) {
- // filtredBpaDocs = bpaDocs?.BPA?.DocTypeMapping?.filter(data => (data.WFState == "INPROGRESS"))
- filtredBpaDocs = bpaDocs?.BPA?.DocTypeMapping?.filter(data => (data.WFState == applicationData?.status ? applicationData?.status : "INPROGRESS" && data.RiskType == applicationData?.riskType && data.ServiceType == applicationData?.additionalDetails?.serviceType && data.applicationType == applicationData?.additionalDetails?.applicationType))
- }
- let documentsList = [];
- filtredBpaDocs?.[0]?.docTypes?.forEach(doc => {
- let code = doc.code; doc.dropdownData = []; doc.uploadedDocuments = [];
- commonDocs?.["common-masters"]?.DocumentType?.forEach(value => {
- let values = value.code.slice(0, code.length);
- if (code === values) {
- doc.hasDropdown = true;
- value.i18nKey = value.code;
- doc.dropdownData.push(value);
- }
- });
- doc.uploadedDocuments[0] = {};
- doc.uploadedDocuments[0].values = [];
- docs?.[0]?.values?.map(upDocs => {
- if (code === `${upDocs?.documentType?.split('.')[0]}.${upDocs?.documentType?.split('.')[1]}`) {
- doc.uploadedDocuments[0].values.push(upDocs)
- }
- })
- documentsList.push(doc);
- });
- sessionStorage.setItem("BPA_DOCUMENTS", JSON.stringify(documentsList));
- setBpaTaxDocuments(documentsList);
-
- }, [!bpaDocsLoading, !commonDocsLoading]);
-
- useEffect(() => {
- let count = 0;
- bpaTaxDocuments.map(doc => {
- let isRequired = false;
- documents.map(data => {
- if (doc.required && doc.code == `${data.documentType.split('.')[0]}.${data.documentType.split('.')[1]}`) {
- isRequired = true;
- }
- });
- if (!isRequired && doc.required) {
- count = count + 1;
- }
- });
- if ((count == "0" || count == 0) && documents.length > 0) setEnableSubmit(false);
- else setEnableSubmit(true);
- }, [documents, checkRequiredFields])
-
- useEffect(() => {
- if ( applicationStatus === "DOC_VERIFICATION_INPROGRESS" && actions?.length > 0 ) setCheckEnablingDocs(true);
- else setCheckEnablingDocs(false);
- }, [applicationData, bpaActionsDetails])
-
- return (
-
- {bpaTaxDocuments?.map((document, index) => {
- return (
-
-
-
- );
- })}
-
- );
-}
-
-function SelectDocument({
- t,
- document: doc,
- setDocuments,
- error,
- setError,
- documents,
- setCheckRequiredFields,
- index,
- applicationStatus,
- actions,
- bpaTaxDocuments,
- checkEnablingDocs
-}) {
-
- const filteredDocument = documents?.filter((item) => item?.documentType?.includes(doc?.code))[0];
- const tenantId = Digit.ULBService.getStateId();
- const [selectedDocument, setSelectedDocument] = useState(
- filteredDocument
- ? { ...filteredDocument, active: true, code: filteredDocument?.documentType, i18nKey: filteredDocument?.documentType }
- : doc?.dropdownData?.length === 1
- ? doc?.dropdownData[0]
- : {}
- );
- const [file, setFile] = useState(null);
- const [uploadedFile, setUploadedFile] = useState(() => filteredDocument?.fileStoreId || null);
- const [selectArrayFiles, SetSelectArrayFiles] = useState([]);
- const handleSelectDocument = (value) => setSelectedDocument(value);
- const allowedFileTypes = /(.*?)(jpg|jpeg|png|image|pdf)$/i;
-
- function selectfiles(e) {
- e && setFile(e.file);
- }
-
-
- useEffect(() => {
- if (selectedDocument?.code) {
- setDocuments((prev) => {
- const filteredDocumentsByDocumentType = prev?.filter((item) => item?.documentType !== selectedDocument?.code);
- if (uploadedFile?.length === 0 || uploadedFile === null) return filteredDocumentsByDocumentType;
- const filteredDocumentsByFileStoreId = filteredDocumentsByDocumentType?.filter((item) => item?.fileStoreId !== uploadedFile);
- return [
- ...filteredDocumentsByFileStoreId,
- {
- documentType: selectedDocument?.code,
- fileStoreId: uploadedFile,
- documentUid: uploadedFile,
- fileName: file?.name || "",
- id: documents ? documents.find(x => x.documentType === selectedDocument?.code)?.id : undefined,
- },
- ];
- });
- }
- }, [uploadedFile, selectedDocument]);
-
- useEffect(() => {
- (async () => {
- if (selectArrayFiles.length > 0) {
- sessionStorage.removeItem("BPA_DOCUMENTS");
- doc.newUploadedDocs = [];
- selectArrayFiles.map(newDoc => {
- if (selectedDocument?.code) {
- doc.newUploadedDocs.push({
- documentType: selectedDocument?.code,
- fileStoreId: newDoc?.fileStoreId?.fileStoreId,
- documentUid: newDoc?.fileStoreId?.fileStoreId,
- tenantId: newDoc?.fileStoreId?.tenantId
- });
- }
- })
- bpaTaxDocuments[index] = doc;
- sessionStorage.setItem("BPA_DOCUMENTS", JSON.stringify(bpaTaxDocuments));
- }
- })();
- }, [selectArrayFiles, selectedDocument]);
-
- useEffect(() => {
- (async () => {
-
- })();
- }, [file]);
-
- const getData = (index, state) => {
- let data = Object.fromEntries(state);
- let newArr = Object.values(data);
- if (Object.keys(data).length !== 0) SetSelectArrayFiles(newArr);
- selectfiles(newArr[newArr.length - 1]);
- }
-
- return (
-
-
{`${t(doc?.code)}`}
- {doc?.uploadedDocuments?.length &&
}
- {
- checkEnablingDocs ?
-
-
- {doc?.required ? `${t(doc?.code)}* ` : `${t(doc?.code)}`}
-
-
-
-
-
- getData(index, e)}
- t={t}
- allowedFileTypesRegex={allowedFileTypes}
- allowedMaxSizeInMB={5}
- acceptFiles= "image/*, .pdf, .png, .jpeg, .jpg"
- />
-
-
-
: null
- }
-
- );
-}
-
-export default BPADocuments;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/DocumentsPreview.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/DocumentsPreview.js
deleted file mode 100644
index dfd57683def..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/DocumentsPreview.js
+++ /dev/null
@@ -1,49 +0,0 @@
-import React from "react";
-import { useTranslation } from "react-i18next";
-import { CardSubHeader, PDFSvg } from "@egovernments/digit-ui-react-components";
-
-function DocumentsPreview({ documents, svgStyles = {}, isSendBackFlow = false, isHrLine = false, titleStyles }) {
- const { t } = useTranslation();
- const isStakeholderApplication = window.location.href.includes("stakeholder");
-
- return (
-
- {!isStakeholderApplication && documents?.map((document, index) => (
-
- {document?.title ? {t(document?.title)} : null}
-
- {isHrLine && documents?.length != index + 1 ?
: null}
-
- ))}
- {isStakeholderApplication && documents?.map((document, index) => (
-
- {document?.title ? {t(document?.title)} : null}
-
-
- ))}
-
- );
-}
-
-export default DocumentsPreview;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/InfoDetails.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/InfoDetails.js
deleted file mode 100644
index 12e2f64fac6..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/InfoDetails.js
+++ /dev/null
@@ -1,34 +0,0 @@
-import React from "react";
-import { InfoBannerIcon } from "@egovernments/digit-ui-react-components";
-
-const EyeSvgINdex = ({ style }) => {
- return
-
-
-
-}
-const InfoDetails = ({ t, userType = false, infoBannerLabel = "", infoClickLable = "", infoClickInfoLabel = "", infoClickInfoLabel1 = "" }) => {
- userType = userType || Digit.SessionStorage.get("userType");
- return (
-
-
-
-
-
-
{t(infoBannerLabel)}
-
- {`${t(infoClickLable)} `}
-
- {` ${t(infoClickInfoLabel)}`}
-
- {` ${t(infoClickInfoLabel1)}`}
-
-
-
-
- );
-};
-
-export default InfoDetails;
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/InspectionReport.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/InspectionReport.js
deleted file mode 100644
index a824b05a435..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/InspectionReport.js
+++ /dev/null
@@ -1,49 +0,0 @@
-import { StatusTable, Row, CardHeader, CardSectionHeader } from "@egovernments/digit-ui-react-components";
-import React from "react";
-import { useTranslation } from "react-i18next";
-import DocumentsPreview from "./DocumentsPreview";
-
-const getDocuments = (fiDocuments) => {
- const returnDocuments = [{
- title: "BPA_DOCUMENT_DETAILS_LABEL",
- values: fiDocuments?.map(doc => ({
- title: doc?.documentType?.replaceAll('.', '_'),
- documentType: doc?.documentType,
- documentUid: doc?.documentUid,
- fileStoreId: doc?.fileStoreId,
- id: doc?.id,
- url: doc?.url
- }))
- }];
- return returnDocuments;
-};
-
-function InspectionReport({ fiReport, isCitizen=false }) {
- const { t } = useTranslation();
-
- return (
-
-
- {isCitizen?
{`${t(`BPA_FI_REPORT`)}`}:
-
{`${t(`BPA_FI_REPORT`)}`}}
- {fiReport.map((fiData, index) =>
-
-
- {fiReport?.length == 1 ? `${t(`BPA_FI_REPORT`)}` : `${t(`BPA_FI_REPORT`)} - ${index + 1}`}
-
-
- {fiData?.questions?.length &&
- fiData?.questions?.map((qstn) =>
-
-
-
-
)}
-
-
-
)}
-
-
- );
-}
-
-export default InspectionReport;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/NOCDocuments.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/NOCDocuments.js
deleted file mode 100644
index 1581744f756..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/NOCDocuments.js
+++ /dev/null
@@ -1,202 +0,0 @@
-import React, { useEffect, useState } from "react";
-import {
- CardLabel,
- MultiUploadWrapper,
- StatusTable,
- Row,
- LabelFieldPair
-} from "@egovernments/digit-ui-react-components";
-import DocumentsPreview from "./DocumentsPreview";
-
-function SelectDocument({
- t,
- document: doc,
- setNocDocuments,
- setError,
- nocDocuments
-}) {
- const filteredDocument = nocDocuments?.filter((item) => item?.documentType?.includes(doc?.code))[0];
- const tenantId = Digit.ULBService.getStateId();
- const [selectedDocument, setSelectedDocument] = useState();
- const [file, setFile] = useState(null);
- const [uploadedFile, setUploadedFile] = useState(() => filteredDocument?.fileStoreId || null);
- const handleSelectDocument = (value) => setSelectedDocument(value);
- const allowedFileTypes = /(.*?)(jpg|jpeg|png|image|pdf)$/i;
-
- function selectfile(e) {
- e && setFile(e.file);
- }
-
- useEffect(() => {
- if (doc?.dropdownData?.[0]?.code) {
- setNocDocuments((prev) => {
- const filteredDocumentsByDocumentType = prev?.filter((item) => item?.documentType !== doc?.dropdownData?.[0]?.code);
-
- if (uploadedFile?.length === 0 || uploadedFile === null) {
- return filteredDocumentsByDocumentType;
- }
-
- const filteredDocumentsByFileStoreId = filteredDocumentsByDocumentType?.filter((item) => item?.fileStoreId !== uploadedFile);
- return [
- ...filteredDocumentsByFileStoreId,
- {
- documentType: doc?.dropdownData?.[0].code,
- fileStoreId: uploadedFile,
- documentUid: uploadedFile,
- fileName: file?.name || "",
- },
- ];
- });
- }
- }, [uploadedFile]);
-
-
- useEffect(() => {
- (async () => {
- setError(null);
- if (file) {
- const allowedFileTypesRegex = /(.*?)(jpg|jpeg|png|image|pdf)$/i
- if (file.size >= 5242880) {
- setError(t("CS_MAXIMUM_UPLOAD_SIZE_EXCEEDED"));
- } else if (file?.type && !allowedFileTypesRegex.test(file?.type)) {
- setError(t(`NOT_SUPPORTED_FILE_TYPE`))
- } else {
- try {
- setUploadedFile(null);
- const response = await Digit.UploadServices.Filestorage("PT", file, Digit.ULBService.getStateId());
- if (response?.data?.files?.length > 0) {
- setUploadedFile(response?.data?.files[0]?.fileStoreId);
- } else {
- setError(t("CS_FILE_UPLOAD_ERROR"));
- }
- } catch (err) {
- setError(t("CS_FILE_UPLOAD_ERROR"));
- }
- }
- }
- })();
- }, [file]);
-
- const getData =(state) => {
- let data = Object.fromEntries(state);
- let newArr = Object.values(data);
- selectfile(newArr[newArr.length-1]);
- }
-
- return (
-
-
- {doc?.required ? `${t("TL_BUTTON_UPLOAD FILE")}*` : `${t("TL_BUTTON_UPLOAD FILE")}`}
-
- getData(e)}
- t={t}
- allowedFileTypesRegex={allowedFileTypes}
- allowedMaxSizeInMB={5}
- acceptFiles="image/*, .pdf, .png, .jpeg, .jpg"
- />
-
-
-
- );
-}
-const NOCDocuments = ({ t, noc, docs, isNoc, applicationData,NOCdata, bpaActionsDetails }) => {
- const tenantId = Digit.ULBService.getStateId();
- const stateId = Digit.ULBService.getStateId();
- const bpaApplicationStatus = applicationData?.status || "";
- const actions = bpaActionsDetails?.data?.nextActions || [];
- const { isLoading: nocDocsLoading, data: nocDocs } = Digit.Hooks.obps.useMDMS(stateId, "NOC", ["DocumentTypeMapping"], { enabled: isNoc });
- const { isLoading: bpaDocsLoading, data: bpaDocs } = Digit.Hooks.obps.useMDMS(stateId, "BPA", ["DocTypeMapping"], { enabled: !isNoc });
- const { isLoading: commonDocsLoading, data: commonDocs } = Digit.Hooks.obps.useMDMS(stateId, "common-masters", ["DocumentType"]);
- const [commonDocMaping, setCommonDocMaping] = useState([]);
- const [nocTaxDocuments, setNocTaxDocuments] = useState([]);
- const [checkEnablingDocs, setCheckEnablingDocs] = useState(false);
- const [nocDocuments, setNocDocuments] = Digit.Hooks.useSessionStorage(noc?.nocType, []);
- const [error, setError] = useState(null);
- const isEmployee = window.location.href.includes("/employee/")
-
- useEffect(() => {
- setCommonDocMaping(commonDocs?.["common-masters"]?.DocumentType);
- }, [commonDocs]);
-
- useEffect(() => {
- let documents = [];
- let filteredData
- if (isNoc) {
- filteredData = nocDocs?.NOC?.DocumentTypeMapping?.filter((data => {
- return data?.applicationType === noc?.applicationType && data?.nocType === noc?.nocType
- }));
- }
- else {
- filteredData = bpaDocs?.BPA?.DocTypeMapping?.filter(data => (data.WFState == applicationData?.status && data.RiskType == applicationData?.riskType && data.ServiceType == applicationData?.additionalDetails?.serviceType && data.applicationType == applicationData?.additionalDetails?.applicationType))
- }
- if (filteredData?.[0]?.docTypes?.[0]) {
- filteredData[0].docTypes[0].nocType = filteredData[0].nocType;
- filteredData[0].docTypes[0].additionalDetails = {
- submissionDetails: noc?.additionalDetails,
- applicationStatus: noc?.applicationStatus,
- appNumberLink: noc?.applicationNo,
- nocNo: noc?.nocNo
- }
- documents.push(filteredData[0].docTypes[0]);
- }
- let documentsList = [];
- if (documents && documents.length > 0) {
- documents.map((doc) => {
- let code = doc.documentType;
- let nocType = doc.nocType;
- doc.dropdownData = [];
- commonDocMaping?.forEach((value) => {
- let values = value.code.slice(0, code?.length);
- if (code === values) {
- doc.hasDropdown = true;
- doc.dropdownData.push(value);
- }
- });
- documentsList.push(doc);
- });
- setNocTaxDocuments(documentsList);
- }
- }, [nocDocs, commonDocMaping]);
-
- useEffect(() => {
- if (bpaApplicationStatus === 'NOC_VERIFICATION_INPROGRESS' && actions?.length > 0) setCheckEnablingDocs(true);
- else setCheckEnablingDocs(false);
- }, [applicationData, bpaActionsDetails])
-
- return (
-
-
-
- {NOCdata && NOCdata.map((noc,index) => {
- if (noc?.value) {
- if (noc?.field == "STATUS") {
- return
- } else {
- return
- }
- }
- })}
-
-
- {checkEnablingDocs && nocTaxDocuments?.map((document, index) => {
- return (
-
- );
- })}
-
- );
-}
-
-export default NOCDocuments;
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/PermissionCheck.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/PermissionCheck.js
deleted file mode 100644
index 89007789722..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/PermissionCheck.js
+++ /dev/null
@@ -1,87 +0,0 @@
-import { CheckBox, LinkButton, TextInput,Close, CardSubHeader } from "@egovernments/digit-ui-react-components";
-import React, { useEffect, useState } from "react";
-
-const PermissionCheck = ({ permissions, t }) => {
- const [approvalChecks, setApprovalChecks, clearApprovals] = Digit.Hooks.useSessionStorage("OBPS_APPROVAL_CHECKS", permissions?.map(permission => ({ label: permission, checked: false }))); //useState(() => permissions?.map(permission => ({ label: permission, checked: false })))
- const [newApprovals, setNewApprovals, clearNewApprovals] = Digit.Hooks.useSessionStorage('OBPS_NEW_APPROVALS', []);
-
- useEffect(() => {
- return () => {
- Digit.SessionStorage.del("OBPS_NEW_APPROVALS");
- Digit.SessionStorage.del("OBPS_APPROVAL_CHECKS");
- }
- }, [])
-
- const handleAdd = () => {
- setNewApprovals([...newApprovals, { label: '' }]);
- }
-
- const handleRemove = (index) => {
- const values = [...newApprovals];
- values.splice(index, 1);
- setNewApprovals([...values]);
- }
-
- const handleChange = (event, index) => {
- setNewApprovals(() => {
- return newApprovals?.map((approval, id) => {
- if (index === id) {
- return {
- label: event?.target?.value,
- }
- }
- return approval;
- })
- })
- }
-
- const handleCheck = (event, label, index) => {
- const isChecked = event.target.checked;
- setApprovalChecks(() => {
- return approvalChecks?.map((approval, id) => {
- if (index === id) {
- return {
- ...approval,
- checked: isChecked
- }
- }
- return approval;
- })
- })
- }
-
- return (
-
-
{t("BPA_PERMIT_CONDITIONS")}
- {approvalChecks?.map((permission, index) => (
-
handleCheck(event, permission?.label, index))}
- isLabelFirst={true}
- index={index}
- />
- ))}
- {newApprovals?.map((approval, index) => (
- handleChange(event, index)} textInputStyle={{maxWidth: "830px", width: "830px"}} placeholder={"Enter permit conditions.........."} />
- {
-
-
-
-
- }
- style={{ }}
- onClick={(e) => handleRemove(index)}
- />}
-
- ))}
-
-
- )
-}
-
-export default PermissionCheck;
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/PropertyDocuments.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/PropertyDocuments.js
deleted file mode 100644
index ea8cd1eb104..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/PropertyDocuments.js
+++ /dev/null
@@ -1,83 +0,0 @@
-import React, { useState, useEffect } from "react";
-import { useTranslation } from "react-i18next";
-import { CardSubHeader, PDFSvg } from "@egovernments/digit-ui-react-components";
-
-// const PDFSvg = ({ width = 34, height = 34, style, viewBox = "0 0 34 34" }) => (
-//
-// );
-
-function PropertyDocuments({ documents, svgStyles = {}, isSendBackFlow=false }) {
- const { t } = useTranslation();
- const [filesArray, setFilesArray] = useState(() => [] );
- const tenantId = Digit.ULBService.getCurrentTenantId();
- const [pdfFiles, setPdfFiles] = useState({});
-
- useEffect(() => {
- let acc = [];
- documents?.forEach((element, index, array) => {
- acc = [...acc, ...(element.values?element.values:[])];
- });
- setFilesArray(acc?.map((value) => value?.fileStoreId));
- }, [documents]);
-
- useEffect(() => {
- if (filesArray?.length && documents?.[0]?.BS === "BillAmend") {
- Digit.UploadServices.Filefetch(filesArray, Digit.ULBService.getCurrentTenantId()).then((res) => {
- setPdfFiles(res?.data);
- });
- }
- else if(filesArray?.length)
- {
- Digit.UploadServices.Filefetch(filesArray, Digit.ULBService.getStateId()).then((res) => {
- setPdfFiles(res?.data);
- });
- }
-
- }, [filesArray]);
-
- const checkLocation = window.location.href.includes("employee/tl") || window.location.href.includes("/obps") || window.location.href.includes("employee/ws");
- const isStakeholderApplication = window.location.href.includes("stakeholder");
-
- return (
-
- {!isStakeholderApplication && documents?.map((document, index) => (
-
- {document?.title ? {t(document?.title)}: null}
-
-
- ))}
- {isStakeholderApplication && documents?.map((document, index) => (
-
- {document?.title ? {t(document?.title)} : null}
-
-
- ))}
-
- );
-}
-
-export default PropertyDocuments;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/PropertyEstimates.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/PropertyEstimates.js
deleted file mode 100644
index c4cde76709f..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/PropertyEstimates.js
+++ /dev/null
@@ -1,39 +0,0 @@
-import React from "react";
-import { useTranslation } from "react-i18next";
-import { StatusTable, Row, BreakLine } from "@egovernments/digit-ui-react-components";
-
-function PropertyEstimates({ taxHeadEstimatesCalculation }) {
- const { taxHeadEstimates } = taxHeadEstimatesCalculation;
- const { t } = useTranslation();
-
- return (
-
-
-
-
- {taxHeadEstimates?.map((estimate, index) => {
- return (
-
- );
- })}
-
-
-
-
- );
-}
-
-export default PropertyEstimates;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/PropertyFloors.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/PropertyFloors.js
deleted file mode 100644
index 4f33bbdcff4..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/PropertyFloors.js
+++ /dev/null
@@ -1,49 +0,0 @@
-import React from "react";
-import { useTranslation } from "react-i18next";
-import { CardSubHeader, StatusTable, Row, CardSectionHeader } from "@egovernments/digit-ui-react-components";
-
-function PropertyFloors({ floors }) {
- const { t } = useTranslation();
-
- return (
-
- {floors.map((floor) => (
-
-
{t(floor?.title)}
- {floor?.values?.map((value, index) => {
- return (
-
-
- {t(value.title)}
-
-
-
- {value?.values?.map((value, index) => {
- if (value.map === true && value.value !== "N/A") {
- return
} />;
- }
- return (
-
- );
- })}
-
-
-
- );
- })}
-
- ))}
-
- );
-}
-
-export default PropertyFloors;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/PropertyOwners.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/PropertyOwners.js
deleted file mode 100644
index dac9f41c79b..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/PropertyOwners.js
+++ /dev/null
@@ -1,94 +0,0 @@
-import { CardSubHeader, Row, StatusTable } from "@egovernments/digit-ui-react-components";
-import React from "react";
-import { useTranslation } from "react-i18next";
-
-function PropertyOwners({ owners }) {
- const { t } = useTranslation();
-
- const checkLocation = true;
- const checkOwnerLength = owners?.length || 1;
- let cardStyles = { marginTop: "19px" };
- let statusTableStyles = { position: "relative", padding: "8px" };
- let rowContainerStyle = { justifyContent: "space-between", fontSize: "16px", lineHeight: "19px", color: "#0B0C0C" };
- if (checkLocation && Number(checkOwnerLength) > 1) {
- cardStyles = {
- marginTop: "19px",
- background: "#FAFAFA",
- border: "1px solid #D6D5D4",
- borderRadius: "4px",
- padding: "8px",
- lineHeight: "19px",
- maxWidth: "600px",
- minWidth: "280px",
- };
- } else if (checkLocation && !(Number(checkOwnerLength) > 1)) {
- cardStyles = { marginTop: "19px", lineHeight: "19px", maxWidth: "600px", minWidth: "280px" };
- statusTableStyles = { position: "relative", marginTop: "19px" };
- }
-
- if (window.location.href.includes("obps")) {
- cardStyles = { ...cardStyles, maxWidth: "950px" };
- cardStyles = { ...cardStyles, maxWidth: "950px" };
- rowContainerStyle = {};
- }
-
- return (
-
- {owners.map((owner, index) => (
-
- {/* TODO, Later will move to classes */}
-
1
- ? { marginBottom: "8px", paddingBottom: "9px", color: "#0B0C0C", fontSize: "16px", lineHeight: "19px" }
- : { marginBottom: "8px", color: "#505A5F", fontSize: "24px" }
- }
- >
- {checkLocation && Number(checkOwnerLength) > 1 ? `${t(owner?.title)} ${index + 1}` : t(owner?.title)}
-
-
-
-
- {owner?.values?.map((value, index) => {
- if (value.map === true && value.value !== "N/A") {
- return
} />;
- }
- return (
-
-
-
- );
- })}
-
-
-
- ))}
-
- );
-}
-
-export default PropertyOwners;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/Reason.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/Reason.js
deleted file mode 100644
index 0f226935c5b..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/Reason.js
+++ /dev/null
@@ -1,10 +0,0 @@
-import React from "react";
-
-const Reason = ({ headComment, otherComment }) => (
-
-
{headComment}
-
{otherComment}
-
-);
-
-export default Reason;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/ScruntinyDetails.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/ScruntinyDetails.js
deleted file mode 100644
index bde27623ba8..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/ScruntinyDetails.js
+++ /dev/null
@@ -1,46 +0,0 @@
-import { StatusTable, Row, PDFSvg, CardLabel, CardSubHeader } from "@egovernments/digit-ui-react-components";
-import React, { Fragment } from "react";
-import { useTranslation } from "react-i18next";
-
-const ScruntinyDetails = ({ scrutinyDetails, paymentsList=[] }) => {
- const { t } = useTranslation();
- let count = 0;
- const getTextValues = (data) => {
- if (data?.value && data?.isTransLate) return {t(data?.value)};
- else if (data?.value && data?.isTransLate) return t(data?.value);
- else if (data?.value) return data?.value;
- else t("NA");
- }
- return (
-
- {!scrutinyDetails?.isChecklist &&
-
-
- {scrutinyDetails?.values?.map((value, index) => {
- if (value?.isUnit) return
- else if (value?.isHeader && !value?.isUnit) return {t(value?.title)}
- else if (value?.isSubTitle && !value?.isUnit) return {t(value?.title)}
- else return
- })}
- {scrutinyDetails?.permit?.map((value,ind) => {
- return {value?.title}
- })}
-
-
- {scrutinyDetails?.scruntinyDetails?.map((report, index) => {
- return (
-
-
-
- {t(report?.text)}
-
- )
- })}
-
-
-
}
-
- )
-}
-
-export default ScruntinyDetails;
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/SubOccupancyTable.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/SubOccupancyTable.js
deleted file mode 100644
index e266bed6be2..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/SubOccupancyTable.js
+++ /dev/null
@@ -1,126 +0,0 @@
-import React, { Fragment, useMemo } from "react";
-import { Table, StatusTable, Row, CardSubHeader, CardSectionHeader } from "@egovernments/digit-ui-react-components";
-import { useTranslation } from "react-i18next";
-
-const SubOccupancyTable = ({ edcrDetails, applicationData }) => {
- const { t } = useTranslation();
- const isMobile = window.Digit.Utils.browser.isMobile();
-
- const tableHeader = [
- {
- name: "BPA_TABLE_COL_FLOOR",
- id: "Floor",
- },
- {
- name: "BPA_TABLE_COL_LEVEL",
- id: "Level",
- },
- {
- name: "BPA_TABLE_COL_OCCUPANCY",
- id: "Occupancy",
- },
- {
- name: "BPA_TABLE_COL_BUILDUPAREA",
- id: "BuildupArea",
- },
- {
- name: "BPA_TABLE_COL_FLOORAREA",
- id: "FloorArea",
- },
- {
- name: "BPA_TABLE_COL_CARPETAREA",
- id: "CarpetArea",
- }
- ]
-
- const accessData = (plot) => {
- const name = plot;
- return (originalRow, rowIndex, columns) => {
- return originalRow[name];
- }
- }
-
-
- const tableColumns = useMemo(
- () => {
- return tableHeader.map((ob) => ({
- Header: t(`${ob.name}`),
- accessor: accessData(ob.id),
- id: ob.id
- }));
- });
-
- function getFloorData(block) {
- let floors = [];
- block?.building?.floors.map((ob) => {
- floors.push({
- Floor: t(`BPA_FLOOR_NAME_${ob.number}`),
- Level: ob.number,
- Occupancy: t(`${ob.occupancies?.[0]?.type}`),
- BuildupArea: ob.occupancies?.[0]?.builtUpArea,
- FloorArea: ob.occupancies?.[0]?.floorArea || 0,
- CarpetArea: ob.occupancies?.[0]?.CarpetArea || 0,
- key: t(`BPA_FLOOR_NAME_${ob.number}`),
- });
- });
- return floors;
- }
-
- const stringReplaceAll = (str = "", searcher = "", replaceWith = "") => {
- if (searcher == "") return str;
- while (str.includes(searcher)) {
- str = str.replace(searcher, replaceWith);
- }
- return str;
- };
-
- function getSubOccupancyValues(index) {
- let values = applicationData?.landInfo?.unit;
- let returnValue = "";
- if (values?.length > 0) {
- let splitArray = values[index]?.usageCategory?.split(',');
- if (splitArray?.length) {
- const returnValueArray = splitArray.map(data => data ? `${t(`BPA_SUBOCCUPANCYTYPE_${stringReplaceAll(data?.toUpperCase(), "-", "_")}`)}` : "NA");
- returnValue = returnValueArray.join(', ')
- }
- }
- return returnValue ? returnValue : "NA";
- }
-
- return (
-
-
-
- {edcrDetails?.values?.map((value, index) => {
- if (value?.isHeader) return {t(value?.title)}
- else return
- })}
-
-
- {edcrDetails?.subOccupancyTableDetails?.[0]?.value?.planDetail?.blocks.map((block, index) => (
-
0 ? {marginBottom: "30px", background: "#FAFAFA", border: "1px solid #D6D5D4", padding: "8px", borderRadius: "4px", maxWidth: "950px", minWidth: "280px"} : {marginBottom: "30px"}}>
-
{t("BPA_BLOCK_SUBHEADER")} {index + 1}
-
-
-
-
-
{ return { style: {} } }}
- />
-
- ))}
-
-
- )
-}
-
-export default SubOccupancyTable;
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/SubWorkTableDetails.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/SubWorkTableDetails.js
deleted file mode 100644
index 08b89e68419..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/SubWorkTableDetails.js
+++ /dev/null
@@ -1,77 +0,0 @@
-import { EditIcon } from '@egovernments/digit-ui-react-components';
-import React from 'react'
-import { useTranslation } from "react-i18next";
-import { useHistory } from 'react-router-dom';
-
-const SubWorkTableDetails = ({data}) => {
- const { t } = useTranslation();
- const history = useHistory();
- const getStyles = (index) => {
- let obj = {}
- switch (index) {
- case 1:
- obj = { "width": "1vw" }
- break;
- case 2:
- obj = { "width": "60vw" }
- break;
- case 3:
- obj = { "width": "20vw" }
- break;
- case 4:
- obj = { "width": "10vw" }
- break;
- default:
- obj = { "width": "1vw" }
- break;
- }
- return obj
- }
- const renderHeader = (headers) => {
- return headers?.map((key, index) => {
- return {t(key)} |
- })
- }
-
- const renderBody = (rows) => {
- return rows?.map((row, index) => {
- return
- {row[0]} |
- { row[1] === t("WORKS_TOTAL_AMT") ? {row[1]} : {row[1]} } |
- {row[1] === t("WORKS_TOTAL_AMT")
- ? {row[2]} |
- : {row[2]} | }
- {row[3] &&
- history.push(
- {
- pathname: `/digit-ui/employee/contracts/create-contract?estimateNumber=${data?.state?.estimateNumber}&task=${data?.state?.estimateDetails[index]?.name}&subEstimate=${data?.state?.estimateDetails[index]?.estimateDetailNumber}`,
- state:{index, data}
- }
- )}>
- {row[3]}
-
- | }
- {/* {showDelete() && removeRow(row)}>} | */}
-
- })
- }
-
- return (
-
-
- {renderHeader(data?.headers)}
-
-
- {renderBody(data?.tableRows)}
- {/*
- |
- |
- |
- |
-
*/}
-
-
- )
-}
-
-export default SubWorkTableDetails
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/TLCaption.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/TLCaption.js
deleted file mode 100644
index e5fbcde20cd..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/TLCaption.js
+++ /dev/null
@@ -1,34 +0,0 @@
-import React from "react";
-import { useTranslation } from "react-i18next";
-import { TelePhone, DisplayPhotos, UnMaskComponent } from "@egovernments/digit-ui-react-components";
-import Reason from "./Reason";
-
-const TLCaption = ({ data,OpenImage,privacy={}}) => {
-
- const { t } = useTranslation();
- return (
-
- {data.date &&
{data.date}
}
-
{data.name}
- {data.mobileNumber &&
-
-
-
- }
- {data.source &&
{t("ES_APPLICATION_DETAILS_APPLICATION_CHANNEL_" + data.source.toUpperCase())}
}
- {data.comment &&
}
- {data?.wfComment ?
{data?.wfComment?.map( e =>
-
-
{t("WF_COMMON_COMMENTS")}
-
{e}
-
- )}
: null}
- {data?.thumbnailsToShow?.thumbs?.length > 0 ?
-
{t("CS_COMMON_ATTACHMENTS")}
- {OpenImage(src, index,data?.thumbnailsToShow)}} />
- : null}
-
- );
-};
-
-export default TLCaption;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/TLTradeAccessories.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/TLTradeAccessories.js
deleted file mode 100644
index 536a2ce3eca..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/TLTradeAccessories.js
+++ /dev/null
@@ -1,52 +0,0 @@
-
-import React from "react";
-import { useTranslation } from "react-i18next";
-import { CardSubHeader, StatusTable, Row, CardSectionHeader } from "@egovernments/digit-ui-react-components";
-
-function TLTradeAccessories({ units }) {
- const { t } = useTranslation();
- return (
-
- {units.map((unit, index) => (
- // TODO, Later will move to classes
-
-
{`${t(unit?.title)} ${index + 1}`}
-
-
-
- {unit?.values?.map((value, index) => {
- if (value.map === true && value.value !== "N/A") {
- return
} />;
- }
- return (
-
- );
- })}
-
-
-
- ))}
-
- );
-}
-
-export default TLTradeAccessories;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/TLTradeUnits.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/TLTradeUnits.js
deleted file mode 100644
index bf1c1fbc780..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/TLTradeUnits.js
+++ /dev/null
@@ -1,51 +0,0 @@
-import React from "react";
-import { useTranslation } from "react-i18next";
-import { CardSubHeader, StatusTable, Row, CardSectionHeader } from "@egovernments/digit-ui-react-components";
-
-function TLTradeUnits({ units }) {
- const { t } = useTranslation();
- return (
-
- {units.map((unit, index) => (
- // TODO, Later will move to classes
-
-
{`${t(unit?.title)} ${index + 1}`}
-
-
-
- {unit?.values?.map((value, index) => {
- if (value.map === true && value.value !== "N/A") {
- return
} />;
- }
- return (
-
- );
- })}
-
-
-
- ))}
-
- );
-}
-
-export default TLTradeUnits;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/ViewBreakup.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/ViewBreakup.js
deleted file mode 100644
index 5608aeb2d2a..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/ViewBreakup.js
+++ /dev/null
@@ -1,73 +0,0 @@
-import React, { useState, Fragment } from "react";
-import { useTranslation } from "react-i18next";
-import { CardSectionHeader, Modal, Row, StatusTable } from "@egovernments/digit-ui-react-components";
-
-const ViewBreakup = ({ wsAdditionalDetails, workflowDetails }) => {
- const { t } = useTranslation();
- const [popup, showPopUp] = useState(false);
- const [breakUpData, setBreakUpData] = useState({});
-
- const Heading = (props) => {
- return {props.label}
;
- };
-
- const Close = () => (
-
- );
-
- const CloseBtn = (props) => {
- return (
-
-
-
- );
- };
-
- const onPopupOpen = () => {
- let breakupData = wsAdditionalDetails.additionalDetails.data || {};
- const sessionBillData = sessionStorage.getItem("Digit.ADHOC_BILL_ADD_REBATE_DATA");
- const sessionBillFormData = sessionBillData ? JSON.parse(sessionBillData) : {};
- if (sessionBillFormData?.value?.totalAmount) breakupData = sessionBillFormData?.value;
- setBreakUpData(breakupData);
- showPopUp(true);
- }
-
- return (
-
-
- {wsAdditionalDetails?.additionalDetails?.isViewBreakup ?
onPopupOpen()} style={{ marginTop: "12px" }}>
- {t("WS_PAYMENT_VIEW_BREAKUP")}
-
: null
- }
- {popup &&
-
}
- headerBarEnd={
{ showPopUp(false); }} />}
- hideSubmit={true}
- popupStyles={{ overflowY: "auto" }} //maxHeight: "calc(100% - 90px)"
- headerBarMainStyle={{ marginBottom: "0px" }}
- popupModuleMianStyles={{ paddingTop: "0px" }}
- >
- {
- {t("WS_APPLICATION_FEE_HEADER")}
- {breakUpData?.billSlabData?.FEE?.map(data => ₹{Number(data?.amount) || 0}} textStyle={{ textAlign: "right" }} />)}
-
- ₹{Number(breakUpData?.fee) || 0}} textStyle={{ textAlign: "right", fontWeight: "700", fontSize: "24px" }} />
- {t("WS_SERVICE_FEE_HEADER")}
- {breakUpData?.billSlabData?.CHARGES?.map(data => ₹{Number(data?.amount) || 0}} textStyle={{ textAlign: "right" }} />)}
-
- ₹{Number(breakUpData?.charge) || 0}} textStyle={{ textAlign: "right", fontWeight: "700", fontSize: "24px" }} />
- {breakUpData?.billSlabData?.TAX?.map(data => ₹{Number(data?.amount) || 0}} textStyle={{ textAlign: "right" }} />)}
-
- ₹{Number(breakUpData?.totalAmount) || 0}} textStyle={{ textAlign: "right", fontWeight: "700", fontSize: "24px" }} />
-
}
- }
-
-
- )
-}
-
-export default ViewBreakup;
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/WSAdditonalDetails.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/WSAdditonalDetails.js
deleted file mode 100644
index 06814062d96..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/WSAdditonalDetails.js
+++ /dev/null
@@ -1,399 +0,0 @@
-import { StatusTable, Row, CardSubHeader } from "@egovernments/digit-ui-react-components";
-import React, { Fragment } from "react";
-import { useTranslation } from "react-i18next";
-import { getQueryStringParams } from "../../../ws/src/utils";
-
-const cardSubHeaderStyles = () => {
- // return { fontSize: "24px", padding: "0px", margin: "0px", color: "#505A5F" };
- return { fontSize: "24px", marginBottom: "16px", marginTop: "32px" };
-};
-
-const cardDivStyles = () => {
- return {
- border: "1px solid #D6D5D4",
- background: "#FAFAFA",
- borderRadius: "4px",
- padding: "10px 10px 0px 10px",
- marginBottom: "10px",
- display: "flex",
- };
-};
-
-const convertEpochToDate = (dateEpoch) => {
- if (dateEpoch) {
- const dateFromApi = new Date(dateEpoch);
- let month = dateFromApi.getMonth() + 1;
- let day = dateFromApi.getDate();
- let year = dateFromApi.getFullYear();
- month = (month > 9 ? "" : "0") + month;
- day = (day > 9 ? "" : "0") + day;
- return `${day}/${month}/${year}`;
- } else {
- return null;
- }
-};
-
-const WSAdditonalDetails = ({ wsAdditionalDetails, oldValue }) => {
- const { t } = useTranslation();
- let filters = getQueryStringParams(location.search);
- const serviceType = filters?.service;
- const isModify = filters?.mode;
-
- const oldValueData = oldValue?.[1];
-
- const stringReplaceAll = (str = "", searcher = "", replaceWith = "") => {
- if (searcher == "") return str;
- while (str.includes(searcher)) {
- str = str.replace(searcher, replaceWith);
- }
- return str;
- };
-
- const renderSWConnectionDetails = () => {
- return (
-
- {oldValueData?.connectionType ? (
-
|
- ) : (
-
{"NA"}
- )}
-
- {oldValueData?.noOfWaterClosets ? (
-
|
- ) : (
-
{"NA"}
- )}
- {oldValueData?.noOfToilets ? (
-
|
- ) : (
-
{"NA"}
- )}
-
- );
- };
-
- const renderWSConnectionDetails = () => {
- return (
-
- {oldValueData?.connectionType && (
)}
- {oldValueData?.noOfTaps && (
)}
- {oldValueData?.waterSource && (
)}
- {oldValueData?.pipeSize && (
)}
- {oldValueData?.waterSource && (
)}
-
- );
- };
-
- const renderSWPlumberDetails = () => {
- return (
-
- {oldValueData?.additionalDetails?.detailsProvidedBy !== wsAdditionalDetails?.additionalDetails?.plumberDetails[0]?.value &&
- oldValueData?.additionalDetails?.detailsProvidedBy !== null ? (
-
|
- ) : (
-
{"NA"}
- )}
- {oldValueData?.plumberInfo ? (
-
|
- ) : (
-
{"NA"}
- )}
- {oldValueData?.plumberInfo ? (
-
|
- ) : (
-
{"NA"}
- )}
- {oldValueData?.plumberInfo ? (
-
|
- ) : (
-
{"NA"}
- )}
-
- );
- };
-
- const renderWSPlumberDetails = () => {
- return (
-
- {oldValueData?.additionalDetails?.detailsProvidedBy !== wsAdditionalDetails?.additionalDetails?.plumberDetails[0]?.value ? (
-
|
- ) : (
-
{"NA"}
- )}
-
- );
- };
-
- const renderSWRoadCuttingDetails = () => {
- {
- oldValueData?.roadCuttingInfo?.map((info) => {
- return (
-
-
-
-
- );
- });
- }
- };
-
- const renderSWActivationDetails = () => {
- return (
-
- {oldValueData?.connectionExecutionDate ? (
-
|
- ) : (
-
{"NA"}
- )}
-
- );
- };
-
- const renderWSActivationDetails = () => {
- return (
-
- {oldValueData?.meterId && (
)}
- {oldValueData?.additionalDetails?.initialMeterReading && (
)}
- {oldValueData?.meterInstallationDate && (
)}
- {oldValueData?.connectionExecutionDate && (
)}
-
- );
- };
-
- var { connectionDetails, plumberDetails, roadCuttingDetails, activationDetails } = wsAdditionalDetails?.additionalDetails || {connectionDetails:[], plumberDetails: []};
-
- // binding old values with new values
- if(isModify === "MODIFY"){
-
- connectionDetails = connectionDetails?.map((value) => {
- if(value.title == "WS_SERV_DETAIL_CONN_TYPE" && oldValueData?.connectionType) value["oldValue"] = [
- { value:value?.value, className:"newValue", style:{ display:"inline"} },
- {
- value:`${t("WS_OLD_LABEL_NAME")} ${oldValueData?.connectionType}`,
- className:"oldValue", style:{color:'gray', paddingLeft:"10px", display:"inline", fontSize:"13px"}
- }];
- if(value.title == "WS_SERV_DETAIL_NO_OF_TAPS" && oldValueData?.noOfTaps) value["oldValue"] = [
- {value:value?.value,className:"newValue", style:{ display:"inline"}},
- {value:`${t("WS_OLD_LABEL_NAME")} ${oldValueData?.noOfTaps}`, style:{color:'gray', paddingLeft:"10px", display:"inline", fontSize:"13px"},className:"oldValue"}
- ];
- if(value.title == "WS_SERV_DETAIL_WATER_SOURCE" && oldValueData?.waterSource) value["oldValue"] = [
- {value:value?.value, className:"newValue", style:{ display:"inline"}},
- {
- value: `${t("WS_OLD_LABEL_NAME")} ${t(oldValueData?.waterSource?.toUpperCase()?.split(".")[0])}`,
- style:{color:'gray', paddingLeft:"10px", display:"inline", fontSize:"13px"}, className:"oldValue"
- }
- ];
- if(value.title == "WS_PIPE_SIZE_IN_INCHES_LABEL" && oldValueData?.pipeSize) value["oldValue"] = [
- {value:value?.value, className:"newValue", style:{ display:"inline"}},
- {
- value: `${t("WS_OLD_LABEL_NAME")} ${oldValueData?.pipeSize}`,
- style:{color:'gray', paddingLeft:"10px", display:"inline", fontSize:"13px"}, className:"oldValue"
- }
- ];
- if(value.title == "WS_SERV_DETAIL_WATER_SUB_SOURCE" && oldValueData?.waterSource) value["oldValue"] = [
- {value:value?.value, className:"newValue", style:{ display:"inline"}},
- {
- value: `${t("WS_OLD_LABEL_NAME")} ${t(oldValueData?.waterSource?.toUpperCase()?.split(".")[1])}`,
- style:{color:'gray', paddingLeft:"10px", display:"inline", fontSize:"13px"}, className:"oldValue"
- }
- ];
- if(value.title == "WS_NUMBER_WATER_CLOSETS_LABEL" && oldValueData?.noOfWaterClosets) value["oldValue"] = [
- {value:value?.value, className:"newValue", style:{ display:"inline"}},
- {
- value: `${t("WS_OLD_LABEL_NAME")} ${oldValueData?.noOfWaterClosets}`,
- style:{color:'gray', paddingLeft:"10px", display:"inline", fontSize:"13px"}, className:"oldValue"
- }
- ];
- if(value.title == "WS_SERV_DETAIL_NO_OF_TOILETS" && oldValueData?.noOfWaterClosets) value["oldValue"] = [
- {value:value?.value, className:"newValue", style:{ display:"inline"}},
- {
- value: `${t("WS_OLD_LABEL_NAME")} ${oldValueData?.noOfWaterClosets}`,
- style:{color:'gray', paddingLeft:"10px", display:"inline", fontSize:"13px"}, className:"oldValue"
- }
- ];
-
- return value;
- })
-
- plumberDetails = plumberDetails?.map((value) => {
- if(value.title == "WS_ADDN_DETAILS_PLUMBER_PROVIDED_BY" && oldValueData?.additionalDetails?.detailsProvidedBy && oldValueData?.additionalDetails?.detailsProvidedBy !== value.value ) value["oldValue"] = [
- {value:value?.value, className:"newValue", style:{ display:"inline"}},
- {
- value: `${t("WS_OLD_LABEL_NAME")} ${oldValueData?.additionalDetails?.detailsProvidedBy}`,
- style:{color:'gray', paddingLeft:"10px", display:"inline", fontSize:"13px"}, className:"oldValue"
- }
- ];
- if(value.title == "WS_ADDN_DETAILS_PLUMBER_LICENCE_NO_LABEL" && oldValueData?.plumberInfo[0]?.licenseNo ) value["oldValue"] = [
- {value:value?.value, className:"newValue", style:{ display:"inline"}},
- {
- value: `${t("WS_OLD_LABEL_NAME")} ${oldValueData?.plumberInfo[0]?.licenseNo}`,
- style:{color:'gray', paddingLeft:"10px", display:"inline", fontSize:"13px"}, className:"oldValue"
- }
- ];
- if(value.title == "WS_ADDN_DETAILS_PLUMBER_NAME_LABEL" && oldValueData?.plumberInfo[0]?.name ) value["oldValue"] = [
- {value:value?.value, className:"newValue", style:{ display:"inline"}},
- {
- value: `${t("WS_OLD_LABEL_NAME")} ${oldValueData?.plumberInfo[0]?.name}`,
- style:{color:'gray', paddingLeft:"10px", display:"inline", fontSize:"13px"}, className:"oldValue"
- }
- ];
- if(value.title == "WS_PLUMBER_MOBILE_NO_LABEL" && oldValueData?.plumberInfo[0]?.mobileNumber ) value["oldValue"] = [
- {value:value?.value, className:"newValue", style:{ display:"inline"}},
- {
- value: `${t("WS_OLD_LABEL_NAME")} ${oldValueData?.plumberInfo[0]?.mobileNumber}`,
- style:{color:'gray', paddingLeft:"10px", display:"inline", fontSize:"13px"}, className:"oldValue"
- }
- ];
- return value;
- })
-
- roadCuttingDetails = roadCuttingDetails?.map((roadDetail) => {
- const roadDetailValues = roadDetail?.values?.map((value) => {
- if(value.title == "WS_ADDN_DETAIL_ROAD_TYPE" && oldValueData?.roadCuttingInfo[0]?.roadType) value["oldValue"] = [
- {value:value?.value, className:"newValue", style:{ display:"inline"}},
- {
- value: `${t("WS_OLD_LABEL_NAME")} ${oldValueData?.roadCuttingInfo[0]?.roadType}`,
- style:{color:'gray', paddingLeft:"10px", display:"inline", fontSize:"13px"}, className:"oldValue"
- }
- ];
- if(value.title == "WS_ROAD_CUTTING_AREA_LABEL" && oldValueData?.roadCuttingInfo[0]?.roadCuttingArea) value["oldValue"] = [
- {value:value?.value, className:"newValue", style:{ display:"inline"}},
- {
- value: `${t("WS_OLD_LABEL_NAME")} ${oldValueData?.roadCuttingInfo[0]?.roadCuttingArea}`,
- style:{color:'gray', paddingLeft:"10px", display:"inline", fontSize:"13px"}, className:"oldValue"
- }
- ];
- return value;
- })
- return ({...roadDetail,values:roadDetailValues});
- })
-
- activationDetails = activationDetails?.map((value) => {
- if(value.title == "WS_SERV_DETAIL_CONN_EXECUTION_DATE" && oldValueData?.connectionExecutionDate) value["oldValue"] = [
- {value:value?.value, className:"newValue", style:{ display:"inline"}},
- {
- value: `${t("WS_OLD_LABEL_NAME")} ${convertEpochToDate(oldValueData?.connectionExecutionDate)}`,
- style:{color:'gray', paddingLeft:"10px", display:"inline", fontSize:"13px"}, className:"oldValue"
- }
- ];
-
- if(value.title == "WS_SERV_DETAIL_METER_ID" && oldValueData?.meterId) value["oldValue"] = [
- {value:value?.value, className:"newValue", style:{ display:"inline"}},
- {
- value: `${t("WS_OLD_LABEL_NAME")} ${oldValueData?.meterId}`,
- style:{color:'gray', paddingLeft:"10px", display:"inline", fontSize:"13px"}, className:"oldValue"
- }
- ];
-
- if(value.title == "WS_INITIAL_METER_READING_LABEL" && oldValueData?.initialMeterReading) value["oldValue"] = [
- {value:value?.value, className:"newValue", style:{ display:"inline"}},
- {
- value: `${t("WS_OLD_LABEL_NAME")} ${oldValueData?.initialMeterReading}`,
- style:{color:'gray', paddingLeft:"10px", display:"inline", fontSize:"13px"}, className:"oldValue"
- }
- ];
-
- if(value.title == "WS_INSTALLATION_DATE_LABEL" && oldValueData?.meterInstallationDate) value["oldValue"] = [
- {value:value?.value, className:"newValue", style:{ display:"inline"}},
- {
- value: `${t("WS_OLD_LABEL_NAME")} ${convertEpochToDate(oldValueData?.meterInstallationDate)}`,
- style:{color:'gray', paddingLeft:"10px", display:"inline", fontSize:"13px"}, className:"oldValue"
- }
- ];
- if(value.title == "WS_SERV_DETAIL_CONN_EXECUTION_DATE" && oldValueData?.connectionExecutionDate) value["oldValue"] = [
- {value:value?.value, className:"newValue", style:{ display:"inline"}},
- {
- value: `${t("WS_OLD_LABEL_NAME")} ${convertEpochToDate(oldValueData?.connectionExecutionDate)}`,
- style:{color:'gray', paddingLeft:"10px", display:"inline", fontSize:"13px"}, className:"oldValue"
- }
- ];
- return value;
- })
- };
-
- return (
-
-
- {wsAdditionalDetails?.additionalDetails?.connectionDetails && (
-
- {t("WS_COMMON_CONNECTION_DETAIL")}
-
-
- {connectionDetails?.map((value, index) => {
- return (
-
-
-
- );
- })}
-
-
-
- )}
- {wsAdditionalDetails?.additionalDetails?.plumberDetails && (
-
- {t("WS_COMMON_PLUMBER_DETAILS")}
-
-
-
- {plumberDetails?.map((value, index) => {
- return
;
- })}
-
-
-
- )}
- {wsAdditionalDetails?.additionalDetails?.roadCuttingDetails && (
-
- {t("WS_ROAD_CUTTING_DETAILS")}
-
-
- {roadCuttingDetails?.map((value) => {
- return (
-
1
- ? {
- border: "1px solid #D6D5D4",
- background: "#FAFAFA",
- borderRadius: "4px",
- padding: "10px 10px 0px 10px",
- margin: "5px 0px",
- }
- : {}
- }
- >
- {value?.values?.map((roadValue) => (
-
- ))}
-
- );
- })}
-
-
-
- )}
- {wsAdditionalDetails?.additionalDetails?.activationDetails && (
-
- {t("WS_ACTIVATION_DETAILS")}
-
-
- {activationDetails?.map((value, index) => {
- return (
-
- );
- })}
-
-
-
- )}
-
-
- );
-};
-
-export default WSAdditonalDetails;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/WSFeeEstimation.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/WSFeeEstimation.js
deleted file mode 100644
index 9a4fe591f9d..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/WSFeeEstimation.js
+++ /dev/null
@@ -1,346 +0,0 @@
-import React, { useState, Fragment, useEffect } from "react";
-import { useTranslation } from "react-i18next";
-import { Card, CardSectionHeader, CardLabel } from "@egovernments/digit-ui-react-components";
-import { Modal, Dropdown, Row, StatusTable, TextInput, Toast } from "@egovernments/digit-ui-react-components";
-import cloneDeep from "lodash/cloneDeep";
-
-const Penality_menu = [
- {
- title: "PT_PENDING_DUES_FROM_EARLIER",
- value: "Pending dues from earlier",
- },
- {
- title: "PT_MISCALCULATION_OF_EARLIER_ASSESSMENT",
- value: "Miscalculation of earlier Assessment",
- },
- {
- title: "PT_ONE_TIME_PENALITY",
- value: "One time penality",
- },
- {
- title: "PT_OTHERS",
- value: "Others",
- },
-]
-const Rebate_menu = [
- {
- title: "PT_ADVANCED_PAID_BY_CITIZEN_EARLIER",
- value: "Advanced Paid By Citizen Earlier",
- },
- {
- title: "PT_REBATE_PROVIDED_BY_COMMISSIONER_EO",
- value: "Rebate provided by commissioner/EO",
- },
- {
- title: "PT_ADDITIONAL_AMOUNT_CHARGED_FROM_THE_CITIZEN",
- value: "Additional amount charged from the citizen",
- },
- {
- title: "PT_OTHERS",
- value: "Others",
- },
-];
-
-
-const WSFeeEstimation = ({ wsAdditionalDetails, workflowDetails }) => {
- const { t } = useTranslation();
- const [sessionFormData, setSessionFormData, clearSessionFormData] = Digit.Hooks.useSessionStorage("ADHOC_ADD_REBATE_DATA", {});
- const [sessionBillFormData, setSessionBillFormData, clearBillSessionFormData] = Digit.Hooks.useSessionStorage("ADHOC_BILL_ADD_REBATE_DATA", {});
- const isPaid = wsAdditionalDetails?.additionalDetails?.isPaid ? true : false;
- const [popup, showPopUp] = useState(false);
- const [fields, setFields] = useState(sessionFormData ? sessionFormData : {});
- const [showToast, setShowToast] = useState(null);
- const [billDetails, setBillDetails] = useState(wsAdditionalDetails.additionalDetails.data ? wsAdditionalDetails.additionalDetails.data : {});
- const [values, setValues] = useState(wsAdditionalDetails.additionalDetails.values ? wsAdditionalDetails.additionalDetails.values : []);
-
- const stateCode = Digit.ULBService.getStateId();
- const { isMdmsLoading, data: mdmsRes } = Digit.Hooks.ws.useMDMS(stateCode, "BillingService", ["TaxHeadMaster"]);
-
- useEffect(() => {
- const data = { ...wsAdditionalDetails?.additionalDetails?.appDetails?.additionalDetails };
- setSessionFormData(data);
- setFields(data);
- if (sessionFormData?.billDetails?.length > 0) {
- const values = [
- { title: "WS_APPLICATION_FEE_HEADER", value: sessionFormData?.billDetails?.[0]?.fee },
- { title: "WS_SERVICE_FEE_HEADER", value: sessionFormData?.billDetails?.[0]?.charge },
- { title: "WS_TAX_HEADER", value: sessionFormData?.billDetails?.[0]?.taxAmount },
- ];
- setValues(values);
- setBillDetails(sessionFormData?.billDetails?.[0]);
- }
- }, []);
-
- let validation = {};
-
- const Heading = (props) => {
- return {props.label}
;
- };
-
- const Close = () => (
-
- );
-
- const CloseBtn = (props) => {
- return (
-
-
-
- );
- };
-
- const closeToast = () => {
- setShowToast(false);
- };
-
- const addAdhocRebatePenality = (e) => {
- const adhocAmount = fields?.adhocPenalty ? Number(fields?.adhocPenalty) : 0;
- const rebateAmount = fields?.adhocRebate ? Number(fields?.adhocRebate) : 0;
- if (adhocAmount || rebateAmount) {
-
- const totalAmount = wsAdditionalDetails?.additionalDetails?.data?.totalAmount;
- const demandId = wsAdditionalDetails?.additionalDetails?.data?.billDetails?.[0]?.demandId;
-
- if (rebateAmount > totalAmount) {
- setShowToast({ isError: false, isWarning: true, key: "error", message: t("ERR_WS_REBATE_GREATER_THAN_AMOUNT") });
- } else {
- const applicationNo = wsAdditionalDetails?.additionalDetails?.appDetails?.applicationNo;
- const tenantId = wsAdditionalDetails?.additionalDetails?.appDetails?.tenantId;
- const appAdditionalDetails = { ...wsAdditionalDetails?.additionalDetails?.appDetails?.additionalDetails, ...fields }
- wsAdditionalDetails.additionalDetails.appDetails.additionalDetails = appAdditionalDetails;
-
- const data = {
- CalculationCriteria:
- wsAdditionalDetails?.additionalDetails?.appDetails?.service == "WATER"
- ? [
- {
- applicationNo: applicationNo,
- tenantId: tenantId,
- waterConnection: wsAdditionalDetails.additionalDetails.appDetails,
- },
- ]
- : [
- {
- applicationNo: applicationNo,
- tenantId: tenantId,
- sewerageConnection: wsAdditionalDetails.additionalDetails.appDetails,
- },
- ],
- isconnectionCalculation: false,
- };
-
- let businessService = wsAdditionalDetails?.additionalDetails?.appDetails?.service == "WATER" ? "WS" : "SW";
- Digit.WSService.wsCalculationEstimate(data, businessService)
- .then((result, err) => {
- if (result?.Calculation?.[0]?.taxHeadEstimates?.length > 0) {
- result?.Calculation?.[0]?.taxHeadEstimates?.forEach(data => data.amount = data.estimateAmount);
- }
-
- result.Calculation[0].billSlabData = _.groupBy(result?.Calculation?.[0]?.taxHeadEstimates, 'category');
- const values = [
- { title: "WS_APPLICATION_FEE_HEADER", value: result.Calculation?.[0]?.fee },
- { title: "WS_SERVICE_FEE_HEADER", value: result.Calculation?.[0]?.charge },
- { title: "WS_TAX_HEADER", value: result.Calculation?.[0]?.taxAmount },
- ];
- setSessionBillFormData(cloneDeep(result.Calculation[0]));
- setBillDetails(result?.Calculation?.[0]);
- setValues(values);
- fields.billDetails = result?.Calculation;
- setSessionFormData(fields);
- showPopUp(false);
- })
- .catch((e) => {
- setShowToast({ isError: true, isWarning: false, key: "error", message: e?.response?.data?.Errors[0]?.message ? t(`${e?.response?.data?.Errors[0]?.code}`) : t("PT_COMMON_ADD_REBATE_PENALITY") });
- });
- }
- } else {
- setShowToast({ isError: false, isWarning: true, key: "warning", message: t("ERR_WS_ENTER_ATLEAST_ONE_FIELD") });
- }
- }
-
- const selectedValuesData = (value, isDropDownValue = false, e) => {
- let values = { ...fields };
- if (isDropDownValue) {
- values[`${value}_data`] = e;
- values[value] = e.title;
- if (e.title == "PT_OTHERS" && value == "adhocPenaltyReason") values[`adhocPenaltyComment`] = "";
- if (e.title == "PT_OTHERS" && value == "adhocRebateReason") values[`adhocRebateComment`] = "";
- } else {
- values[value] = e.target.value;
- }
- setFields(values);
- }
-
- return (
-
-
- {values &&
-
-
- {values?.map((value, index) => {
- return
- })}
-
-
-
-
-
-
- }
- {
- wsAdditionalDetails?.additionalDetails?.isAdhocRebate ?
{
- showPopUp(true)
- }}
- >
- {t("WS_PAYMENT_ADD_REBATE_PENALTY")}
-
: null
- }
- {popup &&
-
}
- headerBarEnd={
-
{
- setFields(sessionFormData);
- showPopUp(false);
- }} />}
- actionCancelLabel={t("PT_CANCEL")}
- actionCancelOnSubmit={() => {
- setFields(sessionFormData);
- showPopUp(false);
- }}
- actionSaveLabel={t("PT_ADD")}
- actionSaveOnSubmit={(e) => addAdhocRebatePenality(e)}
- hideSubmit={false}
- popupStyles={{ overflowY: "auto" }}
- >
- {
-
-
- {t("PT_AD_PENALTY")}
-
- {t("PT_TX_HEADS")}
-
-
- selectedValuesData("adhocPenaltyReason", true, e)}
- selected={fields?.adhocPenaltyReason_data || ""}
- isPropertyAssess={true}
- name={"adhocPenaltyReason_data"}
- t={t}
- />
-
- {fields?.adhocPenaltyReason_data?.title === "PT_OTHERS" &&
-
{t("PT_REASON")}
-
- selectedValuesData("adhocPenaltyComment", false, e)}
- {...(validation = {
- isRequired: true,
- pattern: "^[a-zA-Z-.`' ]*$",
- type: "text",
- title: t("TL_NAME_ERROR_MESSAGE"),
- })}
- />
-
-
}
- {t("PT_HEAD_AMT")}
-
- selectedValuesData("adhocPenalty", false, e)}
- {...(validation = {
- isRequired: true,
- pattern: "^[1-9]+[0-9]*$",
- title: t("ERR_DEFAULT_INPUT_FIELD_MSG"),
- })}
- />
-
-
-
-
- {t("PT_AD_REBATE")}
- {t("PT_TX_HEADS")}
-
- selectedValuesData("adhocRebateReason", true, e)}
- selected={fields?.adhocRebateReason_data || ""}
- name={"adhocRebateReason_data"}
- isPropertyAssess={true}
- t={t}
- />
-
- {fields?.adhocRebateReason_data?.title === "PT_OTHERS" &&
- {t("PT_REASON")}
- selectedValuesData("adhocRebateComment", false, e)}
- {...(validation = {
- isRequired: true,
- pattern: "^[a-zA-Z-.`' ]*$",
- type: "text",
- title: t("TL_NAME_ERROR_MESSAGE"),
- })}
- />
-
}
- {t("PT_HEAD_AMT")}
-
- selectedValuesData("adhocRebate", false, e)}
- {...(validation = {
- isRequired: true,
- pattern: "^[1-9]+[0-9]*$",
- title: t("ERR_DEFAULT_INPUT_FIELD_MSG"),
- })}
- />
-
-
-
- } }
- {showToast &&
- }
-
-
- )
-}
-
-export default WSFeeEstimation;
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/WeekDateRange.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/WeekDateRange.js
deleted file mode 100644
index 75069dd741f..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/components/WeekDateRange.js
+++ /dev/null
@@ -1,30 +0,0 @@
-import React, { useCallback, useState } from "react";
-import { useTranslation } from "react-i18next";
-
-const WeekDateRange = (props) => {
- const [localSearchParams, setLocalSearchParams] = useState(() => ({}));
- const { t } = useTranslation();
- const handleChange = useCallback((data) => {
- setLocalSearchParams(() => ({ ...data }));
- }, []);
-
- return (
-
- );
-};
-
-export default WeekDateRange;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/AcceptDso.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/AcceptDso.js
deleted file mode 100644
index e870f2e9a67..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/AcceptDso.js
+++ /dev/null
@@ -1,45 +0,0 @@
-import React from "react";
-import { Dropdown } from "@egovernments/digit-ui-react-components";
-
-export const configAcceptDso = ({ t, dsoData, dso, selectVehicleNo, vehicleNoList, vehicleNo, vehicle, action }) => {
- return {
- label: {
- heading: `ES_FSM_ACTION_TITLE_${action}`,
- submit: `CS_COMMON_${action}`,
- cancel: "CS_COMMON_CANCEL",
- },
- form: [
- {
- body: [
- {
- label: t("ES_FSM_ACTION_VEHICLE_REGISTRATION_NO"),
- isMandatory: true,
- type: "dropdown",
- populators: (
-
- ),
- },
- {
- label: t("ES_FSM_ACTION_VEHICLE_CAPACITY_IN_LTRS"),
- isMandatory: true,
- type: "text",
- populators: {
- name: "capacity",
- validation: {
- required: true,
- },
- },
- disable: true,
- },
- ],
- },
- ],
- };
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/AssignDso.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/AssignDso.js
deleted file mode 100644
index 418caf1e4bc..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/AssignDso.js
+++ /dev/null
@@ -1,115 +0,0 @@
-import React from "react";
-import { DatePicker, Dropdown, CardLabelError } from "@egovernments/digit-ui-react-components";
-
-function todayDate() {
- var today = new Date();
- var dd = today.getDate();
- var mm = today.getMonth() + 1;
- var yyyy = today.getFullYear();
-
- if (dd < 10) {
- dd = "0" + dd;
- }
-
- if (mm < 10) {
- mm = "0" + mm;
- }
-
- return yyyy + "-" + mm + "-" + dd;
-}
-
-function getFilteredDsoData(dsoData, vehicle) {
- return dsoData?.filter((e) => e.vehicles?.find((veh) => veh?.type == vehicle?.code));
-}
-
-export const configAssignDso = ({ t, dsoData, dso, selectDSO, vehicleMenu, vehicle, selectVehicle, action }) => {
- return {
- label: {
- heading: `ES_FSM_ACTION_TITLE_${action}`,
- submit: `CS_COMMON_${action}`,
- cancel: "CS_COMMON_CANCEL",
- },
- form: [
- {
- body: [
- {
- label: t("ES_FSM_ACTION_VEHICLE_TYPE"),
- isMandatory: true,
- type: "dropdown",
- populators: (
-
- ),
- },
- {
- label: t("ES_FSM_ACTION_DSO_NAME"),
- isMandatory: true,
- type: "dropdown",
- populators: (
-
- {getFilteredDsoData(dsoData, vehicle) && !getFilteredDsoData(dsoData, vehicle).length ? (
- {t("ES_COMMON_NO_DSO_AVAILABLE_WITH_SUCH_VEHICLE")}
- ) : null}
-
-
- ),
- },
- {
- label: t("ES_FSM_ACTION_VEHICLE_CAPACITY_IN_LTRS"),
- isMandatory: true,
- type: "text",
- populators: {
- name: "capacity",
- validation: {
- required: true,
- },
- },
- disable: true,
- },
- // {
- // label: t("ES_FSM_ACTION_SERVICE_DATE"),
- // isMandatory: true,
- // type: "date",
- // populators: {
- // name: "date",
- // validation: {
- // required: true,
- // },
- // min: Digit.Utils.date.getDate(),
- // defaultValue: Digit.Utils.date.getDate(),
- // },
- // },
- {
- label: t("ES_FSM_ACTION_SERVICE_DATE"),
- isMandatory: true,
- type: "custom",
- populators: {
- name: "date",
- validation: {
- required: true,
- },
- customProps: { min: Digit.Utils.date.getDate() },
- defaultValue: Digit.Utils.date.getDate(),
- component: (props, customProps) => ,
- },
- },
- ],
- },
- ],
- };
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/BPAApproverApplication.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/BPAApproverApplication.js
deleted file mode 100644
index ca66865bb77..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/BPAApproverApplication.js
+++ /dev/null
@@ -1,77 +0,0 @@
-import { Dropdown, UploadFile } from "@egovernments/digit-ui-react-components";
-import React from "react";
-
-export const configBPAApproverApplication = ({
- t,
- action,
- approvers,
- selectedApprover,
- setSelectedApprover,
- selectFile,
- uploadedFile,
- setUploadedFile,
- assigneeLabel,
- businessService,
- error
-}) => {
- let isRejectOrRevocate = false;
- if(action?.action == "REVOCATE" || action?.action == "REJECT" || action.action == "SKIP_PAYMENT" || action?.action == "SEND_BACK_TO_CITIZEN" || action?.action == "APPROVE") {
- isRejectOrRevocate = true;
- }
-
- let isCommentRequired = false;
- if(action?.action == "REVOCATE" || action?.action == "REJECT") {
- isCommentRequired = true;
- }
-
- return {
- label: {
- heading: `WF_${action?.action}_APPLICATION`,
- submit: `WF_${businessService}_${action?.action}`,
- cancel: "BPA_CITIZEN_CANCEL_BUTTON",
- },
- form: [
- {
- body: [
- {
- label: action.isTerminateState || isRejectOrRevocate ? null : t(assigneeLabel || `WF_ROLE_${action.assigneeRoles?.[0]}`),
- type: "dropdown",
- populators: action.isTerminateState || isRejectOrRevocate ? null : (
-
- ),
- },
- {
- label: t("WF_COMMON_COMMENTS"),
- type: "textarea",
- isMandatory: isCommentRequired,
- populators: {
- name: "comments",
- },
- },
- {
- label: `${t("WF_APPROVAL_UPLOAD_HEAD")}`,
- populators: (
- {
- setUploadedFile(null);
- }}
- message={uploadedFile ? `1 ${t(`ES_PT_ACTION_FILEUPLOADED`)}` : t(`CS_ACTION_NO_FILEUPLOADED`)}
- accept= "image/*, .pdf, .png, .jpeg, .jpg"
- iserror={error}
- />
- ),
- },
- ],
- },
- ],
- };
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/BPAREGApproverApplication.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/BPAREGApproverApplication.js
deleted file mode 100644
index 0bdba14bc5b..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/BPAREGApproverApplication.js
+++ /dev/null
@@ -1,71 +0,0 @@
-import { Dropdown, UploadFile } from "@egovernments/digit-ui-react-components";
-import React from "react";
-
-export const configBPAREGApproverApplication = ({
- t,
- action,
- approvers,
- selectedApprover,
- setSelectedApprover,
- selectFile,
- uploadedFile,
- setUploadedFile,
- assigneeLabel,
- businessService,
- error
-}) => {
- let checkCondtions = true;
- if (action?.action == "SENDBACKTOCITIZEN") checkCondtions = false;
- if (action.isTerminateState) checkCondtions = false;
-
- return {
- label: {
- heading: `WF_${action?.action}_APPLICATION`,
- submit: `WF_${businessService?.toUpperCase()}_${action?.action}`,
- cancel: "WF_EMPLOYEE_BPAREG_CANCEL",
- },
- form: [
- {
- body: [
- {
- label: !checkCondtions ? null : t("WF_ASSIGNEE_NAME_LABEL"),
- placeholder: !checkCondtions ? null : t("WF_ASSIGNEE_NAME_PLACEHOLDER"),
- type: "dropdown",
- populators: !checkCondtions ? null : (
-
- ),
- },
- {
- label: t("WF_COMMON_COMMENTS"),
- type: "textarea",
- populators: {
- name: "comments",
- },
- },
- {
- label: t("BPA_APPROVAL_CHECKLIST_BUTTON_UP_FILE"),
- populators: (
- {
- setUploadedFile(null);
- }}
- message={uploadedFile ? `1 ${t(`ES_PT_ACTION_FILEUPLOADED`)}` : t(`CS_ACTION_NO_FILEUPLOADED`)}
- accept= "image/*, .pdf, .png, .jpeg, .jpg"
- iserror={error}
- />
- )
- },
- ],
- },
- ],
- };
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/CompleteApplication.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/CompleteApplication.js
deleted file mode 100644
index a4c7c96b2fd..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/CompleteApplication.js
+++ /dev/null
@@ -1,46 +0,0 @@
-import React from "react";
-import { DatePicker } from "@egovernments/digit-ui-react-components";
-
-export const configCompleteApplication = ({ t, vehicle, applicationCreatedTime = 0, action }) => ({
- label: {
- heading: `ES_FSM_ACTION_TITLE_${action}`,
- submit: `CS_COMMON_${action}`,
- cancel: "CS_COMMON_CANCEL",
- },
- form: [
- {
- body: [
- {
- label: t("ES_FSM_ACTION_DESLUGED_DATE_LABEL"),
- isMandatory: true,
- type: "custom",
- populators: {
- name: "desluged",
- validation: {
- required: true,
- },
- defaultValue: Digit.Utils.date.getDate(),
- customProps: {
- min: Digit.Utils.date.getDate(applicationCreatedTime),
- max: Digit.Utils.date.getDate(),
- },
- component: (props, customProps) => ,
- },
- },
- {
- label: t("ES_FSM_ACTION_WASTE_VOLUME_LABEL"),
- type: "text",
- isMandatory: true,
- populators: {
- name: "wasteCollected",
- validation: {
- required: true,
- validate: (value) => parseInt(value) <= parseInt(vehicle.capacity),
- },
- error: `${t("ES_FSM_ACTION_INVALID_WASTE_VOLUME")} ${vehicle?.capacity} ${t("CS_COMMON_LITRES")}`,
- },
- },
- ],
- },
- ],
-});
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/NOCApproverApplication.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/NOCApproverApplication.js
deleted file mode 100644
index 12922b0575e..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/NOCApproverApplication.js
+++ /dev/null
@@ -1,79 +0,0 @@
-import { Dropdown, UploadFile } from "@egovernments/digit-ui-react-components";
-import React from "react";
-
-export const configNOCApproverApplication = ({
- t,
- action,
- approvers,
- selectedApprover,
- setSelectedApprover,
- selectFile,
- uploadedFile,
- setUploadedFile,
- assigneeLabel,
- businessService,
- error
-}) => {
-
- let isCommentRequired = false;
- if(action?.action == "REVOCATE" || action?.action == "REJECT") {
- isCommentRequired = true;
- }
-
- let isRejectOrRevocate = false;
- if(action?.action == "APPROVE" || action?.action == "REJECT" || action.action == "AUTO_APPROVE" || action.action == "AUTO_REJECT") {
- isRejectOrRevocate = true;
- }
-
- return {
- label: {
- heading: `WF_${action?.action}_APPLICATION`,
- submit: `WF_${businessService}_${action?.action}`,
- cancel: "CORE_LOGOUTPOPUP_CANCEL",
- },
- form: [
- {
- body: [
- {
- label: action.isTerminateState || isRejectOrRevocate ? null : t(assigneeLabel || `WF_ROLE_${action.assigneeRoles?.[0]}`),
- type: "dropdown",
- populators: action.isTerminateState || isRejectOrRevocate ? null : (
-
- ),
- },
- {
- label: t("WF_COMMON_COMMENTS"),
- type: "textarea",
- isMandatory: isCommentRequired,
- populators: {
- name: "comments",
- },
- },
- {
- label: `${t("WF_APPROVAL_UPLOAD_HEAD")}`,
- populators: (
- {
- setUploadedFile(null);
- }}
- showHint={true}
- message={uploadedFile ? `1 ${t(`ES_PT_ACTION_FILEUPLOADED`)}` : t(`CS_ACTION_NO_FILEUPLOADED`)}
- accept= "image/*, .pdf, .png, .jpeg, .jpg"
- iserror={error}
- />
- ),
- },
- ],
- },
- ],
- };
-};
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/PTApproverApplication.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/PTApproverApplication.js
deleted file mode 100644
index afcc6a19be2..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/PTApproverApplication.js
+++ /dev/null
@@ -1,66 +0,0 @@
-import { Dropdown, UploadFile } from "@egovernments/digit-ui-react-components";
-import React from "react";
-
-export const configPTApproverApplication = ({
- t,
- action,
- approvers,
- selectedApprover,
- setSelectedApprover,
- selectFile,
- uploadedFile,
- setUploadedFile,
- assigneeLabel,
- businessService,
-}) => {
- return {
- label: {
- heading: `WF_${action?.action}_APPLICATION`,
- submit: `WF_${businessService}_${action?.action}`,
- cancel: "ES_PT_COMMON_CANCEL",
- },
- form: [
- {
- body: [
- {
- label: action.isTerminateState || action?.action === "SENDBACKTOCITIZEN" ? null : t(assigneeLabel || `WF_ROLE_${action.assigneeRoles?.[0]}`),
- // isMandatory: !action.isTerminateState,
- type: "dropdown",
- populators: action.isTerminateState || action?.action === "SENDBACKTOCITIZEN" ? null : (
-
- ),
- },
- {
- label: t("ES_PT_ACTION_COMMENTS"),
- type: "textarea",
- populators: {
- name: "comments",
- },
- },
- {
- label: `${t("ES_PT_ATTACH_FILE")}${action.docUploadRequired ? " *" : ""}`,
- populators: (
- {
- setUploadedFile(null);
- }}
- showHint={true}
- hintText={t("PT_ATTACH_RESTRICTIONS_SIZE")}
- message={uploadedFile ? `1 ${t(`ES_PT_ACTION_FILEUPLOADED`)}` : t(`ES_PT_ACTION_NO_FILEUPLOADED`)}
- />
- ),
- },
- ],
- },
- ],
- };
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/PTAssessProperty.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/PTAssessProperty.js
deleted file mode 100644
index dd04037aab6..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/PTAssessProperty.js
+++ /dev/null
@@ -1,26 +0,0 @@
-import React from "react";
-import { RadioButtons } from "@egovernments/digit-ui-react-components";
-
-export const configPTAssessProperty = ({ t, action, financialYears, selectedFinancialYear, setSelectedFinancialYear }) => {
- return {
- label: {
- heading: `WF_${action.action}_APPLICATION`,
- submit: `WF_PT.CREATE_${action.action}`,
- cancel: "ES_PT_COMMON_CANCEL",
- },
- form: [
- {
- body: [
- {
- label: t("ES_PT_FINANCIAL_YEARS"),
- isMandatory: true,
- type: "radio",
- populators: (
-
- ),
- },
- ],
- },
- ],
- };
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/ReassignDso.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/ReassignDso.js
deleted file mode 100644
index 132a5bc6a7c..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/ReassignDso.js
+++ /dev/null
@@ -1,101 +0,0 @@
-import React from "react";
-import { Dropdown } from "@egovernments/digit-ui-react-components";
-
-function getFilteredDsoData(dsoData, vehicle) {
- return dsoData?.filter((e) => e.vehicles?.find((veh) => veh?.type == vehicle?.code));
-}
-
-export const configReassignDSO = ({
- t,
- dsoData,
- dso,
- selectDSO,
- vehicleMenu,
- vehicle,
- selectVehicle,
- reassignReasonMenu,
- reassignReason,
- selectReassignReason,
- action,
- showReassignReason,
-}) => ({
- label: {
- heading: `ES_FSM_ACTION_TITLE_${action}`,
- submit: `CS_COMMON_${action}`,
- cancel: "CS_COMMON_CANCEL",
- },
- form: [
- {
- body: [
- ...(showReassignReason
- ? [
- {
- label: t("ES_FSM_ACTION_REASSIGN_REASON"),
- type: "dropdown",
- isMandatory: true,
- populators: (
-
- ),
- },
- ]
- : []),
- {
- label: t("ES_FSM_ACTION_VEHICLE_TYPE"),
- isMandatory: vehicle ? false : true,
- type: "dropdown",
- populators: (
-
- ),
- },
- {
- label: t("ES_FSM_ACTION_DSO_NAME"),
- isMandatory: true,
- type: "dropdown",
- populators: (
-
- ),
- },
- {
- label: t("ES_FSM_ACTION_VEHICLE_CAPACITY_IN_LTRS"),
- type: "text",
- populators: {
- name: "capacity",
- validation: {
- required: true,
- },
- },
- disable: true,
- },
- {
- label: t("ES_FSM_ACTION_SERVICE_DATE"),
- isMandatory: true,
- type: "date",
- populators: {
- name: "date",
- validation: {
- required: true,
- },
- min: Digit.Utils.date.getDate(),
- defaultValue: Digit.Utils.date.getDate(),
- },
- },
- ],
- },
- ],
-});
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/RejectApplication.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/RejectApplication.js
deleted file mode 100644
index a18bdaf1110..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/RejectApplication.js
+++ /dev/null
@@ -1,31 +0,0 @@
-import React from "react";
-import { Dropdown } from "@egovernments/digit-ui-react-components";
-
-export const configRejectApplication = ({ t, rejectMenu, setReason, reason, action }) => {
- return {
- label: {
- heading: `ES_FSM_ACTION_TITLE_${action}`,
- submit: `CS_COMMON_${action}`,
- cancel: "CS_COMMON_CANCEL",
- },
- form: [
- {
- body: [
- {
- label: t(`ES_FSM_ACTION_${action.toUpperCase()}_REASON`),
- type: "dropdown",
- populators: ,
- isMandatory: true,
- },
- {
- label: t("ES_FSM_ACTION_COMMENTS"),
- type: "textarea",
- populators: {
- name: "comments",
- },
- },
- ],
- },
- ],
- };
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/TLApproverApplication.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/TLApproverApplication.js
deleted file mode 100644
index 23b20e5be2b..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/TLApproverApplication.js
+++ /dev/null
@@ -1,83 +0,0 @@
-import { Dropdown, UploadFile } from "@egovernments/digit-ui-react-components";
-import React from "react";
-
-export const configTLApproverApplication = ({
- t,
- action,
- approvers,
- selectedApprover,
- setSelectedApprover,
- selectFile,
- uploadedFile,
- setUploadedFile,
- assigneeLabel,
- businessService,
-}) => {
- let checkCondtions = true;
- if (action?.action == "SENDBACKTOCITIZEN" || action?.action == "APPROVE") checkCondtions = false;
- if (action.isTerminateState) checkCondtions = false;
-
- return {
- label: {
- heading: `WF_${action?.action}_APPLICATION`,
- submit: `WF_${businessService?.toUpperCase()}_${action?.action}`,
- cancel: "WF_EMPLOYEE_NEWTL_CANCEL",
- },
- form: [
- {
- body: [
- {
- label: !checkCondtions ? null : t("WF_ASSIGNEE_NAME_LABEL"),
- placeholder: !checkCondtions ? null : t("WF_ASSIGNEE_NAME_PLACEHOLDER"),
- // isMandatory: false,
- type: "dropdown",
- populators: !checkCondtions ? null : (
-
- ),
- },
- {
- label: t("WF_COMMON_COMMENTS"),
- type: "textarea",
- populators: {
- name: "comments",
- },
- },
- {
- label: t("TL_APPROVAL_CHECKLIST_BUTTON_UP_FILE"),
- populators: (
- {
- setUploadedFile(null);
- }}
- message={uploadedFile ? `1 ${t(`ES_PT_ACTION_FILEUPLOADED`)}` : t(`CS_ACTION_NO_FILEUPLOADED`)}
- />
- )
- },
- // {
- // label: action.docUploadRequired ? t("ES_PT_UPLOAD_FILE") : null,
- // populators: action.docUploadRequired ? (
- // {
- // setUploadedFile(null);
- // }}
- // message={uploadedFile ? `1 ${t(`ES_PT_ACTION_FILEUPLOADED`)}` : t(`ES_PT_ACTION_NO_FILEUPLOADED`)}
- // />
- // ) : null,
- // },
- ],
- },
- ],
- };
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/WSApproverApplication.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/WSApproverApplication.js
deleted file mode 100644
index 2f5f2d45a6a..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/WSApproverApplication.js
+++ /dev/null
@@ -1,73 +0,0 @@
-import { Dropdown, UploadFile } from "@egovernments/digit-ui-react-components";
-import React from "react";
-
-export const configWSApproverApplication = ({
- t,
- action,
- approvers,
- selectedApprover,
- setSelectedApprover,
- selectFile,
- uploadedFile,
- setUploadedFile,
- assigneeLabel,
- businessService,
- error
-}) => {
- let checkCondtions = true;
- if (action?.action?.includes("SEND_BACK") || action?.action == "APPROVE_FOR_CONNECTION") checkCondtions = false;
- if (action.isTerminateState) checkCondtions = false;
-
- return {
- label: {
- heading: `WF_${action?.action}_APPLICATION`,
- submit: `WF_${businessService?.toUpperCase()}_${action?.action}`,
- cancel: "CS_COMMON_CANCEL",
- },
- form: [
- {
- body: [
- {
- label: !checkCondtions ? null : t("WF_ASSIGNEE_NAME_LABEL"),
- placeholder: !checkCondtions ? null : t("WF_ASSIGNEE_NAME_PLACEHOLDER"),
- // isMandatory: false,
- type: "dropdown",
- populators: !checkCondtions ? null : (
-
- ),
- },
- {
- label: t("WF_COMMON_COMMENTS"),
- type: "textarea",
- populators: {
- name: "comments",
- },
- },
- {
- label: t("WS_APPROVAL_CHECKLIST_BUTTON_UP_FILE"),
- populators: (
- {
- setUploadedFile(null);
- }}
- message={uploadedFile ? `1 ${t(`ES_PT_ACTION_FILEUPLOADED`)}` : t(`CS_ACTION_NO_FILEUPLOADED`)}
- error={error}
- iserror={error}
- />
- )
- },
- ],
- },
- ],
- };
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/WSDisconnectApplication.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/WSDisconnectApplication.js
deleted file mode 100644
index 5acdcebe041..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/WSDisconnectApplication.js
+++ /dev/null
@@ -1,89 +0,0 @@
-import { Dropdown, UploadFile, DatePicker } from "@egovernments/digit-ui-react-components";
-import React from "react";
-
-export const configWSDisConnectApplication = ({
- t,
- action,
- approvers,
- selectedApprover,
- setSelectedApprover,
- selectFile,
- uploadedFile,
- setUploadedFile,
- assigneeLabel,
- businessService,
- error
-}) => {
- let checkCondtions = true, isDatePickerDisplay = false;
- if (action?.action?.includes("SEND_BACK") || action?.action == "APPROVE_FOR_DISCONNECTION" || action?.action == "RESUBMIT_APPLICATION") checkCondtions = false;
- if (action.isTerminateState) checkCondtions = false;
- if (action?.action == "EXECUTE_DISCONNECTION" || action?.action == "DISCONNECTION_EXECUTED") isDatePickerDisplay = true;
-
-
- return {
- label: {
- heading: `WF_${action?.action}_APPLICATION`,
- submit: `WF_${businessService?.toUpperCase()}_${action?.action}`,
- cancel: "CS_COMMON_CANCEL",
- },
- form: [
- {
- body: [
- {
- label: !checkCondtions ? null : t("WF_ASSIGNEE_NAME_LABEL"),
- placeholder: !checkCondtions ? null : t("WF_ASSIGNEE_NAME_PLACEHOLDER"),
- // isMandatory: false,
- type: "dropdown",
- populators: !checkCondtions ? null : (
-
- ),
- },
- isDatePickerDisplay && {
- label: t("ES_FSM_ACTION_SERVICE_DATE"),
- isMandatory: isDatePickerDisplay ? true : false,
- type: "custom",
- populators: isDatePickerDisplay ? {
- name: "date",
- validation: {
- required: true,
- },
- // customProps: { max: Digit.Utils.date.getDate() },
- defaultValue: Digit.Utils.date.getDate(),
- component: (props, customProps) => ,
- } : null,
- },
- {
- label: t("WF_COMMON_COMMENTS"),
- type: "textarea",
- populators: {
- name: "comments",
- },
- },
- {
- label: t("WS_APPROVAL_CHECKLIST_BUTTON_UP_FILE"),
- populators: (
- {
- setUploadedFile(null);
- }}
- message={uploadedFile ? `1 ${t(`ES_PT_ACTION_FILEUPLOADED`)}` : t(`CS_ACTION_NO_FILEUPLOADED`)}
- error={error}
- iserror={error}
- />
- )
- },
- ],
- },
- ],
- };
-};
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/configApproveModal.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/configApproveModal.js
deleted file mode 100644
index 03beb885925..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/configApproveModal.js
+++ /dev/null
@@ -1,53 +0,0 @@
-import { Dropdown } from '@egovernments/digit-ui-react-components';
-import React, { useState } from 'react'
-
-const configApproveModal = ({
- t,
- action
-}) => {
- if(action?.action === 'ADMINSANCTION'){
- return {
- label: {
- heading: `WORKS_APPROVE_ESTIMATE`,
- submit: `WORKS_APPROVE_ESTIMATE`,
- cancel: "CS_COMMON_CANCEL",
- },
- form: [
- {
- body: [
- {
- label: t("WF_COMMON_COMMENTS"),
- type: "textarea",
- populators: {
- name: "comments",
- },
- },
- ]
- }
- ]
- }
-
- }else
- return {
- label: {
- heading: `WORKS_APPROVE_LOI`,
- submit: `WORKS_APPROVE_LOI`,
- cancel: "CS_COMMON_CANCEL",
- },
- form: [
- {
- body: [
- {
- label: t("WF_COMMON_COMMENTS"),
- type: "textarea",
- populators: {
- name: "comments",
- },
- },
- ]
- }
- ]
- }
-}
-
-export default configApproveModal
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/configAttendanceApproveModal.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/configAttendanceApproveModal.js
deleted file mode 100644
index 06a29a26339..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/configAttendanceApproveModal.js
+++ /dev/null
@@ -1,27 +0,0 @@
-
-const configAttendanceApproveModal = ({ t, action }) => {
- if (action?.applicationStatus === "APPROVED") {
- return {
- label: {
- heading: t("ATM_PROCESSINGMODAL_HEADER"),
- submit: t("ATM_FORWARD_FOR_APPROVAL"),
- cancel: t("CS_COMMON_CANCEL"),
- },
- form: [
- {
- body: [
- {
- label: t("WF_COMMON_COMMENTS"),
- type: "textarea",
- populators: {
- name: "comments",
- },
- },
- ],
- },
- ]
- };
- }
-};
-
-export default configAttendanceApproveModal;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/configAttendanceCheckModal.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/configAttendanceCheckModal.js
deleted file mode 100644
index 374219cc6d4..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/configAttendanceCheckModal.js
+++ /dev/null
@@ -1,93 +0,0 @@
-const configAttendanceCheckModal = ({
- t,
- action,
- businessService,
- approvers,
- selectedApprover,
- setSelectedApprover,
- designation,
- selectedDesignation,
- setSelectedDesignation,
- department,
- selectedDept,
- setSelectedDept,
- approverLoading = false,
-}) => {
- let checkConditions = true;
- if (action.isTerminateState) checkConditions = false;
-
- if (designation?.length === 0 || department?.length === 0) return {};
-
- if (action?.applicationStatus === "ATTENDANCE_CHECKED") {
- return {
- label: {
- heading: t("ATM_PROCESSINGMODAL_HEADER"),
- submit: t("ATM_FORWARD_FOR_CHECK"),
- cancel: t("WORKS_CANCEL"),
- },
- form: [
- {
- body: [
- {
- isMandatory: true,
- key: "department",
- type: "radioordropdown",
- label: !checkConditions ? null : t("ATM_APPROVER_DEPT"),
- disable: false,
- populators: {
- name: "department",
- optionsKey: "i18nKey",
- error: "Department is required",
- required: true,
- options: department,
- },
- },
- {
- isMandatory: true,
- key: "designation",
- type: "radioordropdown",
- label: !checkConditions ? null : t("ATM_APPROVER_DESIGNATION"),
- disable: false,
- populators: {
- name: "designation",
- optionsKey: "i18nKey",
- error: "Designation is required",
- required: true,
- options: designation,
- },
- },
- {
- isMandatory: true,
- key: "approvers",
- type: "radioordropdown",
- label: !checkConditions ? null : t("WORKS_APPROVER"),
- disable: false,
- populators: {
- name: "approvers",
- optionsKey: "nameOfEmp",
- error: "Designation is required",
- required: true,
- options: approvers,
- },
- },
- {
- label: t("WF_COMMON_COMMENTS"),
- type: "textarea",
- populators: {
- name: "comments",
- },
- },
- ],
- },
- ],
- defaultValues: {
- department: "",
- designation: "",
- approvers: "",
- comments: "",
- },
- };
- }
-};
-
-export default configAttendanceCheckModal;
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/configAttendanceRejectModal.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/configAttendanceRejectModal.js
deleted file mode 100644
index c732127aac7..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/configAttendanceRejectModal.js
+++ /dev/null
@@ -1,61 +0,0 @@
-import { LabelFieldPair,CardLabel} from '@egovernments/digit-ui-react-components';
-import React from 'react'
-
-const configAttendanceRejectModal = ({
- t,
- empDepartment,
- empDesignation,
- empName
-}) => {
-
- const fieldLabelStyle = {
- "display" : "grid",
- "gridTemplateColumns" : "60% 1fr"
- };
-
- return {
- label: {
- heading: t("ATM_PROCESSINGMODAL_HEADER"),
- submit: t("ATM_CONFIRM_REJECT"),
- cancel: t("CS_COMMON_CANCEL"),
- },
- form: [
- {
- body: [
- {
- withoutLabel:true,
- populators:
- {t("ATM_DEPARTMENT")}
- {empDepartment}
- ,
- },
- {
- withoutLabel:true,
- populators:
- {t("ATM_DESIGNATION")}
- {empDesignation}
- ,
- },
- {
- withoutLabel:true,
- populators:
- {t("ATM_REJECTED_BY")}
- {empName}
- ,
- },
- {
- label: t("WF_COMMON_COMMENTS"),
- type: "textarea",
- key: "org_name",
- populators: {
- name: "comments",
- },
- },
- ]
- }
- ]
- }
-
-}
-
-export default configAttendanceRejectModal
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/configCheckModal.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/configCheckModal.js
deleted file mode 100644
index c267eb9f32f..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/configCheckModal.js
+++ /dev/null
@@ -1,105 +0,0 @@
-import { Dropdown,Loader } from '@egovernments/digit-ui-react-components';
-import React,{useState} from 'react'
-
-const configCheckModal = ({
- t,
- action,
- businessService,
- approvers,
- selectedApprover,
- setSelectedApprover,
- designation,
- selectedDesignation,
- setSelectedDesignation,
- department,
- selectedDept,
- setSelectedDept,
- approverLoading=false,
-}) => {
-
- let checkConditions = true
- if (action.isTerminateState) checkConditions = false;
-
- if(designation?.length===0 || department?.length===0) return {}
-
- return {
- label: {
- heading: `WORKS_CHECK_FORWARD`,
- submit: `WORKS_FORWARD_FOR_APPROVAL`,
- cancel: "WORKS_CANCEL",
- },
- form: [
- {
- body:[
- {
- label: !checkConditions ? null : t("WORKS_APPROVER_DEPT"),
- placeholder: !checkConditions ? null : t("WF_ASSIGNEE_NAME_PLACEHOLDER"),
- isMandatory: true,
- type: "goToDefaultCase",
- populators: !checkConditions ? null : (
- {
- setSelectedDept(val)
- setSelectedApprover("")
- //setValue()
- }}
- selected={selectedDept}
- t={t}
- />
- ),
- },
- {
- label: !checkConditions ? null : t("WORKS_APPROVER_DESIGNATION"),
- //placeholder: !checkConditions ? null : t("WF_ASSIGNEE_NAME_PLACEHOLDER"),
- isMandatory: true,
- type: "goToDefaultCase",
- populators: !checkConditions ? null : (
- {
- setSelectedDesignation(val)
- setSelectedApprover("")
- //resetting approver dropdown when dept/designation changes
- }}
- selected={selectedDesignation}
- t={t}
- />
- ),
- },
- {
- label: !checkConditions ? null : t("WORKS_APPROVER"),
- //placeholder: !checkConditions ? null : t("WF_ASSIGNEE_NAME_PLACEHOLDER"),
- isMandatory: true,
- type: "goToDefaultCase",
- populators: !checkConditions ? null : (
- approverLoading ? :
- ),
- },
- {
- label: t("WF_COMMON_COMMENTS"),
- type: "textarea",
- populators: {
- name: "comments",
- },
- },
- ]
- }
- ]
- }
-}
-
-export default configCheckModal
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/configRejectModal.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/configRejectModal.js
deleted file mode 100644
index ae4be5af3fd..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/configRejectModal.js
+++ /dev/null
@@ -1,127 +0,0 @@
-import { Dropdown,LabelFieldPair,CardLabel} from '@egovernments/digit-ui-react-components';
-import React, { useState } from 'react'
-
-const configRejectModal = ({
- t,
- action,
- rejectReasons,
- selectedReason,
- setSelectedReason,
- loiNumber,
- department,
- estimateNumber
-}) => {
-
- let checkConditions = true
- if (action.isTerminateState) checkConditions = false;
-
- if(rejectReasons?.length === 0) return {}
- if(loiNumber){
- return {
- label: {
- heading: `WORKS_REJECT_LOI`,
- submit: `WORKS_REJECT_LOI`,
- //cancel: "CS_COMMON_CANCEL",
- },
- form: [
- {
- body: [
- {
- withoutLabel:true,
- populators:
- {t("WORKS_DEPARTMENT")}
- {"ENGG"}
- ,
- },
- {
- //label: t("WORKS_LOI_ID"),
- //type: "text",
- withoutLabel: true,
- populators:
- {t("WORKS_LOI_ID")}
- {loiNumber}
-
- },
- {
- label: !checkConditions ? null : t("WORKS_REJECT_REASON"),
- //placeholder: !checkConditions ? null : t("WF_ASSIGNEE_NAME_PLACEHOLDER"),
- // isMandatory: false,
- type: "goToDefaultCase",
- populators: !checkConditions ? null : (
-
- ),
- },
- {
- label: t("WF_COMMON_COMMENTS"),
- type: "textarea",
- populators: {
- name: "comments",
- },
- },
- ]
- }
- ]
- }
- }else{
- return {
- label: {
- heading: `WORKS_REJECT_ESTIMATE`,
- submit: `WORKS_REJECT_ESTIMATE`,
- //cancel: "CS_COMMON_CANCEL",
- },
- form: [
- {
- body: [
- {
- withoutLabel:true,
- populators:
- {t("WORKS_DEPARTMENT")}
- {"ENGG"}
- ,
- },
- {
- //label: t("WORKS_LOI_ID"),
- //type: "text",
- withoutLabel: true,
- populators:
- {t("WORKS_ESTIMATE_ID")}
- {estimateNumber}
-
- },
- {
- label: !checkConditions ? null : t("WORKS_REJECT_REASON"),
- //placeholder: !checkConditions ? null : t("WF_ASSIGNEE_NAME_PLACEHOLDER"),
- // isMandatory: false,
- type: "goToDefaultCase",
- populators: !checkConditions ? null : (
-
- ),
- },
- {
- label: t("WF_COMMON_COMMENTS"),
- type: "textarea",
- populators: {
- name: "comments",
- },
- },
- ]
- }
- ]
- }
-
- }
-}
-
-export default configRejectModal
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/configViewBillApproveModal.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/configViewBillApproveModal.js
deleted file mode 100644
index cd01fdc4414..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/configViewBillApproveModal.js
+++ /dev/null
@@ -1,57 +0,0 @@
-import React from 'react'
-import { LabelFieldPair,CardLabel} from '@egovernments/digit-ui-react-components';
-
-const configViewBillApprovalModal = ({
- t,
-}) => {
- const fieldLabelStyle = {
- "display" : "grid",
- "gridTemplateColumns" : "60% 1fr"
- };
- return {
- label: {
- heading: t("EXP_PROCESSINGMODAL_HEADER"),
- submit: t("EXP_FORWARD_FOR_APPROVAL"),
- cancel: t("CS_COMMON_CANCEL"),
- },
- form: [
- {
- body: [
- {
- withoutLabel:true,
- populators:
- {t("EXP_DEPARTMENT")}
- Engineering
- ,
- },
- {
- withoutLabel:true,
- populators:
- {t("EXP_DESIGNATION")}
- Junior Engineer
- ,
- },
- {
- withoutLabel:true,
- populators:
- {t("EXP_APPROVER")}
- {"RASHMI"}
- ,
- },
- {
- label: t("WF_COMMON_COMMENTS"),
- type: "textarea",
- populators: {
- name: "comments",
- },
- },
- ],
- },
- ],
- defaultValues: {
- comments: "",
- },
- };
-}
-
-export default configViewBillApprovalModal
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/configViewBillCheckModal.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/configViewBillCheckModal.js
deleted file mode 100644
index 53204b28e75..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/configViewBillCheckModal.js
+++ /dev/null
@@ -1,107 +0,0 @@
-import { Dropdown, Loader } from '@egovernments/digit-ui-react-components';
-import React, { useState } from 'react'
-
-const configViewBillCheckModal = ({
- t,
- approvers,
- selectedApprover,
- setSelectedApprover,
- designation,
- selectedDesignation,
- setSelectedDesignation,
- department,
- selectedDept,
- setSelectedDept,
- approverLoading = false,
-}) => {
-
- let checkConditions = true
-
-
- if (designation?.length === 0 || department?.length === 0) return {}
-
- return {
- label: {
- heading: t("EXP_FORWARD_BILL_FOR_APPROVAL"),
- submit: t("EXP_FORWARD_BILL_FOR_APPROVAL"),
- cancel: t("CS_COMMON_CANCEL"),
- },
- form: [
- {
- body: [
- {
- label: !checkConditions ? null : t("WORKS_APPROVER_DEPT"),
- placeholder: !checkConditions ? null : t("WF_ASSIGNEE_NAME_PLACEHOLDER"),
- isMandatory: true,
- type: "goToDefaultCase",
- populators: !checkConditions ? null : (
- {
- setSelectedDept(val)
- setSelectedApprover("")
- //setValue()
- }}
- selected={selectedDept}
- t={t}
- />
- ),
- },
- {
- label: !checkConditions ? null : t("WORKS_APPROVER_DESIGNATION"),
- //placeholder: !checkConditions ? null : t("WF_ASSIGNEE_NAME_PLACEHOLDER"),
- isMandatory: true,
- type: "goToDefaultCase",
- name: "designation",
- populators: !checkConditions ? null : (
- {
- setSelectedDesignation(val)
- setSelectedApprover("")
- //resetting approver dropdown when dept/designation changes
- }}
- selected={selectedDesignation}
- t={t}
- />
- ),
- },
- {
- label: !checkConditions ? null : t("WORKS_APPROVER"),
- //placeholder: !checkConditions ? null : t("WF_ASSIGNEE_NAME_PLACEHOLDER"),
- isMandatory: true,
- type: "goToDefaultCase",
- populators: !checkConditions ? null : (
- approverLoading ? :
- ),
- },
- {
- label: t("WF_COMMON_COMMENTS"),
- type: "textarea",
- populators: {
- name: "comments",
- },
- },
- ]
- }
- ]
- }
-}
-
-export default configViewBillCheckModal;
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/configViewBillRejectModal.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/configViewBillRejectModal.js
deleted file mode 100644
index 716d6179d10..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/configViewBillRejectModal.js
+++ /dev/null
@@ -1,59 +0,0 @@
-import React from 'react'
-import { LabelFieldPair,CardLabel} from '@egovernments/digit-ui-react-components';
-
-const configViewBillRejectModal = ({
- t,
-}) => {
-
- const fieldLabelStyle = {
- "display" : "grid",
- "gridTemplateColumns" : "60% 1fr"
- };
-
- return {
- label: {
- heading: t("EXP_PROCESSINGMODAL_HEADER"),
- submit: t("EXP_CONFIRM_REJECT"),
- cancel: t("CS_COMMON_CANCEL"),
- },
- form: [
- {
- body: [
- {
- withoutLabel:true,
- populators:
- {t("EXP_DEPARTMENT")}
- Engineering
- ,
- },
- {
- withoutLabel:true,
- populators:
- {t("EXP_DESIGNATION")}
- Junior Engineer
- ,
- },
- {
- withoutLabel:true,
- populators:
- {t("EXP_REJECTED_BY")}
- {"RASHMI"}
- ,
- },
- {
- label: t("WF_COMMON_COMMENTS"),
- type: "textarea",
- populators: {
- name: "comments",
- },
- },
- ]
- }
- ],
- defaultValues : {
- comments : "",
- }
- }
-}
-
-export default configViewBillRejectModal
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/index.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/index.js
deleted file mode 100644
index a736b8ed3eb..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/config/index.js
+++ /dev/null
@@ -1,47 +0,0 @@
-import { configAssignDso } from "./AssignDso";
-import { configCompleteApplication } from "./CompleteApplication";
-import { configReassignDSO } from "./ReassignDso";
-import { configRejectApplication } from "./RejectApplication";
-import { configAcceptDso } from "./AcceptDso";
-import { configPTApproverApplication } from "./PTApproverApplication";
-import { configPTAssessProperty } from "./PTAssessProperty";
-import { configTLApproverApplication } from "./TLApproverApplication";
-import { configBPAREGApproverApplication } from "./BPAREGApproverApplication";
-import { configBPAApproverApplication } from "./BPAApproverApplication";
-import { configNOCApproverApplication } from "./NOCApproverApplication";
-import { configWSApproverApplication } from "./WSApproverApplication";
-import { configWSDisConnectApplication } from "./WSDisconnectApplication";
-import configCheckModal from "./configCheckModal"
-import configApproveModal from "./configApproveModal"
-import configRejectModal from "./configRejectModal"
-import configAttendanceApproveModal from "./configAttendanceApproveModal";
-import configAttendanceCheckModal from "./configAttendanceCheckModal";
-import configAttendanceRejectModal from "./configAttendanceRejectModal";
-import configViewBillApproveModal from "./configViewBillApproveModal";
-import configViewBillCheckModal from "./configViewBillCheckModal";
-import configViewBillRejectModal from "./configViewBillRejectModal";
-
-export {
- configAttendanceRejectModal,
- configAttendanceCheckModal,
- configAttendanceApproveModal,
- configCheckModal,
- configApproveModal,
- configRejectModal,
- configAssignDso,
- configCompleteApplication,
- configReassignDSO,
- configRejectApplication,
- configAcceptDso,
- configPTApproverApplication,
- configPTAssessProperty,
- configTLApproverApplication,
- configBPAREGApproverApplication,
- configBPAApproverApplication,
- configNOCApproverApplication,
- configWSApproverApplication,
- configWSDisConnectApplication,
- configViewBillRejectModal,
- configViewBillCheckModal,
- configViewBillApproveModal
-};
diff --git a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/index.js b/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/index.js
deleted file mode 100644
index feb622ab712..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/packages/modules/templates/ApplicationDetails/index.js
+++ /dev/null
@@ -1,368 +0,0 @@
-import React, { useEffect, useState } from "react";
-import { useTranslation } from "react-i18next";
-import { useQueryClient } from "react-query";
-import { format } from "date-fns";
-
-import { Loader } from "@egovernments/digit-ui-react-components";
-
-import ActionModal from "./Modal";
-
-import { useHistory, useParams } from "react-router-dom";
-import ApplicationDetailsContent from "./components/ApplicationDetailsContent";
-import ApplicationDetailsToast from "./components/ApplicationDetailsToast";
-import ApplicationDetailsActionBar from "./components/ApplicationDetailsActionBar";
-import ApplicationDetailsWarningPopup from "./components/ApplicationDetailsWarningPopup";
-
-const ApplicationDetails = (props) => {
- const tenantId = Digit.ULBService.getCurrentTenantId();
- const state = Digit.ULBService.getStateId();
- const { t } = useTranslation();
- const history = useHistory();
- let { id: applicationNumber } = useParams();
- const [displayMenu, setDisplayMenu] = useState(false);
- const [selectedAction, setSelectedAction] = useState(null);
- const [showModal, setShowModal] = useState(false);
- const [isEnableLoader, setIsEnableLoader] = useState(false);
- const [isWarningPop, setWarningPopUp] = useState(false);
- const [modify, setModify] = useState(false);
- const [saveAttendanceState, setSaveAttendanceState] = useState({ displaySave : false, updatePayload: []})
-
- const {
- applicationDetails,
- showToast,
- setShowToast,
- isLoading,
- isDataLoading,
- applicationData,
- mutate,
- nocMutation,
- workflowDetails,
- businessService,
- closeToast,
- moduleCode,
- timelineStatusPrefix,
- forcedActionPrefix,
- statusAttribute,
- ActionBarStyle,
- MenuStyle,
- paymentsList,
- showTimeLine = true,
- oldValue,
- isInfoLabel = false,
- clearDataDetails,
- noBoxShadow,
- sectionHeadStyle,
- showActionBar = true
- } = props;
-
- useEffect(() => {
- if (showToast) {
- workflowDetails.revalidate();
- }
- }, [showToast]);
-
- function onActionSelect(action) {
- if (action) {
- if(action?.isToast){
- setShowToast({ key: "error", error: { message: action?.toastMessage } });
- setTimeout(closeToast, 5000);
- }
- else if (action?.isWarningPopUp) {
- setWarningPopUp(true);
- } else if (action?.redirectionUrll) {
- //here do the loi edit upon rejection
- if (action?.redirectionUrll?.action === "EDIT_LOI_APPLICATION") {
- history.push(`${action?.redirectionUrll?.pathname}`, { data: action?.redirectionUrll?.state });
- }
- if (action?.redirectionUrll?.action === "EDIT_ESTIMATE_APPLICATION") {
- history.push(`${action?.redirectionUrll?.pathname}`,{ data: action?.redirectionUrll?.state });
- }
-
- } else if (!action?.redirectionUrl) {
- if(action?.action === 'EDIT') setModify(true)
- else setShowModal(true);
- } else {
- history.push({
- pathname: action.redirectionUrl?.pathname,
- state: { ...action.redirectionUrl?.state },
- });
- }
- }
- setSelectedAction(action);
- setDisplayMenu(false);
- }
-
- const queryClient = useQueryClient();
-
- const closeModal = () => {
- setSelectedAction(null);
- setShowModal(false);
- };
-
- const closeWarningPopup = () => {
- setWarningPopUp(false);
- };
-
- const getResponseHeader = (action) => {
-
- if(action?.includes("CHECK")){
- return t("WORKS_LOI_RESPONSE_FORWARD_HEADER")
- } else if (action?.includes("APPROVE")){
- return t("WORKS_LOI_RESPONSE_APPROVE_HEADER")
- }else if(action?.includes("REJECT")){
- return t("WORKS_LOI_RESPONSE_REJECT_HEADER")
- }
- }
-
- const getResponseMessage = (action,updatedLOI) => {
-
- if (action?.includes("CHECK")) {
- return t("WORKS_LOI_RESPONSE_MESSAGE_CHECK", { loiNumber: updatedLOI?.letterOfIndentNumber,name:"Nipun",designation:"SE" })
- } else if (action?.includes("APPROVE")) {
- return t("WORKS_LOI_RESPONSE_MESSAGE_APPROVE", { loiNumber: updatedLOI?.letterOfIndentNumber })
- } else if (action?.includes("REJECT")) {
- return t("WORKS_LOI_RESPONSE_MESSAGE_REJECT", { loiNumber: updatedLOI?.letterOfIndentNumber })
- }
- }
-
- const getEstimateResponseHeader = (action) => {
-
- if(action?.includes("CHECK")){
- return t("WORKS_ESTIMATE_RESPONSE_FORWARD_HEADER")
- } else if (action?.includes("TECHNICALSANCATION")){
- return t("WORKS_ESTIMATE_RESPONSE_FORWARD_HEADER")
- }else if (action?.includes("ADMINSANCTION")){
- return t("WORKS_ESTIMATE_RESPONSE_APPROVE_HEADER")
- }else if(action?.includes("REJECT")){
- return t("WORKS_ESTIMATE_RESPONSE_REJECT_HEADER")
- }
- }
-
- const getEstimateResponseMessage = (action,updatedEstimate) => {
-
- if (action?.includes("CHECK")) {
- return t("WORKS_ESTIMATE_RESPONSE_MESSAGE_CHECK", { estimateNumber: updatedEstimate?.estimateNumber,Name:"Super",Designation:"SE",Department:"Health" })
- } else if (action?.includes("TECHNICALSANCATION")) {
- return t("WORKS_ESTIMATE_RESPONSE_MESSAGE_CHECK", { estimateNumber: updatedEstimate?.estimateNumber,Name:"Super",Designation:"SE",Department:"Health" })
- } else if (action?.includes("ADMINSANCTION")) {
- return t("WORKS_ESTIMATE_RESPONSE_MESSAGE_APPROVE", { estimateNumber: updatedEstimate?.estimateNumber })
- } else if (action?.includes("REJECT")) {
- return t("WORKS_ESTIMATE_RESPONSE_MESSAGE_REJECT", { estimateNumber: updatedEstimate?.estimateNumber })
- }
- }
-
- const getAttendanceResponseHeaderAndMessage = (action) => {
- let response = {}
- if (action?.includes("VERIFY")) {
- response.header = t("ATM_ATTENDANCE_VERIFIED")
- response.message = t("ATM_ATTENDANCE_VERIFIED_SUCCESS")
- } else if (action?.includes("REJECT")) {
- response.header = t("ATM_ATTENDANCE_REJECTED")
- response.message = t("ATM_ATTENDANCE_REJECTED_SUCCESS")
- } else if (action?.includes("APPROVE")) {
- response.header = t("ATM_ATTENDANCE_APPROVED")
- response.message = t("ATM_ATTENDANCE_APPROVED_SUCCESS")
- }
- return response
- }
-
- const submitAction = async (data, nocData = false, isOBPS = {}) => {
- const performedAction = data?.workflow?.action
- setIsEnableLoader(true);
- if (mutate) {
- setIsEnableLoader(true);
- mutate(data, {
- onError: (error, variables) => {
- setIsEnableLoader(false);
- setShowToast({ key: "error", error });
- setTimeout(closeToast, 5000);
- },
- onSuccess: (data, variables) => {
- setIsEnableLoader(false);
- //just history.push to the response component from here and show relevant details
- if(data?.letterOfIndents?.[0]){
- const updatedLOI = data?.letterOfIndents?.[0]
- const state = {
- header:getResponseHeader(performedAction,updatedLOI),
- id: updatedLOI?.letterOfIndentNumber,
- info: t("WORKS_LOI_ID"),
- message: getResponseMessage(performedAction,updatedLOI),
- links: [
- {
- name: t("WORKS_CREATE_NEW_LOI"),
- redirectUrl: `/${window.contextPath}/employee/works/create-loi`,
- code: "",
- svg: "CreateEstimateIcon",
- isVisible:false,
- type:"add"
- },
- {
- name: t("WORKS_GOTO_LOI_INBOX"),
- redirectUrl: `/${window.contextPath}/employee/works/LOIInbox`,
- code: "",
- svg: "CreateEstimateIcon",
- isVisible:true,
- type:"inbox"
- },
- ],
- responseData:data,
- requestData:variables
- }
- history.push(`/${window.contextPath}/employee/works/response`, state)
- }
- if(data?.estimates?.[0]){
- const updatedEstimate = data?.estimates?.[0]
- const state = {
- header:getEstimateResponseHeader(performedAction,updatedEstimate),
- id: updatedEstimate?.estimateNumber,
- info: t("WORKS_ESTIMATE_ID"),
- message: getEstimateResponseMessage(performedAction,updatedEstimate),
- links: [
- {
- name: t("WORKS_CREATE_ESTIMATE"),
- redirectUrl: `/${window.contextPath}/employee/works/create-estimate`,
- code: "",
- svg: "CreateEstimateIcon",
- isVisible:false,
- type:"add"
- },
- {
- name: t("WORKS_GOTO_ESTIMATE_INBOX"),
- redirectUrl: `/${window.contextPath}/employee/works/inbox`,
- code: "",
- svg: "RefreshIcon",
- isVisible:true,
- type:"inbox"
- },
- ],
- responseData:data,
- requestData:variables
- }
- history.push(`/${window.contextPath}/employee/works/response`, state)
- }
- if (isOBPS?.bpa) {
- data.selectedAction = selectedAction;
- history.replace(`/${window?.contextPath}/employee/obps/response`, { data: data });
- }
- if (isOBPS?.isStakeholder) {
- data.selectedAction = selectedAction;
- history.push(`/${window?.contextPath}/employee/obps/stakeholder-response`, { data: data });
- }
- if (isOBPS?.isNoc) {
- history.push(`/${window?.contextPath}/employee/noc/response`, { data: data });
- }
- if (data?.Amendments?.length > 0 ){
- //RAIN-6981 instead just show a toast here with appropriate message
- //show toast here and return
- //history.push("/${window?.contextPath}/employee/ws/response-bill-amend", { status: true, state: data?.Amendments?.[0] })
-
- if(variables?.AmendmentUpdate?.workflow?.action.includes("SEND_BACK")){
- setShowToast({ key: "success", label: t("ES_MODIFYSWCONNECTION_SEND_BACK_UPDATE_SUCCESS")})
- } else if (variables?.AmendmentUpdate?.workflow?.action.includes("RE-SUBMIT")){
- setShowToast({ key: "success", label: t("ES_MODIFYSWCONNECTION_RE_SUBMIT_UPDATE_SUCCESS") })
- } else if (variables?.AmendmentUpdate?.workflow?.action.includes("APPROVE")){
- setShowToast({ key: "success", label: t("ES_MODIFYSWCONNECTION_APPROVE_UPDATE_SUCCESS") })
- }
- else if (variables?.AmendmentUpdate?.workflow?.action.includes("REJECT")){
- setShowToast({ key: "success", label: t("ES_MODIFYWSCONNECTION_REJECT_UPDATE_SUCCESS") })
- }
- return
- }
- if(data?.musterRolls?.[0]) {
- const musterRoll = data?.musterRolls?.[0]
- const response = getAttendanceResponseHeaderAndMessage(performedAction)
- const state = {
- header: response?.header,
- message: response?.message,
- info: t("ATM_REGISTER_ID_WEEK"),
- id: `${musterRoll.registerId} | ${format(new Date(musterRoll.startDate), "dd/MM/yyyy")} - ${format(new Date(musterRoll.endDate), "dd/MM/yyyy")}`,
- }
- history.push(`/${window.contextPath}/employee/attendencemgmt/response`, state)
- }
- setShowToast({ key: "success", action: selectedAction });
- clearDataDetails && setTimeout(clearDataDetails, 3000);
- setTimeout(closeToast, 5000);
- queryClient.clear();
- queryClient.refetchQueries("APPLICATION_SEARCH");
- //push false status when reject
-
- },
- });
- }
-
- closeModal();
- };
-
- if (isLoading || isEnableLoader) {
- return ;
- }
-
- return (
-
- {!isLoading ? (
-
-
- {showModal ? (
-
- ) : null}
- {isWarningPop ? (
-
- ) : null}
-
- {showActionBar && }
-
- ) : (
-
- )}
-
- );
-};
-
-export default ApplicationDetails;
diff --git a/frontend/micro-ui/web/micro-ui-internals/publish-develop.sh b/frontend/micro-ui/web/micro-ui-internals/publish-develop.sh
deleted file mode 100644
index 4909658c697..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/publish-develop.sh
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/bin/bash
-
-BASEDIR="$(cd "$(dirname "$0")" && pwd)"
-
-msg() {
- echo -e "\n\n\033[32;32m$1\033[0m"
-}
-
-
-# msg "Pre-building all packages"
-# yarn build
-# sleep 5
-
-msg "Building and publishing css"
-cd "$BASEDIR/packages/css" && rm -rf dist && yarn && npm publish --tag campaign-1.0
-
-
-# msg "Building and publishing libraries"
-# cd "$BASEDIR/packages/modules/workbench-hcm" && rm -rf dist && yarn&& npm publish --tag workbench-1.0
-
diff --git a/frontend/micro-ui/web/micro-ui-internals/publish.sh b/frontend/micro-ui/web/micro-ui-internals/publish.sh
deleted file mode 100644
index 4909658c697..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/publish.sh
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/bin/bash
-
-BASEDIR="$(cd "$(dirname "$0")" && pwd)"
-
-msg() {
- echo -e "\n\n\033[32;32m$1\033[0m"
-}
-
-
-# msg "Pre-building all packages"
-# yarn build
-# sleep 5
-
-msg "Building and publishing css"
-cd "$BASEDIR/packages/css" && rm -rf dist && yarn && npm publish --tag campaign-1.0
-
-
-# msg "Building and publishing libraries"
-# cd "$BASEDIR/packages/modules/workbench-hcm" && rm -rf dist && yarn&& npm publish --tag workbench-1.0
-
diff --git a/frontend/micro-ui/web/micro-ui-internals/scripts/create.sh b/frontend/micro-ui/web/micro-ui-internals/scripts/create.sh
deleted file mode 100755
index 9de72331774..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/scripts/create.sh
+++ /dev/null
@@ -1,3 +0,0 @@
-#!/bin/bash
-
-./scripts/run.sh core utilities
diff --git a/frontend/micro-ui/web/micro-ui-internals/scripts/deploy.sh b/frontend/micro-ui/web/micro-ui-internals/scripts/deploy.sh
deleted file mode 100755
index 5b0c7b831ed..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/scripts/deploy.sh
+++ /dev/null
@@ -1,8 +0,0 @@
-#!/bin/bash
-
-curl -v -X POST https://builds.digit.org/job/builds/job/digit-ui/buildWithParameters \
- --user saurabh-egov:114cbf3df675835931688b2d3f0014a1f7 \
- --data-urlencode json='{"parameter": [{"name":"BRANCH", "value":"origin/'$1'"}]}'
-
-# curl https://builds.digit.org/job/builds/job/digit-ui/lastBuild/api/json | grep --color result\":null
-
diff --git a/frontend/micro-ui/web/micro-ui-internals/scripts/jenkins.sh b/frontend/micro-ui/web/micro-ui-internals/scripts/jenkins.sh
deleted file mode 100755
index a1711fec55b..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/scripts/jenkins.sh
+++ /dev/null
@@ -1,3 +0,0 @@
-#!/bin/bash
-
-./scripts/deploy.sh dev
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/scripts/run.sh b/frontend/micro-ui/web/micro-ui-internals/scripts/run.sh
deleted file mode 100755
index f00c59f13b8..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/scripts/run.sh
+++ /dev/null
@@ -1,32 +0,0 @@
-#!/bin/bash
-
-MODULES=( "components" "core" "libraries" "example" )
-
-RUNARGS=()
-BUILDARGS=()
-
-for var in "$@"
-do
- BUILDARGS=( ${BUILDARGS[@]} build:"$var" )
- RUNARGS=( ${RUNARGS[@]} dev:"$var" )
-done
-
-a=0
-while [ "$a" -lt 3 ]
-do
- BUILD[$a]=build:${MODULES[$a]}
- a=` expr $a + 1 `
-done
-
-echo "BUILDING MODULES:-" ${BUILD[*]} ${BUILDARGS[*]}
-yarn run-p ${BUILD[*]} ${BUILDARGS[*]}
-
-b=0
-while [ "$b" -lt 4 ]
-do
- RUN[$b]=dev:${MODULES[$b]}
- b=` expr $b + 1 `
-done
-
-echo "SERVING MODULES:-" ${RUN[*]} ${RUNARGS[*]}
-yarn run-p ${RUN[*]} ${RUNARGS[*]}
\ No newline at end of file
diff --git a/frontend/micro-ui/web/micro-ui-internals/test.js b/frontend/micro-ui/web/micro-ui-internals/test.js
deleted file mode 100644
index 60c958d0bac..00000000000
--- a/frontend/micro-ui/web/micro-ui-internals/test.js
+++ /dev/null
@@ -1,31 +0,0 @@
-const middleWare_1 = (data, _break, _next) => {
- data.a = "a";
- _next(data);
-};
-
-
-const middleWare_2 = (data, _break, _next) => {
- data.b = "b";
- // _break();
- _next(data);
-};
-
-const middleWare_3 = (data, _break, _next) => {
- data.c = "c";
- _next(data);
-};
-
-let middleWares = [middleWare_1, middleWare_2, middleWare_3];
-
-const callMiddlewares = () => {
- let applyBreak = false;
- let itr = -1;
- let _break = () => (applyBreak = true);
- let _next = (data) => {
- if (!applyBreak && ++itr < middleWares.length) middleWares[itr](data, _break, _next);
- else return;
- };
- _next({});
-};
-
-callMiddlewares();
diff --git a/frontend/micro-ui/web/microplan/App.js b/frontend/micro-ui/web/microplan/App.js
deleted file mode 100644
index afcd26669c6..00000000000
--- a/frontend/micro-ui/web/microplan/App.js
+++ /dev/null
@@ -1,61 +0,0 @@
-import React from "react";
-import { initLibraries } from "@egovernments/digit-ui-libraries";
-
-import { DigitUI } from "@egovernments/digit-ui-module-core";
-
-import { UICustomizations } from "./Customisations/UICustomizations";
-import { initMicroplanningComponents } from "@egovernments/digit-ui-module-hcmmicroplanning";
-
-
-window.contextPath = window?.globalConfigs?.getConfig("CONTEXT_PATH");
-
-const enabledModules = [
- "DSS",
- "NDSS",
- "Utilities",
- "HRMS",
- "Engagement",
- "Workbench",
- "Microplanning"
-];
-
-const moduleReducers = (initData) => ({
- initData,
-});
-
-const initDigitUI = () => {
- window.Digit.ComponentRegistryService.setupRegistry({
-
- });
-
-
- initMicroplanningComponents()
- window.Digit.Customizations = {
- PGR: {},
- commonUiConfig: UICustomizations,
- };
-};
-
-initLibraries().then(() => {
- initDigitUI();
-});
-
-function App() {
- window.contextPath = window?.globalConfigs?.getConfig("CONTEXT_PATH");
- const stateCode =
- window.globalConfigs?.getConfig("STATE_LEVEL_TENANT_ID") ||
- process.env.REACT_APP_STATE_LEVEL_TENANT_ID;
- if (!stateCode) {
- return stateCode is not defined
;
- }
- return (
-
- );
-}
-
-export default App;
diff --git a/frontend/micro-ui/web/microplan/Dockerfile b/frontend/micro-ui/web/microplan/Dockerfile
deleted file mode 100644
index 56388b8e2d7..00000000000
--- a/frontend/micro-ui/web/microplan/Dockerfile
+++ /dev/null
@@ -1,30 +0,0 @@
-FROM egovio/alpine-node-builder-14:yarn AS build
-#FROM ghcr.io/egovernments/alpine-node-builder-14:yarn AS build
-RUN apk update && apk upgrade
-RUN apk add --no-cache git>2.30.0
-ARG WORK_DIR
-WORKDIR /app
-ENV NODE_OPTIONS "--max-old-space-size=4792"
-
-COPY ${WORK_DIR} .
-RUN ls -lah
-
-#RUN node web/envs.js
-RUN cd web/ \
- && node -e 'console.log(v8.getHeapStatistics().heap_size_limit/(1024*1024))' \
- && node -e 'console.log("core only")' \
- && cd microplan/ \
- && chmod +x ./install-deps.sh \
- && ./install-deps.sh \
- && cd ../ \
- && yarn install \
- && yarn build:webpack
-
-FROM nginx:mainline-alpine
-#FROM ghcr.io/egovernments/nginx:mainline-alpine
-ENV WORK_DIR=/var/web/microplan-ui
-
-RUN mkdir -p ${WORK_DIR}
-
-COPY --from=build /app/web/build ${WORK_DIR}/
-COPY --from=build /app/web/microplan/nginx.conf /etc/nginx/conf.d/default.conf
diff --git a/frontend/micro-ui/web/microplan/install-deps.sh b/frontend/micro-ui/web/microplan/install-deps.sh
deleted file mode 100644
index b090c8d6f04..00000000000
--- a/frontend/micro-ui/web/microplan/install-deps.sh
+++ /dev/null
@@ -1,18 +0,0 @@
-#!/bin/sh
-
-BRANCH="$(git branch --show-current)"
-
-echo "Main Branch: $BRANCH"
-
-INTERNALS="micro-ui-internals"
-cd ..
-
-cp microplan/App.js src
-cp microplan/package.json package.json
-cp microplan/webpack.config.js webpack.config.js
-cp microplan/inter-package.json $INTERNALS/package.json
-
-cp $INTERNALS/example/src/UICustomizations.js src/Customisations
-
-echo "UI :: microplan " && echo "Branch: $(git branch --show-current)" && echo "$(git log -1 --pretty=%B)" && echo "installing packages"
-
diff --git a/frontend/micro-ui/web/microplan/inter-package.json b/frontend/micro-ui/web/microplan/inter-package.json
deleted file mode 100644
index 635c9cc954b..00000000000
--- a/frontend/micro-ui/web/microplan/inter-package.json
+++ /dev/null
@@ -1,61 +0,0 @@
-{
- "name": "egovernments",
- "version": "1.0.0",
- "main": "index.js",
- "workspaces": [
- "example",
- "packages/css",
- "packages/modules/*"
- ],
- "author": "JaganKumar ",
- "license": "MIT",
- "private": true,
- "engines": {
- "node": ">=14"
- },
- "scripts": {
- "start": "SKIP_PREFLIGHT_CHECK=true run-s build start:dev",
- "sprint": "SKIP_PREFLIGHT_CHECK=true run-s start:script",
- "start:dev": "run-p dev:**",
- "start:script": "./scripts/create.sh",
- "dev:css": "cd packages/css && yarn start",
- "publish:css": "cd packages/css && yarn publish --access public",
- "dev:example": "cd example && yarn start",
- "dev:hcm-microplanning": "cd packages/modules/hcm-microplanning && yarn start",
- "build": "run-p build:**",
- "build:hcm-microplanning": "cd packages/modules/hcm-microplanning && yarn build",
- "deploy:jenkins": "./scripts/jenkins.sh",
- "clean": "rm -rf node_modules"
- },
- "resolutions": {
- "**/@babel/runtime": "7.20.1",
- "**/babel-preset-react-app": "10.0.0",
- "**/babel-loader": "8.2.2",
- "**/@babel/core": "7.14.0",
- "**/@babel/preset-env": "7.14.0",
- "**/@babel/plugin-transform-modules-commonjs": "7.14.0",
- "**/polished":"4.2.2",
- "fast-uri":"2.1.0"
- },
- "devDependencies": {
- "husky": "7.0.4",
- "lint-staged": "12.3.7",
- "npm-run-all": "4.1.5",
- "prettier": "2.1.2"
- },
- "husky": {},
- "lint-staged": {
- "*.{js,css,md}": "prettier --write"
- },
- "dependencies": {
- "lodash": "4.17.21",
- "microbundle-crl": "0.13.11",
- "@egovernments/digit-ui-react-components": "1.8.1-beta.2",
- "react": "17.0.2",
- "react-dom": "17.0.2",
- "react-hook-form": "6.15.8",
- "react-i18next": "11.16.2",
- "react-query": "3.6.1",
- "react-router-dom": "5.3.0"
- }
-}
diff --git a/frontend/micro-ui/web/microplan/nginx.conf b/frontend/micro-ui/web/microplan/nginx.conf
deleted file mode 100644
index 9c84c01c4be..00000000000
--- a/frontend/micro-ui/web/microplan/nginx.conf
+++ /dev/null
@@ -1,12 +0,0 @@
-server
-{
- listen 80;
- underscores_in_headers on;
-
- location /microplan-ui
- {
- root /var/web;
- index index.html index.htm;
- try_files $uri $uri/ /microplan-ui/index.html;
- }
-}
\ No newline at end of file
diff --git a/frontend/micro-ui/web/microplan/package.json b/frontend/micro-ui/web/microplan/package.json
deleted file mode 100644
index dff749d1780..00000000000
--- a/frontend/micro-ui/web/microplan/package.json
+++ /dev/null
@@ -1,80 +0,0 @@
-{
- "name": "micro-ui",
- "version": "1.0.0",
- "author": "Jagankumar ",
- "license": "MIT",
- "private": true,
- "engines": {
- "node": ">=14"
- },
- "workspaces": [
- "micro-ui-internals/packages/modules/*"
- ],
- "homepage": "/microplan-ui",
- "dependencies": {
- "@egovernments/digit-ui-libraries": "1.8.2-beta.1",
- "@egovernments/digit-ui-module-core": "1.8.2-beta.1",
- "@egovernments/digit-ui-module-utilities": "1.0.1-beta.23",
- "@egovernments/digit-ui-react-components": "1.8.2-beta.1",
- "@egovernments/digit-ui-module-hcmmicroplanning":"0.0.1",
- "@egovernments/digit-ui-components": "0.0.2-beta.2",
- "babel-loader": "8.1.0",
- "clean-webpack-plugin": "4.0.0",
- "react": "17.0.2",
- "react-dom": "17.0.2",
- "jsonpath": "^1.1.1",
- "react-router-dom": "5.3.0",
- "react-scripts": "4.0.1",
- "web-vitals": "1.1.2",
- "terser-brunch": "^4.1.0",
- "react-hook-form": "6.15.8",
- "react-i18next": "11.16.2",
- "react-query": "3.6.1",
- "css-loader": "5.2.6",
- "style-loader": "2.0.0",
- "webpack-cli": "4.10.0"
- },
- "devDependencies": {
- "@babel/plugin-proposal-private-property-in-object": "7.21.0",
- "file-loader": "^6.2.0",
- "http-proxy-middleware": "1.3.1",
- "lodash": "4.17.21",
- "microbundle-crl": "0.13.11",
- "react": "17.0.2",
- "react-dom": "17.0.2",
- "react-hook-form": "6.15.8",
- "react-i18next": "11.16.2",
- "react-query": "3.6.1",
- "react-router-dom": "5.3.0",
- "husky": "7.0.4",
- "lint-staged": "12.3.7",
- "npm-run-all": "4.1.5",
- "prettier": "2.1.2"
- },
- "scripts": {
- "start": "react-scripts start",
- "build": "GENERATE_SOURCEMAP=false SKIP_PREFLIGHT_CHECK=true react-scripts build",
- "build:prepare": "./build.sh",
- "build:libraries": "cd micro-ui-internals && yarn build",
- "build:prod": "webpack --mode production",
- "build:webpack": "yarn build:libraries &&cd .. && ls && cd ./web && ls && yarn build:prod",
- "clean": "rm -rf node_modules"
- },
- "eslintConfig": {
- "extends": [
- "react-app"
- ]
- },
- "browserslist": {
- "production": [
- ">0.2%",
- "not dead",
- "not op_mini all"
- ],
- "development": [
- "last 1 chrome version",
- "last 1 firefox version",
- "last 1 safari version"
- ]
- }
-}
\ No newline at end of file
diff --git a/frontend/micro-ui/web/microplan/webpack.config.js b/frontend/micro-ui/web/microplan/webpack.config.js
deleted file mode 100644
index c8036364605..00000000000
--- a/frontend/micro-ui/web/microplan/webpack.config.js
+++ /dev/null
@@ -1,52 +0,0 @@
-const path = require("path");
-const HtmlWebpackPlugin = require("html-webpack-plugin");
-const { CleanWebpackPlugin } = require("clean-webpack-plugin");
-// const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
-
-module.exports = {
- // mode: 'development',
- entry: "./src/index.js",
- devtool: "none",
- module: {
- rules: [
- {
- test: /\.(js)$/,
- exclude: /node_modules/,
- use: ["babel-loader"],
- },
- {
- test: /\.css$/i,
- use: ["style-loader", "css-loader"],
- },
- {
- test: /\.(png|jpe?g|gif)$/i,
- use: [
- {
- loader: 'file-loader',
- },
- ],
- },
- ],
- },
- output: {
- filename: "[name].bundle.js",
- path: path.resolve(__dirname, "build"),
- publicPath: "/microplan-ui/",
- },
- optimization: {
- splitChunks: {
- chunks: 'all',
- minSize:20000,
- maxSize:50000,
- enforceSizeThreshold:50000,
- minChunks:1,
- maxAsyncRequests:30,
- maxInitialRequests:30
- },
- },
- plugins: [
- new CleanWebpackPlugin(),
- // new BundleAnalyzerPlugin(),
- new HtmlWebpackPlugin({ inject: true, template: "public/index.html" }),
- ],
-};
\ No newline at end of file
diff --git a/frontend/micro-ui/web/package.json b/frontend/micro-ui/web/package.json
deleted file mode 100644
index e90ab5a52ba..00000000000
--- a/frontend/micro-ui/web/package.json
+++ /dev/null
@@ -1,85 +0,0 @@
-{
- "name": "micro-ui",
- "version": "0.1.0",
- "author": "Jagankumar ",
- "license": "MIT",
- "private": true,
- "engines": {
- "node": ">=14"
- },
- "workspaces": [
- "micro-ui-internals/packages/libraries",
- "micro-ui-internals/packages/react-components",
- "micro-ui-internals/packages/modules/*"
- ],
- "homepage": "/digit-ui",
- "dependencies": {
- "@egovernments/digit-ui-libraries": "1.8.1-beta.4",
- "@egovernments/digit-ui-module-workbench": "1.0.1-beta.16",
- "@egovernments/digit-ui-module-core": "1.8.2-beta.2",
- "@egovernments/digit-ui-module-hrms": "1.8.0-beta.2",
- "@egovernments/digit-ui-react-components": "1.8.2-beta.6",
- "@egovernments/digit-ui-components": "0.0.2-beta.1",
- "@egovernments/digit-ui-module-dss": "1.8.0-beta",
- "@egovernments/digit-ui-module-common": "1.8.0-beta",
- "@egovernments/digit-ui-module-utilities": "1.0.0-beta",
- "@egovernments/digit-ui-module-engagement": "1.5.20",
- "babel-loader": "8.1.0",
- "clean-webpack-plugin": "4.0.0",
- "react": "17.0.2",
- "react-dom": "17.0.2",
- "jsonpath": "^1.1.1",
- "react-router-dom": "5.3.0",
- "react-scripts": "4.0.1",
- "web-vitals": "1.1.2",
- "terser-brunch": "^4.1.0",
- "react-hook-form": "6.15.8",
- "react-i18next": "11.16.2",
- "react-query": "3.6.1",
- "css-loader": "5.2.6",
- "style-loader": "2.0.0",
- "webpack-cli": "4.10.0"
- },
- "devDependencies": {
- "@babel/plugin-proposal-private-property-in-object": "7.21.0",
- "http-proxy-middleware": "1.3.1",
- "lodash": "4.17.21",
- "microbundle-crl": "0.13.11",
- "react": "17.0.2",
- "react-dom": "17.0.2",
- "react-hook-form": "6.15.8",
- "react-i18next": "11.16.2",
- "react-query": "3.6.1",
- "react-router-dom": "5.3.0",
- "husky": "7.0.4",
- "lint-staged": "12.3.7",
- "npm-run-all": "4.1.5",
- "prettier": "2.1.2"
- },
- "scripts": {
- "start": "react-scripts start",
- "build": "GENERATE_SOURCEMAP=false SKIP_PREFLIGHT_CHECK=true react-scripts build",
- "build:prepare": "./build.sh",
- "build:libraries": "cd micro-ui-internals && yarn build",
- "build:prod": "webpack --mode production",
- "build:webpack": "yarn build:libraries &&cd .. && ls && cd ./web && ls && yarn build:prod",
- "clean": "rm -rf node_modules"
- },
- "eslintConfig": {
- "extends": [
- "react-app"
- ]
- },
- "browserslist": {
- "production": [
- ">0.2%",
- "not dead",
- "not op_mini all"
- ],
- "development": [
- "last 1 chrome version",
- "last 1 firefox version",
- "last 1 safari version"
- ]
- }
-}
\ No newline at end of file
diff --git a/frontend/micro-ui/web/public/index.html b/frontend/micro-ui/web/public/index.html
deleted file mode 100644
index 661b6fa2425..00000000000
--- a/frontend/micro-ui/web/public/index.html
+++ /dev/null
@@ -1,38 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- DIGIT
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/frontend/micro-ui/web/public/robots.txt b/frontend/micro-ui/web/public/robots.txt
deleted file mode 100644
index e9e57dc4d41..00000000000
--- a/frontend/micro-ui/web/public/robots.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-# https://www.robotstxt.org/robotstxt.html
-User-agent: *
-Disallow:
diff --git a/frontend/micro-ui/web/src/App.js b/frontend/micro-ui/web/src/App.js
deleted file mode 100644
index d871f8e8f4c..00000000000
--- a/frontend/micro-ui/web/src/App.js
+++ /dev/null
@@ -1,74 +0,0 @@
-import React from "react";
-import { initLibraries } from "@egovernments/digit-ui-libraries";
-import {
- paymentConfigs,
- PaymentLinks,
- PaymentModule,
-} from "@egovernments/digit-ui-module-common";
-import { DigitUI,initCoreComponents } from "@egovernments/digit-ui-module-core";
-import { initDSSComponents } from "@egovernments/digit-ui-module-dss";
-import { initEngagementComponents } from "@egovernments/digit-ui-module-engagement";
-import { initHRMSComponents } from "@egovernments/digit-ui-module-hrms";
-import { initUtilitiesComponents } from "@egovernments/digit-ui-module-utilities";
-import { UICustomizations } from "./Customisations/UICustomizations";
-import { initWorkbenchComponents } from "@egovernments/digit-ui-module-workbench";
-// import { initWorkbenchHCMComponents } from "@egovernments/digit-ui-module-hcmworkbench";
-
-window.contextPath = window?.globalConfigs?.getConfig("CONTEXT_PATH");
-
-const enabledModules = [
- "DSS",
- "NDSS",
- "Utilities",
- "HRMS",
- "Engagement",
- "Workbench",
- "Microplanning"
-];
-
-const moduleReducers = (initData) => ({
- initData,
-});
-
-const initDigitUI = () => {
- window.Digit.ComponentRegistryService.setupRegistry({
- PaymentModule,
- ...paymentConfigs,
- PaymentLinks,
- });
- initCoreComponents();
- initDSSComponents();
- initHRMSComponents();
- initEngagementComponents();
- initUtilitiesComponents();
- initWorkbenchComponents();
-
- window.Digit.Customizations = {
- PGR: {},
- commonUiConfig: UICustomizations,
- };
-};
-
-initLibraries().then(() => {
- initDigitUI();
-});
-
-function App() {
- window.contextPath = window?.globalConfigs?.getConfig("CONTEXT_PATH");
- const stateCode =
- window.globalConfigs?.getConfig("STATE_LEVEL_TENANT_ID") ||
- process.env.REACT_APP_STATE_LEVEL_TENANT_ID;
- if (!stateCode) {
- return stateCode is not defined
;
- }
- return (
-
- );
-}
-
-export default App;
diff --git a/frontend/micro-ui/web/src/ComponentRegistry.js b/frontend/micro-ui/web/src/ComponentRegistry.js
deleted file mode 100644
index 9bafce3dc89..00000000000
--- a/frontend/micro-ui/web/src/ComponentRegistry.js
+++ /dev/null
@@ -1,11 +0,0 @@
-class Registry {
- constructor(registry = {}) {
- this._registry = registry;
- }
-
- getComponent(id) {
- return this._registry[id];
- }
-}
-
-export default Registry;
diff --git a/frontend/micro-ui/web/src/Customisations/UICustomizations.js b/frontend/micro-ui/web/src/Customisations/UICustomizations.js
deleted file mode 100644
index 6d17ab0d51b..00000000000
--- a/frontend/micro-ui/web/src/Customisations/UICustomizations.js
+++ /dev/null
@@ -1,428 +0,0 @@
-import { Link } from "react-router-dom";
-import _ from "lodash";
-
-//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 || {};
-
-
-
-const businessServiceMap = {
-
- "muster roll": "MR"
-};
-
-const inboxModuleNameMap = {
- "muster-roll-approval": "muster-roll-service",
-};
-
-export const UICustomizations = {
- businessServiceMap,
- updatePayload: (applicationDetails, data, action, businessService) => {
-
- if (businessService === businessServiceMap.estimate) {
- const workflow = {
- comment: data.comments,
- documents: data?.documents?.map((document) => {
- return {
- documentType: action?.action + " DOC",
- fileName: document?.[1]?.file?.name,
- fileStoreId: document?.[1]?.fileStoreId?.fileStoreId,
- documentUid: document?.[1]?.fileStoreId?.fileStoreId,
- tenantId: document?.[1]?.fileStoreId?.tenantId,
- };
- }),
- assignees: data?.assignees?.uuid ? [data?.assignees?.uuid] : null,
- action: action.action,
- };
- //filtering out the data
- Object.keys(workflow).forEach((key, index) => {
- if (!workflow[key] || workflow[key]?.length === 0) delete workflow[key];
- });
-
- return {
- estimate: applicationDetails,
- workflow,
- };
- }
- if (businessService === businessServiceMap.contract) {
- const workflow = {
- comment: data?.comments,
- documents: data?.documents?.map((document) => {
- return {
- documentType: action?.action + " DOC",
- fileName: document?.[1]?.file?.name,
- fileStoreId: document?.[1]?.fileStoreId?.fileStoreId,
- documentUid: document?.[1]?.fileStoreId?.fileStoreId,
- tenantId: document?.[1]?.fileStoreId?.tenantId,
- };
- }),
- assignees: data?.assignees?.uuid ? [data?.assignees?.uuid] : null,
- action: action.action,
- };
- //filtering out the data
- Object.keys(workflow).forEach((key, index) => {
- if (!workflow[key] || workflow[key]?.length === 0) delete workflow[key];
- });
-
- return {
- contract: applicationDetails,
- workflow,
- };
- }
- if (businessService === businessServiceMap?.["muster roll"]) {
- const workflow = {
- comment: data?.comments,
- documents: data?.documents?.map((document) => {
- return {
- documentType: action?.action + " DOC",
- fileName: document?.[1]?.file?.name,
- fileStoreId: document?.[1]?.fileStoreId?.fileStoreId,
- documentUid: document?.[1]?.fileStoreId?.fileStoreId,
- tenantId: document?.[1]?.fileStoreId?.tenantId,
- };
- }),
- assignees: data?.assignees?.uuid ? [data?.assignees?.uuid] : null,
- action: action.action,
- };
- //filtering out the data
- Object.keys(workflow).forEach((key, index) => {
- if (!workflow[key] || workflow[key]?.length === 0) delete workflow[key];
- });
-
- return {
- musterRoll: applicationDetails,
- workflow,
- };
- }
- if(businessService === businessServiceMap?.["works.purchase"]){
- const workflow = {
- comment: data.comments,
- documents: data?.documents?.map((document) => {
- return {
- documentType: action?.action + " DOC",
- fileName: document?.[1]?.file?.name,
- fileStoreId: document?.[1]?.fileStoreId?.fileStoreId,
- documentUid: document?.[1]?.fileStoreId?.fileStoreId,
- tenantId: document?.[1]?.fileStoreId?.tenantId,
- };
- }),
- assignees: data?.assignees?.uuid ? [data?.assignees?.uuid] : null,
- action: action.action,
- };
- //filtering out the data
- Object.keys(workflow).forEach((key, index) => {
- if (!workflow[key] || workflow[key]?.length === 0) delete workflow[key];
- });
-
- const additionalFieldsToSet = {
- 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},
- workflow,
- };
- }
- },
- enableModalSubmit:(businessService,action,setModalSubmit,data)=>{
- if(businessService === businessServiceMap?.["muster roll"] && action.action==="APPROVE"){
- setModalSubmit(data?.acceptTerms)
- }
- },
- enableHrmsSearch: (businessService, action) => {
- if (businessService === businessServiceMap.estimate) {
- return action.action.includes("TECHNICALSANCTION") || action.action.includes("VERIFYANDFORWARD");
- }
- if (businessService === businessServiceMap.contract) {
- return action.action.includes("VERIFY_AND_FORWARD");
- }
- if (businessService === businessServiceMap?.["muster roll"]) {
- return action.action.includes("VERIFY");
- }
- if(businessService === businessServiceMap?.["works.purchase"]){
- return action.action.includes("VERIFY_AND_FORWARD")
- }
- return false;
- },
- getBusinessService: (moduleCode) => {
- if (moduleCode?.includes("estimate")) {
- return businessServiceMap?.estimate;
- } else if (moduleCode?.includes("contract")) {
- return businessServiceMap?.contract;
- } else if (moduleCode?.includes("muster roll")) {
- return businessServiceMap?.["muster roll"];
- }
- else if (moduleCode?.includes("works.purchase")) {
- return businessServiceMap?.["works.purchase"];
- }
- else if (moduleCode?.includes("works.wages")) {
- return businessServiceMap?.["works.wages"];
- }
- else if (moduleCode?.includes("works.supervision")) {
- return businessServiceMap?.["works.supervision"];
- }
- else {
- return businessServiceMap;
- }
- },
- getInboxModuleName: (moduleCode) => {
- if (moduleCode?.includes("estimate")) {
- return inboxModuleNameMap?.estimate;
- } else if (moduleCode?.includes("contract")) {
- return inboxModuleNameMap?.contracts;
- } else if (moduleCode?.includes("attendence")) {
- return inboxModuleNameMap?.attendencemgmt;
- } else {
- return inboxModuleNameMap;
- }
- },
-
- 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
-
- const attendanceRegisterName = data?.body?.inbox?.moduleSearchCriteria?.attendanceRegisterName?.trim();
- 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);
- delete data.body.inbox.moduleSearchCriteria.assignee;
- if (assignee?.code === "ASSIGNED_TO_ME") {
- data.body.inbox.moduleSearchCriteria.assignee = Digit.UserService.getUser().info.uuid;
- }
-
- //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);
- delete data.body.inbox.moduleSearchCriteria.orgId;
- if(selectedOrg) {
- data.body.inbox.moduleSearchCriteria.orgId = selectedOrg?.[0]?.applicationNumber;
- }
-
- // let selectedWard = _.clone(data.body.inbox.moduleSearchCriteria.ward ? data.body.inbox.moduleSearchCriteria.ward : null);
- // delete data.body.inbox.moduleSearchCriteria.ward;
- // if(selectedWard) {
- // data.body.inbox.moduleSearchCriteria.ward = selectedWard?.[0]?.code;
- // }
-
- let states = _.clone(data.body.inbox.moduleSearchCriteria.state ? data.body.inbox.moduleSearchCriteria.state : []);
- let ward = _.clone(data.body.inbox.moduleSearchCriteria.ward ? data.body.inbox.moduleSearchCriteria.ward : []);
- // delete data.body.inbox.moduleSearchCriteria.locality;
- delete data.body.inbox.moduleSearchCriteria.state;
- delete data.body.inbox.moduleSearchCriteria.ward;
-
- // 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 (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;
-
- //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
- return data;
- },
- postProcess: (responseArray, uiConfig) => {
- const statusOptions = responseArray?.statusMap
- ?.filter((item) => item.applicationstatus)
- ?.map((item) => ({ code: item.applicationstatus, i18nKey: `COMMON_MASTERS_${item.applicationstatus}` }));
- if (uiConfig?.type === "filter") {
- let fieldConfig = uiConfig?.fields?.filter((item) => item.type === "dropdown" && item.populators.name === "musterRollStatus");
- if (fieldConfig.length) {
- fieldConfig[0].populators.options = statusOptions;
- }
- }
- },
- additionalCustomizations: (row, key, column, value, t, searchResult) => {
- if (key === "ATM_MUSTER_ROLL_ID") {
- return (
-
-
- {String(value ? (column.translate ? t(column.prefix ? `${column.prefix}${value}` : value) : value) : t("ES_COMMON_NA"))}
-
-
- );
- }
- if (key === "ATM_ATTENDANCE_WEEK") {
- const week = `${Digit.DateUtils.ConvertTimestampToDate(value?.startDate, "dd/MM/yyyy")}-${Digit.DateUtils.ConvertTimestampToDate(
- value?.endDate,
- "dd/MM/yyyy"
- )}`;
- return {week}
;
- }
- if (key === "ATM_NO_OF_INDIVIDUALS") {
- return {value?.length}
;
- }
- if(key === "ATM_AMOUNT_IN_RS"){
- return {value ? Digit.Utils.dss.formatterWithoutRound(value, "number") : t("ES_COMMON_NA")};
- }
- if (key === "ATM_SLA") {
- return parseInt(value) > 0 ? (
- {t(value) || ""}
- ) : (
- {t(value) || ""}
- );
- }
- if (key === "COMMON_WORKFLOW_STATES") {
- 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`)}
- },
- MobileDetailsOnClick: (row, tenantId) => {
- let link;
- Object.keys(row).map((key) => {
- if (key === "ATM_MUSTER_ROLL_ID")
- link = `/${window.contextPath}/employee/attendencemgmt/view-attendance?tenantId=${tenantId}&musterRollNumber=${row[key]}`;
- });
- return link;
- },
- populateReqCriteria: () => {
- const tenantId = Digit.ULBService.getCurrentTenantId();
- return {
- url: "/org-services/organisation/v1/_search",
- params: { limit: 50, offset: 0 },
- body: {
- SearchCriteria: {
- tenantId: tenantId,
- functions : {
- type : "CBO"
- }
- },
- },
- config: {
- enabled: true,
- select: (data) => {
- return data?.organisations;
- },
- },
- };
- },
- },
- SearchWageSeekerConfig: {
- customValidationCheck: (data) => {
- //checking both to and from date are present
- const { createdFrom, createdTo } = data;
- if ((createdFrom === "" && createdTo !== "") || (createdFrom !== "" && createdTo === ""))
- return { warning: true, label: "ES_COMMON_ENTER_DATE_RANGE" };
-
- return false;
- },
- preProcess: (data) => {
- data.params = { ...data.params, tenantId: Digit.ULBService.getCurrentTenantId() };
-
- let requestBody = { ...data.body.Individual };
- const pathConfig = {
- name: "name.givenName",
- };
- const dateConfig = {
- createdFrom: "daystart",
- createdTo: "dayend",
- };
- const selectConfig = {
- wardCode: "wardCode[0].code",
- socialCategory: "socialCategory.code",
- };
- const textConfig = ["name", "individualId"]
- let Individual = Object.keys(requestBody)
- .map((key) => {
- if (selectConfig[key]) {
- requestBody[key] = _.get(requestBody, selectConfig[key], null);
- } else if (typeof requestBody[key] == "object") {
- requestBody[key] = requestBody[key]?.code;
- } else if (textConfig?.includes(key)) {
- requestBody[key] = requestBody[key]?.trim()
- }
- return key;
- })
- .filter((key) => requestBody[key])
- .reduce((acc, curr) => {
- if (pathConfig[curr]) {
- _.set(acc, pathConfig[curr], requestBody[curr]);
- } else if (dateConfig[curr] && dateConfig[curr]?.includes("day")) {
- _.set(acc, curr, Digit.Utils.date.convertDateToEpoch(requestBody[curr], dateConfig[curr]));
- } else {
- _.set(acc, curr, requestBody[curr]);
- }
- return acc;
- }, {});
-
- data.body.Individual = { ...Individual };
- return data;
- },
- additionalCustomizations: (row, key, column, value, t, searchResult) => {
- //here we can add multiple conditions
- //like if a cell is link then we return link
- //first we can identify which column it belongs to then we can return relevant result
- switch (key) {
- case "MASTERS_WAGESEEKER_ID":
- return (
-
-
- {String(value ? (column.translate ? t(column.prefix ? `${column.prefix}${value}` : value) : value) : t("ES_COMMON_NA"))}
-
-
- );
-
- case "MASTERS_SOCIAL_CATEGORY":
- return value ? {String(t(`MASTERS_${value}`))} : t("ES_COMMON_NA");
-
- case "CORE_COMMON_PROFILE_CITY":
- return value ? {String(t(Digit.Utils.locale.getCityLocale(value)))} : t("ES_COMMON_NA");
-
- case "MASTERS_WARD":
- return value ? (
- {String(t(Digit.Utils.locale.getMohallaLocale(value, row?.tenantId)))}
- ) : (
- t("ES_COMMON_NA")
- );
-
- case "MASTERS_LOCALITY":
- return value ? (
- {String(t(Digit.Utils.locale.getMohallaLocale(value, row?.tenantId)))}
- ) : (
- t("ES_COMMON_NA")
- );
- default:
- return t("ES_COMMON_NA");
- }
- },
- MobileDetailsOnClick: (row, tenantId) => {
- let link;
- Object.keys(row).map((key) => {
- if (key === "MASTERS_WAGESEEKER_ID")
- link = `/${window.contextPath}/employee/masters/view-wageseeker?tenantId=${tenantId}&wageseekerId=${row[key]}`;
- });
- return link;
- },
- additionalValidations: (type, data, keys) => {
- if (type === "date") {
- return data[keys.start] && data[keys.end] ? () => new Date(data[keys.start]).getTime() <= new Date(data[keys.end]).getTime() : true;
- }
- }
- },
-};
diff --git a/frontend/micro-ui/web/src/Customisations/index.js b/frontend/micro-ui/web/src/Customisations/index.js
deleted file mode 100644
index 803b1e8763e..00000000000
--- a/frontend/micro-ui/web/src/Customisations/index.js
+++ /dev/null
@@ -1,19 +0,0 @@
-import { ptComponents } from "./pt";
-import { tlComponents } from "./tl";
-
-var Digit = window.Digit || {};
-
-const customisedComponent = {
- ...ptComponents,
- ...tlComponents
-}
-
-
-
-export const initCustomisationComponents = () => {
- Object.entries(customisedComponent).forEach(([key, value]) => {
- Digit.ComponentRegistryService.setComponent(key, value);
- });
-};
-
-
diff --git a/frontend/micro-ui/web/src/Customisations/pt/index.js b/frontend/micro-ui/web/src/Customisations/pt/index.js
deleted file mode 100644
index 0063fcd4774..00000000000
--- a/frontend/micro-ui/web/src/Customisations/pt/index.js
+++ /dev/null
@@ -1,13 +0,0 @@
-import PropertyUsageType from "./pageComponents/PropertyUsageType";
-import PTVasikaDetails from "./pageComponents/PTVasikaDetails";
-import PTAllotmentDetails from "./pageComponents/PTAllotmentDetails";
-import PTBusinessDetails from "./pageComponents/PTBusinessDetails";
-
-
-
-export const ptComponents = {
- PropertyUsageType: PropertyUsageType,
- PTVasikaDetail:PTVasikaDetails,
- PTAllotmentDetails:PTAllotmentDetails,
- PTBusinessDetails:PTBusinessDetails
-};
diff --git a/frontend/micro-ui/web/src/Customisations/pt/pageComponents/PTAllotmentDetails.js b/frontend/micro-ui/web/src/Customisations/pt/pageComponents/PTAllotmentDetails.js
deleted file mode 100644
index 569aa45e409..00000000000
--- a/frontend/micro-ui/web/src/Customisations/pt/pageComponents/PTAllotmentDetails.js
+++ /dev/null
@@ -1,64 +0,0 @@
-import { CardLabel, CitizenInfoLabel, FormStep, LabelFieldPair, TextInput,CardLabelError } from "@egovernments/digit-ui-react-components";
-import React, { useState } from "react";
-var validation ={};
-const PTAllotmentDetails = ({ t, config, onSelect, value, userType, formData }) => {
-
- const [
- val, setValue
- ] = useState(formData?.[config.key]?.alotmentDetails||"");
-
- const goNext = () => {
- onSelect(config.key, {alotmentDetails:val});
- };
-
-
- if (userType === "employee") {
- return (
-
-
- {t("PT_VASIKA_NO_LABEL") }
-
- setValue(e?.target?.value)}
- // autoFocus={presentInModifyApplication}
- />
-
-
-
- );
- }
- return (
-
-
-
- {`${t("PT_VASIKA_ALLOTMENT_LABEL")}`}
- setValue(e?.target?.value)}
-
- />
-
-
- {}
-
- );
-};
-
-export default PTAllotmentDetails;
diff --git a/frontend/micro-ui/web/src/Customisations/pt/pageComponents/PTBusinessDetails.js b/frontend/micro-ui/web/src/Customisations/pt/pageComponents/PTBusinessDetails.js
deleted file mode 100644
index 3d28785e7e5..00000000000
--- a/frontend/micro-ui/web/src/Customisations/pt/pageComponents/PTBusinessDetails.js
+++ /dev/null
@@ -1,68 +0,0 @@
-import { CardLabel, CitizenInfoLabel, FormStep, LabelFieldPair, TextInput,CardLabelError } from "@egovernments/digit-ui-react-components";
-import React, { useState } from "react";
-var validation ={};
-const PTBusinessDetails = ({ t, config, onSelect, value, userType, formData }) => {
-
-
- const [
- val, setValue
- ] = useState(formData?.[config.key]?.businessDetails||"");
-
- const goNext = () => {
- onSelect(config.key, {businessDetails:val});
- };
-
-
- if (userType === "employee") {
- return (
-
-
- {t("PT_VASIKA_NO_LABEL") }
-
- setValue(e?.target?.value)}
- // autoFocus={presentInModifyApplication}
- />
-
-
-
-
- );
- }
- return (
-
-
-
-
- {`${t("PT_VASIKA_BUS_DETAILS_LABEL")}`}
- setValue(e?.target?.value)}
-
- />
-
-
-
- {}
-
- );
-};
-
-export default PTBusinessDetails;
diff --git a/frontend/micro-ui/web/src/Customisations/pt/pageComponents/PTVasikaDetails.js b/frontend/micro-ui/web/src/Customisations/pt/pageComponents/PTVasikaDetails.js
deleted file mode 100644
index 0e4b6895745..00000000000
--- a/frontend/micro-ui/web/src/Customisations/pt/pageComponents/PTVasikaDetails.js
+++ /dev/null
@@ -1,79 +0,0 @@
-import { CardLabel, CitizenInfoLabel, FormStep, LabelFieldPair, TextInput,CardLabelError } from "@egovernments/digit-ui-react-components";
-import React, { useState } from "react";
-var validation ={};
-const PTVasikaDetails = ({ t, config, onSelect, value, userType, formData }) => {
-
-
- const [
- val, setValue
- ] = useState(formData?.[config.key]?.vasikaNo||"");
- const [
- other, setOther
- ] = useState(formData?.[config.key]?.vasikaArea||"");
- const goNext = () => {
- onSelect(config.key, {vasikaNo:val,vasikaArea:other});
- };
-
-
- if (userType === "employee") {
- return (
-
-
- {t("PT_VASIKA_NO_LABEL") }
-
- setValue(e?.target?.value)}
- // autoFocus={presentInModifyApplication}
- />
-
-
-
-
- );
- }
- return (
-
-
-
-
- {`${t("PT_VASIKA_NO_LABEL")}`}
- setValue(e?.target?.value)}
-
- />
-
- {`${t("PT_VASIKA_AREA_LABEL")}`}
- setOther(e?.target?.value)}
- />
-
- {}
-
- );
-};
-
-export default PTVasikaDetails;
diff --git a/frontend/micro-ui/web/src/Customisations/pt/pageComponents/PropertyUsageType.js b/frontend/micro-ui/web/src/Customisations/pt/pageComponents/PropertyUsageType.js
deleted file mode 100644
index deade4fc2ad..00000000000
--- a/frontend/micro-ui/web/src/Customisations/pt/pageComponents/PropertyUsageType.js
+++ /dev/null
@@ -1,134 +0,0 @@
-import {
- CardLabel, CardLabelError, CitizenInfoLabel, Dropdown, FormStep, LabelFieldPair, RadioButtons
-} from "@egovernments/digit-ui-react-components";
-import React, { useEffect, useState } from "react";
-import { useLocation } from "react-router-dom";
-
-var Digit = window.Digit || {};
-
-const PropertyUsageType = ({ t, config, onSelect, userType, formData, formState, setError, clearErrors, onBlur }) => {
- const [usageCategoryMajor, setPropertyPurpose] = useState(
- formData?.usageCategoryMajor && formData?.usageCategoryMajor?.code === "NONRESIDENTIAL.OTHERS"
- ? { code: `${formData?.usageCategoryMajor?.code}`, i18nKey: `PROPERTYTAX_BILLING_SLAB_OTHERS` }
- : formData?.usageCategoryMajor
- );
-
- const tenantId = Digit.ULBService.getCurrentTenantId();
- const stateId = tenantId.split(".")[0];
- const { data: Menu = { }, isLoading: menuLoading } = Digit.Hooks.pt.usePropertyMDMS(stateId, "PropertyTax", "UsageCategory") || { };
- let usagecat = [];
- usagecat = Menu?.PropertyTax?.UsageCategory || [];
- let i;
- let menu = [];
-
- const { pathname } = useLocation();
- const presentInModifyApplication = pathname.includes("modify");
-
- function usageCategoryMajorMenu(usagecat) {
- if (userType === "employee") {
- const catMenu = usagecat
- ?.filter((e) => e?.code.split(".").length <= 2 && e.code !== "NONRESIDENTIAL")
- ?.map((item) => {
- const arr = item?.code.split(".");
- if (arr.length == 2) return { i18nKey: "PROPERTYTAX_BILLING_SLAB_" + arr[1], code: item?.code };
- else return { i18nKey: "PROPERTYTAX_BILLING_SLAB_" + item?.code, code: item?.code };
- });
- return catMenu;
- } else {
- for (i = 0; i < 10; i++) {
- if (
- Array.isArray(usagecat) &&
- usagecat.length > 0 &&
- usagecat[i].code.split(".")[0] == "NONRESIDENTIAL" &&
- usagecat[i].code.split(".").length == 2
- ) {
- menu.push({ i18nKey: "PROPERTYTAX_BILLING_SLAB_" + usagecat[i].code.split(".")[1], code: usagecat[i].code });
- }
- }
- return menu;
- }
- }
-
- useEffect(() => {
- if (!menuLoading && presentInModifyApplication && userType === "employee") {
- const original = formData?.originalData?.usageCategory;
- const selectedOption = usageCategoryMajorMenu(usagecat).filter((e) => e.code === original)[0];
- setPropertyPurpose(selectedOption);
- }
- }, [menuLoading]);
-
- const onSkip = () => onSelect();
-
-
- function selectPropertyPurpose(value) {
- setPropertyPurpose(value);
- }
-
- function goNext() {
- if (usageCategoryMajor?.i18nKey === "PROPERTYTAX_BILLING_SLAB_OTHERS") {
- usageCategoryMajor.i18nKey = "PROPERTYTAX_BILLING_SLAB_NONRESIDENTIAL";
- onSelect(config.key, usageCategoryMajor);
- } else {
- onSelect(config.key, usageCategoryMajor);
- }
- }
-
- useEffect(() => {
- if (userType === "employee") {
- if (!usageCategoryMajor) {
- setError(config.key, { type: "required", message: t(`CORE_COMMON_REQUIRED_ERRMSG`) });
- } else {
- clearErrors(config.key);
- }
- goNext();
- }
- }, [usageCategoryMajor]);
-
- if (userType === "employee") {
- return (
-
-
- {t("PT_ASSESMENT_INFO_USAGE_TYPE") + " *"}
- {
- selectPropertyPurpose(e);
- }}
- optionKey="i18nKey"
- onBlur={onBlur}
- t={t}
- />
-
- {formState.touched[config.key] ? (
-
- {formState.errors?.[config.key]?.message}
-
- ) : null}
-
- );
- }
-
- return (
-
-
-
-
-
-
- {}
-
- );
-};
-
-export default PropertyUsageType;
diff --git a/frontend/micro-ui/web/src/Customisations/tl/TLCustomisation.js b/frontend/micro-ui/web/src/Customisations/tl/TLCustomisation.js
deleted file mode 100644
index 642acc52090..00000000000
--- a/frontend/micro-ui/web/src/Customisations/tl/TLCustomisation.js
+++ /dev/null
@@ -1,5 +0,0 @@
-export const TLCustomisations = {
- customiseCreateFormData: (formData, licenceObject) => licenceObject,
- customiseRenewalCreateFormData: (formData, licenceObject) => licenceObject,
- customiseSendbackFormData: (formData, licenceObject) => licenceObject
-}
\ No newline at end of file
diff --git a/frontend/micro-ui/web/src/Customisations/tl/index.js b/frontend/micro-ui/web/src/Customisations/tl/index.js
deleted file mode 100644
index fe2ae4f4e6a..00000000000
--- a/frontend/micro-ui/web/src/Customisations/tl/index.js
+++ /dev/null
@@ -1,7 +0,0 @@
-import TLUsageType from "./pageComponents/PropertyUsageType";
-
-
-
-export const tlComponents = {
- TLPropertyUsageType: TLUsageType,
-};
diff --git a/frontend/micro-ui/web/src/Customisations/tl/pageComponents/PropertyUsageType.js b/frontend/micro-ui/web/src/Customisations/tl/pageComponents/PropertyUsageType.js
deleted file mode 100644
index 5520a66fc5a..00000000000
--- a/frontend/micro-ui/web/src/Customisations/tl/pageComponents/PropertyUsageType.js
+++ /dev/null
@@ -1,136 +0,0 @@
-import {
- CardLabel, CardLabelError, CitizenInfoLabel, Dropdown, FormStep, LabelFieldPair, RadioButtons
-} from "@egovernments/digit-ui-react-components";
-import React, { useEffect, useState } from "react";
-import { useLocation } from "react-router-dom";
-
-var Digit = window.Digit || {};
-
-const TLUsageType = ({ t, config, onSelect, userType, formData, formState, setError, clearErrors, onBlur }) => {
- const [usageCategoryMajor, setPropertyPurpose] = useState(
- formData?.usageCategoryMajor && formData?.usageCategoryMajor?.code === "NONRESIDENTIAL.OTHERS"
- ? { code: `${formData?.usageCategoryMajor?.code}`, i18nKey: `PROPERTYTAX_BILLING_SLAB_OTHERS` }
- : formData?.usageCategoryMajor
- );
-
- const tenantId = Digit.ULBService.getCurrentTenantId();
- const stateId = tenantId.split(".")[0];
- const { data: Menu = { }, isLoading: menuLoading } = Digit.Hooks.pt.usePropertyMDMS(stateId, "PropertyTax", "UsageCategory") || { };
- let usagecat = [];
- usagecat = Menu?.PropertyTax?.UsageCategory || [];
- let i;
- let menu = [];
-
- const { pathname } = useLocation();
- const presentInModifyApplication = pathname.includes("modify");
-
- function usageCategoryMajorMenu(usagecat) {
- if (userType === "employee") {
- const catMenu = usagecat
- ?.filter((e) => e?.code.split(".").length <= 2 && e.code !== "NONRESIDENTIAL")
- ?.map((item) => {
- const arr = item?.code.split(".");
- if (arr.length == 2) return { i18nKey: "PROPERTYTAX_BILLING_SLAB_" + arr[1], code: item?.code };
- else return { i18nKey: "PROPERTYTAX_BILLING_SLAB_" + item?.code, code: item?.code };
- });
- return catMenu;
- } else {
- for (i = 0; i < 10; i++) {
- if (
- Array.isArray(usagecat) &&
- usagecat.length > 0 &&
- usagecat[i].code.split(".")[0] == "NONRESIDENTIAL" &&
- usagecat[i].code.split(".").length == 2
- ) {
- menu.push({ i18nKey: "PROPERTYTAX_BILLING_SLAB_" + usagecat[i].code.split(".")[1], code: usagecat[i].code });
- }
- }
- return menu;
- }
- }
-
- useEffect(() => {
- if (!menuLoading && presentInModifyApplication && userType === "employee") {
- const original = formData?.originalData?.usageCategory;
- const selectedOption = usageCategoryMajorMenu(usagecat).filter((e) => e.code === original)[0];
- setPropertyPurpose(selectedOption);
- }
- }, [menuLoading]);
-
- const onSkip = () => onSelect();
-
-
- function selectPropertyPurpose(value) {
- setPropertyPurpose(value);
- }
-
- function goNext() {
- if (usageCategoryMajor?.i18nKey === "PROPERTYTAX_BILLING_SLAB_OTHERS") {
- usageCategoryMajor.i18nKey = "PROPERTYTAX_BILLING_SLAB_NONRESIDENTIAL";
- onSelect(config.key, usageCategoryMajor);
- } else {
- onSelect(config.key, usageCategoryMajor);
- }
- }
-
- useEffect(() => {
- if (userType === "employee") {
- if (!usageCategoryMajor) {
- setError(config.key, { type: "required", message: t(`CORE_COMMON_REQUIRED_ERRMSG`) });
- } else {
- clearErrors(config.key);
- }
- goNext();
- }
- }, [usageCategoryMajor]);
-
- if (userType === "employee") {
- return (
-
-
- {t("PT_ASSESMENT_INFO_USAGE_TYPE") + " *"}
- {
- selectPropertyPurpose(e);
- }}
- optionKey="i18nKey"
- onBlur={onBlur}
- t={t}
- />
-
- {formState.touched[config.key] ? (
-
- {formState.errors?.[config.key]?.message}
-
- ) : null}
-
- );
- }
-
- return (
-
-
-
-
-
- to say this is different element
-
-
- {}
-
- );
-};
-
-export default TLUsageType;
diff --git a/frontend/micro-ui/web/src/index.css b/frontend/micro-ui/web/src/index.css
deleted file mode 100644
index e69de29bb2d..00000000000
diff --git a/frontend/micro-ui/web/src/index.js b/frontend/micro-ui/web/src/index.js
deleted file mode 100644
index 9f20bf1b506..00000000000
--- a/frontend/micro-ui/web/src/index.js
+++ /dev/null
@@ -1,62 +0,0 @@
-import React from 'react';
-import ReactDOM from 'react-dom';
-import { initLibraries } from "@egovernments/digit-ui-libraries";
-import "./index.css";
-import App from './App';
-import { TLCustomisations } from './Customisations/tl/TLCustomisation';
-
-
-initLibraries();
-
-
-window.Digit.Customizations = { PGR: {} ,TL:TLCustomisations};
-
-const user = window.Digit.SessionStorage.get("User");
-
-if (!user || !user.access_token || !user.info) {
- // login detection
-
- const parseValue = (value) => {
- try {
- return JSON.parse(value)
- } catch (e) {
- return value
- }
- }
-
- const getFromStorage = (key) => {
- const value = window.localStorage.getItem(key);
- return value && value !== "undefined" ? parseValue(value) : null;
- }
-
- const token = getFromStorage("token")
-
- const citizenToken = getFromStorage("Citizen.token")
- const citizenInfo = getFromStorage("Citizen.user-info")
- const citizenTenantId = getFromStorage("Citizen.tenant-id")
-
- const employeeToken = getFromStorage("Employee.token")
- const employeeInfo = getFromStorage("Employee.user-info")
- const employeeTenantId = getFromStorage("Employee.tenant-id")
- const userType = token === citizenToken ? "citizen" : "employee";
-
- window.Digit.SessionStorage.set("user_type", userType);
- window.Digit.SessionStorage.set("userType", userType);
-
- const getUserDetails = (access_token, info) => ({ token: access_token, access_token, info })
-
- const userDetails = userType === "citizen" ? getUserDetails(citizenToken, citizenInfo) : getUserDetails(employeeToken, employeeInfo)
-
- window.Digit.SessionStorage.set("User", userDetails);
- window.Digit.SessionStorage.set("Citizen.tenantId", citizenTenantId);
- window.Digit.SessionStorage.set("Employee.tenantId", employeeTenantId);
- // end
-}
-
-ReactDOM.render(
-
-
- ,
- document.getElementById('root')
-);
-
diff --git a/frontend/micro-ui/web/src/setupProxy.js b/frontend/micro-ui/web/src/setupProxy.js
deleted file mode 100644
index 1b8eda94a19..00000000000
--- a/frontend/micro-ui/web/src/setupProxy.js
+++ /dev/null
@@ -1,30 +0,0 @@
-const { createProxyMiddleware } = require("http-proxy-middleware");
-const createProxy = createProxyMiddleware({
- target: process.env.REACT_APP_PROXY_URL,
- changeOrigin: true,
-});
-module.exports = function (app) {
- [
- "/egov-mdms-service",
- "/egov-location",
- "/localization",
- "/egov-workflow-v2",
- "/pgr-services",
- "/filestore",
- "/egov-hrms",
- "/user-otp",
- "/user",
- "/fsm",
- "/billing-service",
- "/collection-services",
- "/pdf-service",
- "/pg-service",
- "/vehicle",
- "/vendor",
- "/property-services",
- "/fsm-calculator/v1/billingSlab/_search",
- "/muster-roll"
- ].forEach((location) =>
- app.use(location, createProxy)
- );
-};
diff --git a/frontend/micro-ui/web/webpack.config.js b/frontend/micro-ui/web/webpack.config.js
deleted file mode 100644
index 5f3dc46967a..00000000000
--- a/frontend/micro-ui/web/webpack.config.js
+++ /dev/null
@@ -1,43 +0,0 @@
-const path = require("path");
-const HtmlWebpackPlugin = require("html-webpack-plugin");
-const { CleanWebpackPlugin } = require("clean-webpack-plugin");
-// const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
-
-module.exports = {
- // mode: 'development',
- entry: "./src/index.js",
- devtool: "none",
- module: {
- rules: [
- {
- test: /\.(js)$/,
- use: ["babel-loader"],
- },
- {
- test: /\.css$/i,
- use: ["style-loader", "css-loader"],
- }
- ],
- },
- output: {
- filename: "[name].bundle.js",
- path: path.resolve(__dirname, "build"),
- publicPath: "/digit-ui/",
- },
- optimization: {
- splitChunks: {
- chunks: 'all',
- minSize:20000,
- maxSize:50000,
- enforceSizeThreshold:50000,
- minChunks:1,
- maxAsyncRequests:30,
- maxInitialRequests:30
- },
- },
- plugins: [
- new CleanWebpackPlugin(),
- // new BundleAnalyzerPlugin(),
- new HtmlWebpackPlugin({ inject: true, template: "public/index.html" }),
- ],
-};
\ No newline at end of file
diff --git a/frontend/micro-ui/web/workbench/App.js b/frontend/micro-ui/web/workbench/App.js
deleted file mode 100644
index 93b15440c5e..00000000000
--- a/frontend/micro-ui/web/workbench/App.js
+++ /dev/null
@@ -1,72 +0,0 @@
-/**
- * The above code initializes various Digit UI modules and components, sets up customizations, and
- * renders the DigitUI component based on the enabled modules and state code.
- * @returns The `App` component is being returned, which renders the `DigitUI` component with the
- * specified props such as `stateCode`, `enabledModules`, `moduleReducers`, and `defaultLanding`. The
- * `DigitUI` component is responsible for rendering the UI based on the provided configuration and
- * modules.
- */
-import React from "react";
-import { initLibraries } from "@egovernments/digit-ui-libraries";
-import { DigitUI } from "@egovernments/digit-ui-module-core";
-// import { initHRMSComponents } from "@egovernments/digit-ui-module-hrms";
-import { UICustomizations } from "./Customisations/UICustomizations";
-import { initWorkbenchComponents } from "@egovernments/digit-ui-module-workbench";
-import { initUtilitiesComponents } from "@egovernments/digit-ui-module-utilities";
-import { initWorkbenchHCMComponents } from "@egovernments/digit-ui-module-hcmworkbench";
-import { initCampaignComponents } from "@egovernments/digit-ui-module-campaign-manager"
-
-window.contextPath = window?.globalConfigs?.getConfig("CONTEXT_PATH");
-
-const enabledModules = [
- "DSS",
- "NDSS",
- "Utilities",
- // "HRMS",
- "Engagement",
- "Workbench",
- "HCMWORKBENCH",
- "Campaign"
-];
-
-const moduleReducers = (initData) => ({
- initData,
-});
-
-const initDigitUI = () => {
- window.Digit.ComponentRegistryService.setupRegistry({});
- window.Digit.Customizations = {
- PGR: {},
- commonUiConfig: UICustomizations,
- };
- // initHRMSComponents();
- initUtilitiesComponents();
- initWorkbenchComponents();
- initWorkbenchHCMComponents();
- initCampaignComponents();
-
-};
-
-initLibraries().then(() => {
- initDigitUI();
-});
-
-function App() {
- window.contextPath = window?.globalConfigs?.getConfig("CONTEXT_PATH");
- const stateCode =
- window.globalConfigs?.getConfig("STATE_LEVEL_TENANT_ID") ||
- process.env.REACT_APP_STATE_LEVEL_TENANT_ID;
- if (!stateCode) {
- return stateCode is not defined
;
- }
- return (
-
- );
-}
-
-export default App;
diff --git a/frontend/micro-ui/web/workbench/Dockerfile b/frontend/micro-ui/web/workbench/Dockerfile
deleted file mode 100644
index 31b3912759b..00000000000
--- a/frontend/micro-ui/web/workbench/Dockerfile
+++ /dev/null
@@ -1,29 +0,0 @@
-FROM egovio/alpine-node-builder-14:yarn AS build
-#FROM ghcr.io/egovernments/alpine-node-builder-14:yarn AS build
-RUN apk update && apk upgrade
-RUN apk add --no-cache git>2.30.0
-ARG WORK_DIR
-WORKDIR /app
-ENV NODE_OPTIONS "--max-old-space-size=4792"
-
-COPY ${WORK_DIR} .
-RUN ls -lah
-
-#RUN node web/envs.js
-RUN cd web/ \
- && node -e 'console.log(v8.getHeapStatistics().heap_size_limit/(1024*1024))' \
- && node -e 'console.log("core only")' \
- && cd workbench/ \
- && ./install-deps.sh \
- && cd ../ \
- && yarn install \
- && yarn build:webpack
-
-FROM nginx:mainline-alpine
-#FROM ghcr.io/egovernments/nginx:mainline-alpine
-ENV WORK_DIR=/var/web/workbench-ui
-
-RUN mkdir -p ${WORK_DIR}
-
-COPY --from=build /app/web/build ${WORK_DIR}/
-COPY --from=build /app/web/workbench/nginx.conf /etc/nginx/conf.d/default.conf
diff --git a/frontend/micro-ui/web/workbench/install-deps.sh b/frontend/micro-ui/web/workbench/install-deps.sh
deleted file mode 100755
index 54b8a4c3d7f..00000000000
--- a/frontend/micro-ui/web/workbench/install-deps.sh
+++ /dev/null
@@ -1,18 +0,0 @@
-#!/bin/sh
-
-BRANCH="$(git branch --show-current)"
-
-echo "Main Branch: $BRANCH"
-
-INTERNALS="micro-ui-internals"
-cd ..
-
-cp workbench/App.js src
-cp workbench/package.json package.json
-cp workbench/webpack.config.js webpack.config.js
-cp workbench/inter-package.json $INTERNALS/package.json
-
-cp $INTERNALS/example/src/UICustomizations.js src/Customisations
-
-echo "UI :: workbench " && echo "Branch: $(git branch --show-current)" && echo "$(git log -1 --pretty=%B)" && echo "installing packages"
-
diff --git a/frontend/micro-ui/web/workbench/inter-package.json b/frontend/micro-ui/web/workbench/inter-package.json
deleted file mode 100644
index 5216443ec23..00000000000
--- a/frontend/micro-ui/web/workbench/inter-package.json
+++ /dev/null
@@ -1,58 +0,0 @@
-{
- "name": "egovernments",
- "version": "1.0.0",
- "main": "index.js",
- "workspaces": [
- "example",
- "packages/css",
- "packages/modules/*"
- ],
- "author": "JaganKumar ",
- "license": "MIT",
- "private": true,
- "engines": {
- "node": ">=14"
- },
- "scripts": {
- "start": "SKIP_PREFLIGHT_CHECK=true run-s build start:dev",
- "sprint": "SKIP_PREFLIGHT_CHECK=true run-s start:script",
- "start:dev": "run-p dev:**",
- "start:script": "./scripts/create.sh",
- "dev:css": "cd packages/css && yarn start",
- "publish:css": "cd packages/css && yarn publish --access public",
- "dev:example": "cd example && yarn start",
- "dev:campaign": "cd packages/modules/campaign-manager && yarn start",
- "build": "run-p build:**",
- "build:campaign": "cd packages/modules/campaign-manager && yarn build",
- "deploy:jenkins": "./scripts/jenkins.sh",
- "clean": "rm -rf node_modules"
- },
- "resolutions": {
- "**/@babel/runtime": "7.20.1",
- "**/babel-preset-react-app": "10.0.0",
- "**/ajv": "8.11.2",
- "fast-uri":"2.1.0"
- },
- "devDependencies": {
- "husky": "7.0.4",
- "lint-staged": "12.3.7",
- "npm-run-all": "4.1.5",
- "prettier": "2.1.2"
- },
- "husky": {},
- "lint-staged": {
- "*.{js,css,md}": "prettier --write"
- },
- "dependencies": {
- "lodash": "4.17.21",
- "microbundle-crl": "0.13.11",
- "@egovernments/digit-ui-react-components": "1.8.2-beta.1",
- "@egovernments/digit-ui-components": "0.0.2-beta.1",
- "react": "17.0.2",
- "react-dom": "17.0.2",
- "react-hook-form": "6.15.8",
- "react-i18next": "11.16.2",
- "react-query": "3.6.1",
- "react-router-dom": "5.3.0"
- }
-}
diff --git a/frontend/micro-ui/web/workbench/nginx.conf b/frontend/micro-ui/web/workbench/nginx.conf
deleted file mode 100644
index 974ef82f241..00000000000
--- a/frontend/micro-ui/web/workbench/nginx.conf
+++ /dev/null
@@ -1,12 +0,0 @@
-server
-{
- listen 80;
- underscores_in_headers on;
-
- location /workbench-ui
- {
- root /var/web;
- index index.html index.htm;
- try_files $uri $uri/ /workbench-ui/index.html;
- }
-}
\ No newline at end of file
diff --git a/frontend/micro-ui/web/workbench/package.json b/frontend/micro-ui/web/workbench/package.json
deleted file mode 100644
index 7cc60ef7bff..00000000000
--- a/frontend/micro-ui/web/workbench/package.json
+++ /dev/null
@@ -1,89 +0,0 @@
-{
- "name": "micro-ui",
- "version": "1.0.0",
- "author": "Jagankumar ",
- "license": "MIT",
- "private": true,
- "engines": {
- "node": ">=14"
- },
- "workspaces": [
- "micro-ui-internals/packages/modules/*"
- ],
- "homepage": "/workbench-ui",
- "dependencies": {
- "@egovernments/digit-ui-libraries": "1.8.2-beta.1",
- "@egovernments/digit-ui-module-workbench": "1.0.2-beta.3",
- "@egovernments/digit-ui-components": "0.0.2-beta.1",
- "@egovernments/digit-ui-module-core": "1.8.2-beta.2",
- "@egovernments/digit-ui-module-utilities": "1.0.1-beta.30",
- "@egovernments/digit-ui-react-components": "1.8.2-beta.6",
- "@egovernments/digit-ui-module-hcmworkbench":"0.0.38",
- "@egovernments/digit-ui-module-campaign-manager": "0.0.1",
- "babel-loader": "8.1.0",
- "clean-webpack-plugin": "4.0.0",
- "react": "17.0.2",
- "react-dom": "17.0.2",
- "jsonpath": "^1.1.1",
- "react-router-dom": "5.3.0",
- "react-scripts": "4.0.1",
- "web-vitals": "1.1.2",
- "terser-brunch": "^4.1.0",
- "react-hook-form": "6.15.8",
- "react-i18next": "11.16.2",
- "react-query": "3.6.1",
- "css-loader": "5.2.6",
- "style-loader": "2.0.0",
- "webpack-cli": "4.10.0"
- },
- "devDependencies": {
- "@babel/plugin-proposal-private-property-in-object": "7.21.0",
- "http-proxy-middleware": "1.3.1",
- "lodash": "4.17.21",
- "microbundle-crl": "0.13.11",
- "react": "17.0.2",
- "react-dom": "17.0.2",
- "react-hook-form": "6.15.8",
- "react-i18next": "11.16.2",
- "react-query": "3.6.1",
- "react-router-dom": "5.3.0",
- "husky": "7.0.4",
- "lint-staged": "12.3.7",
- "npm-run-all": "4.1.5",
- "prettier": "2.1.2"
- },
- "resolutions": {
- "**/babel-loader": "8.2.2",
- "**/@babel/core": "7.14.0",
- "**/@babel/preset-env": "7.14.0",
- "**/@babel/plugin-transform-modules-commonjs": "7.14.0",
- "**/polished":"4.2.2",
- "fast-uri":"2.1.0"
- },
- "scripts": {
- "start": "react-scripts start",
- "build": "GENERATE_SOURCEMAP=false SKIP_PREFLIGHT_CHECK=true react-scripts build",
- "build:prepare": "./build.sh",
- "build:libraries": "cd micro-ui-internals && yarn build",
- "build:prod": "webpack --mode production",
- "build:webpack": "yarn build:libraries &&cd .. && ls && cd ./web && ls && yarn build:prod",
- "clean": "rm -rf node_modules"
- },
- "eslintConfig": {
- "extends": [
- "react-app"
- ]
- },
- "browserslist": {
- "production": [
- ">0.2%",
- "not dead",
- "not op_mini all"
- ],
- "development": [
- "last 1 chrome version",
- "last 1 firefox version",
- "last 1 safari version"
- ]
- }
-}
diff --git a/frontend/micro-ui/web/workbench/webpack.config.js b/frontend/micro-ui/web/workbench/webpack.config.js
deleted file mode 100644
index c19e631fe01..00000000000
--- a/frontend/micro-ui/web/workbench/webpack.config.js
+++ /dev/null
@@ -1,44 +0,0 @@
-const path = require("path");
-const HtmlWebpackPlugin = require("html-webpack-plugin");
-const { CleanWebpackPlugin } = require("clean-webpack-plugin");
-// const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
-
-module.exports = {
- // mode: 'development',
- entry: "./src/index.js",
- devtool: "none",
- module: {
- rules: [
- {
- test: /\.(js)$/,
- exclude: /node_modules/,
- use: ["babel-loader"],
- },
- {
- test: /\.css$/i,
- use: ["style-loader", "css-loader"],
- }
- ],
- },
- output: {
- filename: "[name].bundle.js",
- path: path.resolve(__dirname, "build"),
- publicPath: "/workbench-ui/",
- },
- optimization: {
- splitChunks: {
- chunks: 'all',
- minSize:20000,
- maxSize:50000,
- enforceSizeThreshold:50000,
- minChunks:1,
- maxAsyncRequests:30,
- maxInitialRequests:30
- },
- },
- plugins: [
- new CleanWebpackPlugin(),
- // new BundleAnalyzerPlugin(),
- new HtmlWebpackPlugin({ inject: true, template: "public/index.html" }),
- ],
-};
\ No newline at end of file
diff --git a/health-services/census-service/CHANGELOG.md b/health-services/census-service/CHANGELOG.md
new file mode 100644
index 00000000000..38562489c90
--- /dev/null
+++ b/health-services/census-service/CHANGELOG.md
@@ -0,0 +1,13 @@
+# Changelog
+All notable changes to this module will be documented in this file.
+
+## 1.0.0 - 2024-11-28
+#### Census Service
+The Census Service introduces core functionalities for managing census data:
+
+1. Validation of Census: Ensures data integrity by validating all census requests before processing.
+2. Census Create: Creates new census records after validation and enrichment, publishing request to the designated Kafka topic to handle the creation process asynchronously.
+3. Census Update: Updates existing records post-validation and enrichment by sending request to the designated Kafka update topic.
+4. Census Bulk Update: Updates multiple census records in one operation after successful validation.
+5. Census Search: Enables searching for census records with the provided search criteria.
+6. Plan Facility Consumer: Listens to Plan Facility Update topic to assign facility to a boundary in census.
\ No newline at end of file
diff --git a/health-services/census-service/README.md b/health-services/census-service/README.md
new file mode 100644
index 00000000000..a2e8a9f7b84
--- /dev/null
+++ b/health-services/census-service/README.md
@@ -0,0 +1,18 @@
+# Swagger generated server
+
+Spring Boot Server
+
+
+## Overview
+This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project.
+By using the [OpenAPI-Spec](https://github.com/swagger-api/swagger-core), you can easily generate a server stub.
+This is an example of building a swagger-enabled server in Java using the SpringBoot framework.
+
+The underlying library integrating swagger to SpringBoot is [springfox](https://github.com/springfox/springfox)
+
+Start your server as an simple java application
+
+You can view the api documentation in swagger-ui by pointing to
+http://localhost:8080/
+
+Change default port value in application.properties
\ No newline at end of file
diff --git a/health-services/census-service/pom.xml b/health-services/census-service/pom.xml
new file mode 100644
index 00000000000..7e6f7adc8fb
--- /dev/null
+++ b/health-services/census-service/pom.xml
@@ -0,0 +1,141 @@
+
+ 4.0.0
+ org.egov
+ census-service
+ jar
+ census-service
+ 1.0.0
+
+ 17
+ ${java.version}
+ ${java.version}
+
+
+ org.springframework.boot
+ spring-boot-starter-parent
+ 3.2.2
+
+
+ src/main/java
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+ repackage
+
+
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+ org.egov.common
+ health-services-models
+ 1.0.21-SNAPSHOT
+ compile
+
+
+ junit
+ junit
+ 4.13.2
+ test
+
+
+ org.springframework.boot
+ spring-boot-starter-jdbc
+
+
+ org.flywaydb
+ flyway-core
+ 9.22.3
+
+
+ org.postgresql
+ postgresql
+ 42.7.1
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+
+ io.swagger
+ swagger-core
+ 1.5.18
+
+
+ io.swagger.core.v3
+ swagger-annotations
+ 2.2.8
+
+
+ net.minidev
+ json-smart
+ 2.5.0
+
+
+
+ org.egov.services
+ tracer
+ 2.9.0-SNAPSHOT
+
+
+
+
+
+
+
+ org.egov
+ mdms-client
+ 2.9.0-SNAPSHOT
+ compile
+
+
+ org.projectlombok
+ lombok
+ true
+
+
+
+ com.fasterxml.jackson.datatype
+ jackson-datatype-jsr310
+
+
+
+ org.springframework.boot
+ spring-boot-starter-validation
+
+
+
+
+ repo.egovernments.org
+ eGov ERP Releases Repository
+ https://nexus-repo.egovernments.org/nexus/content/repositories/releases/
+
+
+ repo.egovernments.org.snapshots
+ eGov ERP Releases Repository
+ https://nexus-repo.egovernments.org/nexus/content/repositories/snapshots/
+
+
+ repo.egovernments.org.public
+ eGov Public Repository Group
+ https://nexus-repo.egovernments.org/nexus/content/groups/public/
+
+
+ repo.digit.org
+ eGov DIGIT Releases Repository
+ https://nexus-repo.digit.org/nexus/content/repositories/snapshots/
+
+
+
diff --git a/health-services/census-service/src/main/java/digit/Main.java b/health-services/census-service/src/main/java/digit/Main.java
new file mode 100644
index 00000000000..6e3d79db11c
--- /dev/null
+++ b/health-services/census-service/src/main/java/digit/Main.java
@@ -0,0 +1,20 @@
+package digit;
+
+
+import org.egov.tracer.config.TracerConfiguration;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Import;
+
+@Import({ TracerConfiguration.class })
+@SpringBootApplication
+@ComponentScan(basePackages = { "digit", "digit.web.controllers" , "digit.config"})
+public class Main {
+
+
+ public static void main(String[] args) throws Exception {
+ SpringApplication.run(Main.class, args);
+ }
+
+}
diff --git a/health-services/census-service/src/main/java/digit/config/Configuration.java b/health-services/census-service/src/main/java/digit/config/Configuration.java
new file mode 100644
index 00000000000..8459885357e
--- /dev/null
+++ b/health-services/census-service/src/main/java/digit/config/Configuration.java
@@ -0,0 +1,86 @@
+package digit.config;
+
+import lombok.*;
+import org.egov.tracer.config.TracerConfiguration;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Import;
+import org.springframework.stereotype.Component;
+
+import java.util.List;
+
+@Component
+@Data
+@Import({TracerConfiguration.class})
+@NoArgsConstructor
+@AllArgsConstructor
+@Setter
+@Getter
+public class Configuration {
+
+ // Allowed roles for census
+ @Value("#{${allowed.census.roles}}")
+ private List allowedCensusRoles;
+
+ @Value("#{${workflow.restricted.roles}}")
+ private List workflowRestrictedRoles;
+
+ // Persister Topic
+ @Value("${census.create.topic}")
+ private String censusCreateTopic;
+
+ @Value("${census.update.topic}")
+ private String censusUpdateTopic;
+
+ @Value("${census.bulk.update.topic}")
+ private String censusBulkUpdateTopic;
+
+ @Value("${plan.facility.update.topic}")
+ private String planFcailityUpdateTopic;
+
+ // Boundary Service
+ @Value("${egov.boundary.service.host}")
+ private String boundaryServiceHost;
+
+ @Value("${egov.boundary.relationship.search.endpoint}")
+ private String boundaryRelationshipSearchEndpoint;
+
+ @Value("${egov.boundary.hierarchy.search.endpoint}")
+ private String boundaryHierarchySearchEndpoint;
+
+ // Plan Service
+ @Value("${egov.plan.service.host}")
+ private String planServiceHost;
+
+ @Value("${egov.plan.employee.assignment.search.endpoint}")
+ private String planEmployeeAssignmentSearchEndpoint;
+
+ //Workflow
+ @Value("${egov.workflow.host}")
+ private String wfHost;
+
+ @Value("${egov.workflow.transition.path}")
+ private String wfTransitionPath;
+
+ @Value("${egov.business.service.search.endpoint}")
+ private String businessServiceSearchEndpoint;
+
+ @Value("${workflow.initiate.action}")
+ private List wfInitiateActions;
+
+ @Value("${workflow.intermediate.action}")
+ private List wfIntermediateActions;
+
+ @Value("${workflow.send.back.actions}")
+ private List wfSendBackActions;
+
+ //SMSNotification
+ @Value("${egov.sms.notification.topic}")
+ private String smsNotificationTopic;
+
+ //Pagination
+ @Value("${census.default.offset}")
+ private Integer defaultOffset;
+
+ @Value("${census.default.limit}")
+ private Integer defaultLimit;
+}
diff --git a/health-services/census-service/src/main/java/digit/config/MainConfiguration.java b/health-services/census-service/src/main/java/digit/config/MainConfiguration.java
new file mode 100644
index 00000000000..239331c9cd8
--- /dev/null
+++ b/health-services/census-service/src/main/java/digit/config/MainConfiguration.java
@@ -0,0 +1,41 @@
+package digit.config;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Import;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.MediaType;
+import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
+
+import java.util.TimeZone;
+
+import jakarta.annotation.PostConstruct;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.egov.tracer.config.TracerConfiguration;
+
+
+@Import({TracerConfiguration.class})
+public class MainConfiguration {
+
+ @Value("${app.timezone}")
+ private String timeZone;
+
+ @PostConstruct
+ public void initialize() {
+ TimeZone.setDefault(TimeZone.getTimeZone(timeZone));
+ }
+
+ @Bean
+ public ObjectMapper objectMapper() {
+ return new ObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).setTimeZone(TimeZone.getTimeZone(timeZone));
+ }
+
+ @Bean
+ @Autowired
+ public MappingJackson2HttpMessageConverter jacksonConverter(ObjectMapper objectMapper) {
+ MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
+ converter.setObjectMapper(objectMapper);
+ return converter;
+ }
+}
\ No newline at end of file
diff --git a/health-services/census-service/src/main/java/digit/config/ServiceConstants.java b/health-services/census-service/src/main/java/digit/config/ServiceConstants.java
new file mode 100644
index 00000000000..5d944060848
--- /dev/null
+++ b/health-services/census-service/src/main/java/digit/config/ServiceConstants.java
@@ -0,0 +1,114 @@
+package digit.config;
+
+
+import org.springframework.stereotype.Component;
+
+
+@Component
+public class ServiceConstants {
+
+ public static final String EXTERNAL_SERVICE_EXCEPTION = "External Service threw an Exception: ";
+ public static final String SEARCHER_SERVICE_EXCEPTION = "Exception while fetching from searcher: ";
+
+ public static final String IDGEN_ERROR = "IDGEN ERROR";
+ public static final String NO_IDS_FOUND_ERROR = "No ids returned from idgen Service";
+
+ public static final String ERROR_WHILE_FETCHING_FROM_MDMS = "Exception occurred while fetching category lists from mdms: ";
+
+ public static final String ERROR_WHILE_FETCHING_BOUNDARY_DETAILS = "Exception occurred while fetching boundary relationship from boundary service: ";
+
+ public static final String ERROR_WHILE_FETCHING_BOUNDARY_HIERARCHY_DETAILS = "Exception occurred while fetching boundary hierarchy details from boundary service: ";
+
+ public static final String ERROR_WHILE_FETCHING_EMPLOYEE_ASSIGNMENT_DETAILS = "Exception occurred while fetching plan employee assignment details from plan service: ";
+
+ public static final String ERROR_WHILE_FETCHING_BUSINESS_SERVICE_DETAILS = "Exception occurred while fetching business service details: ";
+
+ public static final String RES_MSG_ID = "uief87324";
+ public static final String SUCCESSFUL = "successful";
+ public static final String FAILED = "failed";
+
+ public static final String URL = "url";
+ public static final String URL_SHORTENING_ERROR_CODE = "URL_SHORTENING_ERROR";
+ public static final String URL_SHORTENING_ERROR_MESSAGE = "Unable to shorten url: ";
+
+ public static final String DOB_FORMAT_Y_M_D = "yyyy-MM-dd";
+ public static final String DOB_FORMAT_D_M_Y = "dd/MM/yyyy";
+ public static final String ILLEGAL_ARGUMENT_EXCEPTION_CODE = "IllegalArgumentException";
+ public static final String OBJECTMAPPER_UNABLE_TO_CONVERT = "ObjectMapper not able to convertValue in userCall";
+ public static final String DOB_FORMAT_D_M_Y_H_M_S = "dd-MM-yyyy HH:mm:ss";
+ public static final String CREATED_DATE = "createdDate";
+ public static final String LAST_MODIFIED_DATE = "lastModifiedDate";
+ public static final String DOB = "dob";
+ public static final String PWD_EXPIRY_DATE = "pwdExpiryDate";
+ public static final String INVALID_DATE_FORMAT_CODE = "INVALID_DATE_FORMAT";
+ public static final String INVALID_DATE_FORMAT_MESSAGE = "Failed to parse date format in user";
+ public static final String CITIZEN_UPPER = "CITIZEN";
+ public static final String CITIZEN_LOWER = "Citizen";
+ public static final String USER = "user";
+ public static final String PIPE_REGEX = "\\|";
+ public static final String FACILITY_ID_FIELD = "facilityId";
+ public static final String FACILITY_NAME_FIELD = "facilityName";
+
+ public static final String PARSING_ERROR_CODE = "PARSING ERROR";
+ public static final String PARSING_ERROR_MESSAGE = "Failed to parse JSON data from PGobject";
+
+ public static final String FAILED_TO_PARSE_BUSINESS_SERVICE_SEARCH = "Failed to parse response of workflow business service search";
+ public static final String BUSINESS_SERVICE_NOT_FOUND = "BUSINESSSERVICE_NOT_FOUND";
+ public static final String THE_BUSINESS_SERVICE = "The businessService ";
+ public static final String NOT_FOUND = " is not found";
+ public static final String TENANTID = "?tenantId=";
+ public static final String BUSINESS_SERVICES = "&businessServices=";
+
+ public static final String NO_BOUNDARY_DATA_FOUND_FOR_GIVEN_BOUNDARY_CODE_CODE = "NO_BOUNDARY_DATA_FOUND_FOR_GIVEN_BOUNDARY_CODE";
+ public static final String NO_BOUNDARY_DATA_FOUND_FOR_GIVEN_BOUNDARY_CODE_MESSAGE = "Invalid or incorrect boundaryCode. No boundary data found.";
+
+ public static final String NO_BUSINESS_SERVICE_DATA_FOUND_CODE = "NO_BUSINESS_SERVICE_DATA_FOUND";
+ public static final String NO_BUSINESS_SERVICE_DATA_FOUND_MESSAGE = "Invalid or incorrect businessService. No business service data found.";
+
+ public static final String USERINFO_MISSING_CODE = "USERINFO_MISSING";
+ public static final String USERINFO_MISSING_MESSAGE = "UserInfo is missing in Request Info ";
+
+ public static final String ERROR_WHILE_UPDATING_ADDITIONAL_DETAILS_CODE = "ERROR_WHILE_UPDATING_ADDITIONAL_DETAILS";
+ public static final String ERROR_WHILE_UPDATING_ADDITIONAL_DETAILS_MESSAGE = "Exception occurred while updating additional details : ";
+
+ public static final String WORKFLOW_INTEGRATION_ERROR_CODE = "WORKFLOW_INTEGRATION_ERROR";
+ public static final String WORKFLOW_INTEGRATION_ERROR_MESSAGE = "Exception occured while integrating with workflow : ";
+
+ public static final String INVALID_PARTNER_CODE = "INVALID_PARTNER";
+ public static final String INVALID_PARTNER_MESSAGE = "Invalid partner assignment or invalid jurisdiction of the assigned partner";
+
+ public static final String INVALID_CENSUS_CODE = "INVALID_CENSUS";
+ public static final String INVALID_CENSUS_MESSAGE = "Provided census does not exist";
+
+ public static final String DUPLICATE_CENSUS_ID_IN_BULK_UPDATE_CODE = "DUPLICATE_CENSUS_ID_IN_BULK_UPDATE";
+ public static final String DUPLICATE_CENSUS_ID_IN_BULK_UPDATE_MESSAGE = "Census provided in the bulk update request are not unique.";
+
+ public static final String INVALID_SOURCE_OR_TENANT_ID_FOR_BULK_UPDATE_CODE = "INVALID_SOURCE_OR_TENANT_ID_FOR_BULK_UPDATE";
+ public static final String INVALID_SOURCE_OR_TENANT_ID_FOR_BULK_UPDATE_MESSAGE = "Tenant id and source should be same across all entries for bulk update.";
+
+ public static final String WORKFLOW_NOT_FOUND_FOR_BULK_UPDATE_CODE = "WORKFLOW_NOT_FOUND_FOR_BULK_UPDATE";
+ public static final String WORKFLOW_NOT_FOUND_FOR_BULK_UPDATE_MESSAGE = "Workflow information is mandatory for each entry for bulk update";
+
+ public static final String DUPLICATE_KEY_IN_ADDITIONAL_FIELD_CODE = "DUPLICATE_KEY_IN_ADDITIONAL_FIELD";
+ public static final String DUPLICATE_KEY_IN_ADDITIONAL_FIELD_MESSGAE = "Duplicate key found in additional field : ";
+
+ public static final String CENSUS_ALREADY_EXISTS_CODE = "CENSUS_ALREADY_EXISTS";
+ public static final String CENSUS_ALREADY_EXISTS_MESSAGE = "Census with the given boundary and source already exists.";
+
+ public static final String DIFFERENT_WORKFLOW_FOR_BULK_UPDATE_CODE = "DIFFERENT_WORKFLOW_FOR_BULK_UPDATE";
+ public static final String DIFFERENT_WORKFLOW_FOR_BULK_UPDATE_MESSAGE = "All entries should be in the same state for bulk transitioning census records.";
+
+ public static final String UNAUTHORIZED_WORKFLOW_ACCESS_CODE = "UNAUTHORIZED_WORKFLOW_ACCESS";
+ public static final String UNAUTHORIZED_WORKFLOW_ACCESS_MESSAGE = "User with provided roles cannot have an active workflow. Please remove the workflow or update user roles.";
+
+ public static final String SEARCH_CRITERIA_EMPTY_CODE = "SEARCH_CRITERIA_EMPTY";
+ public static final String SEARCH_CRITERIA_EMPTY_MESSAGE = "Search criteria cannot be empty";
+
+ public static final String TENANT_ID_EMPTY_CODE = "TENANT_ID_EMPTY";
+ public static final String TENANT_ID_EMPTY_MESSAGE = "Tenant Id cannot be empty, TenantId should be present";
+
+ //Workflow constants
+ public static final String MODULE_NAME_VALUE = "census-service";
+
+ public static final String CENSUS_BUSINESS_SERVICE = "CENSUS";
+}
diff --git a/health-services/census-service/src/main/java/digit/kafka/FacilityCatchmentConsumer.java b/health-services/census-service/src/main/java/digit/kafka/FacilityCatchmentConsumer.java
new file mode 100644
index 00000000000..d5be4b7458c
--- /dev/null
+++ b/health-services/census-service/src/main/java/digit/kafka/FacilityCatchmentConsumer.java
@@ -0,0 +1,99 @@
+package digit.kafka;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import digit.repository.CensusRepository;
+import digit.service.CensusService;
+import digit.service.enrichment.CensusEnrichment;
+import digit.util.BoundaryUtil;
+import digit.util.CommonUtil;
+import digit.web.models.BulkCensusRequest;
+import digit.web.models.Census;
+import digit.web.models.CensusResponse;
+import digit.web.models.boundary.BoundaryTypeHierarchyResponse;
+import digit.web.models.plan.PlanFacilityDTO;
+import digit.web.models.plan.PlanFacilityRequestDTO;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.kafka.annotation.KafkaListener;
+import org.springframework.kafka.support.KafkaHeaders;
+import org.springframework.messaging.handler.annotation.Header;
+import org.springframework.stereotype.Component;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static digit.config.ServiceConstants.FACILITY_ID_FIELD;
+import static digit.config.ServiceConstants.FACILITY_NAME_FIELD;
+
+@Component
+@Slf4j
+public class FacilityCatchmentConsumer {
+
+ private ObjectMapper objectMapper;
+
+ private CensusService service;
+
+ private CensusRepository repository;
+
+ private CommonUtil commonUtil;
+
+ private BoundaryUtil boundaryUtil;
+
+ private CensusEnrichment enrichment;
+
+ public FacilityCatchmentConsumer(ObjectMapper objectMapper, CensusService service, CommonUtil commonUtil, CensusRepository repository, BoundaryUtil boundaryUtil, CensusEnrichment enrichment) {
+ this.objectMapper = objectMapper;
+ this.service = service;
+ this.commonUtil = commonUtil;
+ this.repository = repository;
+ this.boundaryUtil = boundaryUtil;
+ this.enrichment = enrichment;
+ }
+
+ @KafkaListener(topics = {"${plan.facility.update.topic}"})
+ public void listen(Map consumerRecord, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic) {
+ try {
+ PlanFacilityRequestDTO planFacilityRequestDTO = objectMapper.convertValue(consumerRecord, PlanFacilityRequestDTO.class);
+ PlanFacilityDTO planFacilityDTO = planFacilityRequestDTO.getPlanFacilityDTO();
+
+ CensusResponse censusResponse = service.search(commonUtil.getCensusSearchRequest(planFacilityDTO.getTenantId(), planFacilityDTO.getPlanConfigurationId(), planFacilityDTO.getServiceBoundaries(), planFacilityDTO.getInitiallySetServiceBoundaries(), planFacilityRequestDTO.getRequestInfo()));
+ List censusFromSearch = censusResponse.getCensus();
+
+ BoundaryTypeHierarchyResponse boundaryTypeHierarchyResponse = boundaryUtil.fetchBoundaryHierarchy(planFacilityRequestDTO.getRequestInfo(), censusFromSearch.get(0).getTenantId(), censusFromSearch.get(0).getHierarchyType());
+ String facilityId = planFacilityRequestDTO.getPlanFacilityDTO().getFacilityId();
+ String facilityName = planFacilityRequestDTO.getPlanFacilityDTO().getFacilityName();
+
+ Set boundariesWithFacility = new HashSet<>(List.of(planFacilityDTO.getServiceBoundaries().split(",")));
+ Set boundariesWithNoFacility = new HashSet<>(planFacilityDTO.getInitiallySetServiceBoundaries());
+
+ censusFromSearch.forEach(census -> {
+ String boundaryCode = census.getBoundaryCode();
+
+ if (!boundariesWithFacility.contains(boundaryCode)) {
+
+ // Unassigning facilities to the boundaries which were initially assigned that facility
+ census.setAdditionalDetails(commonUtil.removeFieldFromAdditionalDetails(census.getAdditionalDetails(), FACILITY_ID_FIELD));
+ census.setAdditionalDetails(commonUtil.removeFieldFromAdditionalDetails(census.getAdditionalDetails(), FACILITY_NAME_FIELD));
+ census.setFacilityAssigned(Boolean.FALSE);
+ census.setPartnerAssignmentValidationEnabled(Boolean.FALSE);
+
+ } else if (!boundariesWithNoFacility.contains(boundaryCode)) {
+
+ // Assigning facilities to the newly added boundaries in the update request.
+ census.setAdditionalDetails(commonUtil.updateFieldInAdditionalDetails(census.getAdditionalDetails(), FACILITY_ID_FIELD, facilityId));
+ census.setAdditionalDetails(commonUtil.updateFieldInAdditionalDetails(census.getAdditionalDetails(), FACILITY_NAME_FIELD, facilityName));
+ census.setFacilityAssigned(Boolean.TRUE);
+ census.setPartnerAssignmentValidationEnabled(Boolean.FALSE);
+ }
+ });
+
+ // Enrich jurisdiction mapping in census for indexer
+ enrichment.enrichJurisdictionMapping(censusFromSearch, boundaryTypeHierarchyResponse.getBoundaryHierarchy().get(0));
+ repository.bulkUpdate(BulkCensusRequest.builder().requestInfo(planFacilityRequestDTO.getRequestInfo()).census(censusFromSearch).build());
+
+ } catch (Exception exception) {
+ log.error("Error in census consumer", exception);
+ }
+ }
+}
diff --git a/health-services/census-service/src/main/java/digit/kafka/Producer.java b/health-services/census-service/src/main/java/digit/kafka/Producer.java
new file mode 100644
index 00000000000..542f4f686c0
--- /dev/null
+++ b/health-services/census-service/src/main/java/digit/kafka/Producer.java
@@ -0,0 +1,20 @@
+package digit.kafka;
+
+import lombok.extern.slf4j.Slf4j;
+import org.egov.tracer.kafka.CustomKafkaTemplate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+// NOTE: If tracer is disabled change CustomKafkaTemplate to KafkaTemplate in autowiring
+
+@Service
+@Slf4j
+public class Producer {
+
+ @Autowired
+ private CustomKafkaTemplate kafkaTemplate;
+
+ public void push(String topic, Object value) {
+ kafkaTemplate.send(topic, value);
+ }
+}
diff --git a/health-services/census-service/src/main/java/digit/kafka/ResourceCensusConsumer.java b/health-services/census-service/src/main/java/digit/kafka/ResourceCensusConsumer.java
new file mode 100644
index 00000000000..e161225b23a
--- /dev/null
+++ b/health-services/census-service/src/main/java/digit/kafka/ResourceCensusConsumer.java
@@ -0,0 +1,37 @@
+package digit.kafka;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import digit.service.CensusService;
+import digit.web.models.CensusRequest;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.kafka.annotation.KafkaListener;
+import org.springframework.kafka.support.KafkaHeaders;
+import org.springframework.messaging.handler.annotation.Header;
+import org.springframework.stereotype.Component;
+
+import java.util.Map;
+
+@Component
+@Slf4j
+public class ResourceCensusConsumer {
+
+ private CensusService censusService;
+
+ private ObjectMapper mapper;
+
+ public ResourceCensusConsumer(CensusService censusService, ObjectMapper mapper) {
+ this.censusService = censusService;
+ this.mapper = mapper;
+ }
+
+ @KafkaListener(topics = {"${resource.config.consumer.census.create.topic}"})
+ public void listen(Map consumerRecord, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic) {
+ try {
+ CensusRequest censusRequest = mapper.convertValue(consumerRecord, CensusRequest.class);
+ censusRequest.getCensus().setPartnerAssignmentValidationEnabled(Boolean.FALSE);
+ censusService.create(censusRequest);
+ } catch (Exception exception) {
+ log.error("Error in resource census consumer", exception);
+ }
+ }
+}
diff --git a/health-services/census-service/src/main/java/digit/repository/CensusRepository.java b/health-services/census-service/src/main/java/digit/repository/CensusRepository.java
new file mode 100644
index 00000000000..4a9f159e7e9
--- /dev/null
+++ b/health-services/census-service/src/main/java/digit/repository/CensusRepository.java
@@ -0,0 +1,21 @@
+package digit.repository;
+
+import digit.web.models.*;
+
+import java.util.List;
+import java.util.Map;
+
+public interface CensusRepository {
+
+ public void create(CensusRequest censusRequest);
+
+ public List search(CensusSearchCriteria censusSearchCriteria);
+
+ public void update(CensusRequest censusRequest);
+
+ public void bulkUpdate(BulkCensusRequest request);
+
+ public Integer count(CensusSearchCriteria censusSearchCriteria);
+
+ public Map statusCount(CensusSearchRequest censusSearchRequest);
+}
diff --git a/health-services/census-service/src/main/java/digit/repository/ServiceRequestRepository.java b/health-services/census-service/src/main/java/digit/repository/ServiceRequestRepository.java
new file mode 100644
index 00000000000..d09d230e4fa
--- /dev/null
+++ b/health-services/census-service/src/main/java/digit/repository/ServiceRequestRepository.java
@@ -0,0 +1,45 @@
+package digit.repository;
+
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializationFeature;
+import lombok.extern.slf4j.Slf4j;
+import org.egov.tracer.model.ServiceCallException;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Repository;
+import org.springframework.web.client.HttpClientErrorException;
+import org.springframework.web.client.RestTemplate;
+
+import java.util.Map;
+
+import static digit.config.ServiceConstants.*;
+
+@Repository
+@Slf4j
+public class ServiceRequestRepository {
+
+ private ObjectMapper mapper;
+
+ private RestTemplate restTemplate;
+
+ public ServiceRequestRepository(ObjectMapper mapper, RestTemplate restTemplate) {
+ this.mapper = mapper;
+ this.restTemplate = restTemplate;
+ }
+
+
+ public Object fetchResult(StringBuilder uri, Object request) {
+ mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
+ Object response = null;
+ try {
+ response = restTemplate.postForObject(uri.toString(), request, Map.class);
+ } catch (HttpClientErrorException e) {
+ log.error(EXTERNAL_SERVICE_EXCEPTION, e);
+ throw new ServiceCallException(e.getResponseBodyAsString());
+ } catch (Exception e) {
+ log.error(SEARCHER_SERVICE_EXCEPTION, e);
+ }
+
+ return response;
+ }
+}
\ No newline at end of file
diff --git a/health-services/census-service/src/main/java/digit/repository/impl/CensusRepositoryImpl.java b/health-services/census-service/src/main/java/digit/repository/impl/CensusRepositoryImpl.java
new file mode 100644
index 00000000000..c6dec4b4d11
--- /dev/null
+++ b/health-services/census-service/src/main/java/digit/repository/impl/CensusRepositoryImpl.java
@@ -0,0 +1,219 @@
+package digit.repository.impl;
+
+import digit.config.Configuration;
+import digit.kafka.Producer;
+import digit.repository.CensusRepository;
+import digit.repository.querybuilder.CensusQueryBuilder;
+import digit.repository.rowmapper.CensusRowMapper;
+import digit.repository.rowmapper.StatusCountRowMapper;
+import digit.util.CommonUtil;
+import digit.web.models.*;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.jdbc.core.SingleColumnRowMapper;
+import org.springframework.stereotype.Repository;
+import org.springframework.util.CollectionUtils;
+import org.springframework.util.ObjectUtils;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import static digit.config.ServiceConstants.CENSUS_BUSINESS_SERVICE;
+
+@Slf4j
+@Repository
+public class CensusRepositoryImpl implements CensusRepository {
+
+ private Producer producer;
+
+ private Configuration config;
+
+ private CensusQueryBuilder queryBuilder;
+
+ private CensusRowMapper censusRowMapper;
+
+ private JdbcTemplate jdbcTemplate;
+
+ private StatusCountRowMapper statusCountRowMapper;
+
+ private CommonUtil commonUtil;
+
+ public CensusRepositoryImpl(Producer producer, Configuration config, CensusQueryBuilder queryBuilder, CensusRowMapper censusRowMapper, JdbcTemplate jdbcTemplate, StatusCountRowMapper statusCountRowMapper,CommonUtil commonUtil) {
+ this.producer = producer;
+ this.config = config;
+ this.queryBuilder = queryBuilder;
+ this.censusRowMapper = censusRowMapper;
+ this.jdbcTemplate = jdbcTemplate;
+ this.statusCountRowMapper = statusCountRowMapper;
+ this.commonUtil = commonUtil;
+ }
+
+ /**
+ * Pushes a new census record to persister kafka topic.
+ *
+ * @param censusRequest The request containing the census details
+ */
+ @Override
+ public void create(CensusRequest censusRequest) {
+ CensusRequestDTO requestDTO = convertToReqDTO(censusRequest);
+ producer.push(config.getCensusCreateTopic(), requestDTO);
+ }
+
+ /**
+ * Searches for census records based on the provided search criteria.
+ *
+ * @param censusSearchCriteria The criteria to use for searching census records.
+ * @return A list of census records that match the search criteria.
+ */
+ @Override
+ public List search(CensusSearchCriteria censusSearchCriteria) {
+
+ if(censusSearchCriteria.getAreaCodes() != null && censusSearchCriteria.getAreaCodes().isEmpty())
+ return new ArrayList<>();
+
+ // Fetch census ids from database
+ List censusIds = queryDatabaseForCensusIds(censusSearchCriteria);
+
+ // Return empty list back as response if no census ids are found
+ if(CollectionUtils.isEmpty(censusIds)) {
+ log.info("No census ids found for provided census search criteria.");
+ return new ArrayList<>();
+ }
+
+ // Fetch census from database based on the acquired ids
+ return searchCensusByIds(censusIds);
+ }
+
+ private List searchCensusByIds(List censusIds) {
+
+ List