diff --git a/health-services/project-factory/src/server/api/campaignApis.ts b/health-services/project-factory/src/server/api/campaignApis.ts index 10f0d30980..533c5bb888 100644 --- a/health-services/project-factory/src/server/api/campaignApis.ts +++ b/health-services/project-factory/src/server/api/campaignApis.ts @@ -28,7 +28,6 @@ import { getBoundaryOnWhichWeSplit, getLocalizedName, reorderBoundariesOfDataAndValidate, - checkIfSourceIsMicroplan, createIdRequests, createUniqueUserNameViaIdGen, boundaryGeometryManagement, @@ -48,6 +47,7 @@ import { checkAndGiveIfParentCampaignAvailable } from "../utils/onGoingCampaignU import { validateMicroplanFacility } from "../validators/microplanValidators"; import { createPlanFacilityForMicroplan, + isMicropplanCampaignId, updateFacilityDetailsForMicroplan, } from "../utils/microplanUtils"; import { getTransformedLocale } from "../utils/localisationUtils"; @@ -240,7 +240,7 @@ function changeBodyViaElements(elements: any, requestBody: any) { // } // } -function updateErrorsForUser( +async function updateErrorsForUser( request: any, newCreatedData: any[], newSearchedData: any[], @@ -249,7 +249,7 @@ function updateErrorsForUser( userNameAndPassword: any[] ) { const isSourceMicroplan = - request?.body?.ResourceDetails?.additionalDetails?.source == "microplan"; + await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId); newCreatedData.forEach((createdElement: any) => { let foundMatch = false; for (const searchedElement of newSearchedData) { @@ -340,7 +340,7 @@ function updateErrors( }); } -function matchCreatedAndSearchedData( +async function matchCreatedAndSearchedData( createdData: any[], searchedData: any[], request: any, @@ -369,7 +369,7 @@ function matchCreatedAndSearchedData( updateFacilityDetailsForMicroplan(request, newCreatedData); } else { var userNameAndPassword: any = []; - updateErrorsForUser( + await updateErrorsForUser( request, newCreatedData, newSearchedData, @@ -584,7 +584,7 @@ async function matchUserValidation(createdData: any[], request: any) { ? [...request?.body?.sheetErrorDetails, ...errors] : errors; } -function matchViaUserIdAndCreationTime( +async function matchViaUserIdAndCreationTime( createdData: any[], searchedData: any[], request: any, @@ -612,7 +612,7 @@ function matchViaUserIdAndCreationTime( if (count < createdData.length) { request.body.ResourceDetails.status = "PERSISTER_ERROR"; } - matchCreatedAndSearchedData( + await matchCreatedAndSearchedData( createdData, matchingSearchData, request, @@ -828,7 +828,7 @@ async function confirmCreation( request, params ); - matchViaUserIdAndCreationTime( + await matchViaUserIdAndCreationTime( dataToCreate, arraysToMatch, request, @@ -838,7 +838,7 @@ async function confirmCreation( ); } else { const arraysToMatch = await getEmployeesBasedOnUuids(dataToCreate, request); - matchViaUserIdAndCreationTime( + await matchViaUserIdAndCreationTime( dataToCreate, arraysToMatch, request, @@ -858,9 +858,8 @@ async function processValidateAfterSchema( try { validateEmptyActive(dataFromSheet, request?.body?.ResourceDetails?.type, localizationMap); if ( - request?.body?.ResourceDetails?.additionalDetails?.source == - "microplan" && - request?.body?.ResourceDetails?.type == "facility" + await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId) && + request.body.ResourceDetails.type == "facility" ) { validateMicroplanFacility(request, dataFromSheet, localizationMap); } @@ -888,7 +887,7 @@ export async function processValidateAfterSchemaSheetWise( localizationMap?: { [key: string]: string } ) { if ( - request?.body?.ResourceDetails?.additionalDetails?.source == "microplan" && + await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId) && request.body.ResourceDetails.type == "user" ) { await generateProcessedFileAndPersist(request, localizationMap); @@ -1015,7 +1014,7 @@ async function processValidate( if (type == "facility" || type == "user") { const isUpdate = request?.body?.parentCampaignObject ? true : false; if ( - request?.body?.ResourceDetails?.additionalDetails?.source == "microplan" + await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId) ) { schema = await callMdmsTypeSchema( request, @@ -1031,7 +1030,7 @@ async function processValidate( const translatedSchema = await translateSchema(schema, localizationMap); if (Array.isArray(dataFromSheet)) { if ( - request?.body?.ResourceDetails?.additionalDetails?.source != "microplan" + await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId) ) { await validateSheetData( dataFromSheet, @@ -1502,8 +1501,7 @@ async function processAfterValidation( try { validateEmptyActive(dataFromSheet, request?.body?.ResourceDetails?.type, localizationMap); if ( - request?.body?.ResourceDetails?.additionalDetails?.source == - "microplan" && + await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId) && request.body.ResourceDetails.type == "user" ) { await processSearchAndValidation(request); @@ -1574,7 +1572,7 @@ async function processCreate(request: any, localizationMap?: any) { const responseFromCampaignSearch = await getCampaignSearchResponse(request); const campaignType = responseFromCampaignSearch?.CampaignDetails[0]?.projectType; - if (checkIfSourceIsMicroplan(request?.body?.ResourceDetails)) { + if (await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId)) { logger.info(`Data create Source is MICROPLAN`); if (createAndSearchConfig?.parseArrayConfig?.parseLogic) { createAndSearchConfig.parseArrayConfig.parseLogic = @@ -1643,7 +1641,7 @@ async function getSchema( "Fetching schema to validate the created data for type: " + type ); if ( - request?.body?.ResourceDetails?.additionalDetails?.source == "microplan" + await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId) ) { const mdmsResponse = await callMdmsTypeSchema( request, diff --git a/health-services/project-factory/src/server/utils/campaignUtils.ts b/health-services/project-factory/src/server/utils/campaignUtils.ts index 215b9c4cf1..cc45d5fb91 100644 --- a/health-services/project-factory/src/server/utils/campaignUtils.ts +++ b/health-services/project-factory/src/server/utils/campaignUtils.ts @@ -93,7 +93,7 @@ import { modifyNewSheetData, unhideColumnsOfProcessedFile, } from "./onGoingCampaignUpdateUtils"; -import { changeCreateDataForMicroplan, lockSheet } from "./microplanUtils"; +import { changeCreateDataForMicroplan, isMicroplanRequest, isMicropplanCampaignId, lockSheet } from "./microplanUtils"; const _ = require("lodash"); import { searchDataService } from "../service/dataManageService"; import { searchMDMSDataViaV2Api } from "../api/coreApis"; @@ -305,7 +305,7 @@ function enrichActiveAndUUidColumn( } } -function deterMineLastColumnAndEnrichUserDetails( +async function deterMineLastColumnAndEnrichUserDetails( worksheet: any, errorDetailsColumn: number, userNameAndPassword: @@ -313,7 +313,7 @@ function deterMineLastColumnAndEnrichUserDetails( | undefined, request: any, createAndSearchConfig: { uniqueIdentifierColumn?: number } -): string { +){ // Determine the last column let lastColumn: any = errorDetailsColumn; if (createAndSearchConfig?.uniqueIdentifierColumn !== undefined) { @@ -329,7 +329,7 @@ function deterMineLastColumnAndEnrichUserDetails( // Update columns if the request indicates a different source if ( - request?.body?.ResourceDetails?.additionalDetails?.source == "microplan" + await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId) ) { usernameColumn = "F"; passwordColumn = "G"; @@ -387,7 +387,7 @@ function adjustRef(worksheet: any, lastColumn: any) { }; } -function processErrorData( +async function processErrorData( request: any, createAndSearchConfig: any, workbook: any, @@ -418,7 +418,7 @@ function processErrorData( : additionalDetailsErrors; // Determine the last column to set the worksheet ref - const lastColumn = deterMineLastColumnAndEnrichUserDetails( + const lastColumn = await deterMineLastColumnAndEnrichUserDetails( worksheet, errorDetailsColumn, userNameAndPassword, @@ -535,7 +535,7 @@ async function updateStatusFile( "get" ); const isLockSheetNeeded = - request?.body?.ResourceDetails?.additionalDetails?.source == "microplan" + await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId) ? true : false; @@ -554,7 +554,7 @@ async function updateStatusFile( const columnsToUnhide = ["G", "H", "J", "K"]; unhideColumnsOfProcessedFile(worksheet, columnsToUnhide); } - processErrorData( + await processErrorData( request, createAndSearchConfig, workbook, @@ -595,7 +595,7 @@ async function updateStatusFileForEachSheets( "get" ); const isLockSheetNeeded = - request?.body?.ResourceDetails?.additionalDetails?.source == "microplan" + await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId) ? true : false; @@ -702,7 +702,7 @@ async function processData( const requiresToSearchFromSheet = createAndSearchConfig?.requiresToSearchFromSheet; const isSourceMicroplan = - request?.body?.ResourceDetails?.additionalDetails?.source == "microplan"; + await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId); var createData = [], searchData = []; for (const data of dataFromSheet) { @@ -810,7 +810,7 @@ async function generateProcessedFileAndPersist( ) { if ( request.body.ResourceDetails.type == "boundaryWithTarget" || - (request?.body?.ResourceDetails?.additionalDetails?.source == "microplan" && + (await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId) && request.body.ResourceDetails.type == "user") ) { await updateStatusFileForEachSheets(request, localizationMap); @@ -838,7 +838,7 @@ async function generateProcessedFileAndPersist( ...request?.body?.ResourceDetails?.additionalDetails, sheetErrors: request?.body?.additionalDetailsErrors, source: - request?.body?.ResourceDetails?.additionalDetails?.source == "microplan" + await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId) ? "microplan" : null, }, @@ -881,7 +881,7 @@ async function generateProcessedFileAndPersist( if (request?.body?.ResourceDetails?.action == "create") { persistMessage.ResourceDetails.additionalDetails = { source: - request?.body?.ResourceDetails?.additionalDetails?.source == "microplan" + await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId) ? "microplan" : null, fileName: @@ -2484,7 +2484,6 @@ async function appendSheetsToWorkbook( ); const responseFromCampaignSearch = await getCampaignSearchResponse(request); const campaignObject = responseFromCampaignSearch?.CampaignDetails?.[0]; - // const isSourceMicroplan = checkIfSourceIsMicroplan(campaignObject); const mainSheet = workbook.addWorksheet( getLocalizedName(getBoundaryTabName(), localizationMap) ); @@ -2973,16 +2972,15 @@ async function updateAndPersistResourceDetails( lastModifiedTime: Date.now(), }, additionalDetails: - { - ...request?.body?.ResourceDetails?.additionalDetails, - sheetErrors: request?.body?.additionalDetailsErrors, - source: - request?.body?.ResourceDetails?.additionalDetails?.source == - "microplan" - ? "microplan" - : null, - [name]: [fileStoreId], - }, + { + ...request?.body?.ResourceDetails?.additionalDetails, + sheetErrors: request?.body?.additionalDetailsErrors, + source: + await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId) + ? "microplan" + : null, + [name]: [fileStoreId], + } , }; } else { request.body.ResourceDetails = { @@ -3441,7 +3439,7 @@ const getConfigurableColumnHeadersBasedOnCampaignType = async ( const responseFromCampaignSearch = await getCampaignSearchResponse(request); const campaignObject = responseFromCampaignSearch?.CampaignDetails?.[0]; let campaignType = campaignObject?.projectType; - const isSourceMicroplan = checkIfSourceIsMicroplan(campaignObject); + const isSourceMicroplan = await isMicroplanRequest(request); campaignType = isSourceMicroplan ? `${config?.prefixForMicroplanCampaigns}-${campaignType}` : campaignType; @@ -3523,7 +3521,7 @@ async function getFinalValidHeadersForTargetSheetAsPerCampaignType( ); const responseFromCampaignSearch = await getCampaignSearchResponse(request); const campaignObject = responseFromCampaignSearch?.CampaignDetails?.[0]; - const isSourceMicroplan = checkIfSourceIsMicroplan(campaignObject); + const isSourceMicroplan = await isMicroplanRequest(request); var expectedHeadersForTargetSheetUptoHierarchy: any; if (isSourceMicroplan) { expectedHeadersForTargetSheetUptoHierarchy = localizedHierarchy; @@ -3630,10 +3628,6 @@ async function getBoundaryOnWhichWeSplit(request: any, tenantId: any) { return mdmsResponse?.mdms?.[0]?.data?.splitBoundariesOn; } -function checkIfSourceIsMicroplan(objectWithAdditionalDetails: any): boolean { - return objectWithAdditionalDetails?.additionalDetails?.source === "microplan"; -} - function createIdRequests(employees: any[]): any[] { if (employees && Array.isArray(employees) && employees.length > 0) { const { tenantId } = employees[0]; // Assuming all employees have the same tenantId @@ -3782,7 +3776,6 @@ export { getConfigurableColumnHeadersBasedOnCampaignType, getFinalValidHeadersForTargetSheetAsPerCampaignType, getDifferentTabGeneratedBasedOnConfig, - checkIfSourceIsMicroplan, getBoundaryOnWhichWeSplit, createIdRequests, createUniqueUserNameViaIdGen, diff --git a/health-services/project-factory/src/server/utils/genericUtils.ts b/health-services/project-factory/src/server/utils/genericUtils.ts index da91f18f0a..6b04af68ec 100644 --- a/health-services/project-factory/src/server/utils/genericUtils.ts +++ b/health-services/project-factory/src/server/utils/genericUtils.ts @@ -6,7 +6,7 @@ import { produceModifiedMessages } from "../kafka/Producer"; import { generateHierarchyList, getAllFacilities, getCampaignSearchResponse, getHierarchy } from "../api/campaignApis"; import { getBoundarySheetData, getSheetData, createAndUploadFile, createExcelSheet, getTargetSheetData, callMdmsData, callMdmsTypeSchema, getConfigurableColumnHeadersBasedOnCampaignTypeForBoundaryManagement } from "../api/genericApis"; import { logger } from "./logger"; -import { checkIfSourceIsMicroplan, getConfigurableColumnHeadersBasedOnCampaignType, getDifferentTabGeneratedBasedOnConfig, getLocalizedName } from "./campaignUtils"; +import { getConfigurableColumnHeadersBasedOnCampaignType, getDifferentTabGeneratedBasedOnConfig, getLocalizedName } from "./campaignUtils"; import Localisation from "../controllers/localisationController/localisation.controller"; import { executeQuery } from "./db"; import { generatedResourceTransformer } from "./transforms/searchResponseConstructor"; @@ -18,7 +18,7 @@ import { addDataToSheet, formatWorksheet, getNewExcelWorkbook, updateFontNameToR import createAndSearch from "../config/createAndSearch"; import { generateDynamicTargetHeaders } from "./targetUtils"; import { buildSearchCriteria, checkAndGiveIfParentCampaignAvailable, fetchFileUrls, getCreatedResourceIds, modifyProcessedSheetData } from "./onGoingCampaignUpdateUtils"; -import { getReadMeConfigForMicroplan, getRolesForMicroplan, getUserDataFromMicroplanSheet, isMicroplanRequest, modifyBoundaryIfSourceMicroplan } from "./microplanUtils"; +import { getReadMeConfigForMicroplan, getRolesForMicroplan, getUserDataFromMicroplanSheet, isMicroplanRequest, isMicropplanCampaignId, modifyBoundaryIfSourceMicroplan } from "./microplanUtils"; const NodeCache = require("node-cache"); const updateGeneratedResourceTopic = config?.kafka?.KAFKA_UPDATE_GENERATED_RESOURCE_DETAILS_TOPIC; @@ -544,7 +544,7 @@ async function getSchemaBasedOnSource(request: any, isSourceMicroplan: boolean, async function createFacilitySheet(request: any, allFacilities: any[], localizationMap?: { [key: string]: string }) { const responseFromCampaignSearch = await getCampaignSearchResponse(request); - const isSourceMicroplan = checkIfSourceIsMicroplan(responseFromCampaignSearch?.CampaignDetails?.[0]); + const isSourceMicroplan = await isMicropplanCampaignId(request?.query?.campaignId); request.body.isSourceMicroplan = isSourceMicroplan; let schema: any = await getSchemaBasedOnSource(request, isSourceMicroplan, responseFromCampaignSearch?.CampaignDetails?.[0]?.additionalDetails?.resourceDistributionStrategy); const keys = schema?.columns; @@ -1232,7 +1232,7 @@ async function getDataFromSheetFromNormalCampaign(type: any, fileStoreId: any, t async function getDataFromSheet(request: any, fileStoreId: any, tenantId: any, createAndSearchConfig: any, optionalSheetName?: any, localizationMap?: { [key: string]: string }) { - const isSourceMicroplan = request?.body?.ResourceDetails?.additionalDetails?.source == "microplan"; + const isSourceMicroplan = await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId); const type = request?.body?.ResourceDetails?.type; if (isSourceMicroplan) { if (type == 'user') { @@ -1431,7 +1431,7 @@ function getDifferentDistrictTabs(boundaryData: any, differentTabsBasedOnLevel: async function getConfigurableColumnHeadersFromSchemaForTargetSheet(request: any, hierarchy: any, boundaryData: any, differentTabsBasedOnLevel: any, campaignObject: any, localizationMap?: any) { const districtIndex = hierarchy.indexOf(differentTabsBasedOnLevel); let headers: any; - const isSourceMicroplan = checkIfSourceIsMicroplan(campaignObject); + const isSourceMicroplan = await isMicroplanRequest(request); if (isSourceMicroplan) { logger.info(`Source is Microplan.`); headers = getLocalizedHeaders(hierarchy, localizationMap); @@ -1450,7 +1450,7 @@ async function getMdmsDataBasedOnCampaignType(request: any, localizationMap?: an const responseFromCampaignSearch = await getCampaignSearchResponse(request); const campaignObject = responseFromCampaignSearch?.CampaignDetails?.[0]; let campaignType = campaignObject.projectType; - const isSourceMicroplan = checkIfSourceIsMicroplan(campaignObject); + const isSourceMicroplan = await isMicroplanRequest(request); campaignType = (isSourceMicroplan) ? `${config?.prefixForMicroplanCampaigns}-${campaignType}` : campaignType; const mdmsResponse = await callMdmsTypeSchema(request, request?.query?.tenantId || request?.body?.ResourceDetails?.tenantId, false, request?.query?.type || request?.body?.ResourceDetails?.type, campaignType) return mdmsResponse; diff --git a/health-services/project-factory/src/server/utils/microplanUtils.ts b/health-services/project-factory/src/server/utils/microplanUtils.ts index 2442a4d2ed..5fff922465 100644 --- a/health-services/project-factory/src/server/utils/microplanUtils.ts +++ b/health-services/project-factory/src/server/utils/microplanUtils.ts @@ -4,11 +4,12 @@ import config from "./../config"; import { throwError } from "./genericUtils"; import { httpRequest } from "./request"; import { callMdmsData, getSheetData } from "./../api/genericApis"; -import { checkIfSourceIsMicroplan, getLocalizedName } from "./campaignUtils"; +import { getLocalizedName } from "./campaignUtils"; import createAndSearch from "../config/createAndSearch"; import { produceModifiedMessages } from "../kafka/Producer"; import { searchMDMSDataViaV2Api } from "../api/coreApis"; -import { getCampaignSearchResponse } from "../api/campaignApis"; +import { executeQuery } from "./db"; +import { logger } from "./logger"; export const filterData = (data: any) => { @@ -319,7 +320,7 @@ export function updateFacilityDetailsForMicroplan(request: any, createdData: any export async function createPlanFacilityForMicroplan(request: any, localizationMap?: any) { - if (request?.body?.ResourceDetails?.type == 'facility' && request?.body?.ResourceDetails?.additionalDetails?.source == 'microplan') { + if (request?.body?.ResourceDetails?.type == 'facility' && await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId)) { const allFacilityDatas = request?.body?.facilityDataForMicroplan; const planConfigurationId = request?.body?.ResourceDetails?.additionalDetails?.microplanId; request.body.MicroplanDetails = { @@ -462,16 +463,30 @@ export async function getRolesForMicroplan(tenantId: string, localizationMap: an } } -export async function isMicroplanRequest(request: any): Promise { +export async function isMicroplanRequest(request: any) { const campaignId = request?.query?.campaignId || request?.body?.ResourceDetails?.campaignId; - if (campaignId == "microplan") { - return true; + return await isMicropplanCampaignId(campaignId); +} + +export async function isMicropplanCampaignId(campaignId: string) { + if (campaignId == "microplan") return true; + const query = ` + SELECT (additionaldetails->>'source' = 'microplan') AS is_microplan + FROM ${config?.DB_CONFIG.DB_CAMPAIGN_DETAILS_TABLE_NAME} + WHERE id = $1; + `; + + try { + const { rowCount, rows } = await executeQuery(query, [campaignId]); + return rowCount > 0 ? rows[0].is_microplan : false; + } catch (error: any) { + logger.error(`Error checking if campaign ${campaignId} is a microplan request: ${error.message}`); + throw error; } - const responseFromCampaignSearch = await getCampaignSearchResponse(request); - const campaignObject = responseFromCampaignSearch?.CampaignDetails?.[0]; - return checkIfSourceIsMicroplan(campaignObject); } + + export async function getReadMeConfigForMicroplan(request: any) { const mdmsResponse = await callMdmsData(request, "HCM-ADMIN-CONSOLE", "ReadMeConfig", request?.query?.tenantId); if (mdmsResponse?.MdmsRes?.["HCM-ADMIN-CONSOLE"]?.ReadMeConfig) { diff --git a/health-services/project-factory/src/server/utils/targetUtils.ts b/health-services/project-factory/src/server/utils/targetUtils.ts index 7e102feb6d..b9fe6acbd8 100644 --- a/health-services/project-factory/src/server/utils/targetUtils.ts +++ b/health-services/project-factory/src/server/utils/targetUtils.ts @@ -1,12 +1,13 @@ import config from '../config' -import { checkIfSourceIsMicroplan, getConfigurableColumnHeadersBasedOnCampaignType, getLocalizedName } from './campaignUtils'; +import { getConfigurableColumnHeadersBasedOnCampaignType, getLocalizedName } from './campaignUtils'; import _ from 'lodash'; import { replicateRequest } from './genericUtils'; import { callGenerate } from './generateUtils'; +import { isMicroplanRequest } from './microplanUtils'; async function generateDynamicTargetHeaders(request: any, campaignObject: any, localizationMap?: any) { - const isSourceMicroplan = checkIfSourceIsMicroplan(campaignObject); + const isSourceMicroplan = await isMicroplanRequest(request); let headerColumnsAfterHierarchy: any; if (isDynamicTargetTemplateForProjectType(campaignObject?.projectType) && campaignObject.deliveryRules && campaignObject.deliveryRules.length > 0 && !isSourceMicroplan) { const modifiedUniqueDeliveryConditions = modifyDeliveryConditions(campaignObject.deliveryRules); diff --git a/health-services/project-factory/src/server/validators/campaignValidators.ts b/health-services/project-factory/src/server/validators/campaignValidators.ts index 40dc426b5d..906772bf9f 100644 --- a/health-services/project-factory/src/server/validators/campaignValidators.ts +++ b/health-services/project-factory/src/server/validators/campaignValidators.ts @@ -24,7 +24,7 @@ import { generateTargetColumnsBasedOnDeliveryConditions, isDynamicTargetTemplate import { getBoundariesFromCampaignSearchResponse, validateBoundariesIfParentPresent } from "../utils/onGoingCampaignUpdateUtils"; import { validateFacilityBoundaryForLowestLevel, validateLatLongForMicroplanCampaigns, validatePhoneNumberSheetWise, validateTargetsForMicroplanCampaigns, validateUniqueSheetWise, validateUserForMicroplan } from "./microplanValidators"; import { produceModifiedMessages } from "../kafka/Producer"; -import { planConfigSearch, planFacilitySearch } from "../utils/microplanUtils"; +import { isMicroplanRequest, isMicropplanCampaignId, planConfigSearch, planFacilitySearch } from "../utils/microplanUtils"; import { getPvarIds } from "../utils/campaignMappingUtils"; import { fetchProductVariants } from "../api/healthApis"; @@ -150,7 +150,7 @@ async function validateTargets(request: any, data: any[], errors: any[], localiz columnsToValidate = columnsNotToBeFreezed.filter((element: any) => requiredColumns.includes(element)); } const localizedTargetColumnNames = getLocalizedHeaders(columnsToValidate, localizationMap); - if (request?.body?.ResourceDetails?.additionalDetails?.source === "microplan") { + if (await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId)) { validateTargetsForMicroplanCampaigns(data, errors, localizedTargetColumnNames, localizationMap); validateLatLongForMicroplanCampaigns(data, errors, localizationMap); } @@ -296,7 +296,7 @@ export async function validateViaSchema(data: any, schema: any, request: any, lo if (request?.body?.ResourceDetails?.type == "user") { validatePhoneNumber(data, localizationMap); } - if (data?.length > 0 && request?.body?.ResourceDetails?.additionalDetails?.source != "microplan") { + if (data?.length > 0 && await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId)) { if (!request?.body?.parentCampaignObject && data[0]?.[getLocalizedName("HCM_ADMIN_CONSOLE_BOUNDARY_CODE_OLD", localizationMap)]) { throwError("COMMON", 400, "VALIDATION_ERROR", `${request?.body?.ResourceDetails?.type} template downloaded from update campaign flow has been uploaded in create campaign flow`); } @@ -379,7 +379,7 @@ export async function validateViaSchemaSheetWise(dataFromExcel: any, schema: any const validationErrors: any[] = []; const uniqueIdentifierColumnName = getLocalizedName(createAndSearch?.[request?.body?.ResourceDetails?.type]?.uniqueIdentifierColumnName, localizationMap); const activeColumnName = createAndSearch?.[request?.body?.ResourceDetails?.type]?.activeColumnName ? getLocalizedName(createAndSearch?.[request?.body?.ResourceDetails?.type]?.activeColumnName, localizationMap) : null; - if (request?.body?.ResourceDetails?.type == "user" && request?.body?.ResourceDetails?.additionalDetails?.source == "microplan") { + if (request?.body?.ResourceDetails?.type == "user" && await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId)) { validateUserForMicroplan(data, sheetName, request, errorMap, newSchema, rowMapping, localizationMap); } else { @@ -481,7 +481,7 @@ function validateStorageCapacity(obj: any, index: any) { async function validateCampaignId(request: any) { - const { campaignId, tenantId, type, additionalDetails } = request?.body?.ResourceDetails; + const { campaignId, tenantId, type } = request?.body?.ResourceDetails; if (type == "boundary") { return; } @@ -510,7 +510,7 @@ async function validateCampaignId(request: any) { request.body.campaignBoundaries = boundaries } else { - if (!(additionalDetails?.source == "microplan" && type == "user")) { + if (!(campaignId == "microplan" && type == "user")) { throwError("CAMPAIGN", 400, "CAMPAIGN_NOT_FOUND", "Campaign not found while validating campaignId"); } } @@ -699,7 +699,7 @@ async function validateBoundariesForTabs(CampaignDetails: any, resource: any, re const fileResponse = await httpRequest(config.host.filestore + config.paths.filestore + "/url", {}, { tenantId, fileStoreIds: resource.fileStoreId }, "get"); const datas = await getSheetData(fileResponse?.fileStoreIds?.[0]?.url, localizedTab, true, undefined, localizationMap); var boundaryColumn: any; - if (resource?.additionalDetails?.source == 'microplan') { + if (await isMicroplanRequest(request)) { boundaryColumn = getLocalizedName(createAndSearch?.[`${resource.type}Microplan`]?.boundaryValidation?.column, localizationMap); } else { @@ -729,7 +729,7 @@ async function validateBoundariesForTabs(CampaignDetails: any, resource: any, re const errorString = `The following boundary codes are not present in selected boundaries : ${missingBoundaries.join(', ')}` errors.push({ status: "BOUNDARYERROR", rowNumber: rowData.rowNumber, errorDetails: errorString }) } - validateFacilityBoundaryForLowestLevel(request, boundaries, rowData, errors, localizationMap); + await validateFacilityBoundaryForLowestLevel(request, boundaries, rowData, errors, localizationMap); } if (errors?.length > 0) { request.body.ResourceDetails.status = resourceDataStatuses.invalid diff --git a/health-services/project-factory/src/server/validators/microplanValidators.ts b/health-services/project-factory/src/server/validators/microplanValidators.ts index 7d8d7658bf..9c2501a125 100644 --- a/health-services/project-factory/src/server/validators/microplanValidators.ts +++ b/health-services/project-factory/src/server/validators/microplanValidators.ts @@ -3,6 +3,7 @@ import createAndSearch from "../config/createAndSearch"; import { getLocalizedName } from "../utils/campaignUtils"; import { resourceDataStatuses } from "../config/constants"; import config from "../config"; +import { isMicropplanCampaignId } from "../utils/microplanUtils"; export function validatePhoneNumberSheetWise(datas: any[], localizationMap: any, rowMapping: any) { for (const data of datas) { @@ -286,8 +287,8 @@ function enrichErrorForFcailityMicroplan(request: any, item: any, errors: any = } } -export function validateFacilityBoundaryForLowestLevel(request: any, boundaries: any, rowData: any, errors: any = [], localizationMap?: { [key: string]: string }) { - if (request?.body?.ResourceDetails?.type == "facility" && request?.body?.ResourceDetails?.additionalDetails?.source == "microplan") { +export async function validateFacilityBoundaryForLowestLevel(request: any, boundaries: any, rowData: any, errors: any = [], localizationMap?: { [key: string]: string }) { + if (request?.body?.ResourceDetails?.type == "facility" && await isMicropplanCampaignId(request?.body?.ResourceDetails?.campaignId)) { const hierarchy = request?.body?.hierarchyType?.boundaryHierarchy const lastLevel = hierarchy?.[hierarchy.length - 1]?.boundaryType for (const data of rowData?.boundaryCodes) {