Skip to content

Commit

Permalink
Console dropdown logics (#1359)
Browse files Browse the repository at this point in the history
* refactored dropdown

* updated dropdown logic

* refactored dropdown logic

* refactor

* added dropdown related changes

* refactor

* refactor
  • Loading branch information
nitish-egov authored Jan 28, 2025
1 parent 3fc3a41 commit 343393e
Show file tree
Hide file tree
Showing 3 changed files with 96 additions and 61 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2205,8 +2205,7 @@ async function getCodesTarget(request: any, localizationMap?: any) {
entry["Target at the Selected Boundary level"];
if (
Object.keys(entry["Parent Target at the Selected Boundary level"]).length > 0 &&
entry["Parent Target at the Selected Boundary level"] !==
entry["Target at the Selected Boundary level"]
!_.isEqual(entry["Parent Target at the Selected Boundary level"],entry["Target at the Selected Boundary level"])
) {
boundaryCodesWhoseTargetsHasToBeUpdated.push(entry[codeColumnName]);
}
Expand Down
11 changes: 9 additions & 2 deletions health-services/project-factory/src/server/utils/excelUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ function performUnfreezeCells(sheet: any, localizationMap?: any, fileUrl?: any)
}
}
}
sheet.protect('passwordhere', { selectLockedCells: true, selectUnlockedCells: true });
// sheet.protect('passwordhere', { selectLockedCells: true, selectUnlockedCells: true });
}


Expand Down Expand Up @@ -392,5 +392,12 @@ export function enrichUsageColumnForFacility(worksheet: any, localizationMap: an
}
}

function protectSheet(sheet: any) {
sheet.protect('passwordhere', {
selectLockedCells: true,
selectUnlockedCells: true,
});
}


export { getNewExcelWorkbook, getExcelWorkbookFromFileURL, formatWorksheet, addDataToSheet, lockTargetFields, updateFontNameToRoboto, formatFirstRow, formatOtherRows, finalizeSheet };
export { getNewExcelWorkbook, getExcelWorkbookFromFileURL, formatWorksheet, addDataToSheet, lockTargetFields, updateFontNameToRoboto, formatFirstRow, formatOtherRows, finalizeSheet, protectSheet };
143 changes: 86 additions & 57 deletions health-services/project-factory/src/server/utils/genericUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,12 @@ import { generatedResourceStatuses, headingMapping, resourceDataStatuses } from
import { getLocaleFromRequest, getLocaleFromRequestInfo, getLocalisationModuleName } from "./localisationUtils";
import { getBoundaryColumnName, getBoundaryTabName, getLatLongMapForBoundaryCodes } from "./boundaryUtils";
import { getBoundaryDataService, searchDataService } from "../service/dataManageService";
import { addDataToSheet, enrichUsageColumnForFacility, formatWorksheet, getNewExcelWorkbook, updateFontNameToRoboto } from "./excelUtils";
import { addDataToSheet, enrichUsageColumnForFacility, formatWorksheet, getNewExcelWorkbook, protectSheet, updateFontNameToRoboto } from "./excelUtils";
import createAndSearch from "../config/createAndSearch";
import { generateDynamicTargetHeaders } from "./targetUtils";
import { buildSearchCriteria, checkAndGiveIfParentCampaignAvailable, fetchFileUrls, getCreatedResourceIds, modifyProcessedSheetData } from "./onGoingCampaignUpdateUtils";
import { getReadMeConfigForMicroplan, getRolesForMicroplan, getUserDataFromMicroplanSheet, isMicroplanRequest } from "./microplanUtils";
import _ from "lodash";
const NodeCache = require("node-cache");

const updateGeneratedResourceTopic = config?.kafka?.KAFKA_UPDATE_GENERATED_RESOURCE_DETAILS_TOPIC;
Expand Down Expand Up @@ -74,12 +75,11 @@ const throwError = (module = "COMMON", status = 500, code = "UNKNOWN_ERROR", des
throw error;
};


const replicateRequest = (originalRequest: Request, requestBody: any, requestQuery?: any) => {
const newRequest = {
...originalRequest,
body: requestBody,
query: requestQuery || originalRequest.query
body: _.cloneDeep(requestBody), // Deep clone using lodash
query: requestQuery ? _.cloneDeep(requestQuery) : _.cloneDeep(originalRequest.query)
};
return newRequest;
};
Expand Down Expand Up @@ -461,19 +461,19 @@ function correctParentValues(campaignDetails: any) {
return campaignDetails;
}

function setDropdownFromSchema(request: any, schema: any, localizationMap?: { [key: string]: string }) {
const dropdowns = Object.entries(schema.properties)
.filter(([key, value]: any) => Array.isArray(value.enum) && value.enum.length > 0)
.reduce((result: any, [key, value]: any) => {
// Transform the key using localisedValue function
const newKey: any = getLocalizedName(key, localizationMap);
result[newKey] = value.enum;
return result;
}, {});
logger.info(`dropdowns to set ${JSON.stringify(dropdowns)}`)
request.body.dropdowns = dropdowns;
return dropdowns;
}
// function setDropdownFromSchema(request: any, schema: any, localizationMap?: { [key: string]: string }) {
// const dropdowns = Object.entries(schema.properties)
// .filter(([key, value]: any) => Array.isArray(value.enum) && value.enum.length > 0)
// .reduce((result: any, [key, value]: any) => {
// // Transform the key using localisedValue function
// const newKey: any = getLocalizedName(key, localizationMap);
// result[newKey] = value.enum;
// return result;
// }, {});
// logger.info(`dropdowns to set ${JSON.stringify(dropdowns)}`)
// request.body.dropdowns = dropdowns;
// return dropdowns;
// }

function setHiddenColumns(request: any, schema: any, localizationMap?: { [key: string]: string }) {
// from schema.properties find the key whose value have value.hideColumn == true
Expand Down Expand Up @@ -525,7 +525,7 @@ async function createFacilitySheet(request: any, allFacilities: any[], localizat
request.body.isSourceMicroplan = isSourceMicroplan;
let schema: any = await getSchemaBasedOnSource(request, isSourceMicroplan, responseFromCampaignSearch?.CampaignDetails?.[0]?.additionalDetails?.resourceDistributionStrategy);
const keys = schema?.columns;
setDropdownFromSchema(request, schema, localizationMap);
// setDropdownFromSchema(request, schema, localizationMap);
setHiddenColumns(request, schema, localizationMap);
const headers = ["HCM_ADMIN_CONSOLE_FACILITY_CODE", ...keys]
let localizedHeaders;
Expand All @@ -549,7 +549,7 @@ async function createFacilitySheet(request: any, allFacilities: any[], localizat
logger.info("facilities generation done ");
logger.debug(`facility response ${JSON.stringify(facilities)}`)
const facilitySheetData: any = await createExcelSheet(facilities, localizedHeaders);
return facilitySheetData;
return { schema, facilitySheetData };
}


Expand Down Expand Up @@ -727,15 +727,15 @@ async function createFacilityAndBoundaryFile(facilitySheetData: any, boundaryShe
hideUniqueIdentifierColumn(facilitySheet, createAndSearch?.["facility"]?.uniqueIdentifierColumn);
changeFirstRowColumnColour(facilitySheet, 'E06666');

let receivedDropdowns = request.body?.dropdowns;
logger.info("started adding dropdowns in facility", JSON.stringify(receivedDropdowns))
// let receivedDropdowns = request.body?.dropdowns;

if (!receivedDropdowns || Object.keys(receivedDropdowns)?.length == 0) {
logger.info("No dropdowns found");
receivedDropdowns = setDropdownFromSchema(request, schema, localizationMap);
logger.info("refetched drodowns", JSON.stringify(receivedDropdowns))
}
await handledropdownthings(facilitySheet, receivedDropdowns);
// if (!receivedDropdowns || Object.keys(receivedDropdowns)?.length == 0) {
// logger.info("No dropdowns found");
// receivedDropdowns = setDropdownFromSchema(request, schema, localizationMap);
// logger.info("refetched drodowns", JSON.stringify(receivedDropdowns))
// }
await handledropdownthings(facilitySheet, schema, localizationMap);
protectSheet(facilitySheet);
await handleHiddenColumns(facilitySheet, request.body?.hiddenColumns);

// Add boundary sheet to the workbook
Expand All @@ -748,11 +748,20 @@ async function createFacilityAndBoundaryFile(facilitySheetData: any, boundaryShe
request.body.fileDetails = fileDetails;
}

async function handledropdownthings(sheet: any, dropdowns: any) {
let dropdownColumnIndex = -1;
async function handledropdownthings(sheet: any, schema: any, localizationMap: any) {
logger.info(sheet.rowCount)
const dropdowns = Object.entries(schema.properties)
.filter(([key, value]: any) => Array.isArray(value.enum) && value.enum.length > 0)
.reduce((result: any, [key, value]: any) => {
// Transform the key using localisedValue function
const newKey: any = getLocalizedName(key, localizationMap);
result[newKey] = value.enum;
return result;
}, {});
if (dropdowns) {
logger.info("Dropdowns provided:", dropdowns);
for (const key of Object.keys(dropdowns)) {
let dropdownColumnIndex = -1;
if (dropdowns[key]) {
logger.info(`Processing dropdown key: ${key} with values: ${dropdowns[key]}`);
const firstRow = sheet.getRow(1);
Expand All @@ -768,16 +777,32 @@ async function handledropdownthings(sheet: any, dropdowns: any) {
logger.info(`Setting dropdown for column index: ${dropdownColumnIndex}`);
sheet.getColumn(dropdownColumnIndex).eachCell({ includeEmpty: true }, (cell: any, rowNumber: any) => {
if (rowNumber > 1) {
// Set dropdown list with no typing allowed
cell.dataValidation = {
type: 'list',
formulae: [`"${dropdowns[key].join(',')}"`],
showDropDown: true,
error: 'Please select a value from the dropdown list.',
errorStyle: 'stop',
showErrorMessage: true,
errorTitle: 'Invalid Entry'
};
if (cell.protection?.locked) { // Check if the cell is locked
cell.protection = { locked: false };
// Set dropdown list with no typing allowed
cell.dataValidation = {
type: 'list',
formulae: [`"${dropdowns[key].join(',')}"`],
showDropDown: true,
error: 'Please select a value from the dropdown list.',
errorStyle: 'stop',
showErrorMessage: true,
errorTitle: 'Invalid Entry'
};
cell.protection = { locked: true }; // Lock the cell again after adding dropdown
}
else {
cell.dataValidation = {
type: 'list',
formulae: [`"${dropdowns[key].join(',')}"`],
showDropDown: true,
error: 'Please select a value from the dropdown list.',
errorStyle: 'stop',
showErrorMessage: true,
errorTitle: 'Invalid Entry',
allowBlank: true // Allow blank entries
};
}
}
});
} else {
Expand Down Expand Up @@ -829,12 +854,13 @@ async function createUserAndBoundaryFile(userSheetData: any, boundarySheetData:
let receivedDropdowns = request.body?.dropdowns;
logger.info("started adding dropdowns in user", JSON.stringify(receivedDropdowns))

if (!receivedDropdowns || Object.keys(receivedDropdowns)?.length == 0) {
logger.info("No dropdowns found");
receivedDropdowns = setDropdownFromSchema(request, schema, localizationMap);
logger.info("refetched drodowns", JSON.stringify(receivedDropdowns))
}
await handledropdownthings(userSheet, receivedDropdowns);
// if (!receivedDropdowns || Object.keys(receivedDropdowns)?.length == 0) {
// logger.info("No dropdowns found");
// receivedDropdowns = setDropdownFromSchema(request, schema, localizationMap);
// logger.info("refetched drodowns", JSON.stringify(receivedDropdowns))
// }
await handledropdownthings(userSheet, schema, localizationMap);
protectSheet(userSheet);
await handleHiddenColumns(userSheet, request.body?.hiddenColumns);
// Add boundary sheet to the workbook
const localizedBoundaryTab = getLocalizedName(getBoundaryTabName(), localizationMap)
Expand All @@ -854,29 +880,31 @@ async function generateFacilityAndBoundarySheet(tenantId: string, request: any,
const allFacilities = await getAllFacilities(tenantId, request.body);
request.body.generatedResourceCount = allFacilities?.length;
logger.info(`Facilities generation completed and found ${allFacilities?.length} facilities`);
let facilitySheetData: any;
let facilitySheetDataFinal: any;
const localizedFacilityTab = getLocalizedName(config?.facility?.facilityTab, localizationMap);
let schema: any;
let schemaFinal: any;
if (fileUrl) {
/* fetch facility from processed file
and generate facility sheet data */
schema = await callMdmsTypeSchema(request, tenantId, true, typeWithoutWith, "all");
schemaFinal = await callMdmsTypeSchema(request, tenantId, true, typeWithoutWith, "all");
const processedFacilitySheetData = await getSheetData(fileUrl, localizedFacilityTab, false, undefined, localizationMap);
const modifiedProcessedFacilitySheetData = modifyProcessedSheetData(typeWithoutWith, processedFacilitySheetData, schema, localizationMap);
facilitySheetData = modifiedProcessedFacilitySheetData;
setDropdownFromSchema(request, schema, localizationMap);
const modifiedProcessedFacilitySheetData = modifyProcessedSheetData(typeWithoutWith, processedFacilitySheetData, schemaFinal, localizationMap);
facilitySheetDataFinal = modifiedProcessedFacilitySheetData;
// setDropdownFromSchema(request, schema, localizationMap);
}
else {
facilitySheetData = await createFacilitySheet(request, allFacilities, localizationMap);
const { schema, facilitySheetData }: any = await createFacilitySheet(request, allFacilities, localizationMap);
facilitySheetDataFinal = facilitySheetData;
schemaFinal = schema;
}
// request.body.Filters = { tenantId: tenantId, hierarchyType: request?.query?.hierarchyType, includeChildren: true }
if (filteredBoundary && filteredBoundary.length > 0) {
logger.info("proceed with the filtered boundary data")
await createFacilityAndBoundaryFile(facilitySheetData, filteredBoundary, request, localizationMap, fileUrl, schema);
await createFacilityAndBoundaryFile(facilitySheetDataFinal, filteredBoundary, request, localizationMap, fileUrl, schemaFinal);
}
else {
const boundarySheetData: any = await getBoundarySheetData(request, localizationMap);
await createFacilityAndBoundaryFile(facilitySheetData, boundarySheetData, request, localizationMap, fileUrl, schema);
await createFacilityAndBoundaryFile(facilitySheetDataFinal, boundarySheetData, request, localizationMap, fileUrl, schemaFinal);
}
}

Expand All @@ -887,7 +915,7 @@ async function generateUserSheet(request: any, localizationMap?: { [key: string]
let schema: any;
const isUpdate = fileUrl ? true : false;
schema = await callMdmsTypeSchema(request, tenantId, isUpdate, typeWithoutWith);
setDropdownFromSchema(request, schema, localizationMap);
// setDropdownFromSchema(request, schema, localizationMap);
const headers = schema?.columns;
const localizedHeaders = getLocalizedHeaders(headers, localizationMap);
const localizedUserTab = getLocalizedName(config?.user?.userTab, localizationMap);
Expand Down Expand Up @@ -983,7 +1011,7 @@ async function generateUserSheetForMicroPlan(
) {
const { tenantId, type } = request?.query;
const schema = await callMdmsTypeSchema(request, tenantId, false, "user", "microplan");
setDropdownFromSchema(request, schema, localizationMap);
// setDropdownFromSchema(request, schema, localizationMap);
const headers = schema?.columns;
const localizedHeaders = getLocalizedHeaders(headers, localizationMap);

Expand All @@ -1005,7 +1033,8 @@ async function generateUserSheetForMicroPlan(
// Create a sheet for each role, using the role name as the sheet name
const userSheet: any = workbook.addWorksheet(role);
addDataToSheet(request, userSheet, userSheetData, undefined, undefined, true, false, localizationMap, fileUrl, schema);
await handledropdownthings(userSheet, request.body?.dropdowns);
await handledropdownthings(userSheet, schema, localizationMap);
protectSheet(userSheet);
await handleHiddenColumns(userSheet, request.body?.hiddenColumns);
}

Expand Down

0 comments on commit 343393e

Please sign in to comment.