From 175220c39691146c4e9adb09b9cda09a149522b7 Mon Sep 17 00:00:00 2001 From: kaliraja <34502260+Kaali09@users.noreply.github.com> Date: Wed, 16 Jun 2021 14:38:19 +0530 Subject: [PATCH 001/331] Updated the readme.md --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index b838a5b0..720578b4 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,2 @@ # ml-core-service -Centralised Service to support other Services - +Centralised Service to support other Services. From a263254cc6c51e0d36dc7dd2a6ed1aad5de063a3 Mon Sep 17 00:00:00 2001 From: kaliraja <34502260+Kaali09@users.noreply.github.com> Date: Wed, 16 Jun 2021 15:05:31 +0530 Subject: [PATCH 002/331] update the JF as per new JF format --- Jenkinsfile | 56 ++++++++++++++++++++++++----------------------------- 1 file changed, 25 insertions(+), 31 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index a67d5c05..dbf5a230 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -5,41 +5,35 @@ node('build-slave') { String ANSI_BOLD = "\u001B[1m" String ANSI_RED = "\u001B[31m" String ANSI_YELLOW = "\u001B[33m" + ansiColor('xterm') { - stage('Checkout') { - if (!env.hub_org) { - println(ANSI_BOLD + ANSI_RED + "Uh Oh! Please set a Jenkins environment variable named hub_org with value as registery/sunbidrded" + ANSI_NORMAL) - error 'Please resolve the errors and rerun..' - } - else - println(ANSI_BOLD + ANSI_GREEN + "Found environment variable named hub_org with value as: " + hub_org + ANSI_NORMAL) - cleanWs() - if (params.github_release_tag == "") { - checkout scm - commit_hash = sh(script: 'git rev-parse --short HEAD', returnStdout: true).trim() - branch_name = sh(script: 'git name-rev --name-only HEAD | rev | cut -d "/" -f1| rev', returnStdout: true).trim() - build_tag = branch_name + "_" + commit_hash - println(ANSI_BOLD + ANSI_YELLOW + "github_release_tag not specified, using the latest commit hash: " + commit_hash + ANSI_NORMAL) - } - else { - def scmVars = checkout scm - checkout scm: [$class: 'GitSCM', branches: [[name: "refs/tags/$params.github_release_tag"]], userRemoteConfigs: [[url: scmVars.GIT_URL]]] - build_tag = params.github_release_tag - println(ANSI_BOLD + ANSI_YELLOW + "github_release_tag specified, building from github_release_tag: " + params.github_release_tag + ANSI_NORMAL) + timestamps { + stage('Checkout') { + if (!env.hub_org) { + println(ANSI_BOLD + ANSI_RED + "Uh Oh! Please set a Jenkins environment variable named hub_org with value as registery/sunbidrded" + ANSI_NORMAL) + error 'Please resolve the errors and rerun..' + } else + println(ANSI_BOLD + ANSI_GREEN + "Found environment variable named hub_org with value as: " + hub_org + ANSI_NORMAL) } + // cleanWs() + checkout scm + commit_hash = sh(script: 'git rev-parse --short HEAD', returnStdout: true).trim() + build_tag = sh(script: "echo " + params.github_release_tag.split('/')[-1] + "_" + commit_hash + "_" + env.BUILD_NUMBER, returnStdout: true).trim() echo "build_tag: " + build_tag - } - stage('Build') { - env.NODE_ENV = "build" - print "Environment will be : ${env.NODE_ENV}" - sh('git submodule update --init') - sh('git submodule update --init --recursive --remote') - sh('chmod 777 build.sh') - sh("./build.sh ${build_tag} ${env.NODE_NAME} ${hub_org}") - } - stage('ArchiveArtifacts') { + + stage('Build') { + env.NODE_ENV = "build" + print "Environment will be : ${env.NODE_ENV}" + sh('git submodule update --init') + sh('git submodule update --init --recursive --remote') + sh('chmod 777 build.sh') + sh("./build.sh ${build_tag} ${env.NODE_NAME} ${hub_org}") + } + + stage('ArchiveArtifacts') { archiveArtifacts "metadata.json" currentBuild.description = "${build_tag}" + } } } } @@ -47,4 +41,4 @@ node('build-slave') { currentBuild.result = "FAILURE" throw err } -} \ No newline at end of file +} From e45d281ed8e765ddf361a615b40b2b87612361a5 Mon Sep 17 00:00:00 2001 From: kaliraja <34502260+Kaali09@users.noreply.github.com> Date: Wed, 16 Jun 2021 15:11:18 +0530 Subject: [PATCH 003/331] updated the readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 720578b4..38f4c026 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,2 @@ # ml-core-service -Centralised Service to support other Services. +Centralised Service to support other Services.. From 800b1cfe9e35614165f85701ee7789f2a78ab30c Mon Sep 17 00:00:00 2001 From: kaliraja <34502260+Kaali09@users.noreply.github.com> Date: Tue, 29 Jun 2021 16:58:03 +0530 Subject: [PATCH 004/331] updated readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 38f4c026..720578b4 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,2 @@ # ml-core-service -Centralised Service to support other Services.. +Centralised Service to support other Services. From fd513ec0978acd42380aeda015fb34c5019b0db2 Mon Sep 17 00:00:00 2001 From: aman-tunerlabs Date: Mon, 26 Jul 2021 12:58:31 +0530 Subject: [PATCH 005/331] Added Program sorting logic --- module/programs/helper.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/module/programs/helper.js b/module/programs/helper.js index 22875482..29aa5127 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -401,6 +401,10 @@ module.exports = class ProgramsHelper { }); } + let sortQuery = { + $sort: {"createdAt": -1} + } + let projection1 = {}; if( projection && projection.length > 0 ) { @@ -438,7 +442,7 @@ module.exports = class ProgramsHelper { } }; - programDocument.push({ $match : matchQuery }, { $project : projection1 }, facetQuery, projection2); + programDocument.push({ $match : matchQuery }, sortQuery,{ $project : projection1 }, facetQuery, projection2); let programDocuments = await database.models.programs.aggregate(programDocument); From 67158c325982a50f27347dcac0d7da313dd22132 Mon Sep 17 00:00:00 2001 From: aman-tunerlabs Date: Fri, 30 Jul 2021 11:31:10 +0530 Subject: [PATCH 006/331] Modified mongodb healthcheck --- healthCheck/mongodb.js | 1 + 1 file changed, 1 insertion(+) diff --git a/healthCheck/mongodb.js b/healthCheck/mongodb.js index 76fc2576..9b8e196c 100644 --- a/healthCheck/mongodb.js +++ b/healthCheck/mongodb.js @@ -17,6 +17,7 @@ function health_check() { return resolve(false) }); db.once("open", function() { + db.close(function(){}); return resolve(true); }); }) From 23731dbab5b2a7b95940c54a631c6db42c610377 Mon Sep 17 00:00:00 2001 From: aman-tunerlabs Date: Fri, 30 Jul 2021 12:18:41 +0530 Subject: [PATCH 007/331] Mongodb issue fixed --- healthCheck/mongodb.js | 1 + 1 file changed, 1 insertion(+) diff --git a/healthCheck/mongodb.js b/healthCheck/mongodb.js index 9b8e196c..6ac73976 100644 --- a/healthCheck/mongodb.js +++ b/healthCheck/mongodb.js @@ -17,6 +17,7 @@ function health_check() { return resolve(false) }); db.once("open", function() { + // Just for comment db.close(function(){}); return resolve(true); }); From 210ca268a278c0c68de91b6aacf1b042f02c2c79 Mon Sep 17 00:00:00 2001 From: aman-tunerlabs Date: Fri, 30 Jul 2021 12:38:10 +0530 Subject: [PATCH 008/331] Removed comment --- healthCheck/mongodb.js | 1 - 1 file changed, 1 deletion(-) diff --git a/healthCheck/mongodb.js b/healthCheck/mongodb.js index 6ac73976..9b8e196c 100644 --- a/healthCheck/mongodb.js +++ b/healthCheck/mongodb.js @@ -17,7 +17,6 @@ function health_check() { return resolve(false) }); db.once("open", function() { - // Just for comment db.close(function(){}); return resolve(true); }); From 5db2d6e2303e850a165d38db73eaf912db8e54d0 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Wed, 11 Aug 2021 09:19:18 +0530 Subject: [PATCH 009/331] expired survey story --- module/solutions/helper.js | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 39cbb6b2..cfae4ea4 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -651,7 +651,8 @@ module.exports = class SolutionsHelper { "projectTemplateId", "type", "language", - "creator" + "creator", + "endDate" ] ); @@ -1308,13 +1309,23 @@ module.exports = class SolutionsHelper { targetedSolution._id = ""; targetedSolution["creator"] = targetedSolution.creator ? targetedSolution.creator : ""; + let isValid = true; if ( solutionType === constants.common.SURVEY ) { targetedSolution.isCreator = false; - } - mergedData.push(targetedSolution); - delete targetedSolution.type; - delete targetedSolution.externalId; + let validDate = new Date(targetedSolution.endDate); + validDate.setDate(validDate.getDate() + 15 ); + + if(new Date() > new Date(validDate)){ + isValid = false; + } + + } + if(isValid){ + mergedData.push(targetedSolution); + delete targetedSolution.type; + delete targetedSolution.externalId; + } }); } } From 44609a0b41f67da7d1b48ed0e5e4aaeda9ceec0b Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Wed, 18 Aug 2021 13:32:00 +0530 Subject: [PATCH 010/331] expired survey --- generics/constants/common.js | 3 +- module/solutions/helper.js | 68 +++++++++++++++++++----------------- 2 files changed, 37 insertions(+), 34 deletions(-) diff --git a/generics/constants/common.js b/generics/constants/common.js index 89200113..06f5ab4c 100644 --- a/generics/constants/common.js +++ b/generics/constants/common.js @@ -56,5 +56,6 @@ module.exports = { "CREATED_BY_ME" : "createdByMe", "DEFAULT_PAGE_SIZE" : 100, "DEFAULT_PAGE_NO" : 1, - "DHITI" : "dhiti" + "DHITI" : "dhiti", + "DEFAULT_SURVEY_REMOVED_DAY" : 15 }; diff --git a/module/solutions/helper.js b/module/solutions/helper.js index cfae4ea4..0b00a3dc 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -463,10 +463,15 @@ module.exports = class SolutionsHelper { try { let matchQuery = { - "isDeleted" : false, - status : constants.common.ACTIVE + "isDeleted" : false }; + if( type == constants.common.SURVEY ) { + matchQuery["status"] = { $in: [ constants.common.ACTIVE, constants.common.IN_ACTIVE ] } + } else { + matchQuery.status = constants.common.ACTIVE ; + } + if( type !== "" ) { matchQuery["type"] = type; } @@ -683,7 +688,7 @@ module.exports = class SolutionsHelper { * @returns {JSON} - Auto targeted solutions query. */ - static queryBasedOnRoleAndLocation( data ) { + static queryBasedOnRoleAndLocation( data, type = "" ) { return new Promise(async (resolve, reject) => { try { @@ -719,10 +724,20 @@ module.exports = class SolutionsHelper { "scope.roles.code" : { $in : [constants.common.ALL_ROLES,data.role] }, "scope.entities" : { $in : entityIds }, "scope.entityType" : { $in : entityTypes }, - isReusable : false, - "isDeleted" : false, - status : constants.common.ACTIVE + "isReusable" : false, + "isDeleted" : false }; + + if( type === constants.common.SURVEY ) { + + filterQuery["status"] = { $in: [ constants.common.ACTIVE, constants.common.IN_ACTIVE ] } + let validDate = new Date(); + validDate.setDate(validDate.getDate() - constants.common.DEFAULT_SURVEY_REMOVED_DAY ); + filterQuery["endDate"] = { $gte : validDate } + + } else { + filterQuery.status = constants.common.ACTIVE; + } if( data.filter && Object.keys(data.filter).length > 0 ) { @@ -1302,34 +1317,21 @@ module.exports = class SolutionsHelper { if( targetedSolutions.data.data && targetedSolutions.data.data.length > 0 ) { totalCount += targetedSolutions.data.count; - if( mergedData.length !== pageSize ) { - - targetedSolutions.data.data.forEach(targetedSolution => { - targetedSolution.solutionId = targetedSolution._id; - targetedSolution._id = ""; - targetedSolution["creator"] = targetedSolution.creator ? targetedSolution.creator : ""; - - let isValid = true; - if ( solutionType === constants.common.SURVEY ) { - targetedSolution.isCreator = false; - - let validDate = new Date(targetedSolution.endDate); - validDate.setDate(validDate.getDate() + 15 ); - - if(new Date() > new Date(validDate)){ - isValid = false; - } - - } - if(isValid){ - mergedData.push(targetedSolution); - delete targetedSolution.type; - delete targetedSolution.externalId; - } - }); - } + targetedSolutions.data.data.forEach(targetedSolution => { + targetedSolution.solutionId = targetedSolution._id; + targetedSolution._id = ""; + targetedSolution["creator"] = targetedSolution.creator ? targetedSolution.creator : ""; + + if ( solutionType === constants.common.SURVEY ) { + targetedSolution.isCreator = false; + } + + mergedData.push(targetedSolution); + delete targetedSolution.type; + delete targetedSolution.externalId; + + }); } - } if( mergedData.length > 0 ) { From a0c2c432c6066679a76be540035b9a4a9dc48f6e Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Wed, 18 Aug 2021 16:05:46 +0530 Subject: [PATCH 011/331] licence story --- models/solutions.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/models/solutions.js b/models/solutions.js index 62d4768c..1eded623 100644 --- a/models/solutions.js +++ b/models/solutions.js @@ -86,6 +86,7 @@ module.exports = { default : "Domains", type : String }, - criteriaLevelReport : Boolean + criteriaLevelReport : Boolean, + license:Object } }; \ No newline at end of file From c7ba0b21f0b2aca5aa875ffba8e90411a7dc9bd2 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Wed, 18 Aug 2021 17:09:04 +0530 Subject: [PATCH 012/331] report path --- config/globals.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/config/globals.js b/config/globals.js index 458f3998..5718e5bd 100644 --- a/config/globals.js +++ b/config/globals.js @@ -42,6 +42,12 @@ module.exports = function () { } }); + let csvReportsPath = ROOT_PATH + "/public/reports" ; + + if( !fs.existsSync(csvReportsPath)) { + fs.mkdirSync(csvReportsPath); + } + //load base v1 controllers fs.readdirSync( ROOT_PATH + "/controllers/v1/").forEach(function (file) { checkWhetherFolderExistsOrNor(ROOT_PATH + "/controllers/v1/", file); From c97a784e9b6e5a4295da990764502f2d7e991f30 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Wed, 18 Aug 2021 18:38:37 +0530 Subject: [PATCH 013/331] public folder creation --- .env.sample | 1 + .gitignore | 3 +++ config/globals.js | 6 ------ envVariables.js | 4 ++++ 4 files changed, 8 insertions(+), 6 deletions(-) diff --git a/.env.sample b/.env.sample index 981fbc69..c8b43c3a 100644 --- a/.env.sample +++ b/.env.sample @@ -41,3 +41,4 @@ ELASTICSEARCH_HOST_URL = "http://127.0.0.1:9200" ELASTICSEARCH_ENTITIES_INDEX = "entities" // Elastic search index name for storing entities USER_SERVICE_URL = "http://user-service:3000" // Base url of the sunbird enviornment +CSV_REPORTS_PATH = "public/report" \ No newline at end of file diff --git a/.gitignore b/.gitignore index ede208e0..f9092570 100644 --- a/.gitignore +++ b/.gitignore @@ -60,6 +60,9 @@ typings/ # Ignore all credentials gcp,fcm config/credentials/* +# Ignore public directory +public/* + # next.js build output .next diff --git a/config/globals.js b/config/globals.js index 5718e5bd..458f3998 100644 --- a/config/globals.js +++ b/config/globals.js @@ -42,12 +42,6 @@ module.exports = function () { } }); - let csvReportsPath = ROOT_PATH + "/public/reports" ; - - if( !fs.existsSync(csvReportsPath)) { - fs.mkdirSync(csvReportsPath); - } - //load base v1 controllers fs.readdirSync( ROOT_PATH + "/controllers/v1/").forEach(function (file) { checkWhetherFolderExistsOrNor(ROOT_PATH + "/controllers/v1/", file); diff --git a/envVariables.js b/envVariables.js index 251f13d5..1ecd0c87 100644 --- a/envVariables.js +++ b/envVariables.js @@ -131,6 +131,10 @@ let enviromentVariables = { "USER_SERVICE_URL" : { "message" : "Sunbird environment base url", "optional" : false + }, + "CSV_REPORTS_PATH" : { + "message" : "CSV Report Path", + "optional" : false } } From 9df4e82a90069fe107030ca6a1418d7486ccd48e Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep <71248340+priyanka-TL@users.noreply.github.com> Date: Thu, 19 Aug 2021 11:00:32 +0530 Subject: [PATCH 014/331] Update .env.sample --- .env.sample | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.env.sample b/.env.sample index c8b43c3a..eb1b6420 100644 --- a/.env.sample +++ b/.env.sample @@ -41,4 +41,4 @@ ELASTICSEARCH_HOST_URL = "http://127.0.0.1:9200" ELASTICSEARCH_ENTITIES_INDEX = "entities" // Elastic search index name for storing entities USER_SERVICE_URL = "http://user-service:3000" // Base url of the sunbird enviornment -CSV_REPORTS_PATH = "public/report" \ No newline at end of file +CSV_REPORTS_PATH = "public/report" // Report path From 55fd3dde33717709295e746308224d303185c3c8 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Thu, 19 Aug 2021 14:35:04 +0530 Subject: [PATCH 015/331] fix --- envVariables.js | 2 +- generics/file-stream.js | 8 +- ...slate-language-to-csv_2019_12_13_15_18.csv | 259 ------------------ 3 files changed, 4 insertions(+), 265 deletions(-) delete mode 100644 public/pushNotifications/2019_12_13/translate-language-to-csv_2019_12_13_15_18.csv diff --git a/envVariables.js b/envVariables.js index 1ecd0c87..9be0ea2a 100644 --- a/envVariables.js +++ b/envVariables.js @@ -134,7 +134,7 @@ let enviromentVariables = { }, "CSV_REPORTS_PATH" : { "message" : "CSV Report Path", - "optional" : false + "optional" : true } } diff --git a/generics/file-stream.js b/generics/file-stream.js index 0f08dff9..19725f99 100644 --- a/generics/file-stream.js +++ b/generics/file-stream.js @@ -9,7 +9,7 @@ const json2Csv = require('json2csv').Transform; const stream = require("stream"); const fs = require("fs"); const moment = require("moment-timezone"); -const DEFAULT_REPORTS_PATH = gen.utils.checkIfEnvDataExistsOrNot("DEFAULT_REPORTS_PATH"); +const DEFAULT_REPORTS_PATH = ( process.env.CSV_REPORTS_PATH && process.env.CSV_REPORTS_PATH != "" )? process.env.CSV_REPORTS_PATH : "public/reports"; /** * FileStream @@ -21,10 +21,8 @@ let FileStream = class FileStream { constructor(fileName) { const currentDate = new Date(); const fileExtensionWithTime = moment(currentDate).tz("Asia/Kolkata").format("YYYY_MM_DD_HH_mm") + ".csv"; - if(!process.env.CSV_REPORTS_PATH){ - process.env.CSV_REPORTS_PATH = DEFAULT_REPORTS_PATH; - } - const filePath = `${process.env.CSV_REPORTS_PATH}/${moment(currentDate).tz("Asia/Kolkata").format("YYYY_MM_DD")}/`; + + const filePath = `${DEFAULT_REPORTS_PATH}/${moment(currentDate).tz("Asia/Kolkata").format("YYYY_MM_DD")}/`; this.ensureDirectoryPath(filePath); this.input = new stream.Readable({ objectMode: true }); this.fileName = filePath + fileName + "_" + fileExtensionWithTime; diff --git a/public/pushNotifications/2019_12_13/translate-language-to-csv_2019_12_13_15_18.csv b/public/pushNotifications/2019_12_13/translate-language-to-csv_2019_12_13_15_18.csv deleted file mode 100644 index dc08d33a..00000000 --- a/public/pushNotifications/2019_12_13/translate-language-to-csv_2019_12_13_15_18.csv +++ /dev/null @@ -1,259 +0,0 @@ -"key","en" -"ionLabel_date","Date" -"ionLabel_generalQuestions","General Questions" -"ionLabel_selectObservationType","Select a observation Type" -"ionLabel_selectSolution","Select a Solution" -"ionLabel_selectSchool","Select Schools" -"actionSheet_confirmLeave","Are you sure to leave." -"actionSheet_saveCurrentDataConfirmation","Old details will be lost ? Are you sure to overwrite the details" -"actionSheet_edit","Edit" -"actionSheet_delete","Delete" -"actionSheet_confirm","Confirm" -"actionSheet_completeobservation","Are you sure to mark this observation as complete?" -"actionSheet_deleteEntity","Are you sure to remove the entity form observation?" -"actionSheet_deleteSubmission","Are you sure to remove the submission ? " -"actionSheet_surveyAction","Survey Actions" -"actionSheet_restrictAction","Further you won't be able to do any kind of action." -"actionSheet_view","View" -"actionSheet_pleaseEnterPasscode","Please enter the passcode." -"actionSheet_submit","Submit" -"actionSheet_passcode","Passcode" -"actionSheet_login","Login" -"actionSheet_ecmNotApplicableMessage","Do you want mark ECM as not applicable / not allowed?" -"actionSheet_dataLooseConfirm","All your datas will be lost. Do you want to continue?" -"actionSheet_previousUserName","Please enter previous username." -"actionSheet_sessionExpired","Session has expired. Please login again to continue" -"actionSheet_slowInternet","You are connected to a slower data network. Image upload may take longer time. Do you want to continue?" -"actionSheet_name","Name" -"actionSheet_feedback","Feedback" -"actionSheet_send","Send" -"actionSheet_start","Start" -"actionSheet_warning","WARNING!" -"actionSheet_schoolSurveyEarse","All schools survey data will be erased. This action is irreversable.Do you want to continue?" -"actionSheet_appTermination","App termination" -"actionSheet_appTerminationMessage","Do you want to close the app?" -"actionSheet_closeApp","Close App" -"actionSheet_ecmNotApplicable","ECM Not Applicable" -"actionSheet_ecmNotAllowed","ECM Not Allowed" -"actionSheet_confirmDelete","Confirm Delete" -"actionSheet_addImage","Add Images" -"actionSheet_camera","Camera" -"actionSheet_upload","Upload" -"actionSheet_cancel","Cancel" -"actionSheet_confirmDeleteImage","Do you want to delete this image?" -"actionSheet_confirmDeleteInstance","Do you want to delete this instance?" -"actionSheet_entityDelete","Are you sure you want to delete the entity?" -"actionSheet_yes","Yes" -"actionSheet_ok","Ok" -"actionSheet_no","No" -"actionSheet_uploadImage","Upload Image" -"actionSheet_uploadFile","Upload File" -"actionSheet_publish","Publish" -"actionSheet_chooseAction","Choose a action" -"actionSheet_deleteObservation","Are you sure you want to delete the observation?" -"actionSheet_networkSlowAlert","You are connected to a slower data network. Image upload may take longer time. Do you want to continue?" -"actionSheet_reportWithScore","Report with score" -"actionSheet_reportWithoutScore","Report without score" -"buttons_observeAgain","Observe Again" -"buttons_view","View" -"buttons_and","and" -"buttons_addNew","Add New" -"buttons_viewReport","View Report" -"buttons_draft","Draft" -"buttons_publish","Publish" -"buttons_goToEntities","Go TO Entitites" -"buttons_active","Active" -"buttons_completed","Completed" -"buttons_profile","Profile" -"buttons_ratings","Rate" -"buttons_start","Start" -"buttons_survey","survey" -"buttons_delete","Delete" -"buttons_done","Done" -"buttons_previous","Previous" -"buttons_today","Today" -"buttons_about","About" -"buttons_save","Save" -"buttons_addSchools","Add Schools" -"buttons_next","Next" -"buttons_back","Back" -"buttons_upload","Upload" -"buttons_skip","Skip" -"buttons_submit","Submit" -"buttons_cancel","Cancel" -"buttons_addEntity","Add Entity" -"buttons_send","Send" -"buttons_yes","Yes" -"buttons_no","No" -"buttons_login","Login" -"buttons_flag","Flag" -"buttons_parentInfo","Parent Info" -"buttons_add","Add" -"buttons_parent","Parent" -"buttons_registry","Registry" -"buttons_capture","Capture" -"buttons_refresh","Refresh" -"buttons_feedback","Feedback" -"buttons_update","Update" -"buttons_Leader","School Leader" -"buttons_Teacher","Teacher" -"buttons_saveDraft","Draft" -"buttons_markAsComplete","Mark as completed" -"buttons_preview","Preview" -"buttons_viewReports","View Reports" -"buttons_viewObservationReport","View Observation report" -"buttons_viewEntityReport","View Entity Report" -"buttons_edit","Edit" -"buttons_observation","Observation" -"buttons_loadMore","Load More" -"buttons_selectAll","Select All" -"buttons_undo","Undo" -"tabs_home","Home" -"tabs_view","All" -"tabs_mySchool","My Schools" -"tabs_faqs","FAQs" -"tabs_about","About" -"tabs_questions","Questions" -"tabs_rate","Rate" -"tabs_individual","Individual" -"tabs_institutional","Institutions" -"tabs_observations","Observations" -"tabs_myObservation","My Observation" -"tabs_draftObservation","Draft Observation" -"tabs_addObservation","Add Observation" -"tabs_userRolePage","Roles" -"tabs_dashboard","Dashboard" -"tabs_inProgress","In progress" -"tabs_completed","Completed" -"tabs_setting","Settings" -"headings_zone","Zones" -"headings_state","State" -"headings_lastModified","Last Modefied at" -"headings_district","District" -"headings_entities","Entities" -"headings_userRolePage","Roles" -"headings_dashboard","Dashboard" -"headings_cluster","Cluster" -"headings_myActiveAssessment","My active assessments" -"headings_submissionListPage","Submission List" -"headings_addObservation","Add Observation" -"headings_solutionDetails","Solution Details" -"headings_home","Home" -"headings_observations","Observations" -"headings_myInstitutions","My Institutions" -"headings_mySchool","My Schools" -"headings_faqs","FAQs" -"headings_programList","Program List" -"headings_about","About" -"headings_school","School" -"headings_profile","Profile" -"headings_survey","Survey" -"headings_addSchools","Add Schools" -"headings_surveySections","Survey - Sections" -"headings_evidenceMethods","Evidence Methods" -"headings_sections","Sections" -"headings_questionnaire","Questionnaire" -"headings_feedback","Feedback" -"headings_logout","Logout" -"headings_startDate","Start Date" -"headings_endDate","End Date" -"headings_description","Description" -"headings_criteria","Criteria" -"headings_rate","Rate" -"headings_uplaod","Upload" -"headings_images","Images" -"headings_ratedCriterias","Rated Criterias" -"headings_flagCriteria","Flag Criteria" -"headings_questionMap","Question Map" -"headings_remarks","Remarks" -"headings_editSchoolProfile","Edit School Profile" -"headings_schoolProfile","School Profile" -"headings_surveyEcm","Survey - ECM" -"headings_parentContact","Parent Contacts" -"headings_parentRegistry","Parent Registry" -"headings_schoolLeaderRegistry","School Leader Registry" -"headings_teacherRegistry","Teacher Registry" -"headings_generalQuestions","General Questions" -"headings_individualAssessments","Individual Assessments" -"headings_observationDetails","Observation Details" -"headings_dashboardAssessmentListing","Assessments" -"headings_selectAssessment","Select an Assessment type" -"headings_observationList","Observations List" -"headings_hint","Hint" -"headings_submissionPreview","Submission Preview" -"headings_observationReports","Report" -"headings_observationUpdate","Observation Update" -"headings_notifications","Notifications" -"headings_settings","Settings" -"labels_welcome","Welcome" -"labels_assessments","Assessments" -"labels_goTo","Goto" -"labels_name","Name" -"labels_feedback","Feedback" -"labels_choose","Choose" -"labels_language","Language" -"labels_remarks","Remarks" -"labels_image","Image" -"labels_completed","Completed" -"labels_inprogress","In Progress" -"labels_submitted","Submitted" -"labels_notApplicable","NA" -"labels_readytoPublish","Ready to Publish" -"labels_files","Files" -"labels_languages","Languages" -"labels_totalScore","Total score" -"labels_scoreAchieved","Score achieved" -"labels_totalObservations","Total Observations" -"languages_english","English" -"languages_hindi","हिंदी" -"languages_telugu","తెలుగు" -"languages_malayalam","മലയാളം" -"languages_tamil","தமிழ்" -"languages_kannada","ಕನ್ನಡ" -"languages_gujarati","ગુજરાતી" -"message_noReportsFound","No reports found" -"message_noSubmission","No Submissions" -"message_startSearchSchool","search school" -"message_noSchoolFound","No Schools Found" -"message_searchEntities","Search for entities" -"message_startSearchSolution","Search for solutions" -"message_dontCloseApp","Please don't close the app or go back." -"message_of","of" -"message_noProgram","No Program" -"message_program","Program" -"message_images","Images" -"message_startSearchEntity","Start typing entity name" -"message_uploading","Uploading" -"message_completeObservation","Are you sure you want to mark this observation as complete?" -"message_restrictAction","Further you won't be able to do any kind of action." -"message_noQuestionAvailable"," No questions available" -"message_noDraft","No Drafts" -"message_noEntity","No Entity" -"message_no","No" -"message_noSolutionFound","No Solutions" -"message_noProgramsFound","No Programs found." -"message_deleteObservation","Are you sure you want to delete the observation?" -"message_confirmDeleteObservation","You will not see this observation anymore. Do you wish to delete?" -"message_viewAll","View all" -"message_noUnreadNotifications","You have no new Notifications!" -"message_noObservationfound","No observation found" -"toastMessage_selectSolution","Select a Solution" -"toastMessage_selectObservationType","Select a observation Type" -"toastMessage_networkDisconnected","NetWork Disconnected" -"toastMessage_networkConnected","Network Connected" -"toastMessage_ok","OK" -"toastMessage_allValueAreMandatory","Fill Mandatory Field" -"toastMessage_enableInternet","Please enable your internet connection to continue." -"toastMessage_connectToInternet","Please connect to internet " -"toastMessage_networkConnectionForAction","You need network connection for this action." -"toastMessage_noPermissionToPage","You dont have permission to view this page." -"toastMessage_someThingWentWrong","Something went Wrong." -"toastMessage_someThingWentWrongTryLater","Something went Wrong , Please Try after sometime." -"toastMessage_enableToGetGoogleUrls","Unable to get google urls" -"toastMessage_submissionCompleted","Submission completed successfully" -"toastMessage_errorGettingLoaction","Error in getting location" -"toastMessage_fillAllFields","Please fill all the fields" -"toastMessage_loginAgain","Please login again." -"toastMessage_userNameMisMatch","Username didnot match. Please login again." -"toastMessage_loactionForAction","Location should be turned on for this action." -"toastMessage_questionResponseNotRequiredForCompleteAssessment","This questions response is not required to complete the assessment." \ No newline at end of file From 215a66fc10b8faca22f366c6fe226ced42387cf2 Mon Sep 17 00:00:00 2001 From: aman-tunerlabs Date: Thu, 19 Aug 2021 19:14:22 +0530 Subject: [PATCH 016/331] Added v1 in all APIs --- envVariables.js | 3 ++- generics/constants/endpoints.js | 20 ++++++++++---------- generics/file-stream.js | 2 +- generics/helpers/http-request.js | 1 - 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/envVariables.js b/envVariables.js index 9be0ea2a..0cf2dd4b 100644 --- a/envVariables.js +++ b/envVariables.js @@ -134,7 +134,8 @@ let enviromentVariables = { }, "CSV_REPORTS_PATH" : { "message" : "CSV Report Path", - "optional" : true + "optional" : true, + "default": "public/reports" } } diff --git a/generics/constants/endpoints.js b/generics/constants/endpoints.js index 465da2d5..94054ba3 100644 --- a/generics/constants/endpoints.js +++ b/generics/constants/endpoints.js @@ -6,24 +6,24 @@ */ module.exports = { - CREATE_USER_PROFILE : "/userProfile/create", - UPDATE_USER_PROFILE : "/userProfile/update", - VERIFY_USER_PROFILE : "/userProfile/verify", - PLATFORM_USER_PROFILE : "/platformUserRoles/getProfile", - USER_PROFILE_DETAILS : "/userProfile/details", + CREATE_USER_PROFILE : "/v1/userProfile/create", + UPDATE_USER_PROFILE : "/v1/userProfile/update", + VERIFY_USER_PROFILE : "/v1/userProfile/verify", + PLATFORM_USER_PROFILE : "/v1/platformUserRoles/getProfile", + USER_PROFILE_DETAILS : "/v1/userProfile/details", SUNBIRD_GENERATE_DIALCODE : "/dialcode/v1/generate", SUNBIRD_PUBLISH_DIALCODE : "/dialcode/v1/publish", SUNBIRD_DIALCODE_STATUS : "/dialcode/v1/read", SUNBIRD_CONTENT_LINK : "/dialcode/v1/content/link", - SUNBIRD_PUBLISH_CONTENT : "/content/v1/publish", + SUNBIRD_PUBLISH_CONTENT : "/v1/content/v1/publish", USER_READ : "/api/user/v1/read", SUNBIRD_INDEX_SYNC : "/data/v1/index/sync", SUNBIRD_CREATE_CONTENT : "/content/v1/create", SUNBIRD_UPLOAD_CONTENT : "/content/v1/upload", SUNBIRD_ORGANISATION_LISTS : "/organisations/list", SUNBIRD_USER_SEARCH :"/users/search", - GET_USER_ASSIGNED_OBSERVATION : "/observations/userAssigned", - GET_USER_ASSIGNED_SURVEY : "/surveys/userAssigned", - GET_USER_ASSIGNED_PROJECT : "/userProjects/userAssigned", - IMPORTED_PROJECT : "/userProjects/importedProjects" + GET_USER_ASSIGNED_OBSERVATION : "/v1/observations/userAssigned", + GET_USER_ASSIGNED_SURVEY : "/v1/surveys/userAssigned", + GET_USER_ASSIGNED_PROJECT : "/v1/userProjects/userAssigned", + IMPORTED_PROJECT : "/v1/userProjects/importedProjects" } \ No newline at end of file diff --git a/generics/file-stream.js b/generics/file-stream.js index 19725f99..80fab286 100644 --- a/generics/file-stream.js +++ b/generics/file-stream.js @@ -9,7 +9,7 @@ const json2Csv = require('json2csv').Transform; const stream = require("stream"); const fs = require("fs"); const moment = require("moment-timezone"); -const DEFAULT_REPORTS_PATH = ( process.env.CSV_REPORTS_PATH && process.env.CSV_REPORTS_PATH != "" )? process.env.CSV_REPORTS_PATH : "public/reports"; +const DEFAULT_REPORTS_PATH = process.env.CSV_REPORTS_PATH; /** * FileStream diff --git a/generics/helpers/http-request.js b/generics/helpers/http-request.js index 25fd3836..28d95e97 100644 --- a/generics/helpers/http-request.js +++ b/generics/helpers/http-request.js @@ -20,7 +20,6 @@ var convert = require('xml-js'); * @class */ var Request = class Request { - constructor() {} /** * From 28d2c8f812783c8dbbf3d088ff1728d1ee6f8fcd Mon Sep 17 00:00:00 2001 From: aman-tunerlabs Date: Thu, 2 Sep 2021 13:40:29 +0530 Subject: [PATCH 017/331] Removed organisations and root organisations check --- controllers/v1/programs.js | 8 ---- controllers/v1/solutions.js | 6 --- controllers/v1/users.js | 70 -------------------------------- models/programs.js | 5 --- models/solutions.js | 5 --- module/programs/helper.js | 2 - module/programs/validator/v1.js | 2 - module/solutions/validator/v1.js | 2 - module/users/helper.js | 53 +----------------------- 9 files changed, 1 insertion(+), 152 deletions(-) diff --git a/controllers/v1/programs.js b/controllers/v1/programs.js index 0fa8e7b2..c45418be 100644 --- a/controllers/v1/programs.js +++ b/controllers/v1/programs.js @@ -100,10 +100,6 @@ module.exports = class Programs extends Abstract { ], "keywords" : [], "concepts" : [], - "createdFor" : [ - "0126427034137395203", - "0124487522476933120" - ], "userId":"a082787f-8f8f-42f2-a706-35457ca6f1fd", "imageCompression" : { "quality" : 10 @@ -184,10 +180,6 @@ module.exports = class Programs extends Abstract { ], "keywords" : [], "concepts" : [], - "createdFor" : [ - "0126427034137395203", - "0124487522476933120" - ], "userId":"a082787f-8f8f-42f2-a706-35457ca6f1fd", "imageCompression" : { "quality" : 10 diff --git a/controllers/v1/solutions.js b/controllers/v1/solutions.js index ff134626..da8119f9 100644 --- a/controllers/v1/solutions.js +++ b/controllers/v1/solutions.js @@ -23,7 +23,6 @@ module.exports = class Solutions extends Abstract { * "language" : [], * "keywords" : [], * "concepts" : [], - * "createdFor" : ["01305447637218918413"], "themes" : [], "flattenedThemes" : [], "entities" : [ @@ -34,9 +33,6 @@ module.exports = class Solutions extends Abstract { "enableQuestionReadOut" : false, "allowMultipleAssessemts" : false, "isDeleted" : false, - "rootOrganisations" : [ - "01305447637218918413" - ], "programExternalId" : "AMAN_TEST_123-1607937244986", "entityType" : "school", "type" : "improvementProject", @@ -571,7 +567,6 @@ module.exports = class Solutions extends Abstract { " Courses " ], "concepts": [], - "createdFor": [], "themes": [ { "type": "theme", @@ -600,7 +595,6 @@ module.exports = class Solutions extends Abstract { "isAPrivateProgram": false, "allowMultipleAssessemts": false, "isDeleted": false, - "rootOrganisations": [], "deleted": false, "externalId": "99199aec-66b8-11eb-b81d-a08cfd79f8b7-OBSERVATION-TEMPLATE", "name": "Enrollment challenges in DIKSHA Courses", diff --git a/controllers/v1/users.js b/controllers/v1/users.js index 0295b129..c204816e 100644 --- a/controllers/v1/users.js +++ b/controllers/v1/users.js @@ -233,10 +233,8 @@ module.exports = class Users extends Abstract { "keywords 2" ], "concepts": [], - "createdFor": [], "components": [], "isAPrivateProgram": true, - "rootOrganisations": [], "_id": "5f44b08cdbe917732246149f", "deleted": false, "externalId": "Test project program-1598337164794", @@ -255,7 +253,6 @@ module.exports = class Users extends Abstract { "language": [], "keywords": [], "concepts": [], - "createdFor": [], "themes": [], "flattenedThemes": [], "entities": [], @@ -266,7 +263,6 @@ module.exports = class Users extends Abstract { "isAPrivateProgram": false, "allowMultipleAssessemts": false, "isDeleted": false, - "rootOrganisations": [], "_id": "5f44b08cdbe91773224614a0", "deleted": false, "name": "Test project solution", @@ -396,72 +392,6 @@ module.exports = class Users extends Abstract { }) } - /** - * @api {get} /kendra/api/v1/users/getUserOrganisationsAndRootOrganisations - * Get organisation and root organisation - * @apiVersion 1.0.0 - * @apiGroup Users - * @apiHeader {String} X-authenticated-user-token Authenticity token - * @apiSampleRequest /kendra/api/v1/users/getUserOrganisationsAndRootOrganisations - * @apiUse successBody - * @apiUse errorBody - * @apiParamExample {json} Response: - * { - "message": "User organisations fetched successfully", - "status": 200, - "result": { - "createdFor": [ - "01305447637218918413" - ], - "rootOrganisations": [ - "01305447637218918413" - ] - } - } - */ - - /** - * Organisations and root organisations. - * @method - * @name getUserOrganisationsAndRootOrganisations - * @param {Request} req request body. - * @returns {JSON} Organisations and root organisations of user. - */ - - getUserOrganisationsAndRootOrganisations(req) { - - return new Promise(async (resolve, reject) => { - - try { - - const userOrganisations = - await usersHelper.getUserOrganisationsAndRootOrganisations( - (req.params._id && req.params._id != "") ? - req.params._id : - req.userDetails.id, - req.userDetails.userToken - ); - - resolve(userOrganisations); - - } catch (error) { - - return reject({ - status: - error.status || - httpStatusCode["internal_server_error"].status, - - message: - error.message || - httpStatusCode["internal_server_error"].message - }) - - } - - - }) - } - /** * @api {post} /kendra/api/v1/users/solutions/:programId?page=:page&limit=:limit&search=:searchText * @apiVersion 1.0.0 diff --git a/models/programs.js b/models/programs.js index 32a08728..4bc11f16 100644 --- a/models/programs.js +++ b/models/programs.js @@ -12,7 +12,6 @@ module.exports = { language: [String], keywords: [String], concepts: ["json"], - createdFor: [String], imageCompression: {}, components: ["json"], components: ["json"], @@ -20,10 +19,6 @@ module.exports = { default : false, type : Boolean }, - rootOrganisations : { - type : [String], - default : [] - }, scope : { entityType : String, entityTypeId : "ObjectId", diff --git a/models/solutions.js b/models/solutions.js index 1eded623..4d6dcbbc 100644 --- a/models/solutions.js +++ b/models/solutions.js @@ -11,7 +11,6 @@ module.exports = { language: Array, keywords: Array, concepts: Array, - createdFor: Array, scoringSystem: String, levelToScoreMapping: Object, themes: Array, @@ -61,10 +60,6 @@ module.exports = { default : false, type : Boolean }, - rootOrganisations : { - type : [String], - default : [] - }, project : Object, referenceFrom : String, scope : { diff --git a/module/programs/helper.js b/module/programs/helper.js index 29aa5127..0559708d 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -98,8 +98,6 @@ module.exports = class ProgramsHelper { "keywords 2" ], "concepts" : [], - "createdFor" : data.createdFor, - "rootOrganisations" : data.rootOrganisations, "imageCompression" : { "quality" : 10 }, diff --git a/module/programs/validator/v1.js b/module/programs/validator/v1.js index ef7adce0..4cb484c3 100644 --- a/module/programs/validator/v1.js +++ b/module/programs/validator/v1.js @@ -10,8 +10,6 @@ module.exports = (req) => { let programsValidator = { create : function () { - req.checkBody('createdFor').exists().withMessage("required organisation created for id"); - req.checkBody('rootOrganisations').exists().withMessage("required root organisations id"); req.checkBody('externalId').exists().withMessage("required program externalId"); req.checkBody('name').exists().withMessage("required program name"); }, diff --git a/module/solutions/validator/v1.js b/module/solutions/validator/v1.js index 6b3e61d6..e7b98abc 100644 --- a/module/solutions/validator/v1.js +++ b/module/solutions/validator/v1.js @@ -10,8 +10,6 @@ module.exports = (req) => { let solutionsValidator = { create : function () { - req.checkBody('createdFor').exists().withMessage("required organisation created for id"); - req.checkBody('rootOrganisations').exists().withMessage("required root organisations id"); req.checkBody('programExternalId').exists().withMessage("required program externalId"); req.checkBody('entityType').exists().withMessage("required entity type"); req.checkBody('externalId').exists().withMessage("required solution externalId"); diff --git a/module/users/helper.js b/module/users/helper.js index e863e732..71194651 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -140,16 +140,13 @@ module.exports = class UsersHelper { * @returns {Array} - Created user program and solution. */ - static createProgramAndSolution(userId, data, userToken) { + static createProgramAndSolution(userId, data) { return new Promise(async (resolve, reject) => { try { let userPrivateProgram = {}; let dateFormat = gen.utils.epochTime(); - const organisationAndRootOrganisations = - await this.getUserOrganisationsAndRootOrganisations(userId, userToken); - if (data.programId && data.programId !== "") { userPrivateProgram = await programsHelper.programDocuments( @@ -186,9 +183,6 @@ module.exports = class UsersHelper { userId: userId } - programData.createdFor = organisationAndRootOrganisations.result.createdFor; - programData.rootOrganisations = organisationAndRootOrganisations.result.rootOrganisations; - userPrivateProgram = await programsHelper.create( programData @@ -278,8 +272,6 @@ module.exports = class UsersHelper { solutionDataToBeUpdated["description"] = userPrivateProgram.programDescription; } - solutionDataToBeUpdated.createdFor = organisationAndRootOrganisations.result.createdFor; - solutionDataToBeUpdated.rootOrganisations = organisationAndRootOrganisations.result.rootOrganisations; solutionDataToBeUpdated.updatedBy = userId; solution = await solutionsHelper.create(solutionDataToBeUpdated); @@ -310,49 +302,6 @@ module.exports = class UsersHelper { }) } - /** - * Get user organisations and root organisations. - * @method - * @name getUserOrganisationsAndRootOrganisations - * @param {string} userId - logged in user Id. - * @param {object} userToken - Logged in user token. - * @returns {Array} - Get user organisations and root organisations. - */ - - static getUserOrganisationsAndRootOrganisations(userId, userToken) { - return new Promise(async (resolve, reject) => { - try { - - const userProfileData = - await userService.profile(userToken,userId); - - if (!userProfileData.status) { - return resolve({message: userProfileData.message}); - } - - const createdFor = - userProfileData.organisations.map( - organisation => { - return organisation.organisationId - } - ); - - const rootOrganisations = [userProfileData.rootOrgId]; - - return resolve({ - message: constants.apiResponses.USER_ORGANISATIONS_FETCHED, - result: { - createdFor: createdFor, - rootOrganisations: rootOrganisations - } - }); - - } catch (error) { - return reject(error); - } - }) - } - /** * Entities mapping form data. * @method From 670afa62194fb36b3a3315de901b70082997b897 Mon Sep 17 00:00:00 2001 From: aman-tunerlabs Date: Mon, 6 Sep 2021 17:48:32 +0530 Subject: [PATCH 018/331] Hardcoded improvement service url --- generics/services/improvement-project.js | 1 + 1 file changed, 1 insertion(+) diff --git a/generics/services/improvement-project.js b/generics/services/improvement-project.js index c34e5199..ee58eca4 100644 --- a/generics/services/improvement-project.js +++ b/generics/services/improvement-project.js @@ -7,6 +7,7 @@ //dependencies const request = require('request'); +process.env.ML_PROJECT_SERVICE_URL = "http://ml-projects-service:3000" /** * List of user assigned projects. From 460332a44c3266620da490349ccfc9ad9802371d Mon Sep 17 00:00:00 2001 From: aman-tunerlabs Date: Mon, 6 Sep 2021 17:59:53 +0530 Subject: [PATCH 019/331] Modified improvement project default value --- generics/services/improvement-project.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/generics/services/improvement-project.js b/generics/services/improvement-project.js index ee58eca4..eefec691 100644 --- a/generics/services/improvement-project.js +++ b/generics/services/improvement-project.js @@ -7,7 +7,7 @@ //dependencies const request = require('request'); -process.env.ML_PROJECT_SERVICE_URL = "http://ml-projects-service:3000" +process.env.ML_PROJECT_SERVICE_URL = "http://ml-project-service:3000" /** * List of user assigned projects. From 56679421dfad1d320fb8155e6b5c63a00ecbf029 Mon Sep 17 00:00:00 2001 From: aman-tunerlabs Date: Tue, 7 Sep 2021 16:52:48 +0530 Subject: [PATCH 020/331] Added console.log --- generics/services/improvement-project.js | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/generics/services/improvement-project.js b/generics/services/improvement-project.js index eefec691..f957d730 100644 --- a/generics/services/improvement-project.js +++ b/generics/services/improvement-project.js @@ -7,7 +7,7 @@ //dependencies const request = require('request'); -process.env.ML_PROJECT_SERVICE_URL = "http://ml-project-service:3000" +process.env.ML_PROJECT_SERVICE_URL = "http://ml-projects-service:3000" /** * List of user assigned projects. @@ -29,6 +29,8 @@ var assignedProjects = function ( token,search = "",filter = "" ) { if( filter !== "" ) { url = url + "&filter=" + filter; } + + console.log("--- url is ----",url); return new Promise(async (resolve, reject) => { try { @@ -41,9 +43,13 @@ var assignedProjects = function ( token,search = "",filter = "" ) { if (err) { result.success = false; + console.log("--- error is ----",err); } else { let response = JSON.parse(data.body); + + console.log("--- response is ----",response); + if( response.status === httpStatusCode['ok'].status ) { result["data"] = response.result; From c471ef4d4ab4a68eb2e13bd62f1c4189ffa8ea88 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Wed, 8 Sep 2021 09:45:24 +0530 Subject: [PATCH 021/331] cleanup till entities 50% --- controllers/v1/app-releases.js | 292 ---------------------------- controllers/v1/apps.js | 139 ------------- controllers/v1/entities.js | 132 ------------- module/app-releases/helper.js | 275 -------------------------- module/app-releases/validator/v1.js | 28 --- module/apps/helper.js | 173 ---------------- module/apps/validator/v1.js | 12 -- module/entities/helper.js | 110 ----------- module/entities/validator/v1.js | 6 - 9 files changed, 1167 deletions(-) diff --git a/controllers/v1/app-releases.js b/controllers/v1/app-releases.js index 32781fee..2cf26b33 100644 --- a/controllers/v1/app-releases.js +++ b/controllers/v1/app-releases.js @@ -23,298 +23,6 @@ static get name() { return "appReleases"; } - - /** - * @api {post} /kendra-service/api/v1/app-releases/create - * Add latest app release - * @apiVersion 1.0.0 - * @apiGroup appVersion - * @apiSampleRequest /kendra-service/api/v1/app-releases/create - * @apiParamExample {json} Request: - * { - * "appName":"samiksha", - * "version" : "2.2.8", - * "releaseType" : "minor", - * "os" : "android", - * "text" : "A new version of app is available !!!", - * "title" : "New update available!!", - * "status" : "active", - * "appType" : "assessment", - * "releaseNotes":"new feature like image capture is available" - * } - * @apiParamExample {json} Response: - * { - * "message": "App version created", - * "status": 200, - * "result": { - * "appName": "samiksha", - * "version": "2.2.8", - * "releaseType": "minor", - * "os": "android", - * "text": "A new version of app is available !!!", - * "title": "New update available!!", - * "status": "active", - * "appType": "assessment", - * "createdBy" : "", - * "updatedBy" : "", - * "releaseNotes": "new feature like image capture is available", - * "message": "App version updated" - * } - * } - * @apiUse successBody - * @apiUse errorBody - */ - - /** - * Create app version data. - * @method - * @name create - * @param {Request} req request body. - * @returns {JSON} created app version data. - */ - - async create(req) { - return new Promise(async (resolve, reject) => { - try { - - let createAppRelease = await versionHelper.create( - req.body, - req.userDetails.userId - ); - - return resolve({ - message : constants.apiResponses.APP_VERSION_CREATED, - result : createAppRelease - }); - - } catch (error) { - reject({ - status: - error.status || - httpStatusCode["internal_server_error"].status, - - message: - error.message || - httpStatusCode["internal_server_error"].message - }) - } - }) - } - - /** - * @api {post} /kendra-service/api/v1/app-releases/update - * Update app release data - * @apiVersion 1.0.0 - * @apiGroup appVersion - * @apiSampleRequest /kendra-service/api/v1/app-releases/update/5e7cb395fb8ce4182f5ffcac - * @apiParamExample {json} Request: - * { - * "appName":"samiksha", - * "version" : "2.2.8", - * "releaseType" : "minor", - * "os" : "android", - * "text" : "A new version of app is available !!!", - * "title" : "New update available!!", - * "status" : "active", - * "appType" : "assessment", - * "releaseNotes":"new feature like image capture is available" - * } - * @apiParamExample {json} Response: - * { - * "message": "App version updated", - * "status": 200, - * "result": { - * "appName": "samiksha", - * "version": "2.2.9", - * "releaseType": "minor", - * "os": "android", - * "text": "A new version of app is available !!!", - * "title": "New update available!!", - * "status": "active", - * "appType": "assessment", - * "releaseNotes": "new feature like image capture is available", - * "updatedBy" : "", - * "createdBy" : "" - * } - * } - * @apiUse successBody - * @apiUse errorBody - */ - - /** - * Update app version data. - * @method - * @name update - * @param {Request} req request body. - * @returns {JSON} updated app version data. - */ - - async update(req) { - return new Promise(async (resolve, reject) => { - try { - - req.body.updatedBy = req.userDetails.userId; - req.body.updatedAt = new Date(); - - let updateVersionData = await versionHelper.update( - req.params._id, - req.body - ); - - return resolve(updateVersionData); - - } catch (error) { - reject({ - status: - error.status || - httpStatusCode["internal_server_error"].status, - - message: - error.message || - httpStatusCode["internal_server_error"].message - }) - } - }) - } - - /** - * @api {get} /kendra-service/api/v1/app-releases/list?appName=:appName&os=:os&releaseType=:releaseType&status=:status - * List of app releases - * @apiVersion 1.0.0 - * @apiGroup appVersion - * @apiSampleRequest /kendra-service/api/v1/app-releases/list?appName=samiksha&os=android&releaseType=minor&status=active - * @apiParamExample {json} Response: - * { - * "message": "Lists of app version data", - * "status": 200, - * "result": [ - * { - * "_id": "5e664e2437cef27c691183d7", - * "appName": "samiksha", - * "os": "android", - * "version": "2.2.6", - * "__v": 0, - * "appType": "assessment", - * "createdAt": "2020-03-09T14:09:40.940Z", - * "createdBy" : "", - * "releaseNotes": "new feature like image capture is available", - * "releaseType": "minor", - * "status": "inactive", - * "text": "A new version of this app is available.", - * "title": "New update available !", - * "updatedAt": "2020-03-26T11:04:51.976Z", - * "updatedBy" : "" - * } - * ] - * } - * @apiUse successBody - * @apiUse errorBody - */ - - /** - * Lists of app version data. - * @method - * @name list - * @param {Request} req request data. - * @returns {JSON} App version data lists. - */ - - async list(req) { - return new Promise(async (resolve, reject) => { - try { - - let listOfVersionData = await versionHelper.versionDataList( - req.query - ); - - return resolve(listOfVersionData); - - } catch (error) { - reject({ - status: - error.status || - httpStatusCode["internal_server_error"].status, - - message: - error.message || - httpStatusCode["internal_server_error"].message - }) - } - }) - } - - /** - * @api {post} /kendra-service/api/v1/app-releases/upload - * Upload latest app release - * @apiVersion 1.0.0 - * @apiGroup appVersion - * @apiSampleRequest /kendra-service/api/v1/app-releases/upload - * @apiParam {File} versionUpdate Mandatory versionUpdate file of type CSV. - * @apiUse successBody - * @apiUse errorBody - */ - - /** - * Upload latest app version. - * @method - * @name upload - * @param {Request} req request body. - * @returns {JSON} Response consists of message and status code. - */ - - async upload(req) { - return new Promise(async (resolve, reject) => { - - try { - - if (!req.files || !req.files.versionUpdate) { - return resolve( - { - status : httpStatusCode["bad_request"].status, - message : constants.apiResponses.VERSION_UPDATE_FILE_TYPE - } - ) - } - - let versionData = - await csv().fromString(req.files.versionUpdate.data.toString()); - - const fileName = `version-update`; - let fileStream = new csvFileStream(fileName); - let input = fileStream.initStream(); - - (async function () { - await fileStream.getProcessorPromise(); - return resolve({ - isResponseAStream: true, - fileNameWithPath: fileStream.fileNameWithPath() - }); - })(); - - let createdByUser = req.userDetails.userId; - - for( let version = 0; version < versionData.length; version ++) { - - let result = await versionHelper.upload( - versionData[version], - createdByUser - ); - input.push(result); - } - input.push(null); - } catch (error) { - reject({ - status: - error.status || - httpStatusCode["internal_server_error"].status, - - message: - error.message || - httpStatusCode["internal_server_error"].message - }) - } - }) - } }; \ No newline at end of file diff --git a/controllers/v1/apps.js b/controllers/v1/apps.js index 1c49f982..ff7e4f23 100644 --- a/controllers/v1/apps.js +++ b/controllers/v1/apps.js @@ -78,145 +78,6 @@ } }) } - - - /** - * @api {post} /kendra/api/v1/apps/create - * Create an app - * @apiVersion 1.0.0 - * @apiGroup Apps - * @apiSampleRequest /kendra/api/v1/apps/details/create - * @apiParamExample {fromData} Request: - * { - "name": "samiksha", - "displayName": "Samiksha", - "description": "Get the app to discover more", - "playstoreLink": "https://play.google.com/store/apps/details?id=org.shikshalokam.samiksha", - "appStoreLink": "https://apps.apple.com/in/app/shikshalokam-samiksha/id1442066610", - "status": "active" - * } - * @apiParamExample {json} Response: - * { - "message": "App created successfully.", - "status": 200 - * } - * @apiUse successBody - * @apiUse errorBody - */ - - /** - * Create app - * @method - * @name create - * @param {files} req.files.logo - app logo - * @param {String} req.body.name - name of the app - * @param {String} req.body.displayName - displayName of the app - * @param {String} req.body.description - description of the app - * @param {String} req.body.playstoreLink - playstoreLink of the app - * @param {String} req.body.appStoreLink - appStoreLink of the app - * @param {String} req.body.status - status - * @returns {String} - message . - */ - - async create(req) { - return new Promise(async (resolve, reject) => { - try { - - let createDetails = await appsHelper.create( - req.files.logo, - req.body - ); - - return resolve({ - message : createDetails.message, - result : createDetails.data - }); - - } catch (error) { - reject({ - status: - error.status || - httpStatusCode["internal_server_error"].status, - - message: - error.message || - httpStatusCode["internal_server_error"].message - }) - } - }) - } - - /** - * @api {post} /kendra/api/v1/apps/update/{{name}} - * Update app details - * @apiVersion 1.0.0 - * @apiGroup Apps - * @apiSampleRequest /kendra/api/v1/apps/details/update/samiksha - * @apiParamExample {fromData} Request: - * { - "displayName": "Samiksha", - "description": "Get the app to discover more", - "playstoreLink": "https://play.google.com/store/apps/details?id=org.shikshalokam.samiksha", - "appStoreLink": "https://apps.apple.com/in/app/shikshalokam-samiksha/id1442066610", - "status": "active" - * } - * @apiParamExample {json} Response: - * { - "message": "App details updated successfully.", - "status": 200 - * } - * @apiUse successBody - * @apiUse errorBody - */ - - /** - * Update app details - * @method - * @name update - * @param {String} req.params._id - name of the app - * @param {files} req.files.logo - app logo - * @param {String} req.body.displayName - displayName of the app - * @param {String} req.body.description - description of the app - * @param {String} req.body.playstoreLink - playstoreLink of the app - * @param {String} req.body.appStoreLink - appStoreLink of the app - * @param {String} req.body.status - status - * @returns {String} - message . - */ - - async update(req) { - return new Promise(async (resolve, reject) => { - try { - - let file = ""; - - if(req.files && req.files.logo) { - file = req.files.logo; - } - - let updateDetails = await appsHelper.update( - req.params._id, - file, - req.body - ); - - return resolve({ - message: updateDetails.message, - result: updateDetails.data - }); - - } catch (error) { - reject({ - status: - error.status || - httpStatusCode["internal_server_error"].status, - - message: - error.message || - httpStatusCode["internal_server_error"].message - }) - } - }) - } }; \ No newline at end of file diff --git a/controllers/v1/entities.js b/controllers/v1/entities.js index 73068539..3cfab8f1 100644 --- a/controllers/v1/entities.js +++ b/controllers/v1/entities.js @@ -197,68 +197,6 @@ module.exports = class Entities extends Abstract { }) } - /** - * @api {get} /kendra/api/v1/entities/details/:entityId - * Get entities details information - * @apiVersion 1.0.0 - * @apiGroup Entities - * @apiHeader {String} X-authenticated-user-token Authenticity token - * @apiSampleRequest /kendra/api/v1/entities/details/5db173598a8e070bedca6ba1 - * @apiUse successBody - * @apiUse errorBody - * @apiParamExample {json} Response: - * { - * "message": "Entity information fetched successfully", - * "status": 200, - * "result": { - "_id": "5db173598a8e070bedca6ba1", - "entityTypeId": "5d7a290e6371783ceb11064c", - "entityType": "state", - "metaInformation": { - "externalId": "DL", - "name": "Delhi", - "region": "NORTH", - "capital": "NEW DELHI" - }, - "updatedBy": "2be2fd94-f25e-4402-8e36-20907b45c650", - "createdBy": "2be2fd94-f25e-4402-8e36-20907b45c650", - "updatedAt": "2019-10-24T10:16:44.833Z", - "createdAt": "2019-10-24T09:48:09.005Z" - } - } - - /** - * Entity details. - * @method - * @name details - * @param {Object} req - requested entity information. - * @param {String} req.params._id - entity id - * @returns {JSON} - Entity details information. - */ - - details(req) { - - return new Promise(async (resolve, reject) => { - - try { - - let result = await entitiesHelper.details( - req.params._id - ); - - return resolve(result); - - } catch (error) { - - return reject({ - status: error.status || httpStatusCode.internal_server_error.status, - message: error.message || httpStatusCode.internal_server_error.message, - errorObject: error - }) - } - }) - } - /** * @api {get} /kendra/api/v1/entities/listByIds * List entities. @@ -317,76 +255,6 @@ module.exports = class Entities extends Abstract { }) } - /** - * @api {get} /kendra/api/v1/entities/subEntitiesRoles/:entityId - * Get roles based on entity type. - * @apiVersion 1.0.0 - * @apiGroup Entities - * @apiHeader {String} X-authenticated-user-token Authenticity token - * @apiSampleRequest /kendra/api/v1/entities/subEntitiesRoles/5da829874c67d63cca1bd9d0 - * @apiUse successBody - * @apiUse errorBody - * @apiParamExample {json} Response: - * { - "message": "Successfully fetched user roles", - "status": 200, - "result": [ - { - "_id": "5d6e521066a9a45df3aa891e", - "code": "HM", - "title": "Headmaster" - }, - { - "_id": "5d6e521066a9a45df3aa891f", - "code": "CRP", - "title": "Cluster Resource Person" - }, - { - "_id": "5d6e521066a9a45df3aa8920", - "code": "BEO", - "title": "Block Education Officer" - }, - { - "_id": "5d6e521066a9a45df3aa8921", - "code": "DEO", - "title": "District Education Officer" - } - ] - } - */ - - /** - * Roles based on entity type - * @method - * @name subEntitiesRoles - * @param {String} req.params._id - entityId. - * @returns {JSON} - Array of user roles. - */ - - subEntitiesRoles(req) { - return new Promise(async (resolve, reject) => { - - try { - - const subEntityRoles = await entitiesHelper.subEntitiesRoles(req.params._id); - - resolve(subEntityRoles); - - } catch (error) { - - return reject({ - status: - error.status || - httpStatusCode["internal_server_error"].status, - - message: - error.message || - httpStatusCode["internal_server_error"].message - }); - } - }); - } - /** * @api {get} /kendra/api/v1/entities/subEntityTypeList/:entityId * Get entities child hierarchy path. diff --git a/module/app-releases/helper.js b/module/app-releases/helper.js index 548b899e..6d14546a 100644 --- a/module/app-releases/helper.js +++ b/module/app-releases/helper.js @@ -14,281 +14,6 @@ let sessionHelpers = require(ROOT_PATH+"/generics/helpers/sessions"); module.exports = class VersionHelper { - /** - * List of version data. - * @method - * @name list - * @param {Object} filterQueryObject - filter query data. - * @param {Object} [projection = {}] - projected data. - * @returns {Promise} returns a promise. - */ - - static list( filterQueryObject = {} , fields = "all" ) { - return new Promise(async (resolve, reject) => { - try { - - let projection = {}; - - if (fields != "all") { - fields.forEach(element => { - projection[element] = 1; - }); - } - - let versionData = - await database.models.appReleases.find( - filterQueryObject, - projection - ).lean(); - - return resolve(versionData); - - } catch (error) { - return reject(error); - } - }) - - - } - - /** - * Upload app release data. - * @method - * @name upload - * @param {Object} data - app update data. - * @param {String} data.appName - app name of notification. - * @param {String} data.title - title of notification. - * @param {String} data.text - text of notification. - * @param {String} data.version - version of the app. - * @param {String} data.status - status of the update notification. - * @param {String} data.os - device os. - * @param {String} data.releaseType - release type versions - * @returns {Promise} returns a promise. - */ - - static upload( data,userId ) { - return new Promise(async (resolve, reject) => { - try { - - let uploadVersion = - await this.create( - data, - userId - ); - - return resolve(uploadVersion); - - } catch (error) { - return reject(error); - } - }) - } - - /** - * Create app release data. - * @method - * @name create - * @returns {Object} create version data. - */ - - static create( data,userId ) { - return new Promise( async (resolve,reject)=>{ - try { - - // let sessionPath = - // `${constants.common.ALL_APP_VERSION}-${gen.utils.lowerCase(data.appName)}-${gen.utils.lowerCase(data.os)}`; - - data.appName = gen.utils.lowerCase(data.appName); - data.os = gen.utils.lowerCase(data.os); - data.createdBy = userId; - data.updatedBy = userId; - - let versionRelease = await database.models.appReleases.findOneAndUpdate({ - appName : data.appName, - os : data.os, - version : data.version - },{ $set : data },{ upsert : true, new: true }).lean(); - - if( versionRelease._id ) { - - if( versionRelease.status === constants.common.ACTIVE ) { - - await database.models.appReleases.updateMany( - { - _id : { $ne : versionRelease._id }, - appName : data.appName, - os : data.os - }, - { - status : constants.common.IN_ACTIVE - } - ); - - // let versionData = _versionPayload(data); - // sessionHelpers.set(sessionPath,versionData); - } - data.message = constants.apiResponses.APP_VERSION_UPDATED; - } else { - data.message = constants.apiResponses.APP_VERSION_NOT_UPDATED; - } - - return resolve(data); - } catch(e) { - return reject(e); - } - }) - } - - /** - * Update app release data. - * @method - * @name update - * @param updateData - app version update data - * @returns {Object} updated version data. - */ - - static update( id,updateData ) { - return new Promise( async (resolve,reject)=>{ - try { - - let currentAppVersion = await this.list( - { - _id : id - },["_id","appName","os"] - ); - - if( !currentAppVersion[0] ) { - return resolve({ - status : httpStatusCode.bad_request.status, - message : constants.apiResponses.APP_VERSION_NOT_FOUND - }) - } - - // <- Dirty fix.Currently not required. - - // let sessionPath = - // `${constants.common.ALL_APP_VERSION}-${gen.utils.lowerCase(currentAppVersion[0].appName)}-${gen.utils.lowerCase(currentAppVersion[0].os)}`; - - if( updateData.status === constants.common.ACTIVE ) { - - await database.models.appReleases.findOneAndUpdate({ - _id : { $ne : currentAppVersion[0]._id }, - appName : gen.utils.lowerCase(currentAppVersion[0].appName), - os : currentAppVersion[0].os - },{ - $set : { - status : constants.common.IN_ACTIVE - } - }) - } - - let updateAppReleaseData = - await database.models.appReleases.findOneAndUpdate({ - _id : currentAppVersion[0]._id - },{ - $set : updateData - },{ new : true }).lean(); - - if( !updateAppReleaseData || !updateAppReleaseData._id ) { - return resolve({ - status : httpStatusCode.bad_request.status, - message : constants.apiResponses.APP_VERSION_NOT_UPDATED - }) - } - - // <- Dirty fix.Currently not required. - - // let versionData = _versionPayload(updateAppReleaseData); - // sessionHelpers.set(sessionPath,versionData); - - return resolve({ - message : constants.apiResponses.APP_VERSION_UPDATED, - result : updateAppReleaseData - }); - } catch(e) { - return reject(e); - } - }) - } - - /** - * List of all version data. - * @method - * @name versionDataList - * @param requestedData - requestedData - * @returns {Array} List of all app release version. - */ - - static versionDataList( filters = {} ) { - return new Promise( async (resolve,reject)=>{ - try { - - let queryObject = {}; - - if( filters.appName ) { - queryObject["appName"] = filters.appName; - } - - if( filters.os ) { - queryObject["os"] = filters.os; - } - - if( filters.releaseType ) { - queryObject["releaseType"] = filters.releaseType; - } - - if( filters.status ) { - queryObject["status"] = filters.status; - } - - let versionDataList = await this.list( - queryObject - ); - - if( versionDataList.length < 1 ) { - return resolve({ - status : httpStatusCode.bad_request.status, - message : constants.apiResponses.APP_VERSION_NOT_FOUND - }) - } - - return resolve({ - message : constants.apiResponses.APP_VERSION_LISTS, - result : versionDataList - }); - } catch(e) { - return reject(e); - } - }) -} } -/** - * Version payload data. - * @method - * @name _versionPayload - * @returns {Object} return version data. -*/ - -function _versionPayload(data) { - return { - is_read : false, - internal : true, - action : "versionUpdate", - appName : data.appName, - created_at : new Date(), - text : data.text, - title : data.title, - type : "Information", - payload : { - appVersion : data.version, - updateType : data.releaseType, - type : "appUpdate", - releaseNotes : data.releaseNotes, - os : data.os - }, - appType : data.appType - }; - -} diff --git a/module/app-releases/validator/v1.js b/module/app-releases/validator/v1.js index 828fd7ea..79b0c7fb 100644 --- a/module/app-releases/validator/v1.js +++ b/module/app-releases/validator/v1.js @@ -9,34 +9,6 @@ module.exports = (req) => { let appReleaseValidator = { - create : function () { - req.checkBody('appName').exists().withMessage("Name of the app is required"); - req.checkBody('version').exists().withMessage("Version for the app is required"); - req.checkBody('releaseType').exists().withMessage("App release type is required").isIn( - ["major","minor"] - ).withMessage("Release type should be either major or minor"); - req.checkBody('os').exists().withMessage("App os is required").isIn( - [ - "android", - "ios" - ] - ).withMessage("os should be android or ios"); - - req.checkBody('text').exists().withMessage("text is required"); - req.checkBody('title').exists().withMessage("App release title is required"); - req.checkBody('status').exists().withMessage("Status of app release is required"); - req.checkBody('releaseNotes').exists().withMessage("Release notes is required"); - req.checkBody('appType').exists().withMessage("App type is required").isIn( - [ - process.env.ASSESSMENT_APPLICATION_APP_TYPE, - process.env.IMPROVEMENT_PROJECT_APPLICATION_APP_TYPE - ] - ).withMessage(`App Type should be one of the following : ${process.env.ASSESSMENT_APPLICATION_APP_TYPE} or ${process.env.IMPROVEMENT_PROJECT_APPLICATION_APP_TYPE}`); - }, - update : function () { - req.checkParams('_id').exists().withMessage("required version id"); - } - } if ( appReleaseValidator[req.params.method] ) { diff --git a/module/apps/helper.js b/module/apps/helper.js index 20b2d41d..9751b37c 100644 --- a/module/apps/helper.js +++ b/module/apps/helper.js @@ -164,178 +164,5 @@ module.exports = class AppsHelper { }) } - - /** - * Create app details - * @method - * @name create - * @param {file} logo - logo of the app - * @param {Object} appDetails - details of the app - * @returns {String} - message. - */ - - static create(logo= {}, appDetails = {}) { - return new Promise(async (resolve, reject) => { - try { - - if (!Object.keys(logo).length) { - throw new Error(constants.apiResponses.LOGO_REQUIRED) - } - - if (!appDetails.name) { - throw new Error(constants.apiResponses.NAME_FIELD_REQUIRED) - } - - if (!appDetails.description) { - throw new Error(constants.apiResponses.DESCRIPTION_REQUIRED) - } - - if (!appDetails.displayName) { - throw new Error(constants.apiResponses.DiSPLAY_NAME_REQUIRED) - } - - if (!appDetails.playstoreLink) { - throw new Error(constants.apiResponses.PLAYSTORE_LINK_REQUIRED) - } - - let bucketName = ""; - if (process.env.CLOUD_STORAGE == constants.common.GOOGLE_CLOUD_SERVICE) { - bucketName = process.env.GCP_BUCKET_NAME - } - else if (process.env.CLOUD_STORAGE == constants.common.AWS_SERVICE) { - bucketName = process.env.AWS_BUCKET_NAME - } - else if (process.env.CLOUD_STORAGE == constants.common.AZURE_SERVICE) { - bucketName = process.env.AZURE_STORAGE_CONTAINER - } - - let filePath = constants.common.APPS_UPLOAD_FILE_PATH + appDetails.name + path.extname(logo.name); - - let uploadFile = await filesHelper.upload - ( - logo, - filePath, - bucketName, - process.env.CLOUD_STORAGE - ) - - if (uploadFile["name"] && uploadFile.name !== "") { - appDetails.logo = filePath; - } - - await database.models.apps.create( - { - name: appDetails.name, - displayName: appDetails.displayName, - description: appDetails.description, - playstoreLink: appDetails.playstoreLink, - appStoreLink: appDetails.appStoreLink ? appDetails.appStoreLink : "", - logo: appDetails.logo ? appDetails.logo : "", - createdAt: new Date(), - updatedAt: new Date(), - createdBy: appDetails.createdBy ? appDetails.createdBy : "SYSTEM", - updatedBy: appDetails.updatedBy ? appDetails.updatedBy : "SYSTEM", - status: appDetails.status ? appDetails.status : constants.common.ACTIVE, - isDeleted: appDetails.isDeleted - } - ); - - return resolve({ - success: true, - message: constants.apiResponses.APP_DETAILS_CREATED, - data: true - }); - - } catch (error) { - return resolve({ - success: false, - message: error.message, - data: false - }); - } - }) - } - - - /** - * Update app details - * @method - * @name update - * @param {String} name - app name - * @param {file} logo - logo of the app - * @param {Object} appDetails - details of the app to update - * @param {String} userId - userId - * @returns {String} - message. - */ - - static update(name= "", logo = {}, appDetails = {}) { - return new Promise(async (resolve, reject) => { - try { - - if(name == "") { - throw new Error(constants.apiResponses.APP_NAME_REQUIRED) - } - - if (!Object.keys(appDetails).length) { - throw new Error(constants.apiResponses.APP_DETAILS_REQUIRED) - } - - if (logo !== "") { - - let bucketName = ""; - if (process.env.CLOUD_STORAGE == constants.common.GOOGLE_CLOUD_SERVICE) { - bucketName = process.env.GCP_BUCKET_NAME - } - else if (process.env.CLOUD_STORAGE == constants.common.AWS_SERVICE) { - bucketName = process.env.AWS_BUCKET_NAME - } - else if (process.env.CLOUD_STORAGE == constants.common.AZURE_SERVICE) { - bucketName = process.env.AZURE_STORAGE_CONTAINER - } - - let filePath = constants.common.APPS_UPLOAD_FILE_PATH + name + path.extname(logo.name); - - let uploadFile = await filesHelper.upload - ( - logo, - filePath, - bucketName, - process.env.CLOUD_STORAGE - ) - - if (uploadFile["name"] && uploadFile.name !== "") { - appDetails.logo = filePath; - } - } - - let appDetailsToSet = {}; - - Object.keys(appDetails).forEach( key => { - appDetailsToSet[key] = appDetails[key] - }) - - await database.models.apps.updateOne( - { name: name }, - { - $set : appDetailsToSet - } - ); - - return resolve({ - success: true, - message: constants.apiResponses.APP_DETAILS_UPDATED, - data: true - }); - - } catch (error) { - return resolve({ - success: false, - message: error.message, - data: false - }); - } - }) - } - } diff --git a/module/apps/validator/v1.js b/module/apps/validator/v1.js index 7b5f1c13..2efd3008 100644 --- a/module/apps/validator/v1.js +++ b/module/apps/validator/v1.js @@ -4,19 +4,7 @@ module.exports = (req) => { getDetails: function () { req.checkParams('_id').exists().withMessage("required app name").notEmpty().withMessage("required app name"); - }, - - create: function () { - req.checkBody('name').exists().withMessage("required name field").notEmpty().withMessage("required name field"); - req.checkBody('displayName').exists().withMessage("required displayName field").notEmpty().withMessage("required name field"); - req.checkBody('description').exists().withMessage("required description field").notEmpty().withMessage("required name field"); - req.checkBody('playstoreLink').exists().withMessage("required playStoreLink field").notEmpty().withMessage("required name field"); - }, - - update: function () { - req.checkParams('_id').exists().withMessage("required app name").notEmpty().withMessage("required app name"); } - } if (appsValidator[req.params.method]) { diff --git a/module/entities/helper.js b/module/entities/helper.js index 18efb73f..7797e42d 100644 --- a/module/entities/helper.js +++ b/module/entities/helper.js @@ -510,44 +510,6 @@ module.exports = class EntitiesHelper { }) } - /** - * Entity details information. - * @method - * @name details - * @param {String} entityId - _id of entity. - * @return {Object} - consists of entity details information. - */ - - static details( entityId ) { - return new Promise(async (resolve, reject) => { - try { - - let entityDocument = await this.entityDocuments( - { - _id : entityId - }, - "all", - ["groups"] - ); - - if ( !entityDocument[0] ) { - return resolve({ - status : httpStatusCode.bad_request.status, - message : constants.apiResponses.ENTITY_NOT_FOUND - }) - } - - resolve({ - message : constants.apiResponses.ENTITY_INFORMATION_FETCHED, - result : entityDocument[0] - }); - - } catch (error) { - return reject(error); - } - }) - } - /** * List of Entities * @method @@ -578,78 +540,6 @@ module.exports = class EntitiesHelper { }); } - /** - * List roles by entity type. - * @method - * @name subEntitiesRoles - * @param entityId - entity id. - * @returns {Object} List of roles by entity id. - */ - - static subEntitiesRoles( entityId ) { - return new Promise(async (resolve, reject) => { - try { - - const entityDocuments = await this.entityDocuments({ - _id : entityId - },["childHierarchyPath","allowedRoles"]); - - if( !entityDocuments.length > 0 ) { - return resolve({ - message : constants.apiResponses.STATE_NOT_FOUND, - result : [] - }) - } - - let queryObject = {}; - - if( entityDocuments[0].allowedRoles && entityDocuments[0].allowedRoles.length > 0 ) { - queryObject["code"] = {}; - queryObject["code"]["$in"] = entityDocuments[0].allowedRoles; - } - - let lengthOfQuery = Object.keys(queryObject).length; - - if( !lengthOfQuery > 0 ) { - - if ( - !entityDocuments[0].childHierarchyPath || - !entityDocuments[0].childHierarchyPath.length > 0 - ) { - return resolve({ - message : constants.apiResponses.SUB_ENTITY_NOT_FOUND, - result : [] - }); - } - - queryObject[ "entityTypes.entityType"] = {}; - queryObject[ "entityTypes.entityType"]["$in"] = - entityDocuments[0].childHierarchyPath; - } - - const rolesData = await userRolesHelper.roleDocuments( - queryObject,["code","title"] - ); - - if( !rolesData.length > 0 ) { - return resolve({ - message : constants.apiResponses.USER_ROLES_NOT_FOUND, - result : [] - }) - } - - return resolve({ - message : constants.apiResponses.USER_ROLES_FETCHED, - result : rolesData - }); - - } catch (error) { - return reject(error); - } - }) - -} - /** * Sub entity type list. * @method diff --git a/module/entities/validator/v1.js b/module/entities/validator/v1.js index 890ad290..8088ab7b 100644 --- a/module/entities/validator/v1.js +++ b/module/entities/validator/v1.js @@ -6,12 +6,6 @@ module.exports = (req) => { immediateEntities : function () { req.checkParams('_id').exists().withMessage("required Entity id"); }, - details : function () { - req.checkParams('_id').exists().withMessage("required Entity id"); - }, - subEntitiesRoles : function() { - req.checkParams('_id').exists().withMessage("required Entity id"); - }, listByIds : function () { req.checkBody('entities').exists().withMessage("required Entity ids") .isArray().withMessage("entities should be array") From b7bbf7962253405df5de7257d91383bd4f03d132 Mon Sep 17 00:00:00 2001 From: aman-tunerlabs Date: Wed, 8 Sep 2021 10:22:47 +0530 Subject: [PATCH 022/331] Removed console.log --- generics/services/improvement-project.js | 7 ------- 1 file changed, 7 deletions(-) diff --git a/generics/services/improvement-project.js b/generics/services/improvement-project.js index f957d730..c34e5199 100644 --- a/generics/services/improvement-project.js +++ b/generics/services/improvement-project.js @@ -7,7 +7,6 @@ //dependencies const request = require('request'); -process.env.ML_PROJECT_SERVICE_URL = "http://ml-projects-service:3000" /** * List of user assigned projects. @@ -29,8 +28,6 @@ var assignedProjects = function ( token,search = "",filter = "" ) { if( filter !== "" ) { url = url + "&filter=" + filter; } - - console.log("--- url is ----",url); return new Promise(async (resolve, reject) => { try { @@ -43,13 +40,9 @@ var assignedProjects = function ( token,search = "",filter = "" ) { if (err) { result.success = false; - console.log("--- error is ----",err); } else { let response = JSON.parse(data.body); - - console.log("--- response is ----",response); - if( response.status === httpStatusCode['ok'].status ) { result["data"] = response.result; From ead7e92d35cb3e3b5b373238d15f7188814111bd Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Wed, 8 Sep 2021 15:34:46 +0530 Subject: [PATCH 023/331] course as a part of program --- generics/constants/api-responses.js | 1 + generics/constants/common.js | 3 +- module/solutions/helper.js | 48 +++++++++++++++++++---------- module/solutions/validator/v1.js | 1 - 4 files changed, 35 insertions(+), 18 deletions(-) diff --git a/generics/constants/api-responses.js b/generics/constants/api-responses.js index ba4eb2bd..6faf8883 100644 --- a/generics/constants/api-responses.js +++ b/generics/constants/api-responses.js @@ -167,4 +167,5 @@ module.exports = { "USER_PLATFORM_ROLES": "List of user platform roles" , "USER_PLATFORM_ROLE_NOT_FOUND": "Not found user platform role", "PLATFORM_USER_PROGRAMS": "List of programs for platform user", + "ENTITY_TYPE_REQUIRED": "required entity type" }; diff --git a/generics/constants/common.js b/generics/constants/common.js index 06f5ab4c..04b9a5ad 100644 --- a/generics/constants/common.js +++ b/generics/constants/common.js @@ -57,5 +57,6 @@ module.exports = { "DEFAULT_PAGE_SIZE" : 100, "DEFAULT_PAGE_NO" : 1, "DHITI" : "dhiti", - "DEFAULT_SURVEY_REMOVED_DAY" : 15 + "DEFAULT_SURVEY_REMOVED_DAY" : 15, + "COURSE" : "course" }; diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 0b00a3dc..ec45fbe4 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -119,21 +119,33 @@ module.exports = class SolutionsHelper { solutionData.programName = programData[0].name; solutionData.programDescription = programData[0].description; - let entityTypeData = - await entityTypesHelper.entityTypesDocument({ - name : solutionData.entityType - },["_id"]); + if( solutionData.type !== constants.common.COURSE ) { - if( !entityTypeData.length > 0 ) { - throw { - message : constants.apiResponses.ENTITY_TYPES_NOT_FOUND - } - } + if( !solutionData.entityType ){ + + return resolve({ + status : httpStatusCode.bad_request.status, + message : constants.apiResponses.ENTITY_TYPE_REQUIRED + }); + + } - solutionData.entityTypeId = entityTypeData[0]._id; + let entityTypeData = + await entityTypesHelper.entityTypesDocument({ + name : solutionData.entityType + },["_id"]); + + if( !entityTypeData.length > 0 ) { + throw { + message : constants.apiResponses.ENTITY_TYPES_NOT_FOUND + } + } + + solutionData.entityTypeId = entityTypeData[0]._id; + } if( solutionData.entities && solutionData.entities.length > 0 ) { - + let entitiesData = await entitiesHelper.entityDocuments({ _id : { $in : solutionData.entities } @@ -744,7 +756,7 @@ module.exports = class SolutionsHelper { let solutionsSkipped = []; if( data.filter.skipSolutions ) { - + data.filter.skipSolutions.forEach( solution => { solutionsSkipped.push(ObjectId(solution.toString())); }); @@ -1298,8 +1310,8 @@ module.exports = class SolutionsHelper { surveyReportPage = gen.utils.convertStringToBoolean(surveyReportPage); - if ( !surveyReportPage ) { - + if ( !surveyReportPage || solutionType == constants.common.COURSE) { + targetedSolutions = await this.forUserRoleAndLocation( requestedData, @@ -1320,7 +1332,10 @@ module.exports = class SolutionsHelper { targetedSolutions.data.data.forEach(targetedSolution => { targetedSolution.solutionId = targetedSolution._id; targetedSolution._id = ""; - targetedSolution["creator"] = targetedSolution.creator ? targetedSolution.creator : ""; + + if( solutionType !== constants.common.COURSE ) { + targetedSolution["creator"] = targetedSolution.creator ? targetedSolution.creator : ""; + } if ( solutionType === constants.common.SURVEY ) { targetedSolution.isCreator = false; @@ -1496,6 +1511,7 @@ function _targetedSolutionTypes() { return [ constants.common.OBSERVATION, constants.common.SURVEY, - constants.common.IMPROVEMENT_PROJECT + constants.common.IMPROVEMENT_PROJECT, + constants.common.COURSE ] } diff --git a/module/solutions/validator/v1.js b/module/solutions/validator/v1.js index e7b98abc..03070930 100644 --- a/module/solutions/validator/v1.js +++ b/module/solutions/validator/v1.js @@ -11,7 +11,6 @@ module.exports = (req) => { create : function () { req.checkBody('programExternalId').exists().withMessage("required program externalId"); - req.checkBody('entityType').exists().withMessage("required entity type"); req.checkBody('externalId').exists().withMessage("required solution externalId"); req.checkBody('name').exists().withMessage("required solution name"); req.checkBody('type').exists().withMessage("required solution type"); From 164189530ec04e496d03ed37922879c8fb7fabf9 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Wed, 8 Sep 2021 17:52:42 +0530 Subject: [PATCH 024/331] user solution list changes --- models/solutions.js | 3 ++- module/solutions/helper.js | 7 +++++-- module/users/helper.js | 3 +++ 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/models/solutions.js b/models/solutions.js index 4d6dcbbc..d4291b95 100644 --- a/models/solutions.js +++ b/models/solutions.js @@ -82,6 +82,7 @@ module.exports = { type : String }, criteriaLevelReport : Boolean, - license:Object + license:Object, + link: String } }; \ No newline at end of file diff --git a/module/solutions/helper.js b/module/solutions/helper.js index ec45fbe4..233e1306 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -669,7 +669,8 @@ module.exports = class SolutionsHelper { "type", "language", "creator", - "endDate" + "endDate", + "link" ] ); @@ -1333,7 +1334,9 @@ module.exports = class SolutionsHelper { targetedSolution.solutionId = targetedSolution._id; targetedSolution._id = ""; - if( solutionType !== constants.common.COURSE ) { + if( solutionType == constants.common.COURSE ) { + targetedSolution["link"] = targetedSolution.link ? targetedSolution.link : ""; + }else{ targetedSolution["creator"] = targetedSolution.creator ? targetedSolution.creator : ""; } diff --git a/module/users/helper.js b/module/users/helper.js index 71194651..ea1c443f 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -443,6 +443,9 @@ module.exports = class UsersHelper { mergedData.map( targetedData => { delete targetedData.programId; delete targetedData.programName; + if( !targetedData.link ){ + targetedData.link = ""; + } return targetedData; }); } From 243595046e251ea89c8c61829324644f0f6f31ff Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Thu, 9 Sep 2021 13:30:09 +0530 Subject: [PATCH 025/331] solution creation from program issue fix --- module/solutions/helper.js | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 233e1306..800681ca 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -186,7 +186,6 @@ module.exports = class SolutionsHelper { }); if( !solutionData.excludeScope && programData[0].scope ) { - let solutionScope = await this.setScope( solutionData.programId, @@ -268,7 +267,6 @@ module.exports = class SolutionsHelper { } if( scopeData.entities && scopeData.entities.length > 0 ) { - let entities = await entitiesHelper.entityDocuments( { @@ -301,6 +299,7 @@ module.exports = class SolutionsHelper { entityIds.push(ObjectId(entities[entity]._id)); } } + } else { entityIds = entities.map(entity => { return ObjectId(entity._id); @@ -344,7 +343,22 @@ module.exports = class SolutionsHelper { } } } + + if(currentSolutionScope && currentSolutionScope.entities.length > 0 ){ + + let entitiesIds = currentSolutionScope.entities; + for(let eachEntity in entitiesIds){ + if(entitiesIds[eachEntity].toString() == entitiesIds[eachEntity]){ + entitiesIds[eachEntity] = ObjectId(entitiesIds[eachEntity]); + } + } + + delete currentSolutionScope.entities; + currentSolutionScope["entities"] = entitiesIds; + + } + let updateSolution = await database.models.solutions.findOneAndUpdate( { From 0a5f96c6e6315d3cd2ef6ebc8b3f7e7c768e937b Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Thu, 9 Sep 2021 13:43:28 +0530 Subject: [PATCH 026/331] remove link if type is not course --- module/solutions/helper.js | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 800681ca..ee6ef773 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -1348,9 +1348,10 @@ module.exports = class SolutionsHelper { targetedSolution.solutionId = targetedSolution._id; targetedSolution._id = ""; - if( solutionType == constants.common.COURSE ) { - targetedSolution["link"] = targetedSolution.link ? targetedSolution.link : ""; - }else{ + if( solutionType === constants.common.COURSE ) { + targetedSolution.link = targetedSolution.link ? targetedSolution.link : ""; + }else { + delete targetedSolution.link; targetedSolution["creator"] = targetedSolution.creator ? targetedSolution.creator : ""; } From c433bdd169ea7757646ca2391c81bea1a65eea28 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Thu, 9 Sep 2021 13:54:09 +0530 Subject: [PATCH 027/331] remove link if type is not course --- module/users/helper.js | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/module/users/helper.js b/module/users/helper.js index ea1c443f..ca759519 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -443,8 +443,12 @@ module.exports = class UsersHelper { mergedData.map( targetedData => { delete targetedData.programId; delete targetedData.programName; - if( !targetedData.link ){ - targetedData.link = ""; + if( targetedData.type === constants.common.COURSE ){ + targetedData.link = targetedData.link ? targetedData.link : ""; + }else{ + if( targetedData.link ){ + delete targetedData.link; + } } return targetedData; }); From 948eed608217a6469756da6c410c3ddf874a5bfe Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Thu, 9 Sep 2021 16:21:49 +0530 Subject: [PATCH 028/331] PR change --- generics/constants/api-responses.js | 3 ++- module/solutions/helper.js | 23 ++++++++++++++--------- module/users/helper.js | 7 ------- 3 files changed, 16 insertions(+), 17 deletions(-) diff --git a/generics/constants/api-responses.js b/generics/constants/api-responses.js index 6faf8883..6f69a4f7 100644 --- a/generics/constants/api-responses.js +++ b/generics/constants/api-responses.js @@ -167,5 +167,6 @@ module.exports = { "USER_PLATFORM_ROLES": "List of user platform roles" , "USER_PLATFORM_ROLE_NOT_FOUND": "Not found user platform role", "PLATFORM_USER_PROGRAMS": "List of programs for platform user", - "ENTITY_TYPE_REQUIRED": "required entity type" + "ENTITY_TYPE_REQUIRED": "required entity type", + "COURSE_LINK_REQUIRED" : "Course link is required" }; diff --git a/module/solutions/helper.js b/module/solutions/helper.js index ee6ef773..d1b2223d 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -119,7 +119,15 @@ module.exports = class SolutionsHelper { solutionData.programName = programData[0].name; solutionData.programDescription = programData[0].description; - if( solutionData.type !== constants.common.COURSE ) { + if( solutionData.type == constants.common.COURSE ) { + + if( !solutionData.link ) { + return resolve({ + status : httpStatusCode.bad_request.status, + message : constants.apiResponses.COURSE_LINK_REQUIRED + }); + } + } else { if( !solutionData.entityType ){ @@ -344,12 +352,12 @@ module.exports = class SolutionsHelper { } } - if(currentSolutionScope && currentSolutionScope.entities.length > 0 ){ + if( currentSolutionScope && currentSolutionScope.entities.length > 0 ){ let entitiesIds = currentSolutionScope.entities; - for(let eachEntity in entitiesIds){ - if(entitiesIds[eachEntity].toString() == entitiesIds[eachEntity]){ + for( let eachEntity in entitiesIds ) { + if( entitiesIds[eachEntity].toString() == entitiesIds[eachEntity] ) { entitiesIds[eachEntity] = ObjectId(entitiesIds[eachEntity]); } } @@ -1325,7 +1333,7 @@ module.exports = class SolutionsHelper { surveyReportPage = gen.utils.convertStringToBoolean(surveyReportPage); - if ( !surveyReportPage || solutionType == constants.common.COURSE) { + if ( !surveyReportPage || solutionType == constants.common.COURSE ) { targetedSolutions = await this.forUserRoleAndLocation( @@ -1348,10 +1356,7 @@ module.exports = class SolutionsHelper { targetedSolution.solutionId = targetedSolution._id; targetedSolution._id = ""; - if( solutionType === constants.common.COURSE ) { - targetedSolution.link = targetedSolution.link ? targetedSolution.link : ""; - }else { - delete targetedSolution.link; + if( solutionType !== constants.common.COURSE ) { targetedSolution["creator"] = targetedSolution.creator ? targetedSolution.creator : ""; } diff --git a/module/users/helper.js b/module/users/helper.js index ca759519..71194651 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -443,13 +443,6 @@ module.exports = class UsersHelper { mergedData.map( targetedData => { delete targetedData.programId; delete targetedData.programName; - if( targetedData.type === constants.common.COURSE ){ - targetedData.link = targetedData.link ? targetedData.link : ""; - }else{ - if( targetedData.link ){ - delete targetedData.link; - } - } return targetedData; }); } From 671eafbcb7b4e70937132c97ec87a79e9e04ecd5 Mon Sep 17 00:00:00 2001 From: aman-tunerlabs Date: Tue, 14 Sep 2021 10:58:12 +0530 Subject: [PATCH 029/331] Added logs in improvement projects --- generics/services/improvement-project.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/generics/services/improvement-project.js b/generics/services/improvement-project.js index c34e5199..aefbf0a0 100644 --- a/generics/services/improvement-project.js +++ b/generics/services/improvement-project.js @@ -28,6 +28,8 @@ var assignedProjects = function ( token,search = "",filter = "" ) { if( filter !== "" ) { url = url + "&filter=" + filter; } + + console.log("url is",url); return new Promise(async (resolve, reject) => { try { From 00b940db75528f7d0b2df2dd4f879efb1b9165e8 Mon Sep 17 00:00:00 2001 From: aman-tunerlabs Date: Tue, 14 Sep 2021 11:21:18 +0530 Subject: [PATCH 030/331] Added logs --- generics/services/improvement-project.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/generics/services/improvement-project.js b/generics/services/improvement-project.js index aefbf0a0..090a024b 100644 --- a/generics/services/improvement-project.js +++ b/generics/services/improvement-project.js @@ -41,10 +41,12 @@ var assignedProjects = function ( token,search = "",filter = "" ) { }; if (err) { + console.log("error is",error); result.success = false; } else { let response = JSON.parse(data.body); + console.log("response is",response); if( response.status === httpStatusCode['ok'].status ) { result["data"] = response.result; From c88e86f30dc1c3667ad390f5dd9be900c53300e5 Mon Sep 17 00:00:00 2001 From: aman-tunerlabs Date: Tue, 14 Sep 2021 13:21:23 +0530 Subject: [PATCH 031/331] logs --- generics/services/improvement-project.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/generics/services/improvement-project.js b/generics/services/improvement-project.js index 090a024b..a93cff33 100644 --- a/generics/services/improvement-project.js +++ b/generics/services/improvement-project.js @@ -41,7 +41,7 @@ var assignedProjects = function ( token,search = "",filter = "" ) { }; if (err) { - console.log("error is",error); + console.log("error is",err); result.success = false; } else { From e6c7787f9c380f085a563d39adee7d736b2e0b4f Mon Sep 17 00:00:00 2001 From: aman-tunerlabs Date: Thu, 16 Sep 2021 11:49:47 +0530 Subject: [PATCH 032/331] Added hardcoded improvement project url --- generics/services/improvement-project.js | 1 + 1 file changed, 1 insertion(+) diff --git a/generics/services/improvement-project.js b/generics/services/improvement-project.js index c34e5199..ee58eca4 100644 --- a/generics/services/improvement-project.js +++ b/generics/services/improvement-project.js @@ -7,6 +7,7 @@ //dependencies const request = require('request'); +process.env.ML_PROJECT_SERVICE_URL = "http://ml-projects-service:3000" /** * List of user assigned projects. From 66685773d74ed239b85cab17288adf27fb796b0a Mon Sep 17 00:00:00 2001 From: Aman Kumar Gupta Date: Wed, 29 Sep 2021 19:44:59 +0530 Subject: [PATCH 033/331] Added:Logs --- app.js | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/app.js b/app.js index ddab8a2c..ba73c659 100644 --- a/app.js +++ b/app.js @@ -45,17 +45,12 @@ app.use(express.static("public")); app.all("*", (req, res, next) => { + console.log({"Debugging ML Core Service": true}); console.log("-------Request log starts here------------------"); - console.log( - "%s %s on %s from ", - req.method, - req.url, - new Date(), - req.headers["user-agent"] - ); - console.log("Request Headers: ", req.headers); - console.log("Request Body: ", req.body); - console.log("Request Files: ", req.files); + console.log("Request URL: ", req.url); + console.log("Request Headers: ", JSON.stringify(req.headers)); + console.log("Request Body: ", JSON.stringify(req.body)); + // console.log("Request Files: ", req.files); console.log("-------Request log ends here------------------"); next(); }); From c2c4247206db1decfa53a3c76027a744eccd0bc5 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Thu, 30 Sep 2021 18:06:37 +0530 Subject: [PATCH 034/331] v1 --- controllers/v1/entities.js | 55 --- controllers/v1/programs.js | 65 ---- controllers/v1/solutions.js | 118 ------ controllers/v1/static-links.js | 206 ----------- controllers/v1/user-extension.js | 346 ----------------- controllers/v1/user-profile.js | 194 ---------- controllers/v1/users.js | 251 ------------- module/entities/helper.js | 35 -- module/entities/validator/v1.js | 5 - module/solutions/helper.js | 74 ---- module/solutions/validator/v1.js | 3 - module/static-links/helper.js | 201 ---------- module/static-links/validator/v1.js | 5 - module/user-extension/helper.js | 511 -------------------------- module/user-extension/validator/v1.js | 4 - module/user-profile/helper.js | 307 ---------------- module/user-profile/validator/v1.js | 8 - module/users/helper.js | 81 ---- module/users/validator/v1.js | 16 +- 19 files changed, 1 insertion(+), 2484 deletions(-) diff --git a/controllers/v1/entities.js b/controllers/v1/entities.js index 3cfab8f1..782890cc 100644 --- a/controllers/v1/entities.js +++ b/controllers/v1/entities.js @@ -255,61 +255,6 @@ module.exports = class Entities extends Abstract { }) } - /** - * @api {get} /kendra/api/v1/entities/subEntityTypeList/:entityId - * Get entities child hierarchy path. - * @apiVersion 1.0.0 - * @apiGroup Entities - * @apiHeader {String} X-authenticated-user-token Authenticity token - * @apiSampleRequest /kendra/api/v1/entities/subEntityTypeList/5da829874c67d63cca1bd9d0 - * @apiUse successBody - * @apiUse errorBody - * @apiParamExample {json} Response: - * { - "message": "Entities child hierarchy path fetched successfully", - "status": 200, - "result": [ - "district", - "block", - "cluster", - "school" - ] - } - */ - - /** - * Entities child hierarchy path - * @method - * @name subEntitiesRoles - * @param {String} req.params._id - entityId. - * @returns {JSON} - Entities child hierarchy path - */ - - subEntityTypeList(req) { - return new Promise(async (resolve, reject) => { - - try { - - const subEntityTypeListData = - await entitiesHelper.subEntityTypeList(req.params._id); - - resolve(subEntityTypeListData); - - } catch (error) { - - return reject({ - status: - error.status || - httpStatusCode["internal_server_error"].status, - - message: - error.message || - httpStatusCode["internal_server_error"].message - }); - } - }); - } - /** * @api {get} /kendra/api/v1/entities/getUsersByEntityAndRole/:entityId?role="" * @apiVersion 1.0.0 diff --git a/controllers/v1/programs.js b/controllers/v1/programs.js index 0fa8e7b2..187dfdd4 100644 --- a/controllers/v1/programs.js +++ b/controllers/v1/programs.js @@ -245,71 +245,6 @@ module.exports = class Programs extends Abstract { } }) } - - /** - * @api {post} /assessment/api/v1/programs/forUserRoleAndLocation?page=:page&limit=:limit Auto targeted programs - * @apiVersion 1.0.0 - * @apiName Auto targeted programs - * @apiGroup Programs - * @apiParamExample {json} Request-Body: - * { - "role" : "HM", - "state" : "236f5cff-c9af-4366-b0b6-253a1789766a", - "district" : "1dcbc362-ec4c-4559-9081-e0c2864c2931", - "school" : "c5726207-4f9f-4f45-91f1-3e9e8e84d824" - } - * @apiHeader {String} X-authenticated-user-token Authenticity token - * @apiSampleRequest /assessment/api/v1/programs/forUserRoleAndLocation?page=1&limit=5 - * @apiUse successBody - * @apiUse errorBody - * @apiParamExample {json} Response: - * { - "message": "Targeted programs fetched successfully", - "status": 200, - "result": { - "data": [ - { - "_id": "5ff438b04698083dbfab7284", - "externalId": "TEST_SCOPE_PROGRAM", - "name": "TEST scope in program", - "solutions": 16 - } - ], - "count": 1 - }} - */ - - /** - * Lists of programs based on role and location. - * @method - * @name forUserRoleAndLocation - * @param {Object} req - requested data. - * @returns {Array} List of programs. - */ - - async forUserRoleAndLocation(req) { - return new Promise(async (resolve, reject) => { - try { - - let targetedPrograms = await programsHelper.forUserRoleAndLocation( - req.body, - req.pageSize, - req.pageNo, - req.searchText - ); - - targetedPrograms.result = targetedPrograms.data; - return resolve(targetedPrograms); - - } catch (error) { - return reject({ - status: error.status || httpStatusCode.internal_server_error.status, - message: error.message || httpStatusCode.internal_server_error.message, - errorObject: error - }); - } - }); - } /** * @api {post} /assessment/api/v1/programs/addRolesInScope/:programId Add roles in programs diff --git a/controllers/v1/solutions.js b/controllers/v1/solutions.js index ff134626..181f809b 100644 --- a/controllers/v1/solutions.js +++ b/controllers/v1/solutions.js @@ -675,67 +675,6 @@ module.exports = class Solutions extends Abstract { }); } - /** - * @api {post} /kendra/api/v1/solutions/targetedEntity/:solutionId Targeted entity in solution. - * @apiVersion 1.0.0 - * @apiName Targeted entity in solution. - * @apiGroup Solutions - * @apiParamExample {json} Request-Body: - * { - "state" : "bc75cc99-9205-463e-a722-5326857838f8", - "district" : "b54a5c6d-98be-4313-af1c-33040b1703aa", - "school" : "2a128c91-a5a2-4e25-aa21-3d9196ad8203" - } - * @apiHeader {String} X-authenticated-user-token Authenticity token - * @apiSampleRequest /kendra/api/v1/solutions/targetedEntity/600ac0d1c7de076e6f9943b9 - * @apiUse successBody - * @apiUse errorBody - * @apiParamExample {json} Response: - * { - "message": "Targeted entity in solution fetched successfully", - "status": 200, - "result": { - "_id": "5fd098e2e049735a86b748ad", - "entityType": "district", - "metaInformation": { - "name": "VIZIANAGARAM" - } - }} - */ - - /** - * Targeted entity in solution - * @method - * @name targetedEntity - * @param {Object} req - requested data. - * @param {String} req.params._id - solution id. - * @returns {Array} Details entity. - */ - - async targetedEntity(req) { - return new Promise(async (resolve, reject) => { - try { - - let detailEntity = await solutionsHelper.targetedEntity( - req.params._id, - req.body - ); - - detailEntity["result"] = detailEntity.data; - - return resolve(detailEntity); - - } catch (error) { - return reject({ - status: error.status || httpStatusCode.internal_server_error.status, - message: error.message || httpStatusCode.internal_server_error.message, - errorObject: error - }); - } - }); - } - - /** * @api {post} /kendra/api/v1/solutions/targetedSolutions?type=:solutionType&page=:page&limit=:limit&search=:search&filter=:filter * List of assigned solutions and targetted ones. @@ -813,61 +752,4 @@ module.exports = class Solutions extends Abstract { }) } - /** - * @api {get} /kendra/api/v1/solutions/listByProgramId/:programId - * @apiVersion 1.0.0 - * @apiName List solutions by program id - * @apiGroup Solutions - * @apiSampleRequest /kendra/api/v1/solutions/listByProgramId/5fa28620b6bd9b757dc4e932 - * @apiHeader {String} X-authenticated-user-token Authenticity token - * @apiUse successBody - * @apiUse errorBody - * @apiParamExample {json} Response: - * { - "message": "Solutions lists fetched successfully", - "status": 200, - "result": [ - { - "_id": "5fa28620b6bd9b757dc4e943", - "isRubricDriven": false, - "externalId": "eb670a66-1e5e-11eb-a3bf-000d3af02677-OBSERVATION-TEMPLATE-1604486688116", - "name": "स्कूल सुरक्षा चेकलिस्ट", - "description": "स्कूल सुरक्षा चेकलिस्ट", - "type": "observation", - "subType": "school" - } - ] -} - */ - - /** - * List solutions by program id. - * @method - * @name listByProgramId - * @param {Object} req - requested data. - * @param {String} req.params._id - program id . - * @returns {Array} - */ - - async listByProgramId(req) { - return new Promise(async (resolve, reject) => { - try { - - let solutionData = await solutionsHelper.listByProgramId( - req.params._id - ); - solutionData["result"] = solutionData.data; - - return resolve(solutionData); - } - catch (error) { - reject({ - status: error.status || httpStatusCode.internal_server_error.status, - message: error.message || httpStatusCode.internal_server_error.message, - errorObject: error - }) - } - }) - } - } \ No newline at end of file diff --git a/controllers/v1/static-links.js b/controllers/v1/static-links.js index 8a9dd332..23ec4289 100644 --- a/controllers/v1/static-links.js +++ b/controllers/v1/static-links.js @@ -23,210 +23,4 @@ module.exports = class StaticLinks extends Abstract { return "static-links"; } - /** - * @api {get} /kendra/api/v1/static-links/list Static Link list - * @apiVersion 1.0.0 - * @apiName Static Link list - * @apiGroup Static Links - * @apiHeader {String} X-authenticated-user-token Authenticity token - * @apiSampleRequest /kendra/api/v1/static-links/list - * @apiParamExample {json} Response: - * { - * "message": "Static Links fetched successfully.", - "status": 200, - "result": [ - privacyPolicy": { - "_id": "5d259439a9bc1209d0184390", - "value": "privacyPolicy", - "link": "https://shikshalokam.org/wp-content/uploads/2019/01/data_privacy_policy.html", - "title": "Privacy Policy" - }, - "termsOfUse": { - "_id": "5d259439a9bc1209d0184391", - "value": "termsOfUse", - "link": "https://shikshalokam.org/wp-content/uploads/2019/05/Final-ShikshaLokam-Terms-of-Use-MCM-08052019-Clean-copy-1.html", - "title": "Terms of Use" - } - - ] - } - * @apiUse successBody - * @apiUse errorBody - */ - - /** - * List static links. - * @method - * @name list - * @returns {Array} List of all static links. - */ - - list(req) { - return new Promise(async (resolve, reject) => { - - try { - - let result = await staticLinksHelper.list( - req.headers.apptype, - req.headers.appname - ) - - return resolve(result); - - } catch (error) { - - return reject({ - status: error.status || httpStatusCode.internal_server_error.status, - message: error.message || httpStatusCode.internal_server_error.message, - errorObject: error - }); - - } - - - }) - } - - /** - * @api {post} /kendra/api/v1/static-links/bulkCreate Upload Static Links Information CSV - * @apiVersion 1.0.0 - * @apiName Upload Static Links Information CSV - * @apiGroup Static Links - * @apiParam {File} staticLinks Mandatory static links file of type CSV. - * @apiSampleRequest /kendra/api/v1/static-links/bulkCreate - * @apiUse successBody - * @apiUse errorBody - */ - - /** - * Create bulk static links via csv. - * @method - * @name bulkCreate - * @param {Object} req - request data. - * @param {CSV} req.files.staticLinks - static links data. - * @returns {CSV} - */ - - bulkCreate(req) { - return new Promise(async (resolve, reject) => { - - try { - - let staticLinksCSVData = await csv().fromString(req.files.staticLinks.data.toString()); - - if (!staticLinksCSVData || staticLinksCSVData.length < 1) { - throw constants.apiResponses.FILE_DATA_MISSING; - } - - let newStaticLinkData = await staticLinksHelper.bulkCreate(staticLinksCSVData, req.userDetails); - - if (newStaticLinkData.length > 0) { - const fileName = `StaticLink-Upload`; - let fileStream = new FileStream(fileName); - let input = fileStream.initStream(); - - (async function () { - await fileStream.getProcessorPromise(); - return resolve({ - isResponseAStream: true, - fileNameWithPath: fileStream.fileNameWithPath() - }); - }()); - - await Promise.all(newStaticLinkData.map(async staticLink => { - input.push(staticLink); - })) - - input.push(null); - - } else { - throw constants.apiResponses.SOMETHING_WENT_WRONG; - } - - } catch (error) { - - return reject({ - status: error.status || httpStatusCode.internal_server_error.status, - message: error.message || httpStatusCode.internal_server_error.message, - errorObject: error - }) - - } - - - }) - } - - /** - * @api {post} /kendra/api/v1/static-links/bulkUpdate Upload Static Links Information CSV - * @apiVersion 1.0.0 - * @apiName Upload Static Links Information CSV - * @apiGroup Static Links - * @apiParam {File} staticLinks Mandatory static links file of type CSV. - * @apiSampleRequest /kendra/api/v1/static-links/bulkUpdate - * @apiUse successBody - * @apiUse errorBody - */ - - /** - * Upsate bulk static links via csv. - * @method - * @name bulkUpdate - * @param {Object} req - request data. - * @param {CSV} req.files.staticLinks - static links data. - * @returns {CSV} - */ - - bulkUpdate(req) { - return new Promise(async (resolve, reject) => { - - try { - - - let staticLinksCSVData = await csv().fromString(req.files.staticLinks.data.toString()); - - if (!staticLinksCSVData || staticLinksCSVData.length < 1) { - throw messageConstants.apiResponses.FILE_DATA_MISSING; - } - - let newStaticLinkData = await staticLinksHelper.bulkUpdate(staticLinksCSVData, req.userDetails); - - if (newStaticLinkData.length > 0) { - - const fileName = `StaticLink-Upload`; - let fileStream = new FileStream(fileName); - let input = fileStream.initStream(); - - (async function () { - await fileStream.getProcessorPromise(); - return resolve({ - isResponseAStream: true, - fileNameWithPath: fileStream.fileNameWithPath() - }); - }()); - - await Promise.all(newStaticLinkData.map(async staticLink => { - input.push(staticLink); - })) - - input.push(null); - - } else { - throw constants.apiResponses.SOMETHING_WENT_WRONG; - } - - } catch (error) { - - return reject({ - status: error.status || httpStatusCode.internal_server_error.status, - message: error.message || httpStatusCode.internal_server_error.message, - errorObject: error - }) - - } - - - }) - } - } \ No newline at end of file diff --git a/controllers/v1/user-extension.js b/controllers/v1/user-extension.js index dac17579..6de2add9 100644 --- a/controllers/v1/user-extension.js +++ b/controllers/v1/user-extension.js @@ -22,82 +22,6 @@ module.exports = class UserExtension extends Abstract { return "user-extension"; } - /** - * @api {post} /kendra/api/v1/user-extension/getProfile/{{userId}} Get user profile - * @apiVersion 1.0.0 - * @apiName Get user profile - * @apiGroup User Extension - * @apiHeader {String} X-authenticated-user-token Authenticity token - * @apiSampleRequest /kendra/api/v1/user-extension/getProfile/e97b5582-471c-4649-8401-3cc4249359bb - * @apiUse successBody - * @apiUse errorBody - * @apiParamExample {json} Response: - * { - * "_id": "5d5e4758f89df53a1d26b454", - "externalId": "a1", - "roles": [ - { - "_id": "5d5e47051f5a363a0a187029", - "code": "HM", - "title": "Headmaster", - "immediateSubEntityType": "school", - "entities": [ - { - "_id": "5bfe53ea1d0c350d61b78d0f", - "externalId": "1208138", - "name": "Shri Shiv Middle School, Shiv Kutti, Teliwara, Delhi", - "childrenCount": 0, - "entityType": "school", - "entityTypeId": "5ce23d633c330302e720e65f", - "subEntityGroups": [ - "parent" - ] - } - ] - } - ] - * } - */ - - /** - * Get profile of user. - * @method - * @name getProfile - * @param {Object} req - request data. - * @param {String} req.params._id - user id. - * @returns {JSON} User profile data. - */ - - getProfile(req) { - return new Promise(async (resolve, reject) => { - - try { - - let result = await userExtensionHelper.profileWithEntityDetails({ - userId: (req.params._id && req.params._id != "") ? req.params._id : req.userDetails.userId, - status: constants.common.ACTIVE, - isDeleted: false - },req.headers.appname); - - return resolve({ - message: constants.apiResponses.USER_EXTENSION_FETCHED, - result: result - }); - - } catch (error) { - - return reject({ - status: error.status || httpStatusCode.internal_server_error.status, - message: error.message || httpStatusCode.internal_server_error.message, - errorObject: error - }) - - } - - - }) - } - /** * @api {post} /kendra/api/v1/user-extension/update/{{userId}} Update user profile * @apiVersion 1.0.0 @@ -211,276 +135,6 @@ module.exports = class UserExtension extends Abstract { }) } - - /** - * @api {post} /kendra/api/v1/user-extension/updateProfileRoles/{{userId}} Update profile roles. - * @apiVersion 1.0.0 - * @apiName Update profile roles. - * @apiGroup User Extension - * @apiHeader {String} X-authenticated-user-token Authenticity token - * @apiSampleRequest /kendra/api/v1/user-extension/updateProfileRoles/8f6d6fd2-c069-41f1-b94d-ad2befcc964b - * @apiParamExample {json} Request-body: - * { - "stateId" : "5da829874c67d63cca1bd9d0", - "roles" : [{ - "_id" : "5d7a2d266371783ceb11064e", - "entities" : [ - "5da70ff64c67d63cca1b94e0" - ] - } - ] - } - * @apiUse successBody - * @apiUse errorBody - * @apiParamExample {json} Response: - * { - "message": "User extension updated successfully", - "status": 200, - "result": { - "_id": "5f587db299333547476e8f80", - "externalId": "a1", - "state": { - "_id": "5da829874c67d63cca1bd9d0", - "name": "Punjab" - }, - "roles": [ - { - "_id": "5d7a2d266371783ceb11064e", - "code": "SPD", - "title": "State Project Director", - "immediateSubEntityType": "school", - "entities": [ - { - "_id": "5da70ff64c67d63cca1b94e0", - "externalId": "3200100201", - "name": "PUNJAB GPS ASPAL KHURD", - "childrenCount": 0, - "entityType": "school", - "entityTypeId": "5d15a959e9185967a6d5e8a6", - "subEntityGroups": [], - "relatedEntities": [ - { - "_id": "5da829874c67d63cca1bd9d0", - "entityTypeId": "5d7a290e6371783ceb11064c", - "entityType": "state", - "metaInformation": { - "externalId": "PBS", - "name": "Punjab" - } - }, - { - "_id": "5da829a94c67d63cca1bd9d2", - "entityTypeId": "5d15a959e9185967a6d5e8ac", - "entityType": "district", - "metaInformation": { - "externalId": "BARNALA -3", - "name": "BARNALA" - } - }, - { - "_id": "5da829f64c67d63cca1bd9f1", - "entityTypeId": "5d15a959e9185967a6d5e8ab", - "entityType": "block", - "metaInformation": { - "externalId": "PJ-BARNALA", - "name": "BARNALA" - } - }, - { - "_id": "5da82a1c4c67d63cca1bdae8", - "entityTypeId": "5d15c4ec03cbf959ccabdd2b", - "entityType": "cluster", - "metaInformation": { - "externalId": "PJ-GPS KALEKE", - "name": "GPS KALEKE", - "city": "" - } - } - ] - } - ] - } - ] - } -} - */ - - /** - * Update profile roles. - * @method - * @name updateProfileRoles - * @param {Object} req - request data. - * @param {String} req.params._id - user id. - * @returns {JSON} Update profile roles. - */ - - updateProfileRoles(req) { - return new Promise(async (resolve, reject) => { - - try { - - const userExtensionData = - await userExtensionHelper.updateProfileRoles( - req.body, - req.params._id ? req.params._id : req.userDetails.userId, - req.userDetails.userName - ); - - return resolve(userExtensionData); - - } catch (error) { - - return reject({ - status: error.status || httpStatusCode.internal_server_error.status, - message: error.message || httpStatusCode.internal_server_error.message, - errorObject: error - }) - - } - - - }) - } - - - /** - * @api {get} /kendra/api/v1/user-extension/getEntities?entityType=school&page=1&limi=10&search=govt Get user entities. - * @apiVersion 1.0.0 - * @apiName Get user entities. - * @apiGroup User Extension - * @apiHeader {String} X-authenticated-user-token Authenticity token - * @apiSampleRequest /kendra/api/v1/user-extension/getEntities/?entityType=school&page=1&limi=10&search=govt - * @apiUse successBody - * @apiUse errorBody - * @apiParamExample {json} Response: - { - "message": "User entities fetched successfully.", - "status": 200, - "result": { - "data": [ - { - "_id": "5beaa888af0065f0e0a10515", - "name": "Apple School" - }, - { - "_id": "5bfe53ea1d0c350d61b78d0a", - "name": "Sachdeva Convent School, Street No.-5 Sangam Vihar (Wazirabad - Jagatpur Road), Delhi" - }, - { - "_id": "5bfe53ea1d0c350d61b78d0c", - "name": "Divyansh Public School, Kh.No.28/20 & 29/16/02 Sangam Vihar, Burari, Delhi" - }, - { - "_id": "5de6322c187dca40bbbd0aef", - "name": "gsspachelkalan" - } - ], - "count":4 -} -**/ - - /** - * Get user entities - * @method - * @name getEntities - * @param {Object} req - request data. - * @param {String} req.params._id - user id. - * @param {string} req.query.entityType - entity type - * @returns {JSON} User profile data. - */ - - getEntities(req) { - return new Promise(async (resolve, reject) => { - - try { - - let result = await userExtensionHelper.getEntities( - (req.params._id && req.params._id != "") ? req.params._id : req.userDetails.userId , - req.query.entityType ? req.query.entityType : "", - req.pageSize, - req.pageNo, - req.searchText - ); - - return resolve({ - message: constants.apiResponses.USER_ENTITIES_FOUND, - result: result - }); - - } catch (error) { - - return reject({ - status: error.status || httpStatusCode.internal_server_error.status, - message: error.message || httpStatusCode.internal_server_error.message, - errorObject: error - }) - - } - - - }) - } - - /** - * @api {get} /kendra/api/v1/user-extension/getEntityTypes Get user entity types. - * @apiVersion 1.0.0 - * @apiName Get user entity types - * @apiGroup User Extension - * @apiHeader {String} X-authenticated-user-token Authenticity token - * @apiSampleRequest /kendra/api/v1/user-extension/getEntityTypes - * @apiUse successBody - * @apiUse errorBody - * @apiParamExample {json} Response: - { - "message": "User entity types fetched successfully.", - "status": 200, - "result": [ - "school", - "smc", - "district" - ] -} -**/ - - - /** - * Get user entity types. - * @method - * @name getEntityTypes - * @param {Object} req - request data. - * @param {String} req.params._id - user id. - * @returns {JSON} User profile data. - */ - - getEntityTypes(req) { - return new Promise(async (resolve, reject) => { - - try { - - let result = await userExtensionHelper.getEntityTypes({ - userId: (req.params._id && req.params._id != "") ? req.params._id : req.userDetails.userId, - status: constants.common.ACTIVE, - isDeleted: false, - }); - - return resolve({ - message: constants.apiResponses.USER_ENTITY_TYPE_FOUND, - result: result - }); - - } catch (error) { - - return reject({ - status: error.status || httpStatusCode.internal_server_error.status, - message: error.message || httpStatusCode.internal_server_error.message, - errorObject: error - }) - - } - - - }) - } /** * @api {get} /kendra/api/v1/user-extension/programsByPlatformRoles?role=:role1,role2 List of programs for platform user diff --git a/controllers/v1/user-profile.js b/controllers/v1/user-profile.js index 8bf29d1a..acabd60a 100644 --- a/controllers/v1/user-profile.js +++ b/controllers/v1/user-profile.js @@ -23,199 +23,5 @@ module.exports = class UserProfile extends Abstract { return "user-profile"; } - /** - * @api {get} /kendra/api/v1/user-profile/getForm - * getForm return user profile form - * @apiVersion 1.0.0 - * @apiGroup user profile - * @apiHeader {String} X-authenticated-user-token Authenticity token - * @apiSampleRequest /kendra/api/v1/user-profile/getForm - * @apiUse successBody - * @apiUse errorBody - * @apiParamExample {json} Response: - * { - "message": "User Profile form fetched successfully ", - "status": 200, - "result": { - "form": [ - { - "label": "firstName", - "field": "firstName", - "value": "", - "visible": true, - "editable": true, - "validation": { - "required": true, - "regex": "/^[A-Za-z]+$/" - }, - "input": "text" - }, - { - "label": "lastName", - "field": "lastName", - "value": "", - "visible": true, - "editable": true, - "validation": { - "required": true, - "regex": "/^[A-Za-z]+$/" - }, - "input": "text" - }, - { - "label": "email", - "field": "email", - "value": "", - "visible": true, - "editable": true, - "validation": { - "required": true, - "regex": "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$" - }, - "input": "text" - }, - { - "label": "phoneNumber", - "field": "phoneNumber", - "value": "", - "visible": true, - "editable": true, - "validation": { - "required": true, - "regex": "^((+)?(d{2}[-]))?(d{10}){1}?$" - }, - "input": "text" - }, - { - "label": "state", - "field": "state", - "value": "", - "visible": true, - "editable": true, - "validation": { - "required": true, - "regex": "" - }, - "input": "select", - "options": [ - { - "label": "", - "value": "" - } - ] - } - ], - "statesWithSubEntities": { - "5da829874c67d63cca1bd9d0": [ - "district", - "block", - "cluster", - "school" - ] - } - } - } - */ - - getForm(req) { - return new Promise(async (resolve, reject) => { - - try { - - let userProfileForm = await userProfileHelper.getForm( - req.userDetails, - req.headers['appname'], - req.headers['os'] - ); - - resolve(userProfileForm); - - } catch (error) { - - return reject({ - status: - error.status || - httpStatusCode["internal_server_error"].status, - - message: - error.message || - httpStatusCode["internal_server_error"].message - }); - } - }); - } - - /** - * @api {post} /kendra/api/v1/user-profile/save - * save's the user profile data - * @apiVersion 1.0.0 - * @apiGroup user profile - * @apiHeader {String} X-authenticated-user-token Authenticity token - * @apiSampleRequest /kendra/api/v1/user-profile/save - * @apiUse successBody - * @apiUse errorBody - * @apiParamExample {json} Request: - * { - * "data":{ - * "firstName": "", - * "lastName": "", - * "email": "", - * "phoneNumber": "", - * "district":[{ - * "label":"name", - * "value":"id" - * }] - * } - * @apiParamExample {json} Response: - * { - "message": "User profile Saved successfully", - "status": 200, - "result": { - "data" : { - "firstName" : "A", - "lastName" : "B", - "email" : "a@b.com", - "phoneNumber" : "9591553529", - "district" : [ - { - "label": "name", - "value": "id" - } - ] - } - } - } -} - */ - - save(req) { - return new Promise(async (resolve, reject) => { - - try { - - let userProfileSave = - await userProfileHelper.save( - req.body.data, - req.userDetails.userId, - req.userDetails.userName ? req.userDetails.userName : "" - ); - - resolve( userProfileSave); - - } catch (error) { - - return reject({ - status: - error.status || - httpStatusCode["internal_server_error"].status, - - message: - error.message || - httpStatusCode["internal_server_error"].message - }); - } - }); - } - }; diff --git a/controllers/v1/users.js b/controllers/v1/users.js index 0295b129..99c362be 100644 --- a/controllers/v1/users.js +++ b/controllers/v1/users.js @@ -40,114 +40,6 @@ module.exports = class Users extends Abstract { return "users"; } - /** - * @api {post} /kendra/api/v1/users/create - * create user - * @apiVersion 1.0.0 - * @apiGroup Users - * @apiHeader {String} X-authenticated-user-token Authenticity token - * @apiSampleRequest /kendra/api/v1/users/create - * @apiUse successBody - * @apiUse errorBody - * @apiParamExample {json} Request: - * { - "userName": "a", - "email": "a@a.com", - "role": "SYS_ADMIN", - "createdBy": "SYSTEM", - } - - */ - - /** - * Check whether the email id provided is sys admin or not. - * @method - * @name create - * @param {Request} req request body. - * @returns {JSON} Returns success as true or false. - */ - - create(req) { - - return new Promise(async (resolve, reject) => { - - try { - - let systemAdminDocument = - await usersHelper.create(req.body); - - return resolve(systemAdminDocument); - - } catch (error) { - - return reject({ - status: - error.status || - httpStatusCode["internal_server_error"].status, - - message: - error.message || - httpStatusCode["internal_server_error"].message - }) - - } - - - }) - } - - /** - * @api {post} /kendra/api/v1/users/isSystemAdmin - * check if user is system admin or not. - * @apiVersion 1.0.0 - * @apiGroup Users - * @apiHeader {String} X-authenticated-user-token Authenticity token - * @apiSampleRequest /kendra/api/v1/users/isSystemAdmin - * @apiUse successBody - * @apiUse errorBody - * @apiParamExample {json} Request: - * { - * "email":"a@gmail.com" - } - */ - - /** - * Check whether the email id provided is sys admin or not. - * @method - * @name isSystemAdmin - * @param {Request} req request body. - * @returns {JSON} Returns success as true or false. - */ - - isSystemAdmin(req) { - - return new Promise(async (resolve, reject) => { - - try { - - let systemAdminDocument = - await usersHelper.isSystemAdmin(req.body.email); - - return resolve(systemAdminDocument); - - } catch (error) { - - return reject({ - status: - error.status || - httpStatusCode["internal_server_error"].status, - - message: - error.message || - httpStatusCode["internal_server_error"].message - }) - - } - - - }) - } - /** * @api {get} /kendra/api/v1/users/privatePrograms/:userId List of user private programs * @apiVersion 2.0.0 @@ -318,149 +210,6 @@ module.exports = class Users extends Abstract { }); } - /** - * @api {get} /kendra/api/v1/users/entitiesMappingForm/:stateId?roleId=:roleId - * Entities mapping form. - * @apiVersion 1.0.0 - * @apiGroup Users - * @apiHeader {String} X-authenticated-user-token Authenticity token - * @apiSampleRequest /kendra/api/v1/users/entitiesMappingForm/5da829874c67d63cca1bd9d0?roleId=5d6e521066a9a45df3aa891e - * @apiUse successBody - * @apiUse errorBody - * @apiParamExample {json} Response: - * { - "message": "Entities mapping form fetched successfully", - "status": 200, - "result": [ - { - "field": "district", - "label": "Select District", - "value": "", - "visible": true, - "editable": true, - "input": "text", - "validation": { - "required": false - } - }, - { - "field": "block", - "label": "Select Block", - "value": "", - "visible": true, - "editable": true, - "input": "text", - "validation": { - "required": true - } - }]} - */ - - /** - * Lists of entities mapping form - * @method - * @name entitiesMappingForm - * @param {Request} req request body. - * @returns {JSON} List of entiites mapping form. - */ - - entitiesMappingForm(req) { - - return new Promise(async (resolve, reject) => { - - try { - - const entitiesMappingData = - await usersHelper.entitiesMappingForm( - req.params._id, - req.query.roleId - ); - - resolve(entitiesMappingData); - - } catch (error) { - - return reject({ - status: - error.status || - httpStatusCode["internal_server_error"].status, - - message: - error.message || - httpStatusCode["internal_server_error"].message - }) - - } - - - }) - } - - /** - * @api {get} /kendra/api/v1/users/getUserOrganisationsAndRootOrganisations - * Get organisation and root organisation - * @apiVersion 1.0.0 - * @apiGroup Users - * @apiHeader {String} X-authenticated-user-token Authenticity token - * @apiSampleRequest /kendra/api/v1/users/getUserOrganisationsAndRootOrganisations - * @apiUse successBody - * @apiUse errorBody - * @apiParamExample {json} Response: - * { - "message": "User organisations fetched successfully", - "status": 200, - "result": { - "createdFor": [ - "01305447637218918413" - ], - "rootOrganisations": [ - "01305447637218918413" - ] - } - } - */ - - /** - * Organisations and root organisations. - * @method - * @name getUserOrganisationsAndRootOrganisations - * @param {Request} req request body. - * @returns {JSON} Organisations and root organisations of user. - */ - - getUserOrganisationsAndRootOrganisations(req) { - - return new Promise(async (resolve, reject) => { - - try { - - const userOrganisations = - await usersHelper.getUserOrganisationsAndRootOrganisations( - (req.params._id && req.params._id != "") ? - req.params._id : - req.userDetails.id, - req.userDetails.userToken - ); - - resolve(userOrganisations); - - } catch (error) { - - return reject({ - status: - error.status || - httpStatusCode["internal_server_error"].status, - - message: - error.message || - httpStatusCode["internal_server_error"].message - }) - - } - - - }) - } /** * @api {post} /kendra/api/v1/users/solutions/:programId?page=:page&limit=:limit&search=:searchText diff --git a/module/entities/helper.js b/module/entities/helper.js index 7797e42d..6d982e4c 100644 --- a/module/entities/helper.js +++ b/module/entities/helper.js @@ -540,41 +540,6 @@ module.exports = class EntitiesHelper { }); } - /** - * Sub entity type list. - * @method - * @name subEntityTypeList - * @param entityId - entity id. - * @returns {Array} List of sub entity type. - */ - - static subEntityTypeList( entityId ) { - return new Promise(async (resolve, reject) => { - try { - - const entityDocuments = await this.entityDocuments({ - _id : entityId - },["childHierarchyPath"]); - - if( !entityDocuments.length > 0 ) { - return resolve({ - message : constants.apiResponses.ENTITY_NOT_FOUND, - result : [] - }) - } - - return resolve({ - message : constants.apiResponses.ENTITIES_CHILD_HIERACHY_PATH, - result : entityDocuments[0].childHierarchyPath - }); - - } catch (error) { - return reject(error); - } - }) - - } - /** * Get users by entityId and role * @method diff --git a/module/entities/validator/v1.js b/module/entities/validator/v1.js index 8088ab7b..0c6210ec 100644 --- a/module/entities/validator/v1.js +++ b/module/entities/validator/v1.js @@ -14,11 +14,6 @@ module.exports = (req) => { entitiesValidation(entities) ).withMessage("invalid entity ids"); }, - subEntityTypeList : function () { - req.checkParams('_id') - .exists() - .withMessage("required Entity id"); - }, getUsersByEntityAndRole: function () { req.checkParams('_id').exists().withMessage("required entity id") .isMongoId().withMessage("Invalid entity id"); diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 0b00a3dc..b7abf024 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -1409,80 +1409,6 @@ module.exports = class SolutionsHelper { } }) } - - /** - * Targeted entity in solution - * @method - * @name targetedEntity - * @param {String} solutionId - solution Id. - * @param {Object} requestedData - requested data - * @returns {Object} - Details of the solution. - */ - - static targetedEntity( solutionId,requestedData ) { - return new Promise(async (resolve, reject) => { - try { - - let solutionData = - await this.solutionDocuments({ - _id : solutionId, - isDeleted : false - },["entityType","type"]); - - if( !solutionData.length > 0 ) { - return resolve({ - status : httpStatusCode.bad_request.status, - message : constants.apiResponses.SOLUTION_NOT_FOUND - }); - } - - if( !requestedData[ solutionData[0].entityType ] ) { - return resolve({ - status : httpStatusCode.bad_request.status, - message : constants.apiResponses.SOLUTION_ENTITY_TYPE_NOT_FOUND - }); - } - - let filterQuery = { - "registryDetails.code" : requestedData[solutionData[0].entityType] - }; - - if( gen.utils.checkValidUUID( requestedData[solutionData[0].entityType] ) ) { - filterQuery = { - "registryDetails.locationId" : requestedData[solutionData[0].entityType] - }; - } - - let entities = await entitiesHelper.entityDocuments(filterQuery,["metaInformation.name","entityType"]) - - if( !entities.length > 0 ) { - throw { - message : constants.apiResponses.ENTITY_NOT_FOUND - } - } - - if( entities[0].metaInformation && entities[0].metaInformation.name ) { - entities[0]["entityName"] = entities[0].metaInformation.name; - delete entities[0].metaInformation; - } - - return resolve({ - message : constants.apiResponses.SOLUTION_TARGETED_ENTITY, - success : true, - data : entities[0] - }); - - } catch(error) { - return resolve({ - success : false, - status : error.status ? - error.status : httpStatusCode['internal_server_error'].status, - message : error.message - }) - } - }) - } - }; /** diff --git a/module/solutions/validator/v1.js b/module/solutions/validator/v1.js index 6b3e61d6..fe3e7fef 100644 --- a/module/solutions/validator/v1.js +++ b/module/solutions/validator/v1.js @@ -46,9 +46,6 @@ module.exports = (req) => { }, getSolutions : function () { req.checkQuery("type").exists().withMessage("required solution type") - }, - targetedEntity : function () { - req.checkParams("_id").exists().withMessage("required solution id"); } } diff --git a/module/static-links/helper.js b/module/static-links/helper.js index d6215a26..6da58a4d 100644 --- a/module/static-links/helper.js +++ b/module/static-links/helper.js @@ -57,206 +57,5 @@ module.exports = class StaticLinksHelper { } - /** - * List static links. - * @method - * @name list - * @param {String} [appType = "" ] - app type. - * @param {String} [appname = "" ] - name of app. - * @returns {Array} List of static links data. - */ - - static list(appType = "", appname = "") { - return new Promise(async (resolve, reject) => { - try { - - let appSpecificQuery = { - status: constants.common.ACTIVE, - isDeleted: false - }; - - if (appType && appType !== "") { - appSpecificQuery["appType"] = appType; - } - - let commonSpecificQuery = { ...appSpecificQuery }; - - if (appname && appname !== "") { - appSpecificQuery["appName"] = appname; - } - - let projection = ["value", "link", "title", "metaInformation"]; - let appSpecificStaticLinks = []; - - - if (appSpecificQuery.appType && appSpecificQuery.appName) { - appSpecificStaticLinks = - await this.staticLinksDocuments(appSpecificQuery, projection); - } - - if (appSpecificStaticLinks.length > 0) { - - let appSpecificValue = []; - - appSpecificStaticLinks.forEach(staticLink => { - appSpecificValue.push(staticLink.value); - }); - - commonSpecificQuery["value"] = { $nin: appSpecificValue }; - } - - commonSpecificQuery.isCommon = true; - - let commonStaticLinks = - await this.staticLinksDocuments(commonSpecificQuery, projection); - - let result = {}; - - appSpecificStaticLinks = _.keyBy(appSpecificStaticLinks, 'value'); - commonStaticLinks = _.keyBy(commonStaticLinks, "value"); - result = { ...appSpecificStaticLinks, ...commonStaticLinks }; - - return resolve({ - message: constants.apiResponses.STATIC_LINKS_FETCHED, - result: result - }); - - } catch (error) { - return reject(error); - } - }) - - - } - - /** - * Bulk create static links. - * @method - * @name bulkCreate - * @param {Object} staticLinksCSVData - array of static links - * @param {Object} userDetails - logged in user data. - * @param {String} userDetails.id - logged in user id. - * @returns {Array} List of static links with _SYSTEM_ID. - */ - - static bulkCreate(staticLinksCSVData, userDetails) { - - return new Promise(async (resolve, reject) => { - try { - - const staticLinksUploadedData = await Promise.all( - staticLinksCSVData.map(async staticLink => { - - - try { - - let newLink = await database.models.staticLinks.create( - _.merge({ - "status": "active", - "updatedBy": userDetails.id, - "createdBy": userDetails.id - }, gen.utils.valueParser(staticLink)) - ); - - if (newLink._id) { - staticLink["_SYSTEM_ID"] = newLink._id; - staticLink.status = "Success"; - } else { - staticLink["_SYSTEM_ID"] = ""; - staticLink.status = "Failed"; - } - - } catch (error) { - staticLink["_SYSTEM_ID"] = ""; - staticLink.status = error.message; - } - - - return staticLink; - }) - ) - - - return resolve(staticLinksUploadedData); - - } catch (error) { - return reject(error) - } - }) - - } - - /** - * Bulk update static links. - * @method - * @name bulkUpdate - * @param {Object} staticLinksCSVData - array of static links - * @param {Object} userDetails - logged in user data. - * @param {String} userDetails.id - logged in user id. - * @returns {Array} List of static links with _SYSTEM_ID. - */ - - static bulkUpdate(staticLinksCSVData, userDetails) { - - return new Promise(async (resolve, reject) => { - try { - - const staticLinksUploadedData = await Promise.all( - staticLinksCSVData.map(async staticLink => { - - try { - - let updatedData = - _.merge({ - "updatedBy": userDetails.id - }, gen.utils.valueParser(staticLink)); - - let unSetData = {}; - - if (staticLink.appName && staticLink.appName !== "") { - updatedData["isCommon"] = false; - } else { - updatedData["isCommon"] = true; - unSetData["appName"] = 1; - } - - let updateLink = await database.models.staticLinks.findOneAndUpdate( - { - _id: staticLink._SYSTEM_ID - }, - { - "$unset": unSetData, - "$set": _.omit(updatedData, ["_SYSTEM_ID"]) - } - ); - - if (updateLink._id) { - staticLink["_SYSTEM_ID"] = updateLink._id; - staticLink.status = "Success"; - } else { - staticLink["_SYSTEM_ID"] = ""; - staticLink.status = "Failed"; - } - - } catch (error) { - staticLink["_SYSTEM_ID"] = ""; - staticLink.status = error.message; - } - - - return staticLink; - }) - ) - - - return resolve(staticLinksUploadedData); - - } catch (error) { - return reject(error); - } - }) - - } - } \ No newline at end of file diff --git a/module/static-links/validator/v1.js b/module/static-links/validator/v1.js index d2af8004..27caa984 100644 --- a/module/static-links/validator/v1.js +++ b/module/static-links/validator/v1.js @@ -8,11 +8,6 @@ module.exports = (req) => { let staticLinksValidator = { - list: function () { - req.checkHeaders('apptype').exists().withMessage("required app type") - } - - } if (staticLinksValidator[req.params.method]) { diff --git a/module/user-extension/helper.js b/module/user-extension/helper.js index 4c9f80b0..d5d9f509 100644 --- a/module/user-extension/helper.js +++ b/module/user-extension/helper.js @@ -187,219 +187,6 @@ module.exports = class UserExtensionHelper { }) } - /** - * Get profile with entity details - * @method - * @name profileWithEntityDetails - * @param {Object} filterQueryObject - filtered data. - * @returns {Object} - */ - - static profileWithEntityDetails(filterQueryObject, appName) { - return new Promise(async (resolve, reject) => { - try { - - const entityTypesArray = await entityTypesHelper.entityTypesDocument( - "all", - [ - "name", - "immediateChildrenEntityType" - ] - ); - - let enityTypeToImmediateChildrenEntityMap = {}; - - if (entityTypesArray.length > 0) { - entityTypesArray.forEach(entityType => { - enityTypeToImmediateChildrenEntityMap[entityType.name] = (entityType.immediateChildrenEntityType && entityType.immediateChildrenEntityType.length > 0) ? entityType.immediateChildrenEntityType : []; - }) - } - - let queryObject = [ - { - $match: filterQueryObject - }, - { - $lookup: { - "from": "entities", - "localField": "roles.entities", - "foreignField": "_id", - "as": "entityDocuments" - } - }, - { - $lookup: { - "from": "userRoles", - "localField": "roles.roleId", - "foreignField": "_id", - "as": "roleDocuments" - } - }, - { - $project: { - "externalId": 1, - "roles": 1, - "roleDocuments._id": 1, - "roleDocuments.code": 1, - "roleDocuments.title": 1, - "entityDocuments._id": 1, - "entityDocuments.metaInformation.externalId": 1, - "entityDocuments.metaInformation.name": 1, - "entityDocuments.groups": 1, - "entityDocuments.entityType": 1, - "entityDocuments.entityTypeId": 1, - "ratings": 1 - } - } - ]; - - let userExtensionData = - await database.models.userExtension.aggregate(queryObject); - let relatedEntities = []; - - if (userExtensionData[0]) { - - let roleMap = {}; - - if (userExtensionData[0].entityDocuments && userExtensionData[0].entityDocuments.length > 0) { - - let projection = [ - "metaInformation.externalId", - "metaInformation.name", - "metaInformation.addressLine1", - "metaInformation.addressLine2", - "metaInformation.administration", - "metaInformation.city", - "metaInformation.country", - "entityTypeId", - "entityType" - ]; - - relatedEntities = - await entitiesHelper.relatedEntities( - userExtensionData[0].entityDocuments[0]._id, - userExtensionData[0].entityDocuments[0].entityTypeId, - userExtensionData[0].entityDocuments[0].entityType, - projection - ); - - } - - // <- Dirty fix. Profile update for only Goa state. - // In future can be removed if required for all state. - - let goaStateExists = false; - let goaState = constants.common.GOA_STATE.toUpperCase(); - - if (relatedEntities.length > 0) { - - let checkGoaStateExistsOrNot = relatedEntities.some( - entity => entity.metaInformation.name.toUpperCase() === goaState - ); - - if ( - checkGoaStateExistsOrNot && - appName === constants.common.UNNATI_APP_NAME - ) { - goaStateExists = true; - } - - } - - if (userExtensionData[0].roleDocuments && userExtensionData[0].roleDocuments.length > 0) { - - userExtensionData[0].roleDocuments.forEach(role => { - roleMap[role._id.toString()] = role; - }) - let entityMap = {}; - - if (userExtensionData[0].entityDocuments && userExtensionData[0].entityDocuments.length > 0) { - - userExtensionData[0].entityDocuments.forEach(entity => { - entity.metaInformation.childrenCount = 0; - entity.metaInformation.entityType = entity.entityType; - entity.metaInformation.entityTypeId = entity.entityTypeId; - entity.metaInformation.subEntityGroups = new Array; - - Array.isArray(enityTypeToImmediateChildrenEntityMap[entity.entityType]) && enityTypeToImmediateChildrenEntityMap[entity.entityType].forEach(immediateChildrenEntityType => { - if (entity.groups && entity.groups[immediateChildrenEntityType]) { - entity.metaInformation.immediateSubEntityType = immediateChildrenEntityType; - entity.metaInformation.childrenCount = entity.groups[immediateChildrenEntityType].length; - } - }) - - entity.groups && Array.isArray(Object.keys(entity.groups)) && Object.keys(entity.groups).forEach(subEntityType => { - entity.metaInformation.subEntityGroups.push(subEntityType); - }) - - // <- Dirty fix. Profile update for only Goa state. - // In future can be removed if required for all state. - - if ( - appName === constants.common.UNNATI_APP_NAME && - entity.metaInformation.name.toUpperCase() === goaState - ) { - goaStateExists = true; - } - - entityMap[entity._id.toString()] = entity; - }) - } - - for (let userExtensionRoleCounter = 0; userExtensionRoleCounter < userExtensionData[0].roles.length; userExtensionRoleCounter++) { - for (let userExtenionRoleEntityCounter = 0; userExtenionRoleEntityCounter < userExtensionData[0].roles[userExtensionRoleCounter].entities.length; userExtenionRoleEntityCounter++) { - userExtensionData[0].roles[userExtensionRoleCounter].entities[userExtenionRoleEntityCounter] = { - _id: entityMap[userExtensionData[0].roles[userExtensionRoleCounter].entities[userExtenionRoleEntityCounter].toString()]._id, - ...entityMap[userExtensionData[0].roles[userExtensionRoleCounter].entities[userExtenionRoleEntityCounter].toString()].metaInformation - }; - } - roleMap[userExtensionData[0].roles[userExtensionRoleCounter].roleId.toString()].immediateSubEntityType = (userExtensionData[0].roles[userExtensionRoleCounter].entities[0] && userExtensionData[0].roles[userExtensionRoleCounter].entities[0].entityType) ? userExtensionData[0].roles[userExtensionRoleCounter].entities[0].entityType : ""; - roleMap[userExtensionData[0].roles[userExtensionRoleCounter].roleId.toString()].entities = userExtensionData[0].roles[userExtensionRoleCounter].entities; - } - } - - let showPopupForm = false; - let userProfile = await database.models.userProfile.findOne( - { - userId: filterQueryObject.userId, - status: { - $in: [ - constants.common.USER_PROFILE_VERIFIED_STATUS, - constants.common.USER_PROFILE_PENDING_STATUS - ] - } - }, { _id: 1, status: 1 }).lean(); - - if (userProfile == null) { - showPopupForm = true - } - - return resolve( - _.merge(_.omit( - userExtensionData[0], - ["roles", "entityDocuments", "roleDocuments"] - ), - { roles: _.isEmpty(roleMap) ? [] : Object.values(roleMap) }, - { relatedEntities: relatedEntities }, - { - allowProfileUpdateForm: goaStateExists - }, { - showPopupForm: goaStateExists && showPopupForm ? true : false - } - ) - ); - } else { - return resolve({ - status: httpStatusCode['bad_request'].status, - message: constants.apiResponses.USER_EXTENSION_NOT_FOUND - }); - } - } catch (error) { - return reject(error); - } - }) - } - /** * Update user profile data. * @method @@ -431,159 +218,6 @@ module.exports = class UserExtensionHelper { }); } - /** - * Update profile roles - * @method - * @name updateProfileRoles - * @param {Object} requestedData - requested data. - * @param {String} userId - Logged in user id. - * @param {String} userName - Logged in user name. - * @returns {Object} - */ - - static updateProfileRoles(requestedData, userId, userName) { - - return new Promise(async (resolve, reject) => { - try { - - const userExtensionData = await this.userExtensionDocument({ - userId: userId - }, { - "roles": 1, - "createdBy": 1, - "externalId": 1 - }); - - if ( - userExtensionData && - userExtensionData.roles && userExtensionData.roles.length > 0 - ) { - return resolve({ - message: constants.apiResponses.USER_DATA_EXISTS, - result: [] - }) - } - - const entityData = await entitiesHelper.entityDocuments({ - _id: requestedData.stateId - }, ["_id", "metaInformation.name"]); - - if (!entityData.length > 0) { - return resolve({ - message: constants.apiResponses.STATE_NOT_FOUND, - result: [] - }) - } - - requestedData["state"] = { - _id: ObjectId(requestedData.stateId), - name: entityData[0].metaInformation.name - } - - for ( - let pointerToRole = 0; - pointerToRole < requestedData.roles.length; - pointerToRole++ - ) { - - const rolesData = - await userRolesHelper.roleDocuments( - { - _id: requestedData.roles[pointerToRole]._id - }, [ - "code", - "entityTypes" - ] - ); - - if (!rolesData.length > 0) { - return resolve({ - message: constants.apiResponses.USER_ROLES_NOT_FOUND, - result: [] - }); - } - - let entityTypes = rolesData[0].entityTypes.map(roleData => { - return roleData.entityType; - }) - - let entities = []; - - if ( !requestedData.roles[pointerToRole].entities || (requestedData.roles[pointerToRole].entities && requestedData.roles[pointerToRole].entities.length == 0 )) { - entities.push(requestedData.stateId); - } - - if (requestedData.roles[pointerToRole].entities && requestedData.roles[pointerToRole].entities.length > 0) { - const entitiesData = await entitiesHelper.entityDocuments({ - _id: { $in: requestedData.roles[pointerToRole].entities }, - entityType: { $in: entityTypes } - }, ["_id"]); - - if (entitiesData.length > 0) { - - entities = entitiesData.map(entity => { - return entity._id - }); - } - } - - requestedData.roles[pointerToRole].roleId = rolesData[0]._id; - requestedData.roles[pointerToRole].code = rolesData[0].code; - requestedData.roles[pointerToRole].entities = entities; - - delete requestedData.roles[pointerToRole]._id; - } - - if (!userExtensionData) { - - requestedData.userId = userId; - requestedData.createdBy = - userExtensionData && userExtensionData.createdBy ? - userExtensionData.createdBy : userId; - - requestedData.status = constants.common.ACTIVE; - requestedData.externalId = - userExtensionData && userExtensionData.externalId ? - userExtensionData.externalId : userName; - - requestedData.isDeleted = false; - } - - requestedData.updatedBy = userId; - - await database.models.userExtension.findOneAndUpdate({ - userId: userId - }, { - $set: requestedData - }, { - upsert: true, - new: true - }); - - const responseData = await this.profileWithEntityDetailsV2({ - userId: userId, - status: constants.common.ACTIVE, - isDeleted: false - }); - - //update user role in elasticsearch - if (requestedData.roles.length > 0) { - await this.updateUserRolesInEntitiesElasticSearch(userId, requestedData.roles); - } - - await this.pushUserToElasticSearch(userId); - - resolve({ - message: constants.apiResponses.USER_EXTENSION_UPDATED, - result: responseData.result - }); - - } catch (error) { - return reject(error); - } - }) - } - /** * Get profile with entity details * @method @@ -764,151 +398,6 @@ module.exports = class UserExtensionHelper { }) } - /** - * Get profile with entity details - * @method - * @name getEntities - * @param {Object} userId - Logged in user id. - * @param {String} entityType - entity type - * @param {String} pageSize - Size of page. - * @param {String} pageNo - Recent page no. - * @param {String} search - search text. - * @returns {Object} - */ - - static getEntities(userId, entityType, pageSize, pageNo, searchText) { - return new Promise(async (resolve, reject) => { - try { - - let filterQueryObject = { - userId : userId, - status: constants.common.ACTIVE, - isDeleted: false - } - - if (searchText !== "") { - filterQueryObject["$or"] = [ - { "entityDocuments.metaInformation.name": new RegExp(searchText, 'i') }, - ]; - } - if (entityType) { - filterQueryObject['entityDocuments.entityType'] = entityType; - } - let queryObject = [ - { - $lookup: { - "from": "entities", - "localField": "roles.entities", - "foreignField": "_id", - "as": "entityDocuments" - } - }, - { - $unwind: "$entityDocuments" - }, - { - $match: filterQueryObject - }, - { - $facet: { - "totalCount": [ - { "$count": "count" } - ], - "data": [ - { $skip: pageSize * (pageNo - 1) }, - { $limit: pageSize } - ], - } - }, { - $project: { - "data": 1, - "count": { - $arrayElemAt: ["$totalCount.count", 0] - } - } - } - ]; - - let userExtensionData = - await database.models.userExtension.aggregate(queryObject); - - - let entityDocuments = []; - if (userExtensionData[0]) { - userExtensionData[0].data.forEach(entity => { - entityDocuments.push({ - _id: entity.entityDocuments._id, - name: entity.entityDocuments.metaInformation.name, - }); - }); - return resolve({ data: entityDocuments, count: userExtensionData[0].count }) - - } else { - return resolve({ - status: httpStatusCode['bad_request'].status, - message: constants.apiResponses.USER_ENTITIES_NOT_FOUND - }); - } - } catch (error) { - return reject(error); - } - }) - } - - /** - * Get user entity types - * @method - * @name getEntityTypes - * @param {Object} filterQueryObject - filtered data. - * @returns {Object} - */ - - static getEntityTypes(filterQueryObject) { - return new Promise(async (resolve, reject) => { - try { - - let entityTypes = []; - let queryObject = [ - { - $lookup: { - "from": "entities", - "localField": "roles.entities", - "foreignField": "_id", - "as": "entityDocuments" - } - }, - { - $match: filterQueryObject - } - ]; - - let userExtensionData = - await database.models.userExtension.aggregate(queryObject); - - if (userExtensionData[0]) { - - if (userExtensionData[0].entityDocuments && userExtensionData[0].entityDocuments.length > 0) { - - userExtensionData[0].entityDocuments.forEach(entity => { - if (entity.entityType && !entityTypes.includes(entity.entityType)) { - entityTypes.push(entity.entityType); - } - }); - } - return resolve(entityTypes) - - } else { - return resolve({ - status: httpStatusCode['bad_request'].status, - message: constants.apiResponses.USER_ENTITY_TYPE_NOT_FOUND - }); - } - } catch (error) { - return reject(error); - } - }) - } - /** * Update user roles in entities elastic search * @method diff --git a/module/user-extension/validator/v1.js b/module/user-extension/validator/v1.js index d9b6be9f..7eedcbdb 100644 --- a/module/user-extension/validator/v1.js +++ b/module/user-extension/validator/v1.js @@ -8,10 +8,6 @@ module.exports = (req) => { let userExtensionValidator = { - updateProfileRoles : function () { - req.checkBody('stateId').exists().withMessage("State id is required"); - req.checkBody('roles').exists().withMessage("Roles data is required"); - }, solutions: function () { req.checkParams('_id').exists().withMessage('Required program id'); } diff --git a/module/user-profile/helper.js b/module/user-profile/helper.js index 9c18712f..f32c75b6 100644 --- a/module/user-profile/helper.js +++ b/module/user-profile/helper.js @@ -39,201 +39,6 @@ module.exports = class UserProfileHelper { } - /** - * Get user profile form data. - * @method - * @name getForm - * @returns {json} Response consists of user form data. - */ - - static getForm(loggedInUser, appName = "", device = "") { - return new Promise(async (resolve, reject) => { - try { - - let formData = await formsHelper.formsDocument({ - name: constants.common.USER_PROFILE_FORM_NAME - }); - - if( !formData[0] ) { - return reject({ - message : - constants.apiResponses.COULD_NOT_GET_FORM - }); - } - - let name = appName + "." + device; - let userProfileScreenVisitedTrack = { - [name] : true - }; - - let userExtensionData = - await database.models.userExtension.findOne( - { - userId: loggedInUser.userId - },{ - userProfileScreenVisitedTrack: 1 - }).lean(); - - if ( userExtensionData ) { - let updateData = {}; - - if ( userExtensionData.userProfileScreenVisitedTrack ) { - updateData = userExtensionData.userProfileScreenVisitedTrack; - updateData[name] = true; - } else { - updateData = userProfileScreenVisitedTrack; - } - - database.models.userExtension.findOneAndUpdate( - { - userId: loggedInUser.userId - }, { - "$set": { userProfileScreenVisitedTrack: updateData } - } - ); - } - - let states = - await entitiesHelper.entityDocuments( - { - entityType: constants.common.STATE_ENTITY_TYPE - },[ - "entityTypeId", - "metaInformation.name", - "groups", - "childHierarchyPath" - ] - ); - - let statesInformation = []; - let childHierarchyForState = {}; - - await Promise.all(states.map(async function (state) { - - if ( state.groups && Object.keys(state.groups).length > 0) { - - let stateWithSubEntity = - await _checkStateWithSubEntities( - state.groups, - state.entityTypeId - ); - - if ( stateWithSubEntity ) { - childHierarchyForState[state._id] = - state.childHierarchyPath; - } - } - - statesInformation.push({ - label: state.metaInformation.name, - value: state._id - }); - })); - - let userData = await this.list( { - userId : loggedInUser.userId, - deleted : false - }, { - metaInformation: 1, - _id: 1, - status : 1 - }); - - if ( userData.length < 1 ) { - let userProfileCreated = await this.create( - loggedInUser - ); - - userData = userProfileCreated; - } - - let canSubmit = true; - - if( Array.isArray(userData) && userData.length > 0 ) { - - let verifiedUserProfile = userData.find( - user=>user.status === - constants.common.USER_PROFILE_VERIFIED_STATUS - ); - - let pendingUserProfile = userData.find( - user=>user.status === - constants.common.USER_PROFILE_PENDING_STATUS - ); - - if( verifiedUserProfile ) { - userData = verifiedUserProfile; - - if( pendingUserProfile ) { - canSubmit = false; - } - - } else if(pendingUserProfile) { - userData = pendingUserProfile; - canSubmit = false; - } else { - userData = userData[0]; - } - } - - if( ! _.isEmpty(userData.metaInformation.state)) { - - let entitiesSequence = - childHierarchyForState[userData.metaInformation.state.value.toString()]; - - entitiesSequence.forEach(entitySequence=>{ - - let entityData = userData.metaInformation[entitySequence]; - - if( entityData ) { - - let form = { ...formData[0].value[0] }; - form.label = - entitySequence.charAt(0).toUpperCase() + entitySequence.slice(1); - - form.editable = canSubmit ? canSubmit : false; - form.field = entitySequence; - form.input = "multiselect"; - form.value = entityData; - form.validation = {}; - formData[0].value.push(form); - } - - }) - } - - formData[0].value.forEach(form=>{ - - if( form.field == "state" ) { - - form["options"] = states.map(state=>{ - return { - label : state.metaInformation.name, - value : state._id, - } - }); - } - - form.editable = canSubmit ? canSubmit : false; - form.value = - userData.metaInformation[form.field] ? - userData.metaInformation[form.field] : ""; - }) - - return resolve({ - result : { - form: formData[0].value, - statesWithSubEntities: childHierarchyForState, - canSubmit : canSubmit - }, - message : constants.apiResponses.FORM_FETCH - }); - } catch (error) { - return reject(error); - } - }); - } - /** * Create userProfile * @method @@ -371,118 +176,6 @@ module.exports = class UserProfileHelper { } - /* - * save user profile data. - * @method - * @name save - * @return {json} Response consists of saved user profile data. - */ - - static save( metaInformationData, userId,externalId ) { - return new Promise(async (resolve, reject) => { - try { - - let userProfileData = await this.list({ - userId: userId, - status : - constants.common.USER_PROFILE_PENDING_VERIFICATION_STATUS - },{ - status: 1, - _id: 1 - }); - - if( userProfileData && userProfileData[0] ) { - return resolve({ - message : - constants.apiResponses.PROFILE_UNDER_PENDING_VERIFICATION - }); - } - - - let updateUserProfileData = { - updatedBy : userId, - status : - constants.common.USER_PROFILE_PENDING_VERIFICATION_STATUS, - submittedAt : new Date() - } - - Object.keys(metaInformationData).forEach(metaDataKey=>{ - - if( Array.isArray(metaInformationData[metaDataKey]) && - metaInformationData[metaDataKey].length > 0 - ) { - metaInformationData[metaDataKey].forEach(entity=>{ - entity.value = - gen.utils.convertStringToObjectId(entity.value); - }) - } else { - - if( - typeof(metaInformationData[metaDataKey]) === "string" - ) { - - metaInformationData[metaDataKey] = - gen.utils.convertStringToObjectId( - metaInformationData[metaDataKey] - ); - - } else { - - metaInformationData[metaDataKey].value = - gen.utils.convertStringToObjectId( - metaInformationData[metaDataKey].value - ); - } - } - }); - - updateUserProfileData["metaInformation"] = metaInformationData; - - userProfileData = await this.list({ - userId: userId, - status : constants.common.USER_PROFILE_NOT_VERIFIED_STATUS - },{ - status: 1, - _id: 1 - }); - - let saveUserProfileInformation; - - if( userProfileData && userProfileData[0] ) { - - saveUserProfileInformation = - await database.models.userProfile.findOneAndUpdate( - { - _id: userProfileData[0]._id - },{ - $set : updateUserProfileData - },{ new : true } - ).lean(); - - } else { - - updateUserProfileData["userId"] = userId; - updateUserProfileData["createdBy"] = userId; - updateUserProfileData["externalId"] = externalId; - - saveUserProfileInformation = - await database.models.userProfile.create( - updateUserProfileData - ); - } - - return resolve({ - result : saveUserProfileInformation.metaInformation, - message : constants.apiResponses.USER_PROFILE_SAVED - }); - - } catch (error) { - return reject(error); - } - }); - } - - /** * User profile whose information is not verified or not sent for verification. * @method diff --git a/module/user-profile/validator/v1.js b/module/user-profile/validator/v1.js index 6152b2c2..c3c8fab2 100644 --- a/module/user-profile/validator/v1.js +++ b/module/user-profile/validator/v1.js @@ -2,14 +2,6 @@ module.exports = (req) => { let userProfileValidator = { - getForm : function() { - req.checkHeaders('appname').exists().withMessage("required app name in headers"), - req.checkHeaders('os').exists().withMessage('required os in headers') - }, - save: function () { - req.checkBody('data').exists().withMessage("Required meta information data"); - } - } if (userProfileValidator[req.params.method]) { diff --git a/module/users/helper.js b/module/users/helper.js index e863e732..0de026fa 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -21,87 +21,6 @@ const userService = require(ROOT_PATH + "/generics/services/users"); module.exports = class UsersHelper { - /** - * create user. - * @method - * @name create - * @param {Object} userData user data. - * @param {String} userData.email email id of the user. - * @param {String} userData.userName name of the user. - * @param {String} userData.role role of the user. - * @returns {Promise} returns a promise. - */ - - static create(userData) { - return new Promise(async (resolve, reject) => { - try { - - let checkUserExistence = - await database.models.users.findOne({ - email: userData.email - }).lean(); - - if (checkUserExistence) { - throw { - message: "User already exists" - } - } - - let createUser = - await database.models.users.create(userData) - - let response = { - success: true, - message: "User created successfully" - } - - if (!createUser) { - response["success"] = false; - response["message"] = "User could not be created"; - } - - return resolve(response); - - } catch (error) { - return reject(error); - } - }) - } - - /** - * check if the provided email is sys admin or not. - * @method - * @name isSystemAdmin - * @param {String} userEmail user email address. - * @returns {Promise} returns a promise. - */ - - static isSystemAdmin(userEmail) { - return new Promise(async (resolve, reject) => { - try { - - let userDocument = - await database.models.users.findOne({ - email: userEmail, - role: "SYS_ADMIN" - }).lean(); - - let response = { - success: true - } - - if (!userDocument) { - response["success"] = false; - } - - return resolve(response); - - } catch (error) { - return reject(error); - } - }) - } - /** * List of all private programs created by user * @method diff --git a/module/users/validator/v1.js b/module/users/validator/v1.js index a0494d8d..ec218d91 100644 --- a/module/users/validator/v1.js +++ b/module/users/validator/v1.js @@ -1,21 +1,7 @@ module.exports = (req) => { let userValidator = { - create : function () { - req.checkBody('email').exists().withMessage("required email id"); - req.checkBody('userName').exists() - .withMessage("required name of the user"); - - req.checkBody('role').exists() - .withMessage("required role of the user"); - }, - isSystemAdmin: function () { - req.checkBody('email').exists().withMessage("required email id"); - }, - entitiesMappingForm : function () { - req.checkParams('_id').exists().withMessage("required Entity id"); - req.checkQuery('roleId').exists().withMessage("required role id"); - }, + solutions : function () { req.checkParams('_id').exists().withMessage("required Program id"); }, From 3cf45558ba1f1ffdf2610e976d7689d908a0332f Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Thu, 30 Sep 2021 20:33:12 +0530 Subject: [PATCH 035/331] added surveyReportPage in url --- generics/services/samiksha.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/generics/services/samiksha.js b/generics/services/samiksha.js index a0035482..124b16ff 100644 --- a/generics/services/samiksha.js +++ b/generics/services/samiksha.js @@ -89,6 +89,10 @@ var assignedSurveys = function ( token,search = "",filter = "" ) { if( filter !== "" ) { userAssignedUrl = userAssignedUrl + "&filter=" + filter; } + + if( surveyReportPage !== "" ) { + userAssignedUrl = userAssignedUrl + "&surveyReportPage=" + surveyReportPage; + } return new Promise(async (resolve, reject) => { try { From dc382d9f427ac9df333f7c5e16a511df5294354e Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Thu, 30 Sep 2021 21:45:19 +0530 Subject: [PATCH 036/331] fix --- generics/services/samiksha.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/generics/services/samiksha.js b/generics/services/samiksha.js index 124b16ff..7ef24518 100644 --- a/generics/services/samiksha.js +++ b/generics/services/samiksha.js @@ -80,7 +80,7 @@ var assignedObservations = function ( token,search = "",filter = "" ) { * @returns {Promise} returns a promise. */ -var assignedSurveys = function ( token,search = "",filter = "" ) { +var assignedSurveys = function ( token,search = "",filter = "", surveyReportPage = "" ) { let userAssignedUrl = process.env.ML_SURVEY_SERVICE_URL + @@ -108,7 +108,7 @@ var assignedSurveys = function ( token,search = "",filter = "" ) { } else { let response = JSON.parse(data.body); - + console.log(response.result,"response.result") if( response.status === httpStatusCode['ok'].status ) { result["data"] = response.result; } else { From 2b54ed532e7aa59befcbeac42979ec17664af058 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Thu, 30 Sep 2021 21:46:50 +0530 Subject: [PATCH 037/331] remove console --- generics/services/samiksha.js | 1 - 1 file changed, 1 deletion(-) diff --git a/generics/services/samiksha.js b/generics/services/samiksha.js index 7ef24518..728f9d35 100644 --- a/generics/services/samiksha.js +++ b/generics/services/samiksha.js @@ -108,7 +108,6 @@ var assignedSurveys = function ( token,search = "",filter = "", surveyReportPage } else { let response = JSON.parse(data.body); - console.log(response.result,"response.result") if( response.status === httpStatusCode['ok'].status ) { result["data"] = response.result; } else { From 9a7d077979077f927e0e82c2a5bac0ba8b6a8d07 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Fri, 1 Oct 2021 11:05:12 +0530 Subject: [PATCH 038/331] logs --- generics/services/samiksha.js | 3 +++ module/solutions/helper.js | 4 ++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/generics/services/samiksha.js b/generics/services/samiksha.js index 728f9d35..dcd1c4bd 100644 --- a/generics/services/samiksha.js +++ b/generics/services/samiksha.js @@ -93,6 +93,8 @@ var assignedSurveys = function ( token,search = "",filter = "", surveyReportPage if( surveyReportPage !== "" ) { userAssignedUrl = userAssignedUrl + "&surveyReportPage=" + surveyReportPage; } + + console.log(userAssignedUrl, "userAssignedUrl") return new Promise(async (resolve, reject) => { try { @@ -108,6 +110,7 @@ var assignedSurveys = function ( token,search = "",filter = "", surveyReportPage } else { let response = JSON.parse(data.body); + console.log(response,"assignedSurveys response") if( response.status === httpStatusCode['ok'].status ) { result["data"] = response.result; } else { diff --git a/module/solutions/helper.js b/module/solutions/helper.js index d1b2223d..69dfee2c 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -1332,7 +1332,7 @@ module.exports = class SolutionsHelper { }; surveyReportPage = gen.utils.convertStringToBoolean(surveyReportPage); - + console.log(surveyReportPage,"surveyReportPage targetedSolution") if ( !surveyReportPage || solutionType == constants.common.COURSE ) { targetedSolutions = @@ -1351,7 +1351,7 @@ module.exports = class SolutionsHelper { if( targetedSolutions.data.data && targetedSolutions.data.data.length > 0 ) { totalCount += targetedSolutions.data.count; - + console.log(targetedSolutions.data.data,"targetedSolutions data") targetedSolutions.data.data.forEach(targetedSolution => { targetedSolution.solutionId = targetedSolution._id; targetedSolution._id = ""; From 6202c803324865f10ae927174a2bb7a490bbccf3 Mon Sep 17 00:00:00 2001 From: aman-tunerlabs Date: Fri, 1 Oct 2021 14:35:18 +0530 Subject: [PATCH 039/331] removed es helper dependencies --- controllers/v1/dictionary/keywords.js | 217 --------------------- module/dictionary/helper.js | 201 ------------------- module/dictionary/keywords/validator/v1.js | 14 -- module/entities/helper.js | 210 ++++++++++---------- module/user-extension/helper.js | 194 +++++++++--------- 5 files changed, 202 insertions(+), 634 deletions(-) delete mode 100644 controllers/v1/dictionary/keywords.js delete mode 100644 module/dictionary/helper.js delete mode 100644 module/dictionary/keywords/validator/v1.js diff --git a/controllers/v1/dictionary/keywords.js b/controllers/v1/dictionary/keywords.js deleted file mode 100644 index e4946f89..00000000 --- a/controllers/v1/dictionary/keywords.js +++ /dev/null @@ -1,217 +0,0 @@ -/** - * name : keywords.js - * author : Akash Shah - * created-date : 02-Jan-2020 - * Description : Dictionary Keywords - */ - -// dependencies - -const csv = require('csvtojson'); -const csvFileStream = require(ROOT_PATH + "/generics/file-stream"); -const dictionaryHelper = require(MODULES_BASE_PATH + "/dictionary/helper"); - -/** - * Keywords - * @class -*/ - -module.exports = class Keywords { - - /** - * @apiDefine errorBody - * @apiError {String} status 4XX,5XX - * @apiError {String} message Error - */ - - /** - * @apiDefine successBody - * @apiSuccess {String} status 200 - * @apiSuccess {String} result Data - */ - - - /** - * @api {post} /kendra/api/v1/dictionary/keywords/upload - * Upload Keywords to Dictionary - * @apiVersion 1.0.0 - * @apiGroup Dictionary - * @apiHeader {String} X-authenticated-user-token Authenticity token - * @apiHeader {String} internal-access-token Internal access token - * @apiParam {File} keywords Mandatory keywords file of type csv. - * @apiSampleRequest /kendra/api/v1/dictionary/keywords/upload - * @apiUse successBody - * @apiUse errorBody - */ - - /** - * Push keywords data to the dictionary index. - * @method - * @name upload - * @param {Request} req request body. - * @returns {csv} Response consists of exactly - * the same csv that we upload with extra column status. - */ - - - async upload(req) { - - return new Promise(async (resolve, reject) => { - - try { - - if (!req.files || !req.files.keywords) { - throw { message: constants.apiResponses.DICTIONARY_KEYWORDS_MISSING_FILE_ERROR }; - } - - const checkIfKeywordsCanBeUploaded = await dictionaryHelper - .keywordsIndexTypeMapExists(); - - if(!checkIfKeywordsCanBeUploaded.data) { - throw { message: constants.apiResponses.DICTIONARY_KEYWORDS_MAPPING_MISSING_ERROR } - } - - let keywordsData = - await csv().fromString(req.files.keywords.data.toString()); - - const fileName = `keywords`; - let fileStream = new csvFileStream(fileName); - let input = fileStream.initStream(); - - (async function () { - await fileStream.getProcessorPromise(); - return resolve({ - isResponseAStream: true, - fileNameWithPath: fileStream.fileNameWithPath() - }); - })(); - - for (let pointerToKeywordsData = 0; - pointerToKeywordsData < keywordsData.length; - pointerToKeywordsData++) { - const row = keywordsData[pointerToKeywordsData]; - row.status = constants.common.FAILED; - if(row.word && row.word != "") { - let addOrRemoveOperation - if(row.action == "remove") { - addOrRemoveOperation = await dictionaryHelper.removeWordFromDictionary(row.word); - } else { - addOrRemoveOperation = await dictionaryHelper.addWordToDictionary(row.word); - } - if(!addOrRemoveOperation.data) { - row.status = constants.common.FAILED; - } else { - row.status = constants.common.SUCCESS; - } - } - input.push(row); - } - - input.push(null); - - } catch (error) { - - return reject({ - status: - error.status || httpStatusCode["internal_server_error"].status, - - message: - error.message || httpStatusCode["internal_server_error"].message, - - errorObject: error - }); - - } - }) - - } - - - /** - * @api {post} /kendra/api/v1/dictionary/keywords/update - * Update content Keywords in Dictionary - * @apiVersion 1.0.0 - * @apiGroup Dictionary - * @apiHeader {String} X-authenticated-user-token Authenticity token - * @apiHeader {String} internal-access-token Internal access token - * @apiParamExample {json} Response: - "keywords": [ - "Keyword1", - "Keyword2", - "Keyword3" - ] - * @apiSampleRequest /kendra/api/v1/dictionary/keywords/update - * @apiUse successBody - * @apiUse errorBody - */ - - /** - * Update Content Keywords in Dictionary. - * @method - * @name update - * @param {Request} req request body. - * @returns {json} Response consists of success or failure to update keywords. - */ - - - async update(req) { - - return new Promise(async (resolve, reject) => { - - try { - - const checkIfKeywordsCanBeUploaded = await dictionaryHelper - .keywordsIndexTypeMapExists(); - - if(!checkIfKeywordsCanBeUploaded.data) { - throw { message: constants.apiResponses.DICTIONARY_KEYWORDS_MAPPING_MISSING_ERROR } - } - - let keywordsData = req.body.keywords; - - let keywordsUpdateResult = new Array; - - for (let pointerToKeywordsData = 0; - pointerToKeywordsData < keywordsData.length; - pointerToKeywordsData++) { - const keyword = keywordsData[pointerToKeywordsData]; - let status = constants.common.FAILED; - if(keyword != "") { - let addOrUpdateKeyword = await dictionaryHelper.addWordToDictionary(keyword); - - if(!addOrUpdateKeyword.data) { - status = constants.common.FAILED; - } else { - status = constants.common.SUCCESS; - } - } - keywordsUpdateResult.push({ - keyword : keyword, - status : status - }); - } - - return resolve({ - result: keywordsUpdateResult, - message: constants.apiResponses.DICTIONARY_KEYWORDS_UPDATE_SUCCESS - }); - - } catch (error) { - - return reject({ - status: - error.status || httpStatusCode["internal_server_error"].status, - - message: - error.message || httpStatusCode["internal_server_error"].message, - - errorObject: error - }); - - } - }) - - } - -}; - diff --git a/module/dictionary/helper.js b/module/dictionary/helper.js deleted file mode 100644 index 7fe6c316..00000000 --- a/module/dictionary/helper.js +++ /dev/null @@ -1,201 +0,0 @@ -/** - * name : dictionary/helper.js - * author : Akash Shah - * created-date : 03-Jan-2020 - * Description : All Dictionary related helper functions. - */ - -// Dependencies - -const elasticSearchHelper = require(GENERIC_HELPERS_PATH + "/elastic-search"); - -// Constants -const dictionaryIndex = gen.utils.checkIfEnvDataExistsOrNot("ELASTICSEARCH_DICTIONARY_INDEX"); -const dictionaryIndexType = gen.utils.checkIfEnvDataExistsOrNot("ELASTICSEARCH_DICTIONARY_INDEX_TYPE"); - -/** - * DictionaryHelper - * @class -*/ - -module.exports = class DictionaryHelper { - - /** - * Find the closest word. - * @method - * @name spellcheck - * @param {String} word word to check for spelling. - * @returns {Promise} returns a promise. - */ - - static spellcheck(word = "") { - return new Promise(async (resolve, reject) => { - try { - - if(word == "") { - throw new Error("Missing word."); - } - - let queryObject = { - query : { - match : { - words : { - query : word, - fuzziness : 2 - } - } - } - } - - const dictionaryIndexMapping = await elasticSearchHelper.searchDocumentFromIndex(dictionaryIndex, dictionaryIndexType, queryObject); - - return resolve({ - success : true, - message : "Matching keyword found.", - data : dictionaryIndexMapping[0].words - }); - - } catch (error) { - return resolve({ - success : true, - message : error.message, - data : false - }); - } - }) - } - - /** - * Check if mapping for dictionary index exists in Elastic search. - * @method - * @name keywordsIndexTypeMapExists - * @returns {Promise} returns a promise. - */ - - static keywordsIndexTypeMapExists() { - return new Promise(async (resolve, reject) => { - try { - - if(dictionaryIndex == "") { - throw new Error("Missing dictionary index name"); - } - - if(dictionaryIndexType == "") { - throw new Error("Missing dictionary index type name"); - } - - const dictionaryIndexMapping = await elasticSearchHelper.getIndexTypeMapping(dictionaryIndex, dictionaryIndexType); - - if(dictionaryIndexMapping.statusCode != httpStatusCode["ok"].status) { - throw new Error("Keywords index type map does not exist."); - } - - return resolve({ - success : true, - message : "Keywords index type map exists", - data : true - }); - - } catch (error) { - return resolve({ - success : true, - message : error.message, - data : false - }); - } - }) - } - - - /** - * Remove word from dictionary index. - * @method - * @name removeWordFromDictionary - * @param {String} word word to remove from dictionary index. - * @returns {Promise} returns a promise. - */ - - static removeWordFromDictionary(word = "") { - return new Promise(async (resolve, reject) => { - try { - - if(word == "") { - throw new Error("Invalid word value."); - } - - word = word.toLowerCase(); - - const dictionaryWordRemoval = await elasticSearchHelper - .deleteDocumentFromIndex( - dictionaryIndex, - dictionaryIndexType, - encodeURI(word) - ); - - if(dictionaryWordRemoval.statusCode != httpStatusCode["ok"].status) { - throw new Error("Failed to remove word from dictionary.") - } - - return resolve({ - success : true, - message : "Success", - data : true - }); - - } catch (error) { - return resolve({ - success : true, - message : error.message, - data : false - }); - } - }) - } - - - /** - * Add word to dictionary index. - * @method - * @name addWordToDictionary - * @param {String} word word to add to dictionary index. - * @returns {Promise} returns a promise. - */ - - static addWordToDictionary(word = "") { - return new Promise(async (resolve, reject) => { - try { - - if(word == "") { - throw new Error("Invalid word value."); - } - - word = word.toLowerCase(); - - const addWordToDictionary = await elasticSearchHelper.createOrUpdateDocumentInIndex( - dictionaryIndex, - dictionaryIndexType, - encodeURI(word), - {words : word } - ); - - if(addWordToDictionary.statusCode != httpStatusCode["ok"].status && addWordToDictionary.statusCode != httpStatusCode["created"].status) { - throw new Error("Failed to add word to dictionary.") - } - - return resolve({ - success : true, - message : "Success", - data : true - }); - - } catch (error) { - return resolve({ - success : true, - message : error.message, - data : false - }); - } - }) - } - -}; \ No newline at end of file diff --git a/module/dictionary/keywords/validator/v1.js b/module/dictionary/keywords/validator/v1.js deleted file mode 100644 index 7478c52e..00000000 --- a/module/dictionary/keywords/validator/v1.js +++ /dev/null @@ -1,14 +0,0 @@ -module.exports = (req) => { - - let keywordsValidator = { - - update: function () { - req.checkBody('keywords').isLength({ min: 1 }).withMessage("required keywords"); - } - } - - if (keywordsValidator[req.params.method]) { - keywordsValidator[req.params.method](); - } - -}; \ No newline at end of file diff --git a/module/entities/helper.js b/module/entities/helper.js index 18efb73f..e924e0b0 100644 --- a/module/entities/helper.js +++ b/module/entities/helper.js @@ -1,6 +1,6 @@ const entityTypesHelper = require(MODULES_BASE_PATH + "/entityTypes/helper"); const userRolesHelper = require(MODULES_BASE_PATH + "/user-roles/helper"); -const elasticSearch = require(GENERIC_HELPERS_PATH + "/elastic-search"); +// const elasticSearch = require(GENERIC_HELPERS_PATH + "/elastic-search"); module.exports = class EntitiesHelper { @@ -695,128 +695,128 @@ module.exports = class EntitiesHelper { * @returns {Array} - List of userIds and entityIds */ - static getUsersByEntityAndRole( entityId= "", role= "" ) { - return new Promise(async (resolve, reject) => { - try { +// static getUsersByEntityAndRole( entityId= "", role= "" ) { +// return new Promise(async (resolve, reject) => { +// try { - if (entityId == "") { - throw new Error(constants.apiResponses.ENTITY_ID_REQUIRED); - } +// if (entityId == "") { +// throw new Error(constants.apiResponses.ENTITY_ID_REQUIRED); +// } - if (role == "") { - throw new Error(constants.apiResponses.ROLE_REQUIRED) - } +// if (role == "") { +// throw new Error(constants.apiResponses.ROLE_REQUIRED) +// } - let userRole = await userRolesHelper.roleDocuments({ - code : role - },[ - "entityTypes" - ]); +// let userRole = await userRolesHelper.roleDocuments({ +// code : role +// },[ +// "entityTypes" +// ]); - if(!userRole.length) { - throw new Error(constants.apiResponses.INVALID_ROLE) - } +// if(!userRole.length) { +// throw new Error(constants.apiResponses.INVALID_ROLE) +// } - let entityType = userRole[0].entityTypes[0].entityType; +// let entityType = userRole[0].entityTypes[0].entityType; - let entityTypeOfInputEntityId = await this.entityDocuments - ( - { _id: entityId }, - ["entityType"] - ) +// let entityTypeOfInputEntityId = await this.entityDocuments +// ( +// { _id: entityId }, +// ["entityType"] +// ) - if (entityTypeOfInputEntityId.length == 0) { - throw new Error(constants.apiResponses.ENTITY_NOT_FOUND); - } +// if (entityTypeOfInputEntityId.length == 0) { +// throw new Error(constants.apiResponses.ENTITY_NOT_FOUND); +// } - let entityDocument = []; - let entityIds = []; - - if (entityType == entityTypeOfInputEntityId[0].entityType) { - entityIds.push(entityId) - } - else { - entityDocument = await this.entityDocuments - ( - { - _id: entityId - }, - [ - `groups.${entityType}` - ] - ) +// let entityDocument = []; +// let entityIds = []; + +// if (entityType == entityTypeOfInputEntityId[0].entityType) { +// entityIds.push(entityId) +// } +// else { +// entityDocument = await this.entityDocuments +// ( +// { +// _id: entityId +// }, +// [ +// `groups.${entityType}` +// ] +// ) - if (entityDocument.length > 0) { - entityIds = entityDocument[0].groups[entityType] - } - } +// if (entityDocument.length > 0) { +// entityIds = entityDocument[0].groups[entityType] +// } +// } - if (!entityIds.length) { - throw new Error(constants.apiResponses.USERS_NOT_FOUND); - } +// if (!entityIds.length) { +// throw new Error(constants.apiResponses.USERS_NOT_FOUND); +// } - let chunkOfEntities = _.chunk(entityIds, 1000); +// let chunkOfEntities = _.chunk(entityIds, 1000); - let entitiesFromEs = []; +// let entitiesFromEs = []; - for(let entities = 0; entities < chunkOfEntities.length; entities++) { +// for(let entities = 0; entities < chunkOfEntities.length; entities++) { - let queryObject = { - "query": { - "ids" : { - "values" : chunkOfEntities[entities] - } - }, - "_source": [`data.roles.${role}`,"data.externalId"] - } - - let entityDocuments = await elasticSearch.searchDocumentFromIndex - ( - process.env.ELASTICSEARCH_ENTITIES_INDEX, - "_doc", - queryObject, - "all", - 1000 - ) +// let queryObject = { +// "query": { +// "ids" : { +// "values" : chunkOfEntities[entities] +// } +// }, +// "_source": [`data.roles.${role}`,"data.externalId"] +// } + +// let entityDocuments = await elasticSearch.searchDocumentFromIndex +// ( +// process.env.ELASTICSEARCH_ENTITIES_INDEX, +// "_doc", +// queryObject, +// "all", +// 1000 +// ) - if (entityDocuments && entityDocuments.length > 0) { - entitiesFromEs = [...entitiesFromEs, ...entityDocuments] - } - } - - if (!entitiesFromEs.length) { - throw new Error(constants.apiResponses.USERS_NOT_FOUND) - } +// if (entityDocuments && entityDocuments.length > 0) { +// entitiesFromEs = [...entitiesFromEs, ...entityDocuments] +// } +// } + +// if (!entitiesFromEs.length) { +// throw new Error(constants.apiResponses.USERS_NOT_FOUND) +// } - let result = []; +// let result = []; - for (let entity = 0; entity < entitiesFromEs.length; entity++) { - if (entitiesFromEs[entity].data.roles && Object.keys(entitiesFromEs[entity].data.roles).length > 0) { - for (let user = 0; user < entitiesFromEs[entity].data.roles[role].length; user++) { - result.push({ - entityId: entitiesFromEs[entity].id, - entityExternalId: entitiesFromEs[entity].data.externalId ? entitiesFromEs[entity].data.externalId : "", - userId: entitiesFromEs[entity].data.roles[role][user] - }) - } - } - } +// for (let entity = 0; entity < entitiesFromEs.length; entity++) { +// if (entitiesFromEs[entity].data.roles && Object.keys(entitiesFromEs[entity].data.roles).length > 0) { +// for (let user = 0; user < entitiesFromEs[entity].data.roles[role].length; user++) { +// result.push({ +// entityId: entitiesFromEs[entity].id, +// entityExternalId: entitiesFromEs[entity].data.externalId ? entitiesFromEs[entity].data.externalId : "", +// userId: entitiesFromEs[entity].data.roles[role][user] +// }) +// } +// } +// } - resolve({ - success: true, - message : constants.apiResponses.USERS_AND_ENTITIES_FETCHED, - data : result - }); - - } catch (error) { - return resolve({ - success: false, - message: error.message, - data: false - }); - } - }) - } +// resolve({ +// success: true, +// message : constants.apiResponses.USERS_AND_ENTITIES_FETCHED, +// data : result +// }); + +// } catch (error) { +// return resolve({ +// success: false, +// message: error.message, +// data: false +// }); +// } +// }) +// } /** * Sub entity type list. diff --git a/module/user-extension/helper.js b/module/user-extension/helper.js index 4c9f80b0..fa35ea89 100644 --- a/module/user-extension/helper.js +++ b/module/user-extension/helper.js @@ -14,7 +14,7 @@ const entityTypesHelper = require(MODULES_BASE_PATH + "/entityTypes/helper"); const entitiesHelper = require(MODULES_BASE_PATH + "/entities/helper"); const userRolesHelper = require(MODULES_BASE_PATH + "/user-roles/helper"); -const elasticSearch = require(GENERIC_HELPERS_PATH + "/elastic-search"); +// const elasticSearch = require(GENERIC_HELPERS_PATH + "/elastic-search"); const programsHelper = require(MODULES_BASE_PATH + "/programs/helper"); const solutionsHelper = require(MODULES_BASE_PATH + "/solutions/helper"); @@ -567,11 +567,11 @@ module.exports = class UserExtensionHelper { }); //update user role in elasticsearch - if (requestedData.roles.length > 0) { - await this.updateUserRolesInEntitiesElasticSearch(userId, requestedData.roles); - } + // if (requestedData.roles.length > 0) { + // await this.updateUserRolesInEntitiesElasticSearch(userId, requestedData.roles); + // } - await this.pushUserToElasticSearch(userId); + // await this.pushUserToElasticSearch(userId); resolve({ message: constants.apiResponses.USER_EXTENSION_UPDATED, @@ -916,66 +916,66 @@ module.exports = class UserExtensionHelper { * @name userId - user id * @name userRoles - array of userRoles. */ -static updateUserRolesInEntitiesElasticSearch(userId = "", userRoles = []) { - return new Promise(async (resolve, reject) => { - try { +// static updateUserRolesInEntitiesElasticSearch(userId = "", userRoles = []) { +// return new Promise(async (resolve, reject) => { +// try { - await Promise.all(userRoles.map( async role => { - await Promise.all(role.entities.map(async entity => { - - let entityDocument = await elasticSearch.getData - ({ - id : entity, - index : process.env.ELASTICSEARCH_ENTITIES_INDEX, - type : "_doc" - }) +// await Promise.all(userRoles.map( async role => { +// await Promise.all(role.entities.map(async entity => { + +// let entityDocument = await elasticSearch.getData +// ({ +// id : entity, +// index : process.env.ELASTICSEARCH_ENTITIES_INDEX, +// type : "_doc" +// }) - if (entityDocument.statusCode == httpStatusCode.ok.status) { +// if (entityDocument.statusCode == httpStatusCode.ok.status) { - entityDocument = entityDocument.body["_source"].data; +// entityDocument = entityDocument.body["_source"].data; - if (!entityDocument.roles) { - entityDocument.roles = {}; - } +// if (!entityDocument.roles) { +// entityDocument.roles = {}; +// } - if (entityDocument.roles[role.code]) { - if (!entityDocument.roles[role.code].includes(userId)) { - entityDocument.roles[role.code].push(userId); - - await elasticSearch.createOrUpdateDocumentInIndex - ( - process.env.ELASTICSEARCH_ENTITIES_INDEX, - "_doc", - entity, - {data: entityDocument } - ) - } - } - else { - entityDocument.roles[role.code] = [userId]; - - await elasticSearch.createOrUpdateDocumentInIndex - ( - process.env.ELASTICSEARCH_ENTITIES_INDEX, - "_doc", - entity, - {data: entityDocument } - ) - } - } - })) - })) - - return resolve({ - success: true - }); - - } - catch (error) { - return reject(error); - } -}) -} +// if (entityDocument.roles[role.code]) { +// if (!entityDocument.roles[role.code].includes(userId)) { +// entityDocument.roles[role.code].push(userId); + +// await elasticSearch.createOrUpdateDocumentInIndex +// ( +// process.env.ELASTICSEARCH_ENTITIES_INDEX, +// "_doc", +// entity, +// {data: entityDocument } +// ) +// } +// } +// else { +// entityDocument.roles[role.code] = [userId]; + +// await elasticSearch.createOrUpdateDocumentInIndex +// ( +// process.env.ELASTICSEARCH_ENTITIES_INDEX, +// "_doc", +// entity, +// {data: entityDocument } +// ) +// } +// } +// })) +// })) + +// return resolve({ +// success: true +// }); + +// } +// catch (error) { +// return reject(error); +// } +// }) +// } /** @@ -986,46 +986,46 @@ static updateUserRolesInEntitiesElasticSearch(userId = "", userRoles = []) { * @returns {Object} */ - static pushUserToElasticSearch(userId) { - return new Promise(async (resolve, reject) => { - try { - - let userInformation = await this.userExtensionDocument - ( - { userId: userId }, - [ "_id", - "status", - "isDeleted", - "deleted", - "roles", - "userId", - "externalId", - "updatedBy", - "createdBy", - "updatedAt", - "createdAt"] - ) +// static pushUserToElasticSearch(userId) { +// return new Promise(async (resolve, reject) => { +// try { + +// let userInformation = await this.userExtensionDocument +// ( +// { userId: userId }, +// [ "_id", +// "status", +// "isDeleted", +// "deleted", +// "roles", +// "userId", +// "externalId", +// "updatedBy", +// "createdBy", +// "updatedAt", +// "createdAt"] +// ) - await elasticSearch.createOrUpdateDocumentInIndex( - process.env.ELASTICSEARCH_USER_EXTENSION_INDEX, - "_doc", - userId, - { - data : userInformation - } - ); - - return resolve({ - success : true - }); +// await elasticSearch.createOrUpdateDocumentInIndex( +// process.env.ELASTICSEARCH_USER_EXTENSION_INDEX, +// "_doc", +// userId, +// { +// data : userInformation +// } +// ); + +// return resolve({ +// success : true +// }); - } - catch(error) { - return reject(error); - } - }) +// } +// catch(error) { +// return reject(error); +// } +// }) - } +// } /** * List of programs for platform user From a33f9e9adde214e7e9707e1ebbbf2e6e51635c02 Mon Sep 17 00:00:00 2001 From: aman-tunerlabs Date: Fri, 1 Oct 2021 14:50:49 +0530 Subject: [PATCH 040/331] removed es --- .env.sample | 5 --- config/db/elastic-search.js | 68 +++++++++++++++++------------------ config/index.js | 8 ++--- envVariables.js | 12 ------- healthCheck/elastic-search.js | 32 ----------------- healthCheck/health-check.js | 8 ----- package.json | 1 - 7 files changed, 38 insertions(+), 96 deletions(-) delete mode 100644 healthCheck/elastic-search.js diff --git a/.env.sample b/.env.sample index eb1b6420..ed3a93c5 100644 --- a/.env.sample +++ b/.env.sample @@ -35,10 +35,5 @@ ML_SURVEY_SERVICE_URL = "http://ml-survey-service:3000" # ML Project Service Service ML_PROJECT_SERVICE_URL = "http://ml-project-service:3000" // ML Project service url -# Elastic search configurations -ELASTICSEARCH_COMMUNICATIONS_ON_OFF = "ON/OFF" // Elastic search enable/disable flag E.g. ON/OFF -ELASTICSEARCH_HOST_URL = "http://127.0.0.1:9200" // Elastic search host url -ELASTICSEARCH_ENTITIES_INDEX = "entities" // Elastic search index name for storing entities - USER_SERVICE_URL = "http://user-service:3000" // Base url of the sunbird enviornment CSV_REPORTS_PATH = "public/report" // Report path diff --git a/config/db/elastic-search.js b/config/db/elastic-search.js index 166905fb..b5f97f3e 100644 --- a/config/db/elastic-search.js +++ b/config/db/elastic-search.js @@ -7,37 +7,37 @@ //dependencies -const { Client : esClient } = require('@elastic/elasticsearch'); - -/** - * Elastic search connection. - * @function - * @name connect - * @return {Object} elastic search client - */ - -var connect = function () { - - const elasticSearchClient = new esClient({ - node: process.env.ELASTICSEARCH_HOST_URL, - maxRetries: 5, - requestTimeout: 60000, - sniffOnStart: process.env.ELASTIC_SEARCH_SNIFF_ON_START - }); - - elasticSearchClient.ping({ - }, function (error) { - if (error) { - console.log(error); - } else { - console.log('Elasticsearch connection established.'); - } - }); - - return { - client: elasticSearchClient - }; - -}; - -module.exports = connect; +// const { Client : esClient } = require('@elastic/elasticsearch'); + +// /** +// * Elastic search connection. +// * @function +// * @name connect +// * @return {Object} elastic search client +// */ + +// var connect = function () { + +// const elasticSearchClient = new esClient({ +// node: process.env.ELASTICSEARCH_HOST_URL, +// maxRetries: 5, +// requestTimeout: 60000, +// sniffOnStart: process.env.ELASTIC_SEARCH_SNIFF_ON_START +// }); + +// elasticSearchClient.ping({ +// }, function (error) { +// if (error) { +// console.log(error); +// } else { +// console.log('Elasticsearch connection established.'); +// } +// }); + +// return { +// client: elasticSearchClient +// }; + +// }; + +// module.exports = connect; diff --git a/config/index.js b/config/index.js index 8e7ac046..18fd6178 100644 --- a/config/index.js +++ b/config/index.js @@ -23,9 +23,9 @@ let db_connect = function () { * @name elasticsearch_connect */ -let elasticsearch_connect = function () { - global.elasticsearch = require("./db/elastic-search")(); -}; +// let elasticsearch_connect = function () { +// global.elasticsearch = require("./db/elastic-search")(); +// }; const configuration = { root: require("path").normalize(__dirname + "/.."), @@ -35,6 +35,6 @@ const configuration = { }; db_connect(); -elasticsearch_connect(); +// elasticsearch_connect(); module.exports = configuration; diff --git a/envVariables.js b/envVariables.js index 0cf2dd4b..0056a831 100644 --- a/envVariables.js +++ b/envVariables.js @@ -116,18 +116,6 @@ let enviromentVariables = { "message" : "Required project service API endpoint", "optional" : false }, - "ELASTICSEARCH_COMMUNICATIONS_ON_OFF" : { - "message" : "Enable/Disable elastic search communications", - "optional" : false - }, - "ELASTICSEARCH_HOST_URL" : { - "message" : "Elastic search host url", - "optional" : false - }, - "ELASTICSEARCH_ENTITIES_INDEX" : { - "message" : "Elastic search entities index", - "optional" : false - }, "USER_SERVICE_URL" : { "message" : "Sunbird environment base url", "optional" : false diff --git a/healthCheck/elastic-search.js b/healthCheck/elastic-search.js deleted file mode 100644 index 288216cd..00000000 --- a/healthCheck/elastic-search.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * name : elastic-search.js. - * author : Aman Karki. - * created-date : 02-Feb-2021. - * Description : Elastic Search health check. -*/ - -// Dependencies - -const { Client : esClient } = require('@elastic/elasticsearch'); - -function health_check() { - return new Promise( async (resolve,reject) => { - - const elasticSearchClient = new esClient({ - node: process.env.ELASTICSEARCH_HOST_URL - }); - - elasticSearchClient.ping({ - }, function (error) { - if (error) { - return resolve(false); - } else { - return resolve(true); - } - }); - }) -} - -module.exports = { - health_check : health_check -} \ No newline at end of file diff --git a/healthCheck/health-check.js b/healthCheck/health-check.js index 6ebf8693..0c3af31e 100644 --- a/healthCheck/health-check.js +++ b/healthCheck/health-check.js @@ -10,7 +10,6 @@ const { v1 : uuidv1 } = require('uuid'); const assessmentHealthCheck = require("./assessments"); const mongodbHealthCheck = require("./mongodb"); -const elasticSearchHealthCheck = require("./elastic-search"); const obj = { MONGO_DB: { @@ -23,11 +22,6 @@ const obj = { FAILED_CODE: 'ASSESSMENT_SERVICE_HEALTH_FAILED', FAILED_MESSAGE: 'ASSessment service is not healthy' }, - ELASTIC_SEARCH : { - NAME: 'ElasticSearch.db', - FAILED_CODE: 'ELASTIC_SEARCH_HEALTH_FAILED', - FAILED_MESSAGE: 'Elastic search is not connected' - }, NAME: 'KendraServiceHealthCheck', API_VERSION: '1.0' } @@ -37,11 +31,9 @@ let health_check = async function(req,res) { let checks = []; let mongodbConnection = await mongodbHealthCheck.health_check(); let assessmentServiceStatus = await assessmentHealthCheck.health_check(); - let elasticSearchConnection = await elasticSearchHealthCheck.health_check(); checks.push(checkResult("MONGO_DB",mongodbConnection)); checks.push(checkResult("ASSESSMENT_SERVICE",assessmentServiceStatus)); - checks.push(checkResult("ELASTIC_SEARCH",elasticSearchConnection)); let checkServices = checks.filter( check => check.healthy === false); diff --git a/package.json b/package.json index c40a25d6..4e50fb37 100644 --- a/package.json +++ b/package.json @@ -20,7 +20,6 @@ "license": "ISC", "dependencies": { "@azure/storage-blob": "^12.1.1", - "@elastic/elasticsearch": "^6.7.1", "@google-cloud/storage": "^4.3.1", "adm-zip": "^0.4.14", "aws-sdk": "^2.624.0", From 83fe1f62cdc3561eaddabc41053c6a16561c847c Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Mon, 4 Oct 2021 11:59:32 +0530 Subject: [PATCH 041/331] remove logs --- generics/services/samiksha.js | 3 --- module/solutions/helper.js | 2 -- 2 files changed, 5 deletions(-) diff --git a/generics/services/samiksha.js b/generics/services/samiksha.js index dcd1c4bd..728f9d35 100644 --- a/generics/services/samiksha.js +++ b/generics/services/samiksha.js @@ -93,8 +93,6 @@ var assignedSurveys = function ( token,search = "",filter = "", surveyReportPage if( surveyReportPage !== "" ) { userAssignedUrl = userAssignedUrl + "&surveyReportPage=" + surveyReportPage; } - - console.log(userAssignedUrl, "userAssignedUrl") return new Promise(async (resolve, reject) => { try { @@ -110,7 +108,6 @@ var assignedSurveys = function ( token,search = "",filter = "", surveyReportPage } else { let response = JSON.parse(data.body); - console.log(response,"assignedSurveys response") if( response.status === httpStatusCode['ok'].status ) { result["data"] = response.result; } else { diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 69dfee2c..a6387133 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -1332,7 +1332,6 @@ module.exports = class SolutionsHelper { }; surveyReportPage = gen.utils.convertStringToBoolean(surveyReportPage); - console.log(surveyReportPage,"surveyReportPage targetedSolution") if ( !surveyReportPage || solutionType == constants.common.COURSE ) { targetedSolutions = @@ -1351,7 +1350,6 @@ module.exports = class SolutionsHelper { if( targetedSolutions.data.data && targetedSolutions.data.data.length > 0 ) { totalCount += targetedSolutions.data.count; - console.log(targetedSolutions.data.data,"targetedSolutions data") targetedSolutions.data.data.forEach(targetedSolution => { targetedSolution.solutionId = targetedSolution._id; targetedSolution._id = ""; From 83729cb103bd0e81252e328475b3d2d73f0b62a9 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Tue, 12 Oct 2021 14:10:45 +0530 Subject: [PATCH 042/331] project link --- .env.sample | 2 + controllers/v1/solutions.js | 237 ++++++++++++++ controllers/v1/users.js | 3 +- generics/constants/api-responses.js | 12 +- generics/constants/common.js | 8 +- generics/constants/endpoints.js | 5 +- generics/helpers/utils.js | 15 +- generics/services/improvement-project.js | 200 +++++++++++- module/solutions/helper.js | 387 ++++++++++++++++++++++- module/solutions/validator/v1.js | 9 + module/users/helper.js | 110 +++++-- 11 files changed, 934 insertions(+), 54 deletions(-) diff --git a/.env.sample b/.env.sample index ed3a93c5..6722c40b 100644 --- a/.env.sample +++ b/.env.sample @@ -37,3 +37,5 @@ ML_PROJECT_SERVICE_URL = "http://ml-project-service:3000" USER_SERVICE_URL = "http://user-service:3000" // Base url of the sunbird enviornment CSV_REPORTS_PATH = "public/report" // Report path + +APP_PORTAL_BASE_URL = "https://preprod.ntp.net.in" \ No newline at end of file diff --git a/controllers/v1/solutions.js b/controllers/v1/solutions.js index 69963681..ff12ed89 100644 --- a/controllers/v1/solutions.js +++ b/controllers/v1/solutions.js @@ -746,4 +746,241 @@ module.exports = class Solutions extends Abstract { }) } + /** + * @api {get} /kendra/api/v1/solutions/getLink/:solutionId + * @apiVersion 1.0.0 + * @apiName Get link by solution id + * @apiGroup Solutions + * @apiSampleRequest /kendra/api/v1/solutions/getLink/5fa28620b6bd9b757dc4e932 + * @apiHeader {String} X-authenticated-user-token Authenticity token + * @apiUse successBody + * @apiUse errorBody + * @apiParamExample {json} Response: + * { + "message": "Solution Link generated successfully", + "status": 200, + "result": "https://preprod.ntp.net.in/manage-learn/create-observation/38cd93bdb87489c3890fe0ab00e7d406" + } + */ + + /** + * Get link by solution id. + * @method + * @name getLink + * @param {Object} req - requested data. + * @param {String} req.params._id - solution Id + * @returns {Array} + */ + + async getLink(req) { + return new Promise(async (resolve, reject) => { + try { + + let solutionData = await solutionsHelper.getLink( + req.params._id, + req.userDetails.userId + ); + + return resolve(solutionData); + + } + catch (error) { + reject({ + status: error.status || httpStatusCode.internal_server_error.status, + message: error.message || httpStatusCode.internal_server_error.message, + errorObject: error + }) + } + }) + } + + /** + * @api {post} /kendra/api/v1/solutions/verifyLink/:link + * @apiVersion 1.0.0 + * @apiName verify Link + * @apiGroup Solutions + * @apiSampleRequest /kendra/api/v1/solutions/verifyLink/6f8d395f674dcb3146ade10f972da9d0 + * @apiHeader {String} X-authenticated-user-token Authenticity token + * @apiUse successBody + * @apiUse errorBody + * @apiParamExample {json} Request: + * { + * "role" : "HM", + "state" : "236f5cff-c9af-4366-b0b6-253a1789766a", + "district" : "1dcbc362-ec4c-4559-9081-e0c2864c2931", + "school" : "c5726207-4f9f-4f45-91f1-3e9e8e84d824" + } + * @apiParamExample {json} Response: + * { + "message": "Solution Link verified successfully", + "status": 200, + "result": { + isATargetedSolution : true/false, + type: improvementProject, + solutionId : “5f6853f293734140ccce90cf”, + projectId : “”, + obervationId: “”, + surveyId: “” + } + } + */ + + /** + * verify Link + * @method + * @name verifyLink + * @param {Object} req - requested data. + * @param {String} req.params._id - solution Id + * @returns {Array} + */ + + async verifyLink(req) { + return new Promise(async (resolve, reject) => { + try { + + let solutionData = await solutionsHelper.verifyLink( + req.params._id, + req.body, + req.userDetails.userId, + req.userDetails.userToken + ); + + return resolve(solutionData); + + } + catch (error) { + reject({ + status: error.status || httpStatusCode.internal_server_error.status, + message: error.message || httpStatusCode.internal_server_error.message, + errorObject: error + }) + } + }) + } + + /** + * @api {post} /kendra/api/v1/solutions/getDetails/:solutionId + * @apiVersion 1.0.0 + * @apiName verify Link + * @apiGroup Solutions + * @apiSampleRequest /kendra/api/v1/solutions/getDetails/5ff9d50f9259097d48017bbb + * @apiHeader {String} X-authenticated-user-token Authenticity token + * @apiUse successBody + * @apiUse errorBody + * @apiParamExample {json} Request: + * { + * "role" : "HM", + "state" : "236f5cff-c9af-4366-b0b6-253a1789766a", + "district" : "1dcbc362-ec4c-4559-9081-e0c2864c2931", + "school" : "c5726207-4f9f-4f45-91f1-3e9e8e84d824" + } + * @apiParamExample {json} Response: + * { + "message": "Successfully fetched details", + "status": 200, + "result": { + "_id": "5f97d2f6bf3a3b1c0116c80a", + "status": "published", + "isDeleted": false, + "categories": [ + { + "_id": "5f102331665bee6a740714e8", + "name": "Teachers", + "externalId": "teachers" + }, + { + "name": "newCategory", + "externalId": "", + "_id": "" + } + ], + "tasks": [ + { + "_id": "289d9558-b98f-41cf-81d3-92486f114a49", + "name": "Task 1", + "description": "Task 1 description", + "status": "notStarted", + "isACustomTask": false, + "startDate": "2020-09-29T09:08:41.667Z", + "endDate": "2020-09-29T09:08:41.667Z", + "lastModifiedAt": "2020-09-29T09:08:41.667Z", + "type": "single", + "isDeleted": false, + "attachments": [ + { + "name": "download(2).jpeg", + "type": "image/jpeg", + "sourcePath": "projectId/userId/imageName" + } + ], + "remarks": "Tasks completed", + "assignee": "Aman", + "children": [ + { + "_id": "289d9558-b98f-41cf-81d3-92486f114a50", + "name": "Task 2", + "description": "Task 2 description", + "status": "notStarted", + "children": [], + "isACustomTask": false, + "startDate": "2020-09-29T09:08:41.667Z", + "endDate": "2020-09-29T09:08:41.667Z", + "lastModifiedAt": "2020-09-29T09:08:41.667Z", + "type": "single", + "isDeleted": false, + "externalId": "task 2", + "isDeleteable": false, + "createdAt": "2020-10-28T05:58:24.907Z", + "updatedAt": "2020-10-28T05:58:24.907Z", + "isImportedFromLibrary": false + } + ], + "externalId": "task 1", + "isDeleteable": false, + "createdAt": "2020-10-28T05:58:24.907Z", + "updatedAt": "2020-10-28T05:58:24.907Z", + "isImportedFromLibrary": false + } + ], + "resources": [], + "deleted": false, + "__v": 0, + "description": "Project 1 description" + } +} + */ + + /** + * get solution details + * @method + * @name getDetails + * @param {Object} req - requested data. + * @param {String} req.params._id - solution Id + * @returns {Array} + */ + + async getDetails(req) { + return new Promise(async (resolve, reject) => { + try { + + let solutionData = await solutionsHelper.getDetails( + req.params._id, + req.body, + req.userDetails.userId, + req.userDetails.userToken + ); + + return resolve(solutionData); + + } + catch (error) { + reject({ + status: error.status || httpStatusCode.internal_server_error.status, + message: error.message || httpStatusCode.internal_server_error.message, + errorObject: error + }) + } + }) + } + } \ No newline at end of file diff --git a/controllers/v1/users.js b/controllers/v1/users.js index 28c7b4f3..c6b1685e 100644 --- a/controllers/v1/users.js +++ b/controllers/v1/users.js @@ -191,7 +191,8 @@ module.exports = class Users extends Abstract { req.params._id : req.userDetails.id, req.body, - req.userDetails.userToken + req.userDetails.userToken, + req.query.isATargetedSolution ? req.query.isATargetedSolution : "" ); return resolve(createdProgramAndSolution); diff --git a/generics/constants/api-responses.js b/generics/constants/api-responses.js index 6f69a4f7..cf6ae2ee 100644 --- a/generics/constants/api-responses.js +++ b/generics/constants/api-responses.js @@ -168,5 +168,15 @@ module.exports = { "USER_PLATFORM_ROLE_NOT_FOUND": "Not found user platform role", "PLATFORM_USER_PROGRAMS": "List of programs for platform user", "ENTITY_TYPE_REQUIRED": "required entity type", - "COURSE_LINK_REQUIRED" : "Course link is required" + "COURSE_LINK_REQUIRED" : "Course link is required", + "LINK_GENERATED": "Link generated successfully", + "LINK_REQUIRED_CHECK": "Link is required", + "REQUIRED_USER_AUTH_TOKEN": "User auth token is required", + "INVALID_LINK": "The Link is not valid", + "LINK_IS_EXPIRED": "Link is expired", + "LINK_VERIFIED": "Link is verified successfully", + "SOLUTION_DETAILS_VERIFIED": "Solution verified successfully", + "SOLUTION_NOT_FOUND_OR_NOT_A_TARGETED": "Solution is not targeted to the role", + "PROJECT_TEMPLATE_ID_NOT_FOUND": "Project templates not exists in solution", + }; diff --git a/generics/constants/common.js b/generics/constants/common.js index 04b9a5ad..ef3f000f 100644 --- a/generics/constants/common.js +++ b/generics/constants/common.js @@ -58,5 +58,11 @@ module.exports = { "DEFAULT_PAGE_NO" : 1, "DHITI" : "dhiti", "DEFAULT_SURVEY_REMOVED_DAY" : 15, - "COURSE" : "course" + "COURSE" : "course", + "PREFIX_FOR_PROJECT_LINK" : "manage-learn", + "CREATE_OBSERVATION": "/create-observation/", + "CREATE_SURVEY" : "/create-survey/", + "CREATE_PROJECT" : "/create-project/", + "LINK" : "link", + "DISCOVERED_BY_ME" : "discoveredByMe" }; diff --git a/generics/constants/endpoints.js b/generics/constants/endpoints.js index 94054ba3..85f8b7fc 100644 --- a/generics/constants/endpoints.js +++ b/generics/constants/endpoints.js @@ -25,5 +25,8 @@ module.exports = { GET_USER_ASSIGNED_OBSERVATION : "/v1/observations/userAssigned", GET_USER_ASSIGNED_SURVEY : "/v1/surveys/userAssigned", GET_USER_ASSIGNED_PROJECT : "/v1/userProjects/userAssigned", - IMPORTED_PROJECT : "/v1/userProjects/importedProjects" + IMPORTED_PROJECT : "/v1/userProjects/importedProjects", + GET_PROJECT_DETAILS_BY_LINK : "/v1/userProjects/details", + GET_TEMPLATE_DETAILS : "/v1/project/templates/details", + LIST_PROJECT : "/v1/userProjects/list" } \ No newline at end of file diff --git a/generics/helpers/utils.js b/generics/helpers/utils.js index 5bfe2df1..7e7281af 100644 --- a/generics/helpers/utils.js +++ b/generics/helpers/utils.js @@ -7,6 +7,7 @@ // Dependencies const {validate : uuidValidate,v4 : uuidV4} = require('uuid'); +const md5 = require("md5"); /** * convert string to camelCaseToTitleCase. @@ -213,6 +214,17 @@ function convertStringToBoolean(stringData) { return stringToBoolean; } +/** + * md5 hash + * @function + * @name md5Hash + * @returns {String} returns hashed value. +*/ + +function md5Hash(value) { + return md5(value); +} + module.exports = { camelCaseToTitleCase : camelCaseToTitleCase, lowerCase : lowerCase, @@ -226,5 +238,6 @@ module.exports = { epochTime : epochTime, valueParser : valueParser, checkValidUUID : checkValidUUID, - convertStringToBoolean : convertStringToBoolean + convertStringToBoolean : convertStringToBoolean, + md5Hash : md5Hash }; diff --git a/generics/services/improvement-project.js b/generics/services/improvement-project.js index 34b5737e..9279c4d9 100644 --- a/generics/services/improvement-project.js +++ b/generics/services/improvement-project.js @@ -7,7 +7,7 @@ //dependencies const request = require('request'); -process.env.ML_PROJECT_SERVICE_URL = "http://ml-projects-service:3000" +// process.env.ML_PROJECT_SERVICE_URL = "http://ml-projects-service:3000" /** * List of user assigned projects. @@ -29,8 +29,6 @@ var assignedProjects = function ( token,search = "",filter = "" ) { if( filter !== "" ) { url = url + "&filter=" + filter; } - - console.log("url is",url); return new Promise(async (resolve, reject) => { try { @@ -42,13 +40,10 @@ var assignedProjects = function ( token,search = "",filter = "" ) { }; if (err) { - console.log("error is",err); result.success = false; } else { let response = JSON.parse(data.body); - console.log("response is",response); - if( response.status === httpStatusCode['ok'].status ) { result["data"] = response.result; } else { @@ -135,7 +130,198 @@ var importedProjects = function ( token,programId = "" ) { } +/** + * Get project detail by solutionId. + * @function + * @name getDetail + * @param {String} token - logged in user token. + * @param {String} link - link + * @param {Object} bodyData - bodyData + * @returns {Promise} returns a promise. +*/ + +var getDetail = function ( solutionId, token, bodyData = {} ) { + + let getProjectDetailByLinkUrl = + process.env.ML_PROJECT_SERVICE_URL + + constants.endpoints.GET_PROJECT_DETAILS_BY_LINK + "?solutionId=" + solutionId; + + return new Promise(async (resolve, reject) => { + try { + + function improvementProjectCallback(err, data) { + + let result = { + success : true, + message: "", + status:"" + }; + + if (err) { + result.success = false; + } else { + + let response = data.body; + if( response.status === httpStatusCode['ok'].status ) { + result["data"] = response.result; + } else { + result.success = false; + } + + result.message = response.message; + result.status = response.status; + } + + return resolve(result); + } + + const options = { + headers : { + "content-type": "application/json", + "x-authenticated-user-token" : token + } + }; + + if( bodyData !== "" ) { + options.json = bodyData + } + + request.get(getProjectDetailByLinkUrl,options,improvementProjectCallback) + + } catch (error) { + return reject(error); + } + }) + +} + +/** + * Get template detail. + * @function + * @name getTemplateDetail + * @param {String} token - logged in user token. + * @param {String} templateId - templateId + * @returns {Promise} returns a promise. +*/ + +var getTemplateDetail = function ( templateId, token ) { + + let url = + process.env.ML_PROJECT_SERVICE_URL + + constants.endpoints.GET_TEMPLATE_DETAILS + "/" + templateId; + + return new Promise(async (resolve, reject) => { + try { + + function improvementProjectCallback(err, data) { + + let result = { + success : true, + message: "", + status:"" + }; + + if (err) { + result.success = false; + } else { + + let response = JSON.parse(data.body); + if( response.status == httpStatusCode['ok'].status ) { + result["result"] = response.result; + } else { + result.success = false; + } + + result.message = response.message; + result.status = response.status; + } + + return resolve(result); + } + + const options = { + headers : { + "content-type": "application/json", + "x-authenticated-user-token" : token + } + }; + + request.get(url,options,improvementProjectCallback) + + } catch (error) { + return reject(error); + } + }) + +} + +/** + * List of project. + * @function + * @name projectDocuments + * @param {Object} filterData - Filter data. + * @param {Array} projection - Projected data. + * @param {Array} skipFields - Field to skip. + * @returns {JSON} - List of projects. +*/ + +const projectDocuments = function ( + userToken, + filterData = "all", + projection = "all", + skipFields = "none", +) { + return new Promise(async (resolve, reject) => { + try { + + const url = process.env.ML_PROJECT_SERVICE_URL + constants.endpoints.LIST_PROJECT; + + function improvementProjectCallback(err, data) { + + let result = { + success : true + }; + + if (err) { + result.success = false; + } else { + + let response = data.body; + if( response.status === httpStatusCode['ok'].status) { + result["data"] = response.result; + } else { + result.success = false; + } + } + + return resolve(result); + } + + const options = { + headers : { + "content-type": "application/json", + // "internal-access-token": process.env.INTERNAL_ACCESS_TOKEN, + "x-authenticated-user-token" : userToken + }, + json : { + query : filterData, + projection : projection, + skipFields : skipFields + } + }; + + request.post(url,options,improvementProjectCallback); + + } catch (error) { + return reject(error); + } + }) +} + module.exports = { assignedProjects : assignedProjects, - importedProjects : importedProjects + importedProjects : importedProjects, + getDetail : getDetail, + getTemplateDetail : getTemplateDetail, + projectDocuments : projectDocuments } \ No newline at end of file diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 4d3acfb1..7ede98e2 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -8,11 +8,12 @@ // Dependencies const programsHelper = require(MODULES_BASE_PATH + "/programs/helper"); -const entityTypesHelper = require(MODULES_BASE_PATH + "/entityTypes/helper"); +const entitysolutionTypesHelper = require(MODULES_BASE_PATH + "/entityTypes/helper"); const entitiesHelper = require(MODULES_BASE_PATH + "/entities/helper"); const userRolesHelper = require(MODULES_BASE_PATH + "/user-roles/helper"); const assessmentService = require(ROOT_PATH + '/generics/services/samiksha'); const improvementProjectService = require(ROOT_PATH + '/generics/services/improvement-project'); +const appsPortalBaseUrl = (process.env.APP_PORTAL_BASE_URL && process.env.APP_PORTAL_BASE_URL !== "") ? process.env.APP_PORTAL_BASE_URL + "/" : "https://apps.shikshalokam.org/"; /** * SolutionsHelper @@ -1331,19 +1332,27 @@ module.exports = class SolutionsHelper { success : false }; - surveyReportPage = gen.utils.convertStringToBoolean(surveyReportPage); - if ( !surveyReportPage || solutionType == constants.common.COURSE ) { - - targetedSolutions = - await this.forUserRoleAndLocation( - requestedData, - solutionType, - "", - "", - constants.common.DEFAULT_PAGE_SIZE, - constants.common.DEFAULT_PAGE_NO, - search - ); + let getTargetedSolution = true; + + if(filter === constants.common.DISCOVERED_BY_ME){ + getTargetedSolution = false; + }else if (solutionType === constants.common.COURSE){ + getTargetedSolution = true; + }else if (gen.utils.convertStringToBoolean(surveyReportPage) === true ){ + getTargetedSolution = false; + } + + if( getTargetedSolution ) { + targetedSolutions = + await this.forUserRoleAndLocation( + requestedData, + solutionType, + "", + "", + constants.common.DEFAULT_PAGE_SIZE, + constants.common.DEFAULT_PAGE_NO, + search + ); } if( targetedSolutions.success ) { @@ -1445,6 +1454,330 @@ module.exports = class SolutionsHelper { } }) } + + /** + * Get link by solution id + * @method + * @name getLink + * @param {String} solutionId - solution Id. + * @param {String} appName - app Name. + * @param {String} userId - user Id. + * @returns {Object} - Details of the solution. + */ + + static getLink( solutionId, userId ) { + return new Promise(async (resolve, reject) => { + try { + + let solutionData = await this.solutionDocuments({ + _id : solutionId, + isReusable : false, + isAPrivateProgram: false + },[ + "link","type","author" + ]); + + if ( !Array.isArray(solutionData) || solutionData.length < 1 ) { + return resolve({ + message: constants.apiResponses.SOLUTION_NOT_FOUND, + result: {} + }); + } + + + let prefix = constants.common.PREFIX_FOR_PROJECT_LINK; + + let solutionLink, link; + + if ( !solutionData[0].link ) { + + let updateLink = await gen.utils.md5Hash(solutionData[0]._id + "###" + solutionData[0].author); + let updateSolution = await this.update(solutionId, { link : updateLink } , userId ); + + solutionLink = updateLink; + + } else { + solutionLink = solutionData[0].link; + } + + link = _generateLink(appsPortalBaseUrl, prefix, solutionLink, solutionData[0].type); + + return resolve({ + success : true, + message: constants.apiResponses.LINK_GENERATED, + result: link + }); + + } catch(error) { + return resolve({ + success : false, + status : error.status ? + error.status : httpStatusCode['internal_server_error'].status, + message : error.message + }) + } + }) + } + + /** + * Verify solution link + * @method + * @name verifyLink + * @param {String} solutionId - solution Id. + * @param {String} userId - user Id. + * @param {Object} bodyData - Req Body. + * @returns {Object} - Details of the solution. + */ + + static verifyLink( link = "", bodyData = {}, userId = "", userToken = "" ) { + return new Promise(async (resolve, reject) => { + try { + + let verifySolution = await this.verifySolutionDetails( link, userId, userToken ); + let checkForTargetedSolution = await this.checkForTargetedSolution( link, bodyData, userId, userToken ); + + if ( checkForTargetedSolution && Object.keys( checkForTargetedSolution.result ).length > 0 ) { + + let solutionData = checkForTargetedSolution.result; + if ( !checkForTargetedSolution.result.isATargetedSolution ) { + + if ( solutionData.type == constants.common.IMPROVEMENT_PROJECT ) { + + let filterQuery = { + createdBy: userId, + referenceFrom: constants.common.LINK, + link: link + } + + let checkForProjectExist = await improvementProjectService.projectDocuments( userToken, filterQuery, [ "_id" ] ); + if ( checkForProjectExist.success && checkForProjectExist.data && checkForProjectExist.data.length > 0 && checkForProjectExist.data[ 0 ]._id != "" ) { + checkForTargetedSolution.result[ "projectId" ] = checkForProjectExist.data[ 0 ]._id; + } + } + + } + else { + + let detailFromLink; + if ( solutionData.type == constants.common.IMPROVEMENT_PROJECT ) { + + detailFromLink = await improvementProjectService.getDetail( solutionData.solutionId, userToken, bodyData ); + + if ( !detailFromLink || !detailFromLink.data ) { + return resolve( detailFromLink ) + } + + if ( solutionData.type == constants.common.IMPROVEMENT_PROJECT && detailFromLink.data._id != "" ) { + checkForTargetedSolution.result[ "projectId" ] = detailFromLink.data._id ? detailFromLink.data._id : ""; + } + } + } + + } + + return resolve( checkForTargetedSolution ); + + } catch ( error ) { + return resolve({ + success: false, + status: error.status ? + error.status : httpStatusCode[ 'internal_server_error' ].status, + message: error.message + }) + } + }) + } + + /** + * Verify Solution details. + * @method + * @name verifySolutionDetails + * @param {String} solutionId - Program Id. + * @returns {Object} - Details of the solution. + */ + + static verifySolutionDetails(link = "", userId = "", userToken = "") { + return new Promise(async (resolve, reject) => { + try { + + let response = { + verified: false + }; + + if (link == "") { + throw new Error(constants.apiResponses.LINK_REQUIRED_CHECK) + } + + if (userToken == "") { + throw new Error(constants.apiResponses.REQUIRED_USER_AUTH_TOKEN) + } + + if (userId == "") { + throw new Error(constants.apiResponses.USER_ID_REQUIRED_CHECK) + } + + let solutionData = await this.solutionDocuments({ + link: link, + isReusable: false, + status: { + $ne: constants.common.IN_ACTIVE + } + }, [ + "type", "status", "endDate" + ]); + + if (!Array.isArray(solutionData) || solutionData.length < 1) { + return resolve({ + message: constants.apiResponses.INVALID_LINK, + result: [] + }); + } + + if (solutionData[0].status !== constants.common.ACTIVE) { + return resolve({ + message: constants.apiResponses.LINK_IS_EXPIRED, + result: [] + }); + } + + if (solutionData[0].endDate && new Date() > new Date(solutionData[0].endDate)) { + if (solutionData[0].status === constants.common.ACTIVE) { + let updateSolution = await this.update(solutionData[0]._id, { + status: constants.common.IN_ACTIVE + }, userId); + } + + return resolve({ + message: constants.apiResponses.LINK_IS_EXPIRED, + result: [] + }); + } + + response.verified = true; + return resolve({ + message: constants.apiResponses.LINK_VERIFIED, + result: response + }); + + } catch (error) { + return resolve({ + success: false, + status: error.status ? + error.status : httpStatusCode['internal_server_error'].status, + message: error.message + }) + } + }) + } + + /** + * Check the user is targeted. + * @method + * @name checkForTargetedSolution + * @param {String} link - Solution link. + * @returns {Object} - Details of the solution. + */ + + static checkForTargetedSolution( link = "", bodyData = {}, userId = "", userToken = "" ) { + return new Promise(async (resolve, reject) => { + try { + + let response = { + isATargetedSolution : false, + link : link + }; + + let solutionDetails = await this.solutionDocuments({link:link},["type","_id"]); + + let queryData = await this.queryBasedOnRoleAndLocation(bodyData); + if( !queryData.success ) { + return resolve(queryData); + } + + queryData.data["link"] = link; + let matchQuery = queryData.data; + + let solutionData = await this.solutionDocuments(matchQuery, ["_id","link","type"]); + + if( !Array.isArray(solutionData) || solutionData.length < 1 ) { + response.solutionId = solutionDetails[0]._id; + response.type = solutionDetails[0].type; + return resolve({ + success : true, + message: constants.apiResponses.SOLUTION_NOT_FOUND_OR_NOT_A_TARGETED, + result: response + }); + } + + response.isATargetedSolution = true; + Object.assign(response, solutionData[0]); + response.solutionId = solutionData[0]._id; + delete response._id; + + return resolve({ + success : true, + message: constants.apiResponses.SOLUTION_DETAILS_VERIFIED, + result: response + }); + + } catch(error) { + return resolve({ + success : false, + status : error.status ? + error.status : httpStatusCode['internal_server_error'].status, + message : error.message + }) + } + }) + } + + /** + * Fetch template observation based on solution Id. + * @method + * @name getDetails + * @param {String} solutionId - Solution Id. + * @returns {Object} - Details of the solution. + */ + + static getDetails( solutionId, bodyData = {}, userId = "", userToken = "" ) { + return new Promise(async (resolve, reject) => { + try { + + let solutionData = await this.solutionDocuments({_id:solutionId},["type", "projectTemplateId"]); + if (!Array.isArray(solutionData) || solutionData.length < 1) { + return resolve({ + message: constants.apiResponses.SOLUTION_NOT_FOUND, + result: [] + }); + } + + solutionData = solutionData[0]; + let templateOrQuestionDetails; + + if( solutionData.type === constants.common.IMPROVEMENT_PROJECT ) { + + if( !solutionData.projectTemplateId ) { + throw { + message : constants.apiResponses.PROJECT_TEMPLATE_ID_NOT_FOUND + } + } + + templateOrQuestionDetails = await improvementProjectService.getTemplateDetail( solutionData.projectTemplateId, userToken ); + } + + return resolve(templateOrQuestionDetails); + + } catch(error) { + return resolve({ + success : false, + status : error.status ? + error.status : httpStatusCode['internal_server_error'].status, + message : error.message + }) + } + }) + } + }; /** @@ -1462,3 +1795,29 @@ function _targetedSolutionTypes() { constants.common.COURSE ] } + +/** + * Generate sharing Link. + * @method + * @name _targetedSolutionTypes + * @returns {Array} - Targeted solution types + */ + +function _generateLink(appsPortalBaseUrl, prefix, solutionLink, solutionType) { + + let link; + + switch( solutionType ) { + case constants.common.OBSERVATION: + link = appsPortalBaseUrl + prefix + constants.common.CREATE_OBSERVATION + solutionLink; + break; + case constants.common.IMPROVEMENT_PROJECT: + link = appsPortalBaseUrl + prefix + constants.common.CREATE_PROJECT + solutionLink; + break; + default: + link = appsPortalBaseUrl + prefix + constants.common.CREATE_SURVEY + solutionLink; + } + + return link; + +} diff --git a/module/solutions/validator/v1.js b/module/solutions/validator/v1.js index 4c8a429c..61eb7862 100644 --- a/module/solutions/validator/v1.js +++ b/module/solutions/validator/v1.js @@ -43,6 +43,15 @@ module.exports = (req) => { }, getSolutions : function () { req.checkQuery("type").exists().withMessage("required solution type") + }, + getLink : function () { + req.checkParams("_id").exists().withMessage("required solution id"); + }, + verifyLink : function () { + req.checkParams("_id").exists().withMessage("required solution link"); + }, + getDetails : function () { + req.checkParams("_id").exists().withMessage("required solution Id"); } } diff --git a/module/users/helper.js b/module/users/helper.js index 4c2569ed..4cc8e909 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -59,23 +59,24 @@ module.exports = class UsersHelper { * @returns {Array} - Created user program and solution. */ - static createProgramAndSolution(userId, data) { + static createProgramAndSolution(userId, data, isATargetedSolution = "") { return new Promise(async (resolve, reject) => { try { let userPrivateProgram = {}; let dateFormat = gen.utils.epochTime(); + let parentSolutionInformation = {}; - if (data.programId && data.programId !== "") { + isATargetedSolution = gen.utils.convertStringToBoolean(isATargetedSolution); + //program part + if( data.programId && data.programId !== ""){ - userPrivateProgram = await programsHelper.programDocuments( + let checkforProgramExist = await programsHelper.programDocuments( { - _id: data.programId, - createdBy: userId - } - ); + _id: data.programId + },"all",["__v"]); - if (!userPrivateProgram.length > 0) { + if (!checkforProgramExist.length > 0) { return resolve({ status: httpStatusCode['bad_request'].status, message: constants.apiResponses.PROGRAM_NOT_FOUND, @@ -83,10 +84,28 @@ module.exports = class UsersHelper { }) } - userPrivateProgram = userPrivateProgram[0]; + if(isATargetedSolution === false){ - } else { + let duplicateProgram = checkforProgramExist[0]; + duplicateProgram.externalId = duplicateProgram.name + "-" + dateFormat, + duplicateProgram.isAPrivateProgram = true; + duplicateProgram.status = constants.common.ACTIVE_STATUS; + duplicateProgram.userId = userId; + duplicateProgram.createdBy = userId; + + userPrivateProgram = await programsHelper.create( + _.omit( + duplicateProgram, + ["_id", "components","scope"] + ) + ); + }else{ + userPrivateProgram = checkforProgramExist[0]; + } + + }else{ + let programData = { name: data.programName, isAPrivateProgram: true, @@ -116,6 +135,7 @@ module.exports = class UsersHelper { isAPrivateProgram: userPrivateProgram.isAPrivateProgram }; + //entities if ( Array.isArray(data.entities) && data.entities && data.entities.length > 0) { let entityData = await entitiesHelper.entityDocuments( @@ -140,15 +160,14 @@ module.exports = class UsersHelper { solutionDataToBeUpdated["entityTypeId"] = entityData[0].entityTypeId; } + //solution part let solution = "" - - if (data.solutionId && data.solutionId !== "") { + if(data.solutionId && data.solutionId !== ""){ let solutionData = await solutionsHelper.solutionDocuments({ - _id: data.solutionId, - isReusable: false - }, ["_id"]); + _id: data.solutionId + },["name","link","type","subType"]); if (!solutionData.length > 0) { @@ -159,20 +178,54 @@ module.exports = class UsersHelper { }) } - solution = - await database.models.solutions.findOneAndUpdate({ - _id: solutionData[0]._id - }, { - $set: solutionDataToBeUpdated - }, { - new: true - }); + if(isATargetedSolution === false){ + + let duplicateSolution = solutionData[0]; + duplicateSolution.externalId = duplicateSolution.name + "-" + dateFormat; + duplicateSolution.isAPrivateProgram = true; + duplicateSolution.isReusable = false; + duplicateSolution.name = duplicateSolution.name; + duplicateSolution.description = duplicateSolution.description; + duplicateSolution.status = constants.common.ACTIVE_STATUS; + duplicateSolution.userId = userId; + duplicateSolution.parentSolutionId = duplicateSolution._id; + + _.merge(duplicateSolution, solutionDataToBeUpdated); + + solution = await solutionsHelper.create( + _.omit( + duplicateSolution, + ["_id","link"] + ) + ); + parentSolutionInformation.solutionId = duplicateSolution._id; + parentSolutionInformation.link = duplicateSolution.link; - } else { + }else{ + + if(solutionData[0].isReusable === false){ + return resolve({ + status: httpStatusCode['bad_request'].status, + message: constants.apiResponses.SOLUTION_NOT_FOUND, + result: {} + }) + } + + solution = + await database.models.solutions.findOneAndUpdate({ + _id: solutionData[0]._id + }, { + $set: solutionDataToBeUpdated + }, { + new: true + }); + } + + }else{ solutionDataToBeUpdated["type"] = - data.type ? data.type : constants.common.ASSESSMENT; + data.type ? data.type : constants.common.ASSESSMENT; solutionDataToBeUpdated["subType"] = data.subType ? data.subType : constants.common.INSTITUTIONAL; @@ -192,11 +245,10 @@ module.exports = class UsersHelper { } solutionDataToBeUpdated.updatedBy = userId; - solution = await solutionsHelper.create(solutionDataToBeUpdated); } - if (solution._id) { + if (solution && solution._id) { await database.models.programs.findOneAndUpdate( { @@ -204,13 +256,15 @@ module.exports = class UsersHelper { }, { $addToSet: { components: ObjectId(solution._id) } }); + } return resolve({ message: constants.apiResponses.USER_PROGRAM_AND_SOLUTION_CREATED, result: { program: userPrivateProgram, - solution: solution + solution: solution, + parentSolutionInformation : parentSolutionInformation } }); From 9bf9df506589833987504d8c037f70ed9d6d7b82 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Wed, 13 Oct 2021 02:26:42 +0530 Subject: [PATCH 043/331] PR changes --- .env.sample | 2 +- controllers/v1/solutions.js | 26 +- controllers/v1/users.js | 2 +- envVariables.js | 5 + generics/constants/common.js | 2 +- generics/constants/endpoints.js | 2 +- generics/services/improvement-project.js | 13 +- module/solutions/helper.js | 1105 +++++++++-------- module/solutions/validator/v1.js | 2 +- module/users/helper.js | 1398 ++++++++++++---------- 10 files changed, 1371 insertions(+), 1186 deletions(-) diff --git a/.env.sample b/.env.sample index 6722c40b..81301951 100644 --- a/.env.sample +++ b/.env.sample @@ -38,4 +38,4 @@ ML_PROJECT_SERVICE_URL = "http://ml-project-service:3000" USER_SERVICE_URL = "http://user-service:3000" // Base url of the sunbird enviornment CSV_REPORTS_PATH = "public/report" // Report path -APP_PORTAL_BASE_URL = "https://preprod.ntp.net.in" \ No newline at end of file +APP_PORTAL_BASE_URL = "https://dev.sunbirded.org" \ No newline at end of file diff --git a/controllers/v1/solutions.js b/controllers/v1/solutions.js index ff12ed89..588ba8c7 100644 --- a/controllers/v1/solutions.js +++ b/controllers/v1/solutions.js @@ -538,12 +538,12 @@ module.exports = class Solutions extends Abstract { } /** - * @api {get} /kendra/api/v1/solutions/details/:solutionId Solution details + * @api {get} /kendra/api/v1/solutions/getDetails/:solutionId Solution details * @apiVersion 1.0.0 * @apiName Details of the solution. * @apiGroup Solutions * @apiHeader {String} X-authenticated-user-token Authenticity token - * @apiSampleRequest /kendra/api/v1/solutions/details/5ffbf8909259097d48017bbf + * @apiSampleRequest /kendra/api/v1/solutions/getDetails/5ffbf8909259097d48017bbf * @apiUse successBody * @apiUse errorBody * @apiParamExample {json} Response: @@ -641,17 +641,17 @@ module.exports = class Solutions extends Abstract { /** * Details of the solution. * @method - * @name details + * @name getDetails * @param {Object} req - requested data. * @param {String} req.params._id - solution id. * @returns {Object} Solution details */ - async details(req) { + async getDetails(req) { return new Promise(async (resolve, reject) => { try { - let solutionData = await solutionsHelper.details( + let solutionData = await solutionsHelper.getDetails( req.params._id ); @@ -747,11 +747,11 @@ module.exports = class Solutions extends Abstract { } /** - * @api {get} /kendra/api/v1/solutions/getLink/:solutionId + * @api {get} /kendra/api/v1/solutions/fetchLink/:solutionId * @apiVersion 1.0.0 * @apiName Get link by solution id * @apiGroup Solutions - * @apiSampleRequest /kendra/api/v1/solutions/getLink/5fa28620b6bd9b757dc4e932 + * @apiSampleRequest /kendra/api/v1/solutions/fetchLink/5fa28620b6bd9b757dc4e932 * @apiHeader {String} X-authenticated-user-token Authenticity token * @apiUse successBody * @apiUse errorBody @@ -766,17 +766,17 @@ module.exports = class Solutions extends Abstract { /** * Get link by solution id. * @method - * @name getLink + * @name fetchLink * @param {Object} req - requested data. * @param {String} req.params._id - solution Id * @returns {Array} */ - async getLink(req) { + async fetchLink(req) { return new Promise(async (resolve, reject) => { try { - let solutionData = await solutionsHelper.getLink( + let solutionData = await solutionsHelper.fetchLink( req.params._id, req.userDetails.userId ); @@ -953,17 +953,17 @@ module.exports = class Solutions extends Abstract { /** * get solution details * @method - * @name getDetails + * @name details * @param {Object} req - requested data. * @param {String} req.params._id - solution Id * @returns {Array} */ - async getDetails(req) { + async details(req) { return new Promise(async (resolve, reject) => { try { - let solutionData = await solutionsHelper.getDetails( + let solutionData = await solutionsHelper.details( req.params._id, req.body, req.userDetails.userId, diff --git a/controllers/v1/users.js b/controllers/v1/users.js index c6b1685e..99ecfa7d 100644 --- a/controllers/v1/users.js +++ b/controllers/v1/users.js @@ -192,7 +192,7 @@ module.exports = class Users extends Abstract { req.userDetails.id, req.body, req.userDetails.userToken, - req.query.isATargetedSolution ? req.query.isATargetedSolution : "" + req.query.createADuplicateSolution ? req.query.createADuplicateSolution : "" ); return resolve(createdProgramAndSolution); diff --git a/envVariables.js b/envVariables.js index 0056a831..ee9f0312 100644 --- a/envVariables.js +++ b/envVariables.js @@ -124,6 +124,11 @@ let enviromentVariables = { "message" : "CSV Report Path", "optional" : true, "default": "public/reports" + }, + "APP_PORTAL_BASE_URL" : { + "message" : "App Portal base url", + "optional" : true, + "default": "https://dev.sunbirded.org" } } diff --git a/generics/constants/common.js b/generics/constants/common.js index ef3f000f..fc9eb7b9 100644 --- a/generics/constants/common.js +++ b/generics/constants/common.js @@ -19,7 +19,7 @@ module.exports = { "STATE_ENTITY_TYPE":"state", "ALL_APP_VERSION" : "allAppVersion", "ACTIVE" : "active", - "IN_ACTIVE" : "inactive", + "INACTIVE" : "inactive", "BODH_DIAL_CODE_LIVE_STATUS" : "Live", "GOA_STATE" : "Goa", "UNNATI_APP_NAME" : "unnati", diff --git a/generics/constants/endpoints.js b/generics/constants/endpoints.js index 85f8b7fc..16c1dc46 100644 --- a/generics/constants/endpoints.js +++ b/generics/constants/endpoints.js @@ -26,7 +26,7 @@ module.exports = { GET_USER_ASSIGNED_SURVEY : "/v1/surveys/userAssigned", GET_USER_ASSIGNED_PROJECT : "/v1/userProjects/userAssigned", IMPORTED_PROJECT : "/v1/userProjects/importedProjects", - GET_PROJECT_DETAILS_BY_LINK : "/v1/userProjects/details", + GET_PROJECT_DETAILS : "/v1/userProjects/details", GET_TEMPLATE_DETAILS : "/v1/project/templates/details", LIST_PROJECT : "/v1/userProjects/list" } \ No newline at end of file diff --git a/generics/services/improvement-project.js b/generics/services/improvement-project.js index 9279c4d9..6393c7f6 100644 --- a/generics/services/improvement-project.js +++ b/generics/services/improvement-project.js @@ -7,7 +7,6 @@ //dependencies const request = require('request'); -// process.env.ML_PROJECT_SERVICE_URL = "http://ml-projects-service:3000" /** * List of user assigned projects. @@ -133,18 +132,18 @@ var importedProjects = function ( token,programId = "" ) { /** * Get project detail by solutionId. * @function - * @name getDetail + * @name getProjectDetail * @param {String} token - logged in user token. * @param {String} link - link * @param {Object} bodyData - bodyData * @returns {Promise} returns a promise. */ -var getDetail = function ( solutionId, token, bodyData = {} ) { +var getProjectDetail = function ( solutionId, token, bodyData = {} ) { - let getProjectDetailByLinkUrl = + let getProjectDetailUrl = process.env.ML_PROJECT_SERVICE_URL + - constants.endpoints.GET_PROJECT_DETAILS_BY_LINK + "?solutionId=" + solutionId; + constants.endpoints.GET_PROJECT_DETAILS + "?solutionId=" + solutionId; return new Promise(async (resolve, reject) => { try { @@ -186,7 +185,7 @@ var getDetail = function ( solutionId, token, bodyData = {} ) { options.json = bodyData } - request.get(getProjectDetailByLinkUrl,options,improvementProjectCallback) + request.get(getProjectDetailUrl,options,improvementProjectCallback) } catch (error) { return reject(error); @@ -321,7 +320,7 @@ const projectDocuments = function ( module.exports = { assignedProjects : assignedProjects, importedProjects : importedProjects, - getDetail : getDetail, + getProjectDetail : getProjectDetail, getTemplateDetail : getTemplateDetail, projectDocuments : projectDocuments } \ No newline at end of file diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 7ede98e2..638833e4 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -8,29 +8,28 @@ // Dependencies const programsHelper = require(MODULES_BASE_PATH + "/programs/helper"); -const entitysolutionTypesHelper = require(MODULES_BASE_PATH + "/entityTypes/helper"); +const entityTypesHelper = require(MODULES_BASE_PATH + "/entityTypes/helper"); const entitiesHelper = require(MODULES_BASE_PATH + "/entities/helper"); const userRolesHelper = require(MODULES_BASE_PATH + "/user-roles/helper"); const assessmentService = require(ROOT_PATH + '/generics/services/samiksha'); const improvementProjectService = require(ROOT_PATH + '/generics/services/improvement-project'); -const appsPortalBaseUrl = (process.env.APP_PORTAL_BASE_URL && process.env.APP_PORTAL_BASE_URL !== "") ? process.env.APP_PORTAL_BASE_URL + "/" : "https://apps.shikshalokam.org/"; +const appsPortalBaseUrl = (process.env.APP_PORTAL_BASE_URL && process.env.APP_PORTAL_BASE_URL !== "") ? process.env.APP_PORTAL_BASE_URL + "/" : "https://dev.sunbirded.org/"; /** * SolutionsHelper * @class */ module.exports = class SolutionsHelper { - - /** + /** * Solution Data * @method * @name solutionDocuments * @param {Array} [filterQuery = "all"] - solution ids. * @param {Array} [fieldsArray = "all"] - projected fields. * @param {Array} [skipFields = "none"] - field not to include - * @returns {Array} List of solutions. + * @returns {Array} List of solutions. */ - + static solutionDocuments( filterQuery = "all", fieldsArray = "all", @@ -94,7 +93,7 @@ module.exports = class SolutionsHelper { }); } - /** + /** * Create solution. * @method * @name createSolution @@ -102,7 +101,7 @@ module.exports = class SolutionsHelper { * @returns {JSON} solution creation data. */ - static createSolution(solutionData) { + static createSolution(solutionData) { return new Promise(async (resolve, reject) => { try { @@ -217,7 +216,7 @@ module.exports = class SolutionsHelper { }); } - /** + /** * Set scope in solution * @method * @name setScope @@ -230,7 +229,7 @@ module.exports = class SolutionsHelper { * @returns {JSON} - scope in solution. */ - static setScope( programId,solutionId,scopeData ) { + static setScope( programId,solutionId,scopeData ) { return new Promise(async (resolve, reject) => { @@ -397,7 +396,7 @@ module.exports = class SolutionsHelper { } }) - } + } /** * Update solution. @@ -408,7 +407,7 @@ module.exports = class SolutionsHelper { * @returns {JSON} solution creation data. */ - static update(solutionId, solutionData, userId) { + static update(solutionId, solutionData, userId) { return new Promise(async (resolve, reject) => { try { @@ -493,7 +492,7 @@ module.exports = class SolutionsHelper { * @returns {JSON} List of solutions. */ - static list(type,subType,filter = {},pageNo,pageSize,searchText,projection) { + static list(type,subType,filter = {},pageNo,pageSize,searchText,projection) { return new Promise(async (resolve, reject) => { try { @@ -502,7 +501,7 @@ module.exports = class SolutionsHelper { }; if( type == constants.common.SURVEY ) { - matchQuery["status"] = { $in: [ constants.common.ACTIVE, constants.common.IN_ACTIVE ] } + matchQuery["status"] = { $in: [ constants.common.ACTIVE, constants.common.INACTIVE ] } } else { matchQuery.status = constants.common.ACTIVE ; } @@ -617,106 +616,106 @@ module.exports = class SolutionsHelper { * @returns {JSON} - List of solutions based on role and location. */ - static forUserRoleAndLocation( - bodyData, - type, - subType = "", - programId, - pageSize, - pageNo, - searchText = "" - ) { - return new Promise(async (resolve, reject) => { - try { - - let queryData = await this.queryBasedOnRoleAndLocation( - bodyData, - type, - subType, - programId - ); - - if( !queryData.success ) { - return resolve(queryData); - } - - let matchQuery = queryData.data; - - if( type === "" && subType === "" ) { - - let targetedTypes = _targetedSolutionTypes(); - - matchQuery["$or"] = []; - - targetedTypes.forEach( type => { + static forUserRoleAndLocation( + bodyData, + type, + subType = "", + programId, + pageSize, + pageNo, + searchText = "" + ) { + return new Promise(async (resolve, reject) => { + try { + + let queryData = await this.queryBasedOnRoleAndLocation( + bodyData, + type, + subType, + programId + ); + + if( !queryData.success ) { + return resolve(queryData); + } + + let matchQuery = queryData.data; + + if( type === "" && subType === "" ) { - let singleType = { - type : type - }; - - if( type === constants.common.IMPROVEMENT_PROJECT ) { - singleType["projectTemplateId"] = { $exists : true }; + let targetedTypes = _targetedSolutionTypes(); + + matchQuery["$or"] = []; + + targetedTypes.forEach( type => { + + let singleType = { + type : type + }; + + if( type === constants.common.IMPROVEMENT_PROJECT ) { + singleType["projectTemplateId"] = { $exists : true }; + } + + matchQuery["$or"].push(singleType); + }) + } else { + + if( type !== "" ) { + matchQuery["type"] = type; + } + + if( subType !== "" ) { + matchQuery["subType"] = subType; } - - matchQuery["$or"].push(singleType); - }) - } else { - - if( type !== "" ) { - matchQuery["type"] = type; } - - if( subType !== "" ) { - matchQuery["subType"] = subType; + + if ( programId !== "" ) { + matchQuery["programId"] = ObjectId(programId); } + + let targetedSolutions = await this.list( + type, + subType, + matchQuery, + pageNo, + pageSize, + searchText, + [ + "name", + "description", + "programName", + "programId", + "externalId", + "projectTemplateId", + "type", + "language", + "creator", + "endDate", + "link" + ] + ); + + return resolve({ + success: true, + message: constants.apiResponses.TARGETED_SOLUTIONS_FETCHED, + data: targetedSolutions.data + }); + + } catch (error) { + + return resolve({ + success : false, + message : error.message, + data : {} + }); + } + + }) + } - if ( programId !== "" ) { - matchQuery["programId"] = ObjectId(programId); - } - - let targetedSolutions = await this.list( - type, - subType, - matchQuery, - pageNo, - pageSize, - searchText, - [ - "name", - "description", - "programName", - "programId", - "externalId", - "projectTemplateId", - "type", - "language", - "creator", - "endDate", - "link" - ] - ); - - return resolve({ - success: true, - message: constants.apiResponses.TARGETED_SOLUTIONS_FETCHED, - data: targetedSolutions.data - }); - - } catch (error) { - - return resolve({ - success : false, - message : error.message, - data : {} - }); - - } - - }) - } - - /** + /** * Auto targeted query field. * @method * @name queryBasedOnRoleAndLocation @@ -724,7 +723,7 @@ module.exports = class SolutionsHelper { * @returns {JSON} - Auto targeted solutions query. */ - static queryBasedOnRoleAndLocation( data, type = "" ) { + static queryBasedOnRoleAndLocation( data, type = "" ) { return new Promise(async (resolve, reject) => { try { @@ -766,7 +765,7 @@ module.exports = class SolutionsHelper { if( type === constants.common.SURVEY ) { - filterQuery["status"] = { $in: [ constants.common.ACTIVE, constants.common.IN_ACTIVE ] } + filterQuery["status"] = { $in: [ constants.common.ACTIVE, constants.common.INACTIVE ] } let validDate = new Date(); validDate.setDate(validDate.getDate() - constants.common.DEFAULT_SURVEY_REMOVED_DAY ); filterQuery["endDate"] = { $gte : validDate } @@ -812,7 +811,7 @@ module.exports = class SolutionsHelper { }) } - /** + /** * Details of solution based on role and location. * @method * @name detailsBasedOnRoleAndLocation @@ -821,7 +820,7 @@ module.exports = class SolutionsHelper { * @returns {JSON} - Details of solution based on role and location. */ - static detailsBasedOnRoleAndLocation( solutionId,bodyData ) { + static detailsBasedOnRoleAndLocation( solutionId,bodyData ) { return new Promise(async (resolve, reject) => { @@ -881,7 +880,7 @@ module.exports = class SolutionsHelper { }) } - /** + /** * Add roles in solution scope. * @method * @name addRolesInScope @@ -890,7 +889,7 @@ module.exports = class SolutionsHelper { * @returns {JSON} - Added roles data. */ - static addRolesInScope( solutionId,roles ) { + static addRolesInScope( solutionId,roles ) { return new Promise(async (resolve, reject) => { try { @@ -967,7 +966,7 @@ module.exports = class SolutionsHelper { }) } - /** + /** * Add entities in solution. * @method * @name addEntitiesInScope @@ -1067,7 +1066,7 @@ module.exports = class SolutionsHelper { }) } - /** + /** * remove roles from solution scope. * @method * @name removeRolesInScope @@ -1076,66 +1075,75 @@ module.exports = class SolutionsHelper { * @returns {JSON} - Removed solution roles. */ - static removeRolesInScope( solutionId,roles ) { + static removeRolesInScope(solutionId, roles) { return new Promise(async (resolve, reject) => { try { + let solutionData = await this.solutionDocuments( + { + _id: solutionId, + scope: { $exists: true }, + isReusable: false, + isDeleted: false, + }, + ["_id"] + ); - let solutionData = - await this.solutionDocuments({ - _id : solutionId, - scope : { $exists : true }, - isReusable : false, - isDeleted : false - },["_id"]); - - if( !solutionData.length > 0 ) { + if (!solutionData.length > 0) { return resolve({ - status : httpStatusCode.bad_request.status, - message : constants.apiResponses.SOLUTION_NOT_FOUND + status: httpStatusCode.bad_request.status, + message: constants.apiResponses.SOLUTION_NOT_FOUND, }); } - let userRoles = await userRolesHelper.roleDocuments({ - code : { $in : roles } - },["_id","code"] + let userRoles = await userRolesHelper.roleDocuments( + { + code: { $in: roles }, + }, + ["_id", "code"] ); - - if( !userRoles.length > 0 ) { + + if (!userRoles.length > 0) { return resolve({ - status : httpStatusCode.bad_request.status, - message : constants.apiResponses.INVALID_ROLE_CODE + status: httpStatusCode.bad_request.status, + message: constants.apiResponses.INVALID_ROLE_CODE, }); } - let updateSolution = await database.models.solutions.findOneAndUpdate({ - _id : solutionId - },{ - $pull : { "scope.roles" : { $in : userRoles } } - },{ new : true }).lean(); + let updateSolution = await database.models.solutions + .findOneAndUpdate( + { + _id: solutionId, + }, + { + $pull: { "scope.roles": { $in: userRoles } }, + }, + { new: true } + ) + .lean(); - if( !updateSolution || !updateSolution._id ) { + if (!updateSolution || !updateSolution._id) { throw { - message : constants.apiResponses.SOLUTION_NOT_UPDATED - } + message: constants.apiResponses.SOLUTION_NOT_UPDATED, + }; } return resolve({ - message : constants.apiResponses.ROLES_REMOVED_IN_SOLUTION, - success : true + message: constants.apiResponses.ROLES_REMOVED_IN_SOLUTION, + success: true, }); - - } catch(error) { + } catch (error) { return resolve({ - success : false, - status : error.status ? - error.status : httpStatusCode['internal_server_error'].status, - message : error.message - }) + success: false, + status: error.status + ? error.status + : httpStatusCode['internal_server_error'].status, + message: error.message, + }); } - }) - } + }); + } - /** + /** * remove entities in solution scope. * @method * @name removeEntitiesInScope @@ -1144,72 +1152,81 @@ module.exports = class SolutionsHelper { * @returns {JSON} - Removed entities from solution scope. */ - static removeEntitiesInScope( solutionId,entities ) { + static removeEntitiesInScope(solutionId, entities) { return new Promise(async (resolve, reject) => { try { + let solutionData = await this.solutionDocuments( + { + _id: solutionId, + scope: { $exists: true }, + isReusable: false, + isDeleted: false, + }, + ["_id", "scope.entityTypeId"] + ); - let solutionData = - await this.solutionDocuments({ - _id : solutionId, - scope : { $exists : true }, - isReusable : false, - isDeleted : false - },["_id","scope.entityTypeId"]); - - if( !solutionData.length > 0 ) { + if (!solutionData.length > 0) { return resolve({ - status : httpStatusCode.bad_request.status, - message : constants.apiResponses.SOLUTION_NOT_FOUND + status: httpStatusCode.bad_request.status, + message: constants.apiResponses.SOLUTION_NOT_FOUND, }); } - let entitiesData = - await entitiesHelper.entityDocuments({ - _id : { $in : entities }, - entityTypeId : solutionData[0].scope.entityTypeId - },["_id"]); - - if( !entitiesData.length > 0 ) { - throw { - message : constants.apiResponses.ENTITIES_NOT_FOUND - }; + let entitiesData = await entitiesHelper.entityDocuments( + { + _id: { $in: entities }, + entityTypeId: solutionData[0].scope.entityTypeId, + }, + ["_id"] + ); + + if (!entitiesData.length > 0) { + throw { + message: constants.apiResponses.ENTITIES_NOT_FOUND, + }; } let entityIds = []; - - entitiesData.forEach(entity => { + + entitiesData.forEach((entity) => { entityIds.push(entity._id); }); - let updateSolution = await database.models.solutions.findOneAndUpdate({ - _id : solutionId - },{ - $pull : { "scope.entities" : { $in : entityIds } } - },{ new : true }).lean(); + let updateSolution = await database.models.solutions + .findOneAndUpdate( + { + _id: solutionId, + }, + { + $pull: { "scope.entities": { $in: entityIds } }, + }, + { new: true } + ) + .lean(); - if( !updateSolution || !updateSolution._id ) { + if (!updateSolution || !updateSolution._id) { throw { - message : constants.apiResponses.SOLUTION_NOT_UPDATED - } + message: constants.apiResponses.SOLUTION_NOT_UPDATED, + }; } return resolve({ - message : constants.apiResponses.ENTITIES_REMOVED_IN_SOLUTION, - success : true + message: constants.apiResponses.ENTITIES_REMOVED_IN_SOLUTION, + success: true, }); - - } catch(error) { + } catch (error) { return resolve({ - success : false, - status : error.status ? - error.status : httpStatusCode['internal_server_error'].status, - message : error.message - }) + success: false, + status: error.status + ? error.status + : httpStatusCode['internal_server_error'].status, + message: error.message, + }); } - }) - } + }); + } - /** + /** * Solution details. * @method * @name details @@ -1217,38 +1234,39 @@ module.exports = class SolutionsHelper { * @returns {Object} - Details of the solution. */ - static details( solutionId ) { + static getDetails(solutionId) { return new Promise(async (resolve, reject) => { try { + let solutionData = await this.solutionDocuments({ + _id: solutionId, + isDeleted: false, + }); - let solutionData = - await this.solutionDocuments({ _id : solutionId,isDeleted : false }); - - if( !solutionData.length > 0 ) { + if ( !solutionData.length > 0 ) { return resolve({ - status : httpStatusCode.bad_request.status, - message : constants.apiResponses.SOLUTION_NOT_FOUND + status: httpStatusCode.bad_request.status, + message: constants.apiResponses.SOLUTION_NOT_FOUND, }); } return resolve({ - message : constants.apiResponses.SOLUTION_DETAILS_FETCHED, - success : true, - data : solutionData[0] + message: constants.apiResponses.SOLUTION_DETAILS_FETCHED, + success: true, + data: solutionData[0], }); - - } catch(error) { + } catch (error) { return resolve({ - success : false, - status : error.status ? - error.status : httpStatusCode['internal_server_error'].status, - message : error.message - }) + success: false, + status: error.status + ? error.status + : httpStatusCode['internal_server_error'].status, + message: error.message, + }); } - }) + }); } - - /** + + /** * List of solutions and targeted ones. * @method * @name targetedSolutions @@ -1256,11 +1274,20 @@ module.exports = class SolutionsHelper { * @returns {Object} - Details of the solution. */ - static targetedSolutions(requestedData,solutionType,userToken,pageSize,pageNo,search,filter, surveyReportPage = "") { + static targetedSolutions( + requestedData, + solutionType, + userToken, + pageSize, + pageNo, + search, + filter, + surveyReportPage = "" + ) { return new Promise(async (resolve, reject) => { - try { + try { - let assignedSolutions = await this.assignedUserSolutions( + let assignedSolutions = await this.assignedUserSolutions( solutionType, userToken, search, @@ -1268,142 +1295,141 @@ module.exports = class SolutionsHelper { surveyReportPage ); - let totalCount = 0; - let mergedData = []; - let solutionIds = []; + let totalCount = 0; + let mergedData = []; + let solutionIds = []; - if( assignedSolutions.success && assignedSolutions.data ) { + if( assignedSolutions.success && assignedSolutions.data ) { - totalCount = assignedSolutions.data.count; - mergedData = assignedSolutions.data.data; + totalCount = assignedSolutions.data.count; + mergedData = assignedSolutions.data.data; - if( mergedData.length > 0 ) { + if ( mergedData.length > 0 ) { + let programIds = []; - let programIds = []; + mergedData.forEach( mergeSolutionData => { + if( mergeSolutionData.solutionId ) { + solutionIds.push(mergeSolutionData.solutionId); + } - mergedData.forEach( mergeSolutionData => { - if( mergeSolutionData.solutionId ) { - solutionIds.push(mergeSolutionData.solutionId); - } + if( mergeSolutionData.programId ) { + programIds.push(mergeSolutionData.programId); + } + }); - if( mergeSolutionData.programId ) { - programIds.push(mergeSolutionData.programId); - } - }); + let programsData = await programsHelper.programDocuments({ + _id : { $in : programIds } + },["name"]); - let programsData = await programsHelper.programDocuments({ - _id : { $in : programIds } - },["name"]); - - if( programsData.length > 0 ) { - - let programs = - programsData.reduce( - (ac, program) => - ({ ...ac, [program._id.toString()]: program }), {} - ); - - mergedData = mergedData.map( data => { - if( data.programId && programs[data.programId.toString()]) { - data.programName = programs[data.programId.toString()].name; - } - return data; - }) - } + if( programsData.length > 0 ) { + + let programs = + programsData.reduce( + (ac, program) => + ({ ...ac, [program._id.toString()]: program }), {} + ); + + mergedData = mergedData.map((data) => { + if( data.programId && programs[data.programId.toString()]) { + data.programName = programs[data.programId.toString()].name; + } + return data; + }); } } + } - requestedData["filter"] = {}; - if( solutionIds.length > 0 ) { - requestedData["filter"]["skipSolutions"] = solutionIds; - } + requestedData['filter'] = {}; + if( solutionIds.length > 0 ) { + requestedData["filter"]["skipSolutions"] = solutionIds; + } - if( filter && filter !== "" ) { - if( filter === constants.common.CREATED_BY_ME ) { - requestedData["filter"]["isAPrivateProgram"] = { - $ne : false - }; - } else if( filter === constants.common.ASSIGN_TO_ME ) { - requestedData["filter"]["isAPrivateProgram"] = false; - } + if( filter && filter !== "" ) { + if( filter === constants.common.CREATED_BY_ME ) { + requestedData["filter"]["isAPrivateProgram"] = { + $ne : false + }; + } else if( filter === constants.common.ASSIGN_TO_ME ) { + requestedData["filter"]["isAPrivateProgram"] = false; } + } - let targetedSolutions = { - success : false - }; + let targetedSolutions = { + success: false, + }; - let getTargetedSolution = true; + let getTargetedSolution = true; - if(filter === constants.common.DISCOVERED_BY_ME){ + if ( filter === constants.common.DISCOVERED_BY_ME ) { getTargetedSolution = false; - }else if (solutionType === constants.common.COURSE){ + } else if ( solutionType === constants.common.COURSE ) { getTargetedSolution = true; - }else if (gen.utils.convertStringToBoolean(surveyReportPage) === true ){ - getTargetedSolution = false; - } + } else if ( gen.utils.convertStringToBoolean(surveyReportPage) === true ) { + getTargetedSolution = false; + } - if( getTargetedSolution ) { - targetedSolutions = - await this.forUserRoleAndLocation( - requestedData, - solutionType, - "", - "", - constants.common.DEFAULT_PAGE_SIZE, - constants.common.DEFAULT_PAGE_NO, - search - ); - } + if( getTargetedSolution ) { + targetedSolutions = + await this.forUserRoleAndLocation( + requestedData, + solutionType, + "", + "", + constants.common.DEFAULT_PAGE_SIZE, + constants.common.DEFAULT_PAGE_NO, + search + ); + } - if( targetedSolutions.success ) { - - if( targetedSolutions.data.data && targetedSolutions.data.data.length > 0 ) { - totalCount += targetedSolutions.data.count; - targetedSolutions.data.data.forEach(targetedSolution => { - targetedSolution.solutionId = targetedSolution._id; - targetedSolution._id = ""; - - if( solutionType !== constants.common.COURSE ) { - targetedSolution["creator"] = targetedSolution.creator ? targetedSolution.creator : ""; - } - - if ( solutionType === constants.common.SURVEY ) { - targetedSolution.isCreator = false; - } + if( targetedSolutions.success ) { + + if( targetedSolutions.data.data && targetedSolutions.data.data.length > 0 ) { + totalCount += targetedSolutions.data.count; + targetedSolutions.data.data.forEach(targetedSolution => { + targetedSolution.solutionId = targetedSolution._id; + targetedSolution._id = ""; + + if( solutionType !== constants.common.COURSE ) { + targetedSolution["creator"] = targetedSolution.creator ? targetedSolution.creator : ""; + } - mergedData.push(targetedSolution); - delete targetedSolution.type; - delete targetedSolution.externalId; + if ( solutionType === constants.common.SURVEY ) { + targetedSolution.isCreator = false; + } - }); - } - } + mergedData.push(targetedSolution); + delete targetedSolution.type; + delete targetedSolution.externalId; + + }); + } + } - if( mergedData.length > 0 ) { - let startIndex = pageSize * (pageNo - 1); - let endIndex = startIndex + pageSize; - mergedData = mergedData.slice(startIndex,endIndex) - } + if( mergedData.length > 0 ) { + let startIndex = pageSize * (pageNo - 1); + let endIndex = startIndex + pageSize; + mergedData = mergedData.slice(startIndex,endIndex) + } return resolve({ - success : true, - message : constants.apiResponses.TARGETED_OBSERVATION_FETCHED, - data : { - data : mergedData, - count : totalCount - } + success: true, + message: constants.apiResponses.TARGETED_OBSERVATION_FETCHED, + data: { + data: mergedData, + count: totalCount, + }, }); - } catch (error) { return reject({ status: error.status || httpStatusCode.internal_server_error.status, - message: error.message || httpStatusCode.internal_server_error.message, - errorObject: error + message: + error.message || httpStatusCode.internal_server_error.message, + errorObject: error, }); } - }) + }); } - /** + /** * Solution details. * @method * @name assignedUserSolutions @@ -1444,7 +1470,7 @@ module.exports = class SolutionsHelper { } return resolve(userAssignedSolutions); - } catch(error) { + } catch(error) { return resolve({ success : false, status : error.status ? @@ -1458,65 +1484,77 @@ module.exports = class SolutionsHelper { /** * Get link by solution id * @method - * @name getLink + * @name fetchLink * @param {String} solutionId - solution Id. * @param {String} appName - app Name. * @param {String} userId - user Id. * @returns {Object} - Details of the solution. */ - static getLink( solutionId, userId ) { + static fetchLink(solutionId, userId) { return new Promise(async (resolve, reject) => { try { - let solutionData = await this.solutionDocuments({ - _id : solutionId, - isReusable : false, - isAPrivateProgram: false - },[ - "link","type","author" - ]); + let solutionData = await this.solutionDocuments( + { + _id: solutionId, + isReusable: false, + isAPrivateProgram: false, + }, + ["link", "type", 'author'] + ); if ( !Array.isArray(solutionData) || solutionData.length < 1 ) { - return resolve({ - message: constants.apiResponses.SOLUTION_NOT_FOUND, - result: {} - }); + return resolve({ + message: constants.apiResponses.SOLUTION_NOT_FOUND, + result: {}, + }); } - let prefix = constants.common.PREFIX_FOR_PROJECT_LINK; - + let solutionLink, link; if ( !solutionData[0].link ) { - let updateLink = await gen.utils.md5Hash(solutionData[0]._id + "###" + solutionData[0].author); - let updateSolution = await this.update(solutionId, { link : updateLink } , userId ); + let updateLink = await gen.utils.md5Hash( + solutionData[0]._id + "###" + solutionData[0].author + ); - solutionLink = updateLink; + let updateSolution = await this.update( + solutionId, + { link: updateLink }, + userId + ); + solutionLink = updateLink; } else { solutionLink = solutionData[0].link; } - link = _generateLink(appsPortalBaseUrl, prefix, solutionLink, solutionData[0].type); + link = _generateLink( + appsPortalBaseUrl, + prefix, + solutionLink, + solutionData[0].type + ); return resolve({ - success : true, - message: constants.apiResponses.LINK_GENERATED, - result: link + success: true, + message: constants.apiResponses.LINK_GENERATED, + result: link, }); - } catch(error) { + } catch (error) { return resolve({ - success : false, - status : error.status ? - error.status : httpStatusCode['internal_server_error'].status, - message : error.message - }) + success: false, + status: error.status + ? error.status + : httpStatusCode['internal_server_error'].status, + message: error.message, + }); } - }) + }); } /** @@ -1529,63 +1567,89 @@ module.exports = class SolutionsHelper { * @returns {Object} - Details of the solution. */ - static verifyLink( link = "", bodyData = {}, userId = "", userToken = "" ) { + static verifyLink(link = "", bodyData = {}, userId = "", userToken = "") { return new Promise(async (resolve, reject) => { try { + let verifySolution = await this.verifySolutionDetails( + link, + userId, + userToken + ); + let checkForTargetedSolution = await this.checkForTargetedSolution( + link, + bodyData, + userId, + userToken + ); - let verifySolution = await this.verifySolutionDetails( link, userId, userToken ); - let checkForTargetedSolution = await this.checkForTargetedSolution( link, bodyData, userId, userToken ); - - if ( checkForTargetedSolution && Object.keys( checkForTargetedSolution.result ).length > 0 ) { + if ( + checkForTargetedSolution && + Object.keys(checkForTargetedSolution.result).length > 0 + ) { let solutionData = checkForTargetedSolution.result; if ( !checkForTargetedSolution.result.isATargetedSolution ) { - if ( solutionData.type == constants.common.IMPROVEMENT_PROJECT ) { let filterQuery = { createdBy: userId, referenceFrom: constants.common.LINK, - link: link - } + link: link, + }; - let checkForProjectExist = await improvementProjectService.projectDocuments( userToken, filterQuery, [ "_id" ] ); - if ( checkForProjectExist.success && checkForProjectExist.data && checkForProjectExist.data.length > 0 && checkForProjectExist.data[ 0 ]._id != "" ) { - checkForTargetedSolution.result[ "projectId" ] = checkForProjectExist.data[ 0 ]._id; + let checkForProjectExist = + await improvementProjectService.projectDocuments( + userToken, + filterQuery, + ["_id"] + ); + if ( + checkForProjectExist.success && + checkForProjectExist.data && + checkForProjectExist.data.length > 0 && + checkForProjectExist.data[0]._id != "" + ) { + checkForTargetedSolution.result['projectId'] = + checkForProjectExist.data[0]._id; } } - - } - else { - + } else { let detailFromLink; if ( solutionData.type == constants.common.IMPROVEMENT_PROJECT ) { - - detailFromLink = await improvementProjectService.getDetail( solutionData.solutionId, userToken, bodyData ); + detailFromLink = await improvementProjectService.getProjectDetail( + solutionData.solutionId, + userToken, + bodyData + ); if ( !detailFromLink || !detailFromLink.data ) { - return resolve( detailFromLink ) + return resolve(detailFromLink); } - if ( solutionData.type == constants.common.IMPROVEMENT_PROJECT && detailFromLink.data._id != "" ) { - checkForTargetedSolution.result[ "projectId" ] = detailFromLink.data._id ? detailFromLink.data._id : ""; + if ( + solutionData.type == constants.common.IMPROVEMENT_PROJECT && + detailFromLink.data._id != "" + ) { + checkForTargetedSolution.result['projectId'] = detailFromLink + .data._id + ? detailFromLink.data._id + : ""; } } } - } - return resolve( checkForTargetedSolution ); - - } catch ( error ) { + return resolve(checkForTargetedSolution); + } catch (error) { return resolve({ success: false, - status: error.status ? - error.status : httpStatusCode[ 'internal_server_error' ].status, - message: error.message - }) + status: error.status + ? error.status + : httpStatusCode['internal_server_error'].status, + message: error.message, + }); } - }) + }); } /** @@ -1596,79 +1660,87 @@ module.exports = class SolutionsHelper { * @returns {Object} - Details of the solution. */ - static verifySolutionDetails(link = "", userId = "", userToken = "") { - return new Promise(async (resolve, reject) => { - try { - - let response = { - verified: false - }; - - if (link == "") { - throw new Error(constants.apiResponses.LINK_REQUIRED_CHECK) - } - - if (userToken == "") { - throw new Error(constants.apiResponses.REQUIRED_USER_AUTH_TOKEN) - } - - if (userId == "") { - throw new Error(constants.apiResponses.USER_ID_REQUIRED_CHECK) - } + static verifySolutionDetails(link = "", userId = "", userToken = "") { + return new Promise(async (resolve, reject) => { + try { + let response = { + verified: false, + }; - let solutionData = await this.solutionDocuments({ - link: link, - isReusable: false, - status: { - $ne: constants.common.IN_ACTIVE - } - }, [ - "type", "status", "endDate" - ]); + if ( link == "" ) { + throw new Error(constants.apiResponses.LINK_REQUIRED_CHECK); + } - if (!Array.isArray(solutionData) || solutionData.length < 1) { - return resolve({ - message: constants.apiResponses.INVALID_LINK, - result: [] - }); - } + if ( userToken == "" ) { + throw new Error(constants.apiResponses.REQUIRED_USER_AUTH_TOKEN); + } - if (solutionData[0].status !== constants.common.ACTIVE) { - return resolve({ - message: constants.apiResponses.LINK_IS_EXPIRED, - result: [] - }); - } + if ( userId == "" ) { + throw new Error(constants.apiResponses.USER_ID_REQUIRED_CHECK); + } - if (solutionData[0].endDate && new Date() > new Date(solutionData[0].endDate)) { - if (solutionData[0].status === constants.common.ACTIVE) { - let updateSolution = await this.update(solutionData[0]._id, { - status: constants.common.IN_ACTIVE - }, userId); - } + let solutionData = await this.solutionDocuments( + { + link: link, + isReusable: false, + status: { + $ne: constants.common.INACTIVE, + }, + }, + ["type", "status", "endDate"] + ); - return resolve({ - message: constants.apiResponses.LINK_IS_EXPIRED, - result: [] - }); - } + if ( !Array.isArray(solutionData) || solutionData.length < 1 ) { + return resolve({ + message: constants.apiResponses.INVALID_LINK, + result: [], + }); + } - response.verified = true; + if ( solutionData[0].status !== constants.common.ACTIVE ) { return resolve({ - message: constants.apiResponses.LINK_VERIFIED, - result: response + message: constants.apiResponses.LINK_IS_EXPIRED, + result: [], }); + } - } catch (error) { - return resolve({ - success: false, - status: error.status ? - error.status : httpStatusCode['internal_server_error'].status, - message: error.message - }) - } - }) - } + if ( + solutionData[0].endDate && + new Date() > new Date(solutionData[0].endDate) + ) { + + if ( solutionData[0].status === constants.common.ACTIVE ) { + let updateSolution = await this.update( + solutionData[0]._id, + { + status: constants.common.INACTIVE, + }, + userId + ); + } + + return resolve({ + message: constants.apiResponses.LINK_IS_EXPIRED, + result: [], + }); + } + + response.verified = true; + return resolve({ + message: constants.apiResponses.LINK_VERIFIED, + result: response, + }); + } catch (error) { + return resolve({ + success: false, + status: error.status + ? error.status + : httpStatusCode['internal_server_error'].status, + message: error.message, + }); + } + }); + } /** * Check the user is targeted. @@ -1678,106 +1750,131 @@ module.exports = class SolutionsHelper { * @returns {Object} - Details of the solution. */ - static checkForTargetedSolution( link = "", bodyData = {}, userId = "", userToken = "" ) { + static checkForTargetedSolution( + link = "", + bodyData = {}, + userId = "", + userToken = "" + ) { return new Promise(async (resolve, reject) => { try { let response = { - isATargetedSolution : false, - link : link + isATargetedSolution: false, + link: link, }; - let solutionDetails = await this.solutionDocuments({link:link},["type","_id"]); - + let solutionDetails = await this.solutionDocuments({ link: link }, [ + "type", + "_id", + "programId", + ]); + let queryData = await this.queryBasedOnRoleAndLocation(bodyData); - if( !queryData.success ) { + if ( !queryData.success ) { return resolve(queryData); } queryData.data["link"] = link; let matchQuery = queryData.data; - let solutionData = await this.solutionDocuments(matchQuery, ["_id","link","type"]); - - if( !Array.isArray(solutionData) || solutionData.length < 1 ) { + let solutionData = await this.solutionDocuments(matchQuery, [ + "_id", + "link", + "type", + "programId", + ]); + + if ( !Array.isArray(solutionData) || solutionData.length < 1 ) { + response.solutionId = solutionDetails[0]._id; response.type = solutionDetails[0].type; + response.programId = solutionDetails[0].programId; return resolve({ - success : true, - message: constants.apiResponses.SOLUTION_NOT_FOUND_OR_NOT_A_TARGETED, - result: response - }); + success: true, + message: + constants.apiResponses.SOLUTION_NOT_FOUND_OR_NOT_A_TARGETED, + result: response, + }); } - + response.isATargetedSolution = true; Object.assign(response, solutionData[0]); response.solutionId = solutionData[0]._id; delete response._id; return resolve({ - success : true, - message: constants.apiResponses.SOLUTION_DETAILS_VERIFIED, - result: response - }); + success: true, + message: constants.apiResponses.SOLUTION_DETAILS_VERIFIED, + result: response, + }); - } catch(error) { + } catch (error) { return resolve({ - success : false, - status : error.status ? - error.status : httpStatusCode['internal_server_error'].status, - message : error.message - }) + success: false, + status: error.status + ? error.status + : httpStatusCode['internal_server_error'].status, + message: error.message, + }); } - }) + }); } /** * Fetch template observation based on solution Id. * @method - * @name getDetails + * @name details * @param {String} solutionId - Solution Id. * @returns {Object} - Details of the solution. */ - static getDetails( solutionId, bodyData = {}, userId = "", userToken = "" ) { + static details(solutionId, bodyData = {}, userId = "", userToken = "") { return new Promise(async (resolve, reject) => { try { - let solutionData = await this.solutionDocuments({_id:solutionId},["type", "projectTemplateId"]); - if (!Array.isArray(solutionData) || solutionData.length < 1) { - return resolve({ - message: constants.apiResponses.SOLUTION_NOT_FOUND, - result: [] - }); - } + let solutionData = await this.solutionDocuments({ _id: solutionId }, [ + "type", + "projectTemplateId", + ]); + if ( !Array.isArray(solutionData) || solutionData.length < 1 ) { + return resolve({ + message: constants.apiResponses.SOLUTION_NOT_FOUND, + result: [], + }); + } + solutionData = solutionData[0]; let templateOrQuestionDetails; - if( solutionData.type === constants.common.IMPROVEMENT_PROJECT ) { - - if( !solutionData.projectTemplateId ) { - throw { - message : constants.apiResponses.PROJECT_TEMPLATE_ID_NOT_FOUND - } - } + if ( solutionData.type === constants.common.IMPROVEMENT_PROJECT ) { + if ( !solutionData.projectTemplateId ) { + throw { + message: constants.apiResponses.PROJECT_TEMPLATE_ID_NOT_FOUND, + }; + } - templateOrQuestionDetails = await improvementProjectService.getTemplateDetail( solutionData.projectTemplateId, userToken ); + templateOrQuestionDetails = + await improvementProjectService.getTemplateDetail( + solutionData.projectTemplateId, + userToken + ); } - return resolve(templateOrQuestionDetails); - - } catch(error) { + return resolve(templateOrQuestionDetails); + + } catch (error) { return resolve({ - success : false, - status : error.status ? - error.status : httpStatusCode['internal_server_error'].status, - message : error.message - }) + success: false, + status: error.status + ? error.status + : httpStatusCode['internal_server_error'].status, + message: error.message, + }); } - }) + }); } - }; /** @@ -1807,7 +1904,7 @@ function _generateLink(appsPortalBaseUrl, prefix, solutionLink, solutionType) { let link; - switch( solutionType ) { + switch (solutionType) { case constants.common.OBSERVATION: link = appsPortalBaseUrl + prefix + constants.common.CREATE_OBSERVATION + solutionLink; break; @@ -1819,5 +1916,5 @@ function _generateLink(appsPortalBaseUrl, prefix, solutionLink, solutionType) { } return link; - + } diff --git a/module/solutions/validator/v1.js b/module/solutions/validator/v1.js index 61eb7862..65444ee3 100644 --- a/module/solutions/validator/v1.js +++ b/module/solutions/validator/v1.js @@ -44,7 +44,7 @@ module.exports = (req) => { getSolutions : function () { req.checkQuery("type").exists().withMessage("required solution type") }, - getLink : function () { + fetchLink : function () { req.checkParams("_id").exists().withMessage("required solution id"); }, verifyLink : function () { diff --git a/module/users/helper.js b/module/users/helper.js index 4cc8e909..93c8a3c0 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -20,592 +20,608 @@ const userService = require(ROOT_PATH + "/generics/services/users"); */ module.exports = class UsersHelper { + /** + * List of all private programs created by user + * @method + * @name privatePrograms + * @param {string} userId - logged in user Id. + * @returns {Array} - List of all private programs created by user. + */ - /** - * List of all private programs created by user - * @method - * @name privatePrograms - * @param {string} userId - logged in user Id. - * @returns {Array} - List of all private programs created by user. - */ - - static privatePrograms(userId) { - return new Promise(async (resolve, reject) => { - try { - - let userPrivatePrograms = - await programsHelper.userPrivatePrograms( - userId - ); - - return resolve({ - message: constants.apiResponses.PRIVATE_PROGRAMS_LIST, - result: userPrivatePrograms - }) - - } catch (error) { - return reject(error); - } - }) - } + static privatePrograms(userId) { + return new Promise(async (resolve, reject) => { + try { + let userPrivatePrograms = await programsHelper.userPrivatePrograms( + userId + ); - /** - * Create user program and solution - * @method - * @name createProgramAndSolution - * @param {string} userId - logged in user Id. - * @param {object} programData - data needed for creation of program. - * @param {object} solutionData - data needed for creation of solution. - * @returns {Array} - Created user program and solution. - */ - - static createProgramAndSolution(userId, data, isATargetedSolution = "") { - return new Promise(async (resolve, reject) => { - try { - - let userPrivateProgram = {}; - let dateFormat = gen.utils.epochTime(); - let parentSolutionInformation = {}; - - isATargetedSolution = gen.utils.convertStringToBoolean(isATargetedSolution); - //program part - if( data.programId && data.programId !== ""){ - - let checkforProgramExist = await programsHelper.programDocuments( - { - _id: data.programId - },"all",["__v"]); - - if (!checkforProgramExist.length > 0) { - return resolve({ - status: httpStatusCode['bad_request'].status, - message: constants.apiResponses.PROGRAM_NOT_FOUND, - result: {} - }) - } - - if(isATargetedSolution === false){ - - let duplicateProgram = checkforProgramExist[0]; - duplicateProgram.externalId = duplicateProgram.name + "-" + dateFormat, - duplicateProgram.isAPrivateProgram = true; - duplicateProgram.status = constants.common.ACTIVE_STATUS; - duplicateProgram.userId = userId; - duplicateProgram.createdBy = userId; - - userPrivateProgram = await programsHelper.create( - _.omit( - duplicateProgram, - ["_id", "components","scope"] - ) - ); - - }else{ - userPrivateProgram = checkforProgramExist[0]; - } - - }else{ - - let programData = { - name: data.programName, - isAPrivateProgram: true, - status: constants.common.ACTIVE_STATUS, - externalId: - data.programExternalId ? - data.programExternalId : - data.programName + "-" + dateFormat, - description: - data.programDescription ? - data.programDescription : - data.programName, - userId: userId - } - - userPrivateProgram = - await programsHelper.create( - programData - ); - } - - let solutionDataToBeUpdated = { - programId: userPrivateProgram._id, - programExternalId: userPrivateProgram.externalId, - programName: userPrivateProgram.name, - programDescription: userPrivateProgram.description, - isAPrivateProgram: userPrivateProgram.isAPrivateProgram - }; - - //entities - if ( Array.isArray(data.entities) && data.entities && data.entities.length > 0) { - - let entityData = await entitiesHelper.entityDocuments( - { - _id: { $in: data.entities } - }, ["entityType", "entityTypeId"] - ); - - if (!entityData.length > 0) { - return resolve({ - status: httpStatusCode['bad_request'].status, - message: constants.apiResponses.ENTITY_NOT_FOUND, - result: {} - }) - } - - if( data.type && data.type !== constants.common.IMPROVEMENT_PROJECT ) { - solutionDataToBeUpdated["entities"] = entityData.map(entity => entity._id); - } - - solutionDataToBeUpdated["entityType"] = entityData[0].entityType; - solutionDataToBeUpdated["entityTypeId"] = entityData[0].entityTypeId; - } - - //solution part - let solution = "" - if(data.solutionId && data.solutionId !== ""){ - - let solutionData = - await solutionsHelper.solutionDocuments({ - _id: data.solutionId - },["name","link","type","subType"]); - - if (!solutionData.length > 0) { - - return resolve({ - status: httpStatusCode['bad_request'].status, - message: constants.apiResponses.SOLUTION_NOT_FOUND, - result: {} - }) - } - - if(isATargetedSolution === false){ - - let duplicateSolution = solutionData[0]; - duplicateSolution.externalId = duplicateSolution.name + "-" + dateFormat; - duplicateSolution.isAPrivateProgram = true; - duplicateSolution.isReusable = false; - duplicateSolution.name = duplicateSolution.name; - duplicateSolution.description = duplicateSolution.description; - duplicateSolution.status = constants.common.ACTIVE_STATUS; - duplicateSolution.userId = userId; - duplicateSolution.parentSolutionId = duplicateSolution._id; - - _.merge(duplicateSolution, solutionDataToBeUpdated); - - solution = await solutionsHelper.create( - _.omit( - duplicateSolution, - ["_id","link"] - ) - ); - - parentSolutionInformation.solutionId = duplicateSolution._id; - parentSolutionInformation.link = duplicateSolution.link; - - }else{ - - if(solutionData[0].isReusable === false){ - return resolve({ - status: httpStatusCode['bad_request'].status, - message: constants.apiResponses.SOLUTION_NOT_FOUND, - result: {} - }) - } - - solution = - await database.models.solutions.findOneAndUpdate({ - _id: solutionData[0]._id - }, { - $set: solutionDataToBeUpdated - }, { - new: true - }); - } - - }else{ - - solutionDataToBeUpdated["type"] = - data.type ? data.type : constants.common.ASSESSMENT; - solutionDataToBeUpdated["subType"] = - data.subType ? data.subType : constants.common.INSTITUTIONAL; - - solutionDataToBeUpdated["isReusable"] = false; - - if (data.solutionName) { - solutionDataToBeUpdated["name"] = data.solutionName; - solutionDataToBeUpdated["externalId"] = - data.solutionExternalId ? - data.solutionExternalId : data.solutionName + "-" + dateFormat; - solutionDataToBeUpdated["description"] = - data.solutionDescription ? data.solutionDescription : data.solutionName; - } else { - solutionDataToBeUpdated["name"] = userPrivateProgram.programName, - solutionDataToBeUpdated["externalId"] = userId + "-" + dateFormat; - solutionDataToBeUpdated["description"] = userPrivateProgram.programDescription; - } - - solutionDataToBeUpdated.updatedBy = userId; - solution = await solutionsHelper.create(solutionDataToBeUpdated); - } - - if (solution && solution._id) { - - await database.models.programs.findOneAndUpdate( - { - _id: userPrivateProgram._id - }, { - $addToSet: { components: ObjectId(solution._id) } - }); - - } - - return resolve({ - message: constants.apiResponses.USER_PROGRAM_AND_SOLUTION_CREATED, - result: { - program: userPrivateProgram, - solution: solution, - parentSolutionInformation : parentSolutionInformation - } - }); - - } catch (error) { - console.log(error); - return reject(error); - } - }) - } + return resolve({ + message: constants.apiResponses.PRIVATE_PROGRAMS_LIST, + result: userPrivatePrograms, + }); + } catch (error) { + return reject(error); + } + }); + } - /** - * Entities mapping form data. - * @method - * @name entitiesMappingForm - * @param {String} stateId - state id. - * @param {String} roleId - role id. - * @returns {Object} returns a list of entitiesMappingForm. - */ - - static entitiesMappingForm(stateId, roleId) { - return new Promise(async (resolve, reject) => { - try { - - const rolesData = await userRolesHelper.roleDocuments({ - _id: roleId - }, ["entityTypes.entityType"]); - - if (!rolesData.length > 0) { - return resolve({ - message: constants.apiResponses.USER_ROLES_NOT_FOUND, - result: [] - }) - } - - const entitiesData = await entitiesHelper.entityDocuments( - { - _id: stateId, - }, ["childHierarchyPath"] - ); - - if (!entitiesData.length > 0) { - return resolve({ - message: constants.apiResponses.ENTITY_NOT_FOUND, - result: [] - }) - } - - let roleEntityType = ""; - - rolesData[0].entityTypes.forEach(roleData => { - if (entitiesData[0].childHierarchyPath.includes(roleData.entityType)) { - roleEntityType = roleData.entityType; - } - }) - - let entityTypeIndex = - entitiesData[0].childHierarchyPath.findIndex(path => path === roleEntityType); - - let form = { - "field": "", - "label": "", - "value": "", - "visible": true, - "editable": true, - "input": "text", - "validation": { - "required": false - } - }; - - let forms = []; - - for ( - let pointerToChildHierarchy = 0; - pointerToChildHierarchy < entityTypeIndex + 1; - pointerToChildHierarchy++ - ) { - let cloneForm = JSON.parse(JSON.stringify(form)); - let entityType = entitiesData[0].childHierarchyPath[pointerToChildHierarchy]; - cloneForm["field"] = entityType; - cloneForm["label"] = `Select ${gen.utils.camelCaseToTitleCase(entityType)}`; - - if (roleEntityType === entityType) { - cloneForm.validation.required = true; - } - - forms.push(cloneForm); - } - - return resolve({ - message: constants.apiResponses.ENTITIES_MAPPING_FORM_FETCHED, - result: forms - }); - - } catch (error) { - return reject(error); - } - }) - } + /** + * Create user program and solution + * @method + * @name createProgramAndSolution + * @param {string} userId - logged in user Id. + * @param {object} programData - data needed for creation of program. + * @param {object} solutionData - data needed for creation of solution. + * @returns {Array} - Created user program and solution. + */ - /** - * User targeted solutions. - * @method - * @name solutions - * @param {String} programId - program id. - * @param {Object} requestedData requested data. - * @param {String} pageSize page size. - * @param {String} pageNo page no. - * @param {String} search search text. - * @returns {Object} targeted user solutions. - */ - - static solutions( programId,requestedData,pageSize,pageNo,search,token ) { - return new Promise(async (resolve, reject) => { - try { - - let programData = await programsHelper.programDocuments({ - _id : programId - },["name"]); - - if( !programData.length > 0 ) { - return resolve({ - status : httpStatusCode["bad_request"].status, - message : constants.apiResponses.PROGRAM_NOT_FOUND - }) - } - - let autoTargetedSolutions = - await solutionsHelper.forUserRoleAndLocation( - requestedData, - "", - "", - programId, - constants.common.DEFAULT_PAGE_SIZE, - constants.common.DEFAULT_PAGE_NO, - search - ); - - let totalCount = 0; - let mergedData = []; - - if( autoTargetedSolutions.data.data && autoTargetedSolutions.data.data.length > 0 ) { - - totalCount = autoTargetedSolutions.data.count; - - mergedData = autoTargetedSolutions.data.data; - - mergedData = - mergedData.map( targetedData => { - delete targetedData.programId; - delete targetedData.programName; - return targetedData; - }); - } - - let importedProjects = - await improvementProjectService.importedProjects( - token, - programId - ); - - if( importedProjects.success ) { - - if( importedProjects.data && importedProjects.data.length > 0 ) { - - totalCount += importedProjects.data.length; - - - importedProjects.data.forEach(importedProject => { - let data = importedProject.solutionInformation; - data["projectTemplateId"] = importedProject.projectTemplateId; - data["type"] = constants.common.IMPROVEMENT_PROJECT; - mergedData.push(data); - }); - - } - } - - if( mergedData.length > 0 ) { - let startIndex = pageSize * (pageNo - 1); - let endIndex = startIndex + pageSize; - mergedData = mergedData.slice(startIndex,endIndex) - } - - let result = { - programName : programData[0].name, - programId : programId, - description : constants.common.TARGETED_SOLUTION_TEXT, - data : mergedData, - count : totalCount - } - - return resolve({ - message : constants.apiResponses.PROGRAM_SOLUTIONS_FETCHED, - success : true, - data : result - }) - } catch (error) { - return resolve({ - success : false, - data : { - description : constants.common.TARGETED_SOLUTION_TEXT, - data : [], - count : 0 - } - }) - } - }) - } + static createProgramAndSolution( + userId, + data, + userToken, + createADuplicateSolution = '' + ) { + return new Promise(async (resolve, reject) => { + try { + let userPrivateProgram = {}; + let dateFormat = gen.utils.epochTime(); + let parentSolutionInformation = {}; + + createADuplicateSolution = gen.utils.convertStringToBoolean( + createADuplicateSolution + ); + //program part + if (data.programId && data.programId !== "") { + let checkforProgramExist = await programsHelper.programDocuments( + { + _id: data.programId, + createdBy: userId, + }, + "all", + ["__v"] + ); + + if (!checkforProgramExist.length > 0) { + return resolve({ + status: httpStatusCode['bad_request'].status, + message: constants.apiResponses.PROGRAM_NOT_FOUND, + result: {}, + }); + } + + if (createADuplicateSolution === true) { + let duplicateProgram = checkforProgramExist[0]; + duplicateProgram = await _createProgramData( + duplicateProgram.name, + duplicateProgram.name + '-' + dateFormat, + true, + constants.common.ACTIVE, + duplicateProgram.description, + userId, + userId + ); + + userPrivateProgram = await programsHelper.create( + _.omit(duplicateProgram, ['_id', 'components', 'scope']) + ); + } else { + userPrivateProgram = checkforProgramExist[0]; + } + } else { + let programData = await _createProgramData( + data.programName, + data.programExternalId + ? data.programExternalId + : data.programName + '-' + dateFormat, + true, + constants.common.ACTIVE, + data.programDescription + ? data.programDescription + : data.programName, + userId + ); + + userPrivateProgram = await programsHelper.create(programData); + } + + let solutionDataToBeUpdated = { + programId: userPrivateProgram._id, + programExternalId: userPrivateProgram.externalId, + programName: userPrivateProgram.name, + programDescription: userPrivateProgram.description, + isAPrivateProgram: userPrivateProgram.isAPrivateProgram, + }; + + //entities + if ( + Array.isArray(data.entities) && + data.entities && + data.entities.length > 0 + ) { + let entityData = await entitiesHelper.entityDocuments( + { + _id: { $in: data.entities }, + }, + ['entityType', 'entityTypeId'] + ); + + if (!entityData.length > 0) { + return resolve({ + status: httpStatusCode['bad_request'].status, + message: constants.apiResponses.ENTITY_NOT_FOUND, + result: {}, + }); + } - /** - * User targeted programs. - * @method - * @name programs - * @param {Object} bodyData - request body data. - * @param {String} pageNo - Page number. - * @param {String} pageSize - Page size. - * @param {String} searchText - Search text. - * @returns {Array} - Get user targeted programs. - */ - - static programs(bodyData, pageNo, pageSize,searchText) { - return new Promise(async (resolve, reject) => { - try { - - let targetedProgrms = await programsHelper.forUserRoleAndLocation( - bodyData, - pageSize, - pageNo, - searchText - ); - - if (!targetedProgrms.success) { - throw { - message : constants.apiResponses.PROGRAM_NOT_FOUND - } - } - - targetedProgrms.data["description"] = constants.apiResponses.PROGRAM_DESCRIPTION; - - return resolve({ - success: true, - message: constants.apiResponses.USER_TARGETED_PROGRAMS_FETCHED, - data : targetedProgrms.data - }); - - } catch (error) { - return resolve({ - success: false, - message: error.message, - data : { - description : constants.common.TARGETED_SOLUTION_TEXT, - data : [], - count : 0 - } - }); + if (data.type && data.type !== constants.common.IMPROVEMENT_PROJECT) { + solutionDataToBeUpdated['entities'] = entityData.map( + (entity) => entity._id + ); + } + + solutionDataToBeUpdated['entityType'] = entityData[0].entityType; + solutionDataToBeUpdated['entityTypeId'] = entityData[0].entityTypeId; + } + + //solution part + let solution = ""; + if (data.solutionId && data.solutionId !== "") { + let solutionData = await solutionsHelper.solutionDocuments( + { + _id: data.solutionId, + }, + ['name', 'link', 'type', 'subType'] + ); + + if (!solutionData.length > 0) { + return resolve({ + status: httpStatusCode['bad_request'].status, + message: constants.apiResponses.SOLUTION_NOT_FOUND, + result: {}, + }); + } + + if (createADuplicateSolution === true) { + let duplicateSolution = solutionData[0]; + let solutionCreationData = await _createSolutionData( + duplicateSolution.name, + duplicateSolution.name + "-" + dateFormat, + true, + constants.common.ACTIVE, + duplicateSolution.description, + userId, + false, + duplicateSolution._id + ); + + _.merge(duplicateSolution, solutionCreationData); + _.merge(duplicateSolution, solutionDataToBeUpdated); + + solution = await solutionsHelper.create( + _.omit(duplicateSolution, ['_id', 'link']) + ); + + parentSolutionInformation.solutionId = duplicateSolution._id; + parentSolutionInformation.link = duplicateSolution.link; + } else { + if (solutionData[0].isReusable === false) { + return resolve({ + status: httpStatusCode['bad_request'].status, + message: constants.apiResponses.SOLUTION_NOT_FOUND, + result: {}, + }); } - }) - } - /** - * List of entity types by location and role. - * @method - * @name entityTypesByLocationAndRole - * @param {String} stateLocationId - state location id. - * @param {String} role - role. - * @returns {Object} returns a list of entity type by location and role. - */ - - static entityTypesByLocationAndRole(stateLocationId, role) { - return new Promise(async (resolve, reject) => { - try { - - let filterQuery = { - "registryDetails.code" : stateLocationId - }; - - if( gen.utils.checkValidUUID( stateLocationId ) ) { - filterQuery = { - "registryDetails.locationId" : stateLocationId - }; - } - - const entitiesData = await entitiesHelper.entityDocuments(filterQuery, ["_id"]); - - if (!entitiesData.length > 0) { - throw { - message: constants.apiResponses.ENTITIES_NOT_EXIST_IN_LOCATION - } - } - - const rolesDocument = await userRolesHelper.roleDocuments({ - code : role.toUpperCase() - },["_id","entityTypes.entityType"]); - - if (!rolesDocument.length > 0) { - throw { - message: constants.apiResponses.USER_ROLES_NOT_FOUND - } - } - - let entityTypes = []; - let stateEntityExists = false; - - rolesDocument[0].entityTypes.forEach( roleDocument => { - if( roleDocument.entityType === constants.common.STATE_ENTITY_TYPE ) { - stateEntityExists = true; - } - }); - - if( stateEntityExists ) { - entityTypes = [constants.common.STATE_ENTITY_TYPE] - } else { - - let entitiesMappingForm = - await this.entitiesMappingForm( - entitiesData[0]._id, - rolesDocument[0]._id - ); - - entitiesMappingForm.result.forEach( entitiesMappingData => { - entityTypes.push(entitiesMappingData.field) - }); - } - - return resolve({ - success : true, - message : constants.apiResponses.ENTITY_TYPES_FETCHED, - data : entityTypes - }); - - } catch (error) { - return resolve({ - success : false, - message : error.message - }); + solution = await database.models.solutions.findOneAndUpdate( + { + _id: solutionData[0]._id, + }, + { + $set: solutionDataToBeUpdated, + }, + { + new: true, + } + ); + } + } else { + + let externalId, description; + if (data.solutionName) { + externalId = data.solutionExternalId + ? data.solutionExternalId + : data.solutionName + "-" + dateFormat; + description = data.solutionDescription + ? data.solutionDescription + : data.solutionName; + } else { + externalId = userId + "-" + dateFormat; + description = userPrivateProgram.programDescription; + } + + let createSolutionData = await _createSolutionData( + data.solutionName + ? data.solutionName + : userPrivateProgram.programName, + externalId, + userPrivateProgram.isAPrivateProgram, + constants.common.ACTIVE, + description, + "", + false, + "", + data.type ? data.type : constants.common.ASSESSMENT, + data.subType ? data.subType : constants.common.INSTITUTIONAL, + userId + ); + + _.merge(solutionDataToBeUpdated, createSolutionData); + + solution = await solutionsHelper.create(solutionDataToBeUpdated); + } + + if (solution && solution._id) { + await database.models.programs.findOneAndUpdate( + { + _id: userPrivateProgram._id, + }, + { + $addToSet: { components: ObjectId(solution._id) }, } - }) - } + ); + } + + return resolve({ + message: constants.apiResponses.USER_PROGRAM_AND_SOLUTION_CREATED, + result: { + program: userPrivateProgram, + solution: solution, + parentSolutionInformation: parentSolutionInformation, + }, + }); + } catch (error) { + return reject(error); + } + }); + } - /** + /** + * Entities mapping form data. + * @method + * @name entitiesMappingForm + * @param {String} stateId - state id. + * @param {String} roleId - role id. + * @returns {Object} returns a list of entitiesMappingForm. + */ + + static entitiesMappingForm(stateId, roleId) { + return new Promise(async (resolve, reject) => { + try { + const rolesData = await userRolesHelper.roleDocuments( + { + _id: roleId, + }, + ['entityTypes.entityType'] + ); + + if (!rolesData.length > 0) { + return resolve({ + message: constants.apiResponses.USER_ROLES_NOT_FOUND, + result: [], + }); + } + + const entitiesData = await entitiesHelper.entityDocuments( + { + _id: stateId, + }, + ['childHierarchyPath'] + ); + + if (!entitiesData.length > 0) { + return resolve({ + message: constants.apiResponses.ENTITY_NOT_FOUND, + result: [], + }); + } + + let roleEntityType = ''; + + rolesData[0].entityTypes.forEach((roleData) => { + if ( + entitiesData[0].childHierarchyPath.includes(roleData.entityType) + ) { + roleEntityType = roleData.entityType; + } + }); + + let entityTypeIndex = entitiesData[0].childHierarchyPath.findIndex( + (path) => path === roleEntityType + ); + + let form = { + field: '', + label: '', + value: '', + visible: true, + editable: true, + input: 'text', + validation: { + required: false, + }, + }; + + let forms = []; + + for ( + let pointerToChildHierarchy = 0; + pointerToChildHierarchy < entityTypeIndex + 1; + pointerToChildHierarchy++ + ) { + let cloneForm = JSON.parse(JSON.stringify(form)); + let entityType = + entitiesData[0].childHierarchyPath[pointerToChildHierarchy]; + cloneForm['field'] = entityType; + cloneForm['label'] = `Select ${gen.utils.camelCaseToTitleCase( + entityType + )}`; + + if (roleEntityType === entityType) { + cloneForm.validation.required = true; + } + + forms.push(cloneForm); + } + + return resolve({ + message: constants.apiResponses.ENTITIES_MAPPING_FORM_FETCHED, + result: forms, + }); + } catch (error) { + return reject(error); + } + }); + } + + /** + * User targeted solutions. + * @method + * @name solutions + * @param {String} programId - program id. + * @param {Object} requestedData requested data. + * @param {String} pageSize page size. + * @param {String} pageNo page no. + * @param {String} search search text. + * @returns {Object} targeted user solutions. + */ + + static solutions(programId, requestedData, pageSize, pageNo, search, token) { + return new Promise(async (resolve, reject) => { + try { + let programData = await programsHelper.programDocuments( + { + _id: programId, + }, + ['name'] + ); + + if (!programData.length > 0) { + return resolve({ + status: httpStatusCode['bad_request'].status, + message: constants.apiResponses.PROGRAM_NOT_FOUND, + }); + } + + let autoTargetedSolutions = + await solutionsHelper.forUserRoleAndLocation( + requestedData, + '', + '', + programId, + constants.common.DEFAULT_PAGE_SIZE, + constants.common.DEFAULT_PAGE_NO, + search + ); + + let totalCount = 0; + let mergedData = []; + + if ( + autoTargetedSolutions.data.data && + autoTargetedSolutions.data.data.length > 0 + ) { + totalCount = autoTargetedSolutions.data.count; + + mergedData = autoTargetedSolutions.data.data; + + mergedData = mergedData.map((targetedData) => { + delete targetedData.programId; + delete targetedData.programName; + return targetedData; + }); + } + + let importedProjects = await improvementProjectService.importedProjects( + token, + programId + ); + + if (importedProjects.success) { + if (importedProjects.data && importedProjects.data.length > 0) { + totalCount += importedProjects.data.length; + + importedProjects.data.forEach((importedProject) => { + let data = importedProject.solutionInformation; + data['projectTemplateId'] = importedProject.projectTemplateId; + data['type'] = constants.common.IMPROVEMENT_PROJECT; + mergedData.push(data); + }); + } + } + + if (mergedData.length > 0) { + let startIndex = pageSize * (pageNo - 1); + let endIndex = startIndex + pageSize; + mergedData = mergedData.slice(startIndex, endIndex); + } + + let result = { + programName: programData[0].name, + programId: programId, + description: constants.common.TARGETED_SOLUTION_TEXT, + data: mergedData, + count: totalCount, + }; + + return resolve({ + message: constants.apiResponses.PROGRAM_SOLUTIONS_FETCHED, + success: true, + data: result, + }); + } catch (error) { + return resolve({ + success: false, + data: { + description: constants.common.TARGETED_SOLUTION_TEXT, + data: [], + count: 0, + }, + }); + } + }); + } + + /** + * User targeted programs. + * @method + * @name programs + * @param {Object} bodyData - request body data. + * @param {String} pageNo - Page number. + * @param {String} pageSize - Page size. + * @param {String} searchText - Search text. + * @returns {Array} - Get user targeted programs. + */ + + static programs(bodyData, pageNo, pageSize, searchText) { + return new Promise(async (resolve, reject) => { + try { + let targetedProgrms = await programsHelper.forUserRoleAndLocation( + bodyData, + pageSize, + pageNo, + searchText + ); + + if (!targetedProgrms.success) { + throw { + message: constants.apiResponses.PROGRAM_NOT_FOUND, + }; + } + + targetedProgrms.data['description'] = + constants.apiResponses.PROGRAM_DESCRIPTION; + + return resolve({ + success: true, + message: constants.apiResponses.USER_TARGETED_PROGRAMS_FETCHED, + data: targetedProgrms.data, + }); + } catch (error) { + return resolve({ + success: false, + message: error.message, + data: { + description: constants.common.TARGETED_SOLUTION_TEXT, + data: [], + count: 0, + }, + }); + } + }); + } + + /** + * List of entity types by location and role. + * @method + * @name entityTypesByLocationAndRole + * @param {String} stateLocationId - state location id. + * @param {String} role - role. + * @returns {Object} returns a list of entity type by location and role. + */ + + static entityTypesByLocationAndRole(stateLocationId, role) { + return new Promise(async (resolve, reject) => { + try { + let filterQuery = { + 'registryDetails.code': stateLocationId, + }; + + if (gen.utils.checkValidUUID(stateLocationId)) { + filterQuery = { + 'registryDetails.locationId': stateLocationId, + }; + } + + const entitiesData = await entitiesHelper.entityDocuments(filterQuery, [ + '_id', + ]); + + if (!entitiesData.length > 0) { + throw { + message: constants.apiResponses.ENTITIES_NOT_EXIST_IN_LOCATION, + }; + } + + const rolesDocument = await userRolesHelper.roleDocuments( + { + code: role.toUpperCase(), + }, + ['_id', 'entityTypes.entityType'] + ); + + if (!rolesDocument.length > 0) { + throw { + message: constants.apiResponses.USER_ROLES_NOT_FOUND, + }; + } + + let entityTypes = []; + let stateEntityExists = false; + + rolesDocument[0].entityTypes.forEach((roleDocument) => { + if (roleDocument.entityType === constants.common.STATE_ENTITY_TYPE) { + stateEntityExists = true; + } + }); + + if (stateEntityExists) { + entityTypes = [constants.common.STATE_ENTITY_TYPE]; + } else { + let entitiesMappingForm = await this.entitiesMappingForm( + entitiesData[0]._id, + rolesDocument[0]._id + ); + + entitiesMappingForm.result.forEach((entitiesMappingData) => { + entityTypes.push(entitiesMappingData.field); + }); + } + + return resolve({ + success: true, + message: constants.apiResponses.ENTITY_TYPES_FETCHED, + data: entityTypes, + }); + } catch (error) { + return resolve({ + success: false, + message: error.message, + }); + } + }); + } + + /** * User Targeted entity. * @method * @name targetedEntity @@ -614,114 +630,182 @@ module.exports = class UsersHelper { * @returns {Object} - Details of the solution. */ - static targetedEntity( solutionId,requestedData ) { + static targetedEntity(solutionId, requestedData) { return new Promise(async (resolve, reject) => { try { - - let solutionData = - await solutionsHelper.solutionDocuments({ - _id : solutionId, - isDeleted : false - },["entityType","type"]); - - if( !solutionData.length > 0 ) { + let solutionData = await solutionsHelper.solutionDocuments( + { + _id: solutionId, + isDeleted: false, + }, + ['entityType', 'type'] + ); + + if (!solutionData.length > 0) { return resolve({ - status : httpStatusCode.bad_request.status, - message : constants.apiResponses.SOLUTION_NOT_FOUND + status: httpStatusCode.bad_request.status, + message: constants.apiResponses.SOLUTION_NOT_FOUND, }); } - - let rolesDocument = await userRolesHelper.roleDocuments({ - code : requestedData.role - },["entityTypes.entityType"]); - - if( !rolesDocument.length > 0 ) { - throw { - status : httpStatusCode["bad_request"].status, - message: constants.apiResponses.USER_ROLES_NOT_FOUND - } + + let rolesDocument = await userRolesHelper.roleDocuments( + { + code: requestedData.role, + }, + ['entityTypes.entityType'] + ); + + if (!rolesDocument.length > 0) { + throw { + status: httpStatusCode['bad_request'].status, + message: constants.apiResponses.USER_ROLES_NOT_FOUND, + }; } - let requestedEntityTypes = Object.keys(_.omit(requestedData,["role"])); - let targetedEntityType = ""; + let requestedEntityTypes = Object.keys(_.omit(requestedData, ['role'])); + let targetedEntityType = ''; - rolesDocument[0].entityTypes.forEach(singleEntityType => { - if( requestedEntityTypes.includes(singleEntityType.entityType) ) { - targetedEntityType = singleEntityType.entityType; - } + rolesDocument[0].entityTypes.forEach((singleEntityType) => { + if (requestedEntityTypes.includes(singleEntityType.entityType)) { + targetedEntityType = singleEntityType.entityType; + } }); - if( !requestedData[targetedEntityType] ) { - throw { - status : httpStatusCode["bad_request"].status, - message: constants.apiResponses.ENTITIES_NOT_ALLOWED_IN_ROLE - } + if (!requestedData[targetedEntityType]) { + throw { + status: httpStatusCode['bad_request'].status, + message: constants.apiResponses.ENTITIES_NOT_ALLOWED_IN_ROLE, + }; } + if (solutionData[0].entityType === targetedEntityType) { + let filterQuery = { + 'registryDetails.code': requestedData[targetedEntityType], + }; + + if (gen.utils.checkValidUUID(requestedData[targetedEntityType])) { + filterQuery = { + 'registryDetails.locationId': requestedData[targetedEntityType], + }; + } - if( solutionData[0].entityType === targetedEntityType ) { - - let filterQuery = { - "registryDetails.code" : requestedData[targetedEntityType] - }; - - if( gen.utils.checkValidUUID( requestedData[targetedEntityType] ) ) { - filterQuery = { - "registryDetails.locationId" : requestedData[targetedEntityType] - }; - } - - let entities = await entitiesHelper.entityDocuments(filterQuery,["groups"]); - - if( !entities.length > 0 ) { - throw { - message : constants.apiResponses.ENTITY_NOT_FOUND - } - } + let entities = await entitiesHelper.entityDocuments(filterQuery, [ + 'groups', + ]); - if( entities[0] && entities[0].groups && Object.keys(entities[0].groups).length > 0 ) { - targetedEntityType = constants.common.STATE_ENTITY_TYPE; - } + if (!entities.length > 0) { + throw { + message: constants.apiResponses.ENTITY_NOT_FOUND, + }; + } + + if ( + entities[0] && + entities[0].groups && + Object.keys(entities[0].groups).length > 0 + ) { + targetedEntityType = constants.common.STATE_ENTITY_TYPE; + } } let filterData = { - "registryDetails.code" : requestedData[targetedEntityType] + 'registryDetails.code': requestedData[targetedEntityType], + }; + + if (gen.utils.checkValidUUID(requestedData[targetedEntityType])) { + filterData = { + 'registryDetails.locationId': requestedData[targetedEntityType], }; - - if( gen.utils.checkValidUUID( requestedData[targetedEntityType] ) ) { - filterData = { - "registryDetails.locationId" : requestedData[targetedEntityType] - }; - } + } - let entities = await entitiesHelper.entityDocuments(filterData,["metaInformation.name","entityType"]) + let entities = await entitiesHelper.entityDocuments(filterData, [ + 'metaInformation.name', + 'entityType', + ]); - if( !entities.length > 0 ) { + if (!entities.length > 0) { throw { - message : constants.apiResponses.ENTITY_NOT_FOUND - } + message: constants.apiResponses.ENTITY_NOT_FOUND, + }; } - if( entities[0].metaInformation && entities[0].metaInformation.name ) { - entities[0]["entityName"] = entities[0].metaInformation.name; + if (entities[0].metaInformation && entities[0].metaInformation.name) { + entities[0]['entityName'] = entities[0].metaInformation.name; delete entities[0].metaInformation; } return resolve({ - message : constants.apiResponses.SOLUTION_TARGETED_ENTITY, - success : true, - data : entities[0] + message: constants.apiResponses.SOLUTION_TARGETED_ENTITY, + success: true, + data: entities[0], }); - - } catch(error) { + } catch (error) { return resolve({ - success : false, - status : error.status ? - error.status : httpStatusCode['internal_server_error'].status, - message : error.message - }) + success: false, + status: error.status + ? error.status + : httpStatusCode['internal_server_error'].status, + message: error.message, + }); } - }) - } + }); + } +}; + +/** + * Generate program creation data. + * @method + * @name _createProgramData + * @returns {Object} - program creation data + */ + +function _createProgramData(name, externalId, isAPrivateProgram, status, description, userId, createdBy = "") { + + let programData = {}; + programData.name = name; + programData.externalId = externalId; + programData.isAPrivateProgram = isAPrivateProgram; + programData.status = status; + programData.description = description; + programData.userId = userId; + programData.createdBy = createdBy; + return programData; + +} + +/** + * Generate solution creation data. + * @method + * @name _createSolutionData + * @returns {Object} - solution creation data + */ + +function _createSolutionData(name = "", externalId = "", isAPrivateProgram = "", status, description = "", userId, isReusable = "", parentSolutionId = "", type = "", subType = "", updatedBy="") { + + let solutionData = {}; + solutionData.name = name; + solutionData.externalId = externalId; + solutionData.isAPrivateProgram = isAPrivateProgram; + solutionData.status = status; + solutionData.description = description; + solutionData.userId = userId; + if( parentSolutionId ) { + solutionData.parentSolutionId = parentSolutionId; + } + if( type){ + solutionData.type = type; + } + if( subType){ + solutionData.subType = subType; + } + if( updatedBy){ + solutionData.updatedBy = updatedBy; + } + if( isReusable){ + solutionData.isReusable = isReusable; + } + + return solutionData; + +} -}; \ No newline at end of file From f0c1e9e7b148d07700b7f6c8a9ae9b32782f6d03 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Wed, 13 Oct 2021 02:38:53 +0530 Subject: [PATCH 044/331] pr change --- module/users/helper.js | 359 +++++++++++++++++++++-------------------- 1 file changed, 183 insertions(+), 176 deletions(-) diff --git a/module/users/helper.js b/module/users/helper.js index 93c8a3c0..4877637c 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -20,29 +20,33 @@ const userService = require(ROOT_PATH + "/generics/services/users"); */ module.exports = class UsersHelper { - /** - * List of all private programs created by user - * @method - * @name privatePrograms - * @param {string} userId - logged in user Id. - * @returns {Array} - List of all private programs created by user. - */ - static privatePrograms(userId) { - return new Promise(async (resolve, reject) => { - try { - let userPrivatePrograms = await programsHelper.userPrivatePrograms( - userId - ); + /** + * List of all private programs created by user + * @method + * @name privatePrograms + * @param {string} userId - logged in user Id. + * @returns {Array} - List of all private programs created by user. + */ - return resolve({ - message: constants.apiResponses.PRIVATE_PROGRAMS_LIST, - result: userPrivatePrograms, - }); - } catch (error) { - return reject(error); - } - }); + static privatePrograms(userId) { + return new Promise(async (resolve, reject) => { + try { + + let userPrivatePrograms = + await programsHelper.userPrivatePrograms( + userId + ); + + return resolve({ + message: constants.apiResponses.PRIVATE_PROGRAMS_LIST, + result: userPrivatePrograms + }) + + } catch (error) { + return reject(error); + } + }) } /** @@ -59,10 +63,11 @@ module.exports = class UsersHelper { userId, data, userToken, - createADuplicateSolution = '' + createADuplicateSolution = "" ) { return new Promise(async (resolve, reject) => { try { + let userPrivateProgram = {}; let dateFormat = gen.utils.epochTime(); let parentSolutionInformation = {}; @@ -71,7 +76,7 @@ module.exports = class UsersHelper { createADuplicateSolution ); //program part - if (data.programId && data.programId !== "") { + if ( data.programId && data.programId !== "" ) { let checkforProgramExist = await programsHelper.programDocuments( { _id: data.programId, @@ -81,7 +86,7 @@ module.exports = class UsersHelper { ["__v"] ); - if (!checkforProgramExist.length > 0) { + if ( !checkforProgramExist.length > 0 ) { return resolve({ status: httpStatusCode['bad_request'].status, message: constants.apiResponses.PROGRAM_NOT_FOUND, @@ -89,7 +94,8 @@ module.exports = class UsersHelper { }); } - if (createADuplicateSolution === true) { + if ( createADuplicateSolution === true ) { + let duplicateProgram = checkforProgramExist[0]; duplicateProgram = await _createProgramData( duplicateProgram.name, @@ -104,10 +110,12 @@ module.exports = class UsersHelper { userPrivateProgram = await programsHelper.create( _.omit(duplicateProgram, ['_id', 'components', 'scope']) ); + } else { userPrivateProgram = checkforProgramExist[0]; } } else { + let programData = await _createProgramData( data.programName, data.programExternalId @@ -138,6 +146,7 @@ module.exports = class UsersHelper { data.entities && data.entities.length > 0 ) { + let entityData = await entitiesHelper.entityDocuments( { _id: { $in: data.entities }, @@ -145,7 +154,7 @@ module.exports = class UsersHelper { ['entityType', 'entityTypeId'] ); - if (!entityData.length > 0) { + if ( !entityData.length > 0 ) { return resolve({ status: httpStatusCode['bad_request'].status, message: constants.apiResponses.ENTITY_NOT_FOUND, @@ -153,7 +162,7 @@ module.exports = class UsersHelper { }); } - if (data.type && data.type !== constants.common.IMPROVEMENT_PROJECT) { + if ( data.type && data.type !== constants.common.IMPROVEMENT_PROJECT ) { solutionDataToBeUpdated['entities'] = entityData.map( (entity) => entity._id ); @@ -165,7 +174,7 @@ module.exports = class UsersHelper { //solution part let solution = ""; - if (data.solutionId && data.solutionId !== "") { + if ( data.solutionId && data.solutionId !== "" ) { let solutionData = await solutionsHelper.solutionDocuments( { _id: data.solutionId, @@ -173,7 +182,7 @@ module.exports = class UsersHelper { ['name', 'link', 'type', 'subType'] ); - if (!solutionData.length > 0) { + if ( !solutionData.length > 0 ) { return resolve({ status: httpStatusCode['bad_request'].status, message: constants.apiResponses.SOLUTION_NOT_FOUND, @@ -181,7 +190,8 @@ module.exports = class UsersHelper { }); } - if (createADuplicateSolution === true) { + if ( createADuplicateSolution === true ) { + let duplicateSolution = solutionData[0]; let solutionCreationData = await _createSolutionData( duplicateSolution.name, @@ -203,64 +213,68 @@ module.exports = class UsersHelper { parentSolutionInformation.solutionId = duplicateSolution._id; parentSolutionInformation.link = duplicateSolution.link; + } else { - if (solutionData[0].isReusable === false) { - return resolve({ - status: httpStatusCode['bad_request'].status, - message: constants.apiResponses.SOLUTION_NOT_FOUND, - result: {}, - }); - } - solution = await database.models.solutions.findOneAndUpdate( - { - _id: solutionData[0]._id, - }, - { - $set: solutionDataToBeUpdated, - }, - { - new: true, + if ( solutionData[0].isReusable === false ) { + return resolve({ + status: httpStatusCode['bad_request'].status, + message: constants.apiResponses.SOLUTION_NOT_FOUND, + result: {}, + }); } + + solution = await database.models.solutions.findOneAndUpdate({ + _id: solutionData[0]._id, + }, + { + $set: solutionDataToBeUpdated, + }, + { + new: true, + } ); - } + } } else { - let externalId, description; - if (data.solutionName) { - externalId = data.solutionExternalId - ? data.solutionExternalId - : data.solutionName + "-" + dateFormat; - description = data.solutionDescription - ? data.solutionDescription - : data.solutionName; - } else { - externalId = userId + "-" + dateFormat; - description = userPrivateProgram.programDescription; - } + let externalId, description; + if ( data.solutionName ) { + + externalId = data.solutionExternalId + ? data.solutionExternalId + : data.solutionName + "-" + dateFormat; + description = data.solutionDescription + ? data.solutionDescription + : data.solutionName; + + } else { + + externalId = userId + "-" + dateFormat; + description = userPrivateProgram.programDescription; + } - let createSolutionData = await _createSolutionData( - data.solutionName - ? data.solutionName - : userPrivateProgram.programName, - externalId, - userPrivateProgram.isAPrivateProgram, - constants.common.ACTIVE, - description, - "", - false, - "", - data.type ? data.type : constants.common.ASSESSMENT, - data.subType ? data.subType : constants.common.INSTITUTIONAL, - userId - ); + let createSolutionData = await _createSolutionData( + data.solutionName + ? data.solutionName + : userPrivateProgram.programName, + externalId, + userPrivateProgram.isAPrivateProgram, + constants.common.ACTIVE, + description, + "", + false, + "", + data.type ? data.type : constants.common.ASSESSMENT, + data.subType ? data.subType : constants.common.INSTITUTIONAL, + userId + ); - _.merge(solutionDataToBeUpdated, createSolutionData); + _.merge(solutionDataToBeUpdated, createSolutionData); - solution = await solutionsHelper.create(solutionDataToBeUpdated); + solution = await solutionsHelper.create(solutionDataToBeUpdated); } - if (solution && solution._id) { + if ( solution && solution._id ) { await database.models.programs.findOneAndUpdate( { _id: userPrivateProgram._id, @@ -279,6 +293,7 @@ module.exports = class UsersHelper { parentSolutionInformation: parentSolutionInformation, }, }); + } catch (error) { return reject(error); } @@ -286,102 +301,94 @@ module.exports = class UsersHelper { } /** - * Entities mapping form data. - * @method - * @name entitiesMappingForm - * @param {String} stateId - state id. - * @param {String} roleId - role id. - * @returns {Object} returns a list of entitiesMappingForm. - */ - - static entitiesMappingForm(stateId, roleId) { - return new Promise(async (resolve, reject) => { - try { - const rolesData = await userRolesHelper.roleDocuments( - { - _id: roleId, - }, - ['entityTypes.entityType'] - ); - - if (!rolesData.length > 0) { - return resolve({ - message: constants.apiResponses.USER_ROLES_NOT_FOUND, - result: [], - }); - } - - const entitiesData = await entitiesHelper.entityDocuments( - { - _id: stateId, - }, - ['childHierarchyPath'] - ); - - if (!entitiesData.length > 0) { - return resolve({ - message: constants.apiResponses.ENTITY_NOT_FOUND, - result: [], - }); - } - - let roleEntityType = ''; - - rolesData[0].entityTypes.forEach((roleData) => { - if ( - entitiesData[0].childHierarchyPath.includes(roleData.entityType) - ) { - roleEntityType = roleData.entityType; - } - }); - - let entityTypeIndex = entitiesData[0].childHierarchyPath.findIndex( - (path) => path === roleEntityType - ); - - let form = { - field: '', - label: '', - value: '', - visible: true, - editable: true, - input: 'text', - validation: { - required: false, - }, - }; - - let forms = []; - - for ( - let pointerToChildHierarchy = 0; - pointerToChildHierarchy < entityTypeIndex + 1; - pointerToChildHierarchy++ - ) { - let cloneForm = JSON.parse(JSON.stringify(form)); - let entityType = - entitiesData[0].childHierarchyPath[pointerToChildHierarchy]; - cloneForm['field'] = entityType; - cloneForm['label'] = `Select ${gen.utils.camelCaseToTitleCase( - entityType - )}`; - - if (roleEntityType === entityType) { - cloneForm.validation.required = true; - } - - forms.push(cloneForm); - } - - return resolve({ - message: constants.apiResponses.ENTITIES_MAPPING_FORM_FETCHED, - result: forms, - }); - } catch (error) { - return reject(error); - } - }); - } + * Entities mapping form data. + * @method + * @name entitiesMappingForm + * @param {String} stateId - state id. + * @param {String} roleId - role id. + * @returns {Object} returns a list of entitiesMappingForm. + */ + + static entitiesMappingForm(stateId, roleId) { + return new Promise(async (resolve, reject) => { + try { + + const rolesData = await userRolesHelper.roleDocuments({ + _id: roleId + }, ["entityTypes.entityType"]); + + if (!rolesData.length > 0) { + return resolve({ + message: constants.apiResponses.USER_ROLES_NOT_FOUND, + result: [] + }) + } + + const entitiesData = await entitiesHelper.entityDocuments( + { + _id: stateId, + }, ["childHierarchyPath"] + ); + + if (!entitiesData.length > 0) { + return resolve({ + message: constants.apiResponses.ENTITY_NOT_FOUND, + result: [] + }) + } + + let roleEntityType = ""; + + rolesData[0].entityTypes.forEach(roleData => { + if (entitiesData[0].childHierarchyPath.includes(roleData.entityType)) { + roleEntityType = roleData.entityType; + } + }) + + let entityTypeIndex = + entitiesData[0].childHierarchyPath.findIndex(path => path === roleEntityType); + + let form = { + "field": "", + "label": "", + "value": "", + "visible": true, + "editable": true, + "input": "text", + "validation": { + "required": false + } + }; + + let forms = []; + + for ( + let pointerToChildHierarchy = 0; + pointerToChildHierarchy < entityTypeIndex + 1; + pointerToChildHierarchy++ + ) { + let cloneForm = JSON.parse(JSON.stringify(form)); + let entityType = entitiesData[0].childHierarchyPath[pointerToChildHierarchy]; + cloneForm["field"] = entityType; + cloneForm["label"] = `Select ${gen.utils.camelCaseToTitleCase(entityType)}`; + + if (roleEntityType === entityType) { + cloneForm.validation.required = true; + } + + forms.push(cloneForm); + } + + return resolve({ + message: constants.apiResponses.ENTITIES_MAPPING_FORM_FETCHED, + result: forms + }); + + } catch (error) { + return reject(error); + } + }) + } /** * User targeted solutions. @@ -415,8 +422,8 @@ module.exports = class UsersHelper { let autoTargetedSolutions = await solutionsHelper.forUserRoleAndLocation( requestedData, - '', - '', + "", + "", programId, constants.common.DEFAULT_PAGE_SIZE, constants.common.DEFAULT_PAGE_NO, @@ -663,7 +670,7 @@ module.exports = class UsersHelper { } let requestedEntityTypes = Object.keys(_.omit(requestedData, ['role'])); - let targetedEntityType = ''; + let targetedEntityType = ""; rolesDocument[0].entityTypes.forEach((singleEntityType) => { if (requestedEntityTypes.includes(singleEntityType.entityType)) { From c3fd73c470348de5287158261c0c4c93084c85e0 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Thu, 14 Oct 2021 10:27:29 +0530 Subject: [PATCH 045/331] PR changes --- controllers/v1/solutions.js | 2 +- module/users/helper.js | 130 ++++++++++++++++++------------------ 2 files changed, 66 insertions(+), 66 deletions(-) diff --git a/controllers/v1/solutions.js b/controllers/v1/solutions.js index 588ba8c7..cf338ac0 100644 --- a/controllers/v1/solutions.js +++ b/controllers/v1/solutions.js @@ -759,7 +759,7 @@ module.exports = class Solutions extends Abstract { * { "message": "Solution Link generated successfully", "status": 200, - "result": "https://preprod.ntp.net.in/manage-learn/create-observation/38cd93bdb87489c3890fe0ab00e7d406" + "result": "https://dev.sunbirded.org/manage-learn/create-observation/38cd93bdb87489c3890fe0ab00e7d406" } */ diff --git a/module/users/helper.js b/module/users/helper.js index 4877637c..37b7d6d8 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -80,7 +80,7 @@ module.exports = class UsersHelper { let checkforProgramExist = await programsHelper.programDocuments( { _id: data.programId, - createdBy: userId, + createdBy: userId }, "all", ["__v"] @@ -88,9 +88,9 @@ module.exports = class UsersHelper { if ( !checkforProgramExist.length > 0 ) { return resolve({ - status: httpStatusCode['bad_request'].status, + status: httpStatusCode["bad_request"].status, message: constants.apiResponses.PROGRAM_NOT_FOUND, - result: {}, + result: {} }); } @@ -99,7 +99,7 @@ module.exports = class UsersHelper { let duplicateProgram = checkforProgramExist[0]; duplicateProgram = await _createProgramData( duplicateProgram.name, - duplicateProgram.name + '-' + dateFormat, + duplicateProgram.name + "-" + dateFormat, true, constants.common.ACTIVE, duplicateProgram.description, @@ -108,7 +108,7 @@ module.exports = class UsersHelper { ); userPrivateProgram = await programsHelper.create( - _.omit(duplicateProgram, ['_id', 'components', 'scope']) + _.omit(duplicateProgram, ["_id", "components", "scope"]) ); } else { @@ -120,7 +120,7 @@ module.exports = class UsersHelper { data.programName, data.programExternalId ? data.programExternalId - : data.programName + '-' + dateFormat, + : data.programName + "-" + dateFormat, true, constants.common.ACTIVE, data.programDescription @@ -137,7 +137,7 @@ module.exports = class UsersHelper { programExternalId: userPrivateProgram.externalId, programName: userPrivateProgram.name, programDescription: userPrivateProgram.description, - isAPrivateProgram: userPrivateProgram.isAPrivateProgram, + isAPrivateProgram: userPrivateProgram.isAPrivateProgram }; //entities @@ -149,27 +149,27 @@ module.exports = class UsersHelper { let entityData = await entitiesHelper.entityDocuments( { - _id: { $in: data.entities }, + _id: { $in: data.entities } }, - ['entityType', 'entityTypeId'] + ["entityType", "entityTypeId"] ); if ( !entityData.length > 0 ) { return resolve({ - status: httpStatusCode['bad_request'].status, + status: httpStatusCode["bad_request"].status, message: constants.apiResponses.ENTITY_NOT_FOUND, - result: {}, + result: {} }); } if ( data.type && data.type !== constants.common.IMPROVEMENT_PROJECT ) { - solutionDataToBeUpdated['entities'] = entityData.map( + solutionDataToBeUpdated["entities"] = entityData.map( (entity) => entity._id ); } - solutionDataToBeUpdated['entityType'] = entityData[0].entityType; - solutionDataToBeUpdated['entityTypeId'] = entityData[0].entityTypeId; + solutionDataToBeUpdated["entityType"] = entityData[0].entityType; + solutionDataToBeUpdated["entityTypeId"] = entityData[0].entityTypeId; } //solution part @@ -179,14 +179,14 @@ module.exports = class UsersHelper { { _id: data.solutionId, }, - ['name', 'link', 'type', 'subType'] + ["name", "link", "type", "subType"] ); if ( !solutionData.length > 0 ) { return resolve({ - status: httpStatusCode['bad_request'].status, + status: httpStatusCode["bad_request"].status, message: constants.apiResponses.SOLUTION_NOT_FOUND, - result: {}, + result: {} }); } @@ -208,7 +208,7 @@ module.exports = class UsersHelper { _.merge(duplicateSolution, solutionDataToBeUpdated); solution = await solutionsHelper.create( - _.omit(duplicateSolution, ['_id', 'link']) + _.omit(duplicateSolution, ["_id", "link"]) ); parentSolutionInformation.solutionId = duplicateSolution._id; @@ -218,20 +218,20 @@ module.exports = class UsersHelper { if ( solutionData[0].isReusable === false ) { return resolve({ - status: httpStatusCode['bad_request'].status, + status: httpStatusCode["bad_request"].status, message: constants.apiResponses.SOLUTION_NOT_FOUND, - result: {}, + result: {} }); } solution = await database.models.solutions.findOneAndUpdate({ - _id: solutionData[0]._id, + _id: solutionData[0]._id }, { - $set: solutionDataToBeUpdated, + $set: solutionDataToBeUpdated }, { - new: true, + new: true } ); } @@ -277,10 +277,10 @@ module.exports = class UsersHelper { if ( solution && solution._id ) { await database.models.programs.findOneAndUpdate( { - _id: userPrivateProgram._id, + _id: userPrivateProgram._id }, { - $addToSet: { components: ObjectId(solution._id) }, + $addToSet: { components: ObjectId(solution._id) } } ); } @@ -290,8 +290,8 @@ module.exports = class UsersHelper { result: { program: userPrivateProgram, solution: solution, - parentSolutionInformation: parentSolutionInformation, - }, + parentSolutionInformation: parentSolutionInformation + } }); } catch (error) { @@ -326,7 +326,7 @@ module.exports = class UsersHelper { const entitiesData = await entitiesHelper.entityDocuments( { - _id: stateId, + _id: stateId }, ["childHierarchyPath"] ); @@ -407,15 +407,15 @@ module.exports = class UsersHelper { try { let programData = await programsHelper.programDocuments( { - _id: programId, + _id: programId }, - ['name'] + ["name"] ); if (!programData.length > 0) { return resolve({ - status: httpStatusCode['bad_request'].status, - message: constants.apiResponses.PROGRAM_NOT_FOUND, + status: httpStatusCode["bad_request"].status, + message: constants.apiResponses.PROGRAM_NOT_FOUND }); } @@ -460,7 +460,7 @@ module.exports = class UsersHelper { importedProjects.data.forEach((importedProject) => { let data = importedProject.solutionInformation; data['projectTemplateId'] = importedProject.projectTemplateId; - data['type'] = constants.common.IMPROVEMENT_PROJECT; + data["type"] = constants.common.IMPROVEMENT_PROJECT; mergedData.push(data); }); } @@ -477,13 +477,13 @@ module.exports = class UsersHelper { programId: programId, description: constants.common.TARGETED_SOLUTION_TEXT, data: mergedData, - count: totalCount, + count: totalCount }; return resolve({ message: constants.apiResponses.PROGRAM_SOLUTIONS_FETCHED, success: true, - data: result, + data: result }); } catch (error) { return resolve({ @@ -491,7 +491,7 @@ module.exports = class UsersHelper { data: { description: constants.common.TARGETED_SOLUTION_TEXT, data: [], - count: 0, + count: 0 }, }); } @@ -525,13 +525,13 @@ module.exports = class UsersHelper { }; } - targetedProgrms.data['description'] = + targetedProgrms.data["description"] = constants.apiResponses.PROGRAM_DESCRIPTION; return resolve({ success: true, message: constants.apiResponses.USER_TARGETED_PROGRAMS_FETCHED, - data: targetedProgrms.data, + data: targetedProgrms.data }); } catch (error) { return resolve({ @@ -560,17 +560,17 @@ module.exports = class UsersHelper { return new Promise(async (resolve, reject) => { try { let filterQuery = { - 'registryDetails.code': stateLocationId, + "registryDetails.code": stateLocationId, }; if (gen.utils.checkValidUUID(stateLocationId)) { filterQuery = { - 'registryDetails.locationId': stateLocationId, + "registryDetails.locationId": stateLocationId, }; } const entitiesData = await entitiesHelper.entityDocuments(filterQuery, [ - '_id', + "_id", ]); if (!entitiesData.length > 0) { @@ -583,12 +583,12 @@ module.exports = class UsersHelper { { code: role.toUpperCase(), }, - ['_id', 'entityTypes.entityType'] + ["_id", "entityTypes.entityType"] ); if (!rolesDocument.length > 0) { throw { - message: constants.apiResponses.USER_ROLES_NOT_FOUND, + message: constants.apiResponses.USER_ROLES_NOT_FOUND }; } @@ -617,12 +617,12 @@ module.exports = class UsersHelper { return resolve({ success: true, message: constants.apiResponses.ENTITY_TYPES_FETCHED, - data: entityTypes, + data: entityTypes }); } catch (error) { return resolve({ success: false, - message: error.message, + message: error.message }); } }); @@ -643,29 +643,29 @@ module.exports = class UsersHelper { let solutionData = await solutionsHelper.solutionDocuments( { _id: solutionId, - isDeleted: false, + isDeleted: false }, - ['entityType', 'type'] + ["entityType", "type"] ); if (!solutionData.length > 0) { return resolve({ status: httpStatusCode.bad_request.status, - message: constants.apiResponses.SOLUTION_NOT_FOUND, + message: constants.apiResponses.SOLUTION_NOT_FOUND }); } let rolesDocument = await userRolesHelper.roleDocuments( { - code: requestedData.role, + code: requestedData.role }, - ['entityTypes.entityType'] + ["entityTypes.entityType"] ); if (!rolesDocument.length > 0) { throw { - status: httpStatusCode['bad_request'].status, - message: constants.apiResponses.USER_ROLES_NOT_FOUND, + status: httpStatusCode["bad_request"].status, + message: constants.apiResponses.USER_ROLES_NOT_FOUND }; } @@ -680,29 +680,29 @@ module.exports = class UsersHelper { if (!requestedData[targetedEntityType]) { throw { - status: httpStatusCode['bad_request'].status, - message: constants.apiResponses.ENTITIES_NOT_ALLOWED_IN_ROLE, + status: httpStatusCode["bad_request"].status, + message: constants.apiResponses.ENTITIES_NOT_ALLOWED_IN_ROLE }; } if (solutionData[0].entityType === targetedEntityType) { let filterQuery = { - 'registryDetails.code': requestedData[targetedEntityType], + "registryDetails.code": requestedData[targetedEntityType] }; if (gen.utils.checkValidUUID(requestedData[targetedEntityType])) { filterQuery = { - 'registryDetails.locationId': requestedData[targetedEntityType], + "registryDetails.locationId": requestedData[targetedEntityType] }; } let entities = await entitiesHelper.entityDocuments(filterQuery, [ - 'groups', + "groups", ]); if (!entities.length > 0) { throw { - message: constants.apiResponses.ENTITY_NOT_FOUND, + message: constants.apiResponses.ENTITY_NOT_FOUND }; } @@ -716,23 +716,23 @@ module.exports = class UsersHelper { } let filterData = { - 'registryDetails.code': requestedData[targetedEntityType], + "registryDetails.code": requestedData[targetedEntityType] }; if (gen.utils.checkValidUUID(requestedData[targetedEntityType])) { filterData = { - 'registryDetails.locationId': requestedData[targetedEntityType], + "registryDetails.locationId": requestedData[targetedEntityType] }; } let entities = await entitiesHelper.entityDocuments(filterData, [ - 'metaInformation.name', - 'entityType', + "metaInformation.name", + "entityType" ]); if (!entities.length > 0) { throw { - message: constants.apiResponses.ENTITY_NOT_FOUND, + message: constants.apiResponses.ENTITY_NOT_FOUND }; } @@ -744,7 +744,7 @@ module.exports = class UsersHelper { return resolve({ message: constants.apiResponses.SOLUTION_TARGETED_ENTITY, success: true, - data: entities[0], + data: entities[0] }); } catch (error) { return resolve({ @@ -752,7 +752,7 @@ module.exports = class UsersHelper { status: error.status ? error.status : httpStatusCode['internal_server_error'].status, - message: error.message, + message: error.message }); } }); From 31647a4372843bbaf95b400b6fee41bdb26b439e Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Mon, 18 Oct 2021 17:20:05 +0530 Subject: [PATCH 046/331] rename samiksha to survey --- controllers/v1/solutions.js | 6 +- generics/constants/endpoints.js | 3 +- generics/services/{samiksha.js => survey.js} | 67 +++++++++++++++++++- module/solutions/helper.js | 43 +++++++++---- 4 files changed, 101 insertions(+), 18 deletions(-) rename generics/services/{samiksha.js => survey.js} (67%) diff --git a/controllers/v1/solutions.js b/controllers/v1/solutions.js index cf338ac0..33799348 100644 --- a/controllers/v1/solutions.js +++ b/controllers/v1/solutions.js @@ -859,11 +859,11 @@ module.exports = class Solutions extends Abstract { } /** - * @api {post} /kendra/api/v1/solutions/getDetails/:solutionId + * @api {post} /kendra/api/v1/solutions/details/:solutionId * @apiVersion 1.0.0 - * @apiName verify Link + * @apiName Get Project Template or Solution Questions * @apiGroup Solutions - * @apiSampleRequest /kendra/api/v1/solutions/getDetails/5ff9d50f9259097d48017bbb + * @apiSampleRequest /kendra/api/v1/solutions/details/5ff9d50f9259097d48017bbb * @apiHeader {String} X-authenticated-user-token Authenticity token * @apiUse successBody * @apiUse errorBody diff --git a/generics/constants/endpoints.js b/generics/constants/endpoints.js index 16c1dc46..2041dfa8 100644 --- a/generics/constants/endpoints.js +++ b/generics/constants/endpoints.js @@ -28,5 +28,6 @@ module.exports = { IMPORTED_PROJECT : "/v1/userProjects/importedProjects", GET_PROJECT_DETAILS : "/v1/userProjects/details", GET_TEMPLATE_DETAILS : "/v1/project/templates/details", - LIST_PROJECT : "/v1/userProjects/list" + LIST_PROJECT : "/v1/userProjects/list", + GET_QUESTIONS : "/v1/solutions/questions" } \ No newline at end of file diff --git a/generics/services/samiksha.js b/generics/services/survey.js similarity index 67% rename from generics/services/samiksha.js rename to generics/services/survey.js index 728f9d35..66498300 100644 --- a/generics/services/samiksha.js +++ b/generics/services/survey.js @@ -1,8 +1,8 @@ /** - * name : samiksha.js + * name : survey.js * author : Aman Jung Karki * Date : 11-Nov-2019 - * Description : All samiksha related api call. + * Description : All survey related api call. */ //dependencies @@ -134,7 +134,68 @@ var assignedSurveys = function ( token,search = "",filter = "", surveyReportPage } +/** + * Get questions from solution. + * @function + * @name getQuestions + * @param {String} token - logged in user token. + * @param {String} solutionId - solution Id + * @returns {Promise} returns a promise. +*/ + +var getQuestions = function ( solutionId, token ) { + + let getQuestionsUrl = + process.env.ML_SURVEY_SERVICE_URL + + constants.endpoints.GET_QUESTIONS + "/" + solutionId; + + return new Promise(async (resolve, reject) => { + try { + + function assessmentCallback(err, data) { + + let result = { + success : true, + message: "", + status:"" + }; + + if (err) { + result.success = false; + } else { + + let response = JSON.parse(data.body); + if( response.status === httpStatusCode['ok'].status ) { + result["result"] = response.result; + } else { + result.success = false; + } + + result.message = response.message; + result.status = response.status; + } + + return resolve(result); + } + + const options = { + headers : { + "content-type": "application/json", + "x-authenticated-user-token" : token + } + }; + + request.get(getQuestionsUrl,options,assessmentCallback) + + } catch (error) { + return reject(error); + } + }) + +} + module.exports = { assignedObservations : assignedObservations, - assignedSurveys : assignedSurveys + assignedSurveys : assignedSurveys, + getQuestions : getQuestions }; \ No newline at end of file diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 638833e4..110ff488 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -11,7 +11,7 @@ const programsHelper = require(MODULES_BASE_PATH + "/programs/helper"); const entityTypesHelper = require(MODULES_BASE_PATH + "/entityTypes/helper"); const entitiesHelper = require(MODULES_BASE_PATH + "/entities/helper"); const userRolesHelper = require(MODULES_BASE_PATH + "/user-roles/helper"); -const assessmentService = require(ROOT_PATH + '/generics/services/samiksha'); +const surveyService = require(ROOT_PATH + '/generics/services/survey'); const improvementProjectService = require(ROOT_PATH + '/generics/services/improvement-project'); const appsPortalBaseUrl = (process.env.APP_PORTAL_BASE_URL && process.env.APP_PORTAL_BASE_URL !== "") ? process.env.APP_PORTAL_BASE_URL + "/" : "https://dev.sunbirded.org/"; @@ -850,7 +850,8 @@ module.exports = class SolutionsHelper { "entityType", "entityTypeId", "language", - "creator" + "creator", + "link" ] ); @@ -1445,7 +1446,7 @@ module.exports = class SolutionsHelper { if ( solutionType === constants.common.OBSERVATION ) { userAssignedSolutions = - await assessmentService.assignedObservations( + await surveyService.assignedObservations( userToken, search, filter @@ -1454,7 +1455,7 @@ module.exports = class SolutionsHelper { } else if ( solutionType === constants.common.SURVEY) { userAssignedSolutions = - await assessmentService.assignedSurveys( + await surveyService.assignedSurveys( userToken, search, filter, @@ -1499,7 +1500,7 @@ module.exports = class SolutionsHelper { { _id: solutionId, isReusable: false, - isAPrivateProgram: false, + isAPrivateProgram: false }, ["link", "type", 'author'] ); @@ -1507,7 +1508,7 @@ module.exports = class SolutionsHelper { if ( !Array.isArray(solutionData) || solutionData.length < 1 ) { return resolve({ message: constants.apiResponses.SOLUTION_NOT_FOUND, - result: {}, + result: {} }); } @@ -1542,7 +1543,7 @@ module.exports = class SolutionsHelper { return resolve({ success: true, message: constants.apiResponses.LINK_GENERATED, - result: link, + result: link }); } catch (error) { @@ -1551,7 +1552,7 @@ module.exports = class SolutionsHelper { status: error.status ? error.status : httpStatusCode['internal_server_error'].status, - message: error.message, + message: error.message }); } }); @@ -1588,8 +1589,9 @@ module.exports = class SolutionsHelper { ) { let solutionData = checkForTargetedSolution.result; + //non targeted solution if ( !checkForTargetedSolution.result.isATargetedSolution ) { - if ( solutionData.type == constants.common.IMPROVEMENT_PROJECT ) { + if ( solutionData.type === constants.common.IMPROVEMENT_PROJECT ) { let filterQuery = { createdBy: userId, @@ -1613,9 +1615,12 @@ module.exports = class SolutionsHelper { checkForProjectExist.data[0]._id; } } + } else { + // targeted solution let detailFromLink; if ( solutionData.type == constants.common.IMPROVEMENT_PROJECT ) { + detailFromLink = await improvementProjectService.getProjectDetail( solutionData.solutionId, userToken, @@ -1635,7 +1640,7 @@ module.exports = class SolutionsHelper { ? detailFromLink.data._id : ""; } - } + } } } @@ -1646,7 +1651,7 @@ module.exports = class SolutionsHelper { status: error.status ? error.status : httpStatusCode['internal_server_error'].status, - message: error.message, + message: error.message }); } }); @@ -1860,6 +1865,22 @@ module.exports = class SolutionsHelper { solutionData.projectTemplateId, userToken ); + + } else if ( solutionData.type === constants.common.OBSERVATION ) { + + templateOrQuestionDetails = + await surveyService.getQuestions( + solutionData._id, + userToken + ); + } else { + + templateOrQuestionDetails = { + status : httpStatusCode.ok.status, + message : constants.apiResponses.SOLUTION_TYPE_INVALID, + result : {} + } + } return resolve(templateOrQuestionDetails); From a1df6ca4617497116d0953802c21230c450a3881 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Tue, 19 Oct 2021 10:44:12 +0530 Subject: [PATCH 047/331] validator --- module/solutions/validator/v1.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/module/solutions/validator/v1.js b/module/solutions/validator/v1.js index 65444ee3..bd0fc17d 100644 --- a/module/solutions/validator/v1.js +++ b/module/solutions/validator/v1.js @@ -50,7 +50,7 @@ module.exports = (req) => { verifyLink : function () { req.checkParams("_id").exists().withMessage("required solution link"); }, - getDetails : function () { + details : function () { req.checkParams("_id").exists().withMessage("required solution Id"); } } From 3fc4e2e72505219d6739282f7fc5e37da5931624 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Tue, 19 Oct 2021 14:01:01 +0530 Subject: [PATCH 048/331] added auto_build_deploy file --- auto_build_deploy | 55 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 auto_build_deploy diff --git a/auto_build_deploy b/auto_build_deploy new file mode 100644 index 00000000..49743f56 --- /dev/null +++ b/auto_build_deploy @@ -0,0 +1,55 @@ +@Library('deploy-conf') _ +node('build-slave') { + try { + String ANSI_GREEN = "\u001B[32m" + String ANSI_NORMAL = "\u001B[0m" + String ANSI_BOLD = "\u001B[1m" + String ANSI_RED = "\u001B[31m" + String ANSI_YELLOW = "\u001B[33m" + + ansiColor('xterm') { + timestamps { + stage('Checkout') { + tag_name = env.JOB_NAME.split("/")[-1] + pre_checks() + if (!env.hub_org) { + println(ANSI_BOLD + ANSI_RED + "Uh Oh! Please set a Jenkins environment variable named hub_org with value as registery/sunbidrded" + ANSI_NORMAL) + error 'Please resolve the errors and rerun..' + } else + println(ANSI_BOLD + ANSI_GREEN + "Found environment variable named hub_org with value as: " + hub_org + ANSI_NORMAL) + } + cleanWs() + def scmVars = checkout scm + checkout scm: [$class: 'GitSCM', branches: [[name: "refs/tags/$tag_name"]], userRemoteConfigs: [[url: scmVars.GIT_URL]]] + build_tag = tag_name + "_" + env.BUILD_NUMBER + commit_hash = sh(script: 'git rev-parse --short HEAD', returnStdout: true).trim() + artifact_version = tag_name + "_" + commit_hash + echo "build_tag: " + build_tag + + // stage Build + env.NODE_ENV = "build" + print "Environment will be : ${env.NODE_ENV}" + sh('git submodule update --init') + sh('git submodule update --init --recursive --remote') + sh('chmod 777 build.sh') + sh("./build.sh ${build_tag} ${env.NODE_NAME} ${hub_org}") + + + // stage ArchiveArtifacts + archiveArtifacts "metadata.json" + currentBuild.description = "${build_tag}" + + } + } + currentBuild.result = "SUCCESS" + slack_notify(currentBuild.result, tag_name) + email_notify() + auto_build_deploy() + } + catch (err) { + currentBuild.result = "FAILURE" + slack_notify(currentBuild.result, tag_name) + email_notify() + throw err + } +} \ No newline at end of file From ebd0e4b0bd61f290dd7baa1f6f7d0bb59d7daf50 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Tue, 19 Oct 2021 19:35:09 +0530 Subject: [PATCH 049/331] PR changes --- generics/constants/common.js | 2 +- module/solutions/helper.js | 4 ++-- module/users/helper.js | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/generics/constants/common.js b/generics/constants/common.js index fc9eb7b9..8c2c42ec 100644 --- a/generics/constants/common.js +++ b/generics/constants/common.js @@ -59,7 +59,7 @@ module.exports = { "DHITI" : "dhiti", "DEFAULT_SURVEY_REMOVED_DAY" : 15, "COURSE" : "course", - "PREFIX_FOR_PROJECT_LINK" : "manage-learn", + "PREFIX_FOR_SOLUTION_LINK" : "manage-learn", "CREATE_OBSERVATION": "/create-observation/", "CREATE_SURVEY" : "/create-survey/", "CREATE_PROJECT" : "/create-project/", diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 638833e4..578932e4 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -13,7 +13,7 @@ const entitiesHelper = require(MODULES_BASE_PATH + "/entities/helper"); const userRolesHelper = require(MODULES_BASE_PATH + "/user-roles/helper"); const assessmentService = require(ROOT_PATH + '/generics/services/samiksha'); const improvementProjectService = require(ROOT_PATH + '/generics/services/improvement-project'); -const appsPortalBaseUrl = (process.env.APP_PORTAL_BASE_URL && process.env.APP_PORTAL_BASE_URL !== "") ? process.env.APP_PORTAL_BASE_URL + "/" : "https://dev.sunbirded.org/"; +const appsPortalBaseUrl = process.env.APP_PORTAL_BASE_URL + "/" ; /** * SolutionsHelper @@ -1511,7 +1511,7 @@ module.exports = class SolutionsHelper { }); } - let prefix = constants.common.PREFIX_FOR_PROJECT_LINK; + let prefix = constants.common.PREFIX_FOR_SOLUTION_LINK; let solutionLink, link; diff --git a/module/users/helper.js b/module/users/helper.js index 37b7d6d8..db2cb673 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -99,7 +99,7 @@ module.exports = class UsersHelper { let duplicateProgram = checkforProgramExist[0]; duplicateProgram = await _createProgramData( duplicateProgram.name, - duplicateProgram.name + "-" + dateFormat, + duplicateProgram.externalId ? duplicateProgram.externalId + "-" + dateFormat : duplicateProgram.name + "-" + dateFormat, true, constants.common.ACTIVE, duplicateProgram.description, @@ -179,7 +179,7 @@ module.exports = class UsersHelper { { _id: data.solutionId, }, - ["name", "link", "type", "subType"] + ["name", "link", "type", "subType", "externalId", "description"] ); if ( !solutionData.length > 0 ) { @@ -195,7 +195,7 @@ module.exports = class UsersHelper { let duplicateSolution = solutionData[0]; let solutionCreationData = await _createSolutionData( duplicateSolution.name, - duplicateSolution.name + "-" + dateFormat, + duplicateSolution.externalId ? duplicateSolution.externalId + "-" + dateFormat : duplicateSolution.name + "-" + dateFormat, true, constants.common.ACTIVE, duplicateSolution.description, From 3378e1fb4581598ce54b5a67050925e8d256366d Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Wed, 20 Oct 2021 14:39:25 +0530 Subject: [PATCH 050/331] logs --- generics/helpers/utils.js | 1 + module/users/helper.js | 9 +++++++++ 2 files changed, 10 insertions(+) diff --git a/generics/helpers/utils.js b/generics/helpers/utils.js index 7e7281af..96439cee 100644 --- a/generics/helpers/utils.js +++ b/generics/helpers/utils.js @@ -206,6 +206,7 @@ function valueParser(dataToBeParsed) { function checkValidUUID(str) { var validateUUID = uuidValidate(str); + console.log(validateUUID,"validateUUID") return validateUUID; } diff --git a/module/users/helper.js b/module/users/helper.js index db2cb673..55fc3135 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -563,16 +563,23 @@ module.exports = class UsersHelper { "registryDetails.code": stateLocationId, }; + console.log(stateLocationId,"stateLocationId input") + console.log(gen.utils.checkValidUUID(stateLocationId), "output of checkValidUUID") + if (gen.utils.checkValidUUID(stateLocationId)) { filterQuery = { "registryDetails.locationId": stateLocationId, }; } + console.log(filterQuery, "filterQuery for check entity") + const entitiesData = await entitiesHelper.entityDocuments(filterQuery, [ "_id", ]); + console.log(entitiesData,"entitiesData") + if (!entitiesData.length > 0) { throw { message: constants.apiResponses.ENTITIES_NOT_EXIST_IN_LOCATION, @@ -586,6 +593,8 @@ module.exports = class UsersHelper { ["_id", "entityTypes.entityType"] ); + console.log(rolesDocument,"rolesDocument") + if (!rolesDocument.length > 0) { throw { message: constants.apiResponses.USER_ROLES_NOT_FOUND From d2d83d9dee3bfcef0cd1cc453ee13216e5dcf62d Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Wed, 20 Oct 2021 14:47:31 +0530 Subject: [PATCH 051/331] remove validation --- module/solutions/validator/v1.js | 3 --- 1 file changed, 3 deletions(-) diff --git a/module/solutions/validator/v1.js b/module/solutions/validator/v1.js index bd0fc17d..b4024224 100644 --- a/module/solutions/validator/v1.js +++ b/module/solutions/validator/v1.js @@ -49,9 +49,6 @@ module.exports = (req) => { }, verifyLink : function () { req.checkParams("_id").exists().withMessage("required solution link"); - }, - details : function () { - req.checkParams("_id").exists().withMessage("required solution Id"); } } From 7a32eddc760454a8208b1d4123158b60a7037d60 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Fri, 22 Oct 2021 18:33:58 +0530 Subject: [PATCH 052/331] fix program creation --- controllers/v1/users.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/controllers/v1/users.js b/controllers/v1/users.js index 99ecfa7d..dc8adffa 100644 --- a/controllers/v1/users.js +++ b/controllers/v1/users.js @@ -189,7 +189,7 @@ module.exports = class Users extends Abstract { await usersHelper.createProgramAndSolution( (req.params._id && req.params._id != "") ? req.params._id : - req.userDetails.id, + req.userDetails.userId, req.body, req.userDetails.userToken, req.query.createADuplicateSolution ? req.query.createADuplicateSolution : "" From 2799d741e2ff1a3a48217d921aada4e5a50d3864 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Fri, 22 Oct 2021 18:36:44 +0530 Subject: [PATCH 053/331] remove logs --- generics/helpers/utils.js | 1 - module/users/helper.js | 9 --------- 2 files changed, 10 deletions(-) diff --git a/generics/helpers/utils.js b/generics/helpers/utils.js index 96439cee..7e7281af 100644 --- a/generics/helpers/utils.js +++ b/generics/helpers/utils.js @@ -206,7 +206,6 @@ function valueParser(dataToBeParsed) { function checkValidUUID(str) { var validateUUID = uuidValidate(str); - console.log(validateUUID,"validateUUID") return validateUUID; } diff --git a/module/users/helper.js b/module/users/helper.js index 55fc3135..db2cb673 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -563,23 +563,16 @@ module.exports = class UsersHelper { "registryDetails.code": stateLocationId, }; - console.log(stateLocationId,"stateLocationId input") - console.log(gen.utils.checkValidUUID(stateLocationId), "output of checkValidUUID") - if (gen.utils.checkValidUUID(stateLocationId)) { filterQuery = { "registryDetails.locationId": stateLocationId, }; } - console.log(filterQuery, "filterQuery for check entity") - const entitiesData = await entitiesHelper.entityDocuments(filterQuery, [ "_id", ]); - console.log(entitiesData,"entitiesData") - if (!entitiesData.length > 0) { throw { message: constants.apiResponses.ENTITIES_NOT_EXIST_IN_LOCATION, @@ -593,8 +586,6 @@ module.exports = class UsersHelper { ["_id", "entityTypes.entityType"] ); - console.log(rolesDocument,"rolesDocument") - if (!rolesDocument.length > 0) { throw { message: constants.apiResponses.USER_ROLES_NOT_FOUND From cd2a93b72b8c73b25767acbe8b0a0c415898825b Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Mon, 25 Oct 2021 12:02:48 +0530 Subject: [PATCH 054/331] readme --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 720578b4..3a4b9396 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,3 @@ # ml-core-service Centralised Service to support other Services. +It is used by ml-survey, ml-project From bc58772cbdce207cc458dff65bf72e054064e2fa Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Mon, 25 Oct 2021 14:17:04 +0530 Subject: [PATCH 055/331] create program fix --- module/users/helper.js | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/module/users/helper.js b/module/users/helper.js index db2cb673..c6ebd465 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -77,11 +77,17 @@ module.exports = class UsersHelper { ); //program part if ( data.programId && data.programId !== "" ) { + + let filterQuery = { + _id: data.programId + } + + if ( createADuplicateSolution === false ) { + filterQuery.createdBy = userId; + } + let checkforProgramExist = await programsHelper.programDocuments( - { - _id: data.programId, - createdBy: userId - }, + filterQuery, "all", ["__v"] ); From c3a66c906d68e351c5befd7195e8b57be769c0bd Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Mon, 25 Oct 2021 20:38:52 +0530 Subject: [PATCH 056/331] observation flow changes --- generics/constants/endpoints.js | 3 +- generics/services/survey.js | 63 ++++++++++++++++++++++++++++++++- module/solutions/helper.js | 21 ++++++++++- 3 files changed, 84 insertions(+), 3 deletions(-) diff --git a/generics/constants/endpoints.js b/generics/constants/endpoints.js index 2041dfa8..bc52a941 100644 --- a/generics/constants/endpoints.js +++ b/generics/constants/endpoints.js @@ -29,5 +29,6 @@ module.exports = { GET_PROJECT_DETAILS : "/v1/userProjects/details", GET_TEMPLATE_DETAILS : "/v1/project/templates/details", LIST_PROJECT : "/v1/userProjects/list", - GET_QUESTIONS : "/v1/solutions/questions" + GET_QUESTIONS : "/v1/solutions/questions", + GET_OBSERVATION : "/v1/observations/details" } \ No newline at end of file diff --git a/generics/services/survey.js b/generics/services/survey.js index 66498300..ac884d13 100644 --- a/generics/services/survey.js +++ b/generics/services/survey.js @@ -194,8 +194,69 @@ var getQuestions = function ( solutionId, token ) { } +/** + * Get observation. + * @function + * @name getObservationDetail + * @param {String} token - logged in user token. + * @param {String} solutionId - solution Id + * @returns {Promise} returns a promise. +*/ + +var getObservationDetail = function ( solutionId, token ) { + + let url = + process.env.ML_SURVEY_SERVICE_URL + + constants.endpoints.GET_OBSERVATION + "?solutionId=" + solutionId; + + return new Promise(async (resolve, reject) => { + try { + + function assessmentCallback(err, data) { + + let result = { + success : true, + message: "", + status:"" + }; + + if (err) { + result.success = false; + } else { + + let response = JSON.parse(data.body); + if( response.status === httpStatusCode['ok'].status ) { + result["result"] = response.result; + } else { + result.success = false; + } + + result.message = response.message; + result.status = response.status; + } + + return resolve(result); + } + + const options = { + headers : { + "content-type": "application/json", + "x-authenticated-user-token" : token + } + }; + + request.get(url,options,assessmentCallback) + + } catch (error) { + return reject(error); + } + }) + +} + module.exports = { assignedObservations : assignedObservations, assignedSurveys : assignedSurveys, - getQuestions : getQuestions + getQuestions : getQuestions, + getObservationDetail : getObservationDetail }; \ No newline at end of file diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 540ce4bb..cf4e10f6 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -1640,7 +1640,23 @@ module.exports = class SolutionsHelper { ? detailFromLink.data._id : ""; } - } + } else if ( solutionData.type == constants.common.OBSERVATION ) { + + detailFromLink = await surveyService.getObservationDetail( + solutionData.solutionId, + userToken + ); + + if ( + solutionData.type == constants.common.OBSERVATION && detailFromLink.result && + detailFromLink.result._id != "" + ) { + checkForTargetedSolution.result["observationId"] = detailFromLink + .result._id + ? detailFromLink.result._id + : ""; + } + } } } @@ -1773,6 +1789,7 @@ module.exports = class SolutionsHelper { "type", "_id", "programId", + "name" ]); let queryData = await this.queryBasedOnRoleAndLocation(bodyData); @@ -1788,12 +1805,14 @@ module.exports = class SolutionsHelper { "link", "type", "programId", + "name" ]); if ( !Array.isArray(solutionData) || solutionData.length < 1 ) { response.solutionId = solutionDetails[0]._id; response.type = solutionDetails[0].type; + response.name = solutionDetails[0].name; response.programId = solutionDetails[0].programId; return resolve({ success: true, From dfbb18f049d0ea8a48903db0904a94135059a504 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Tue, 26 Oct 2021 15:34:16 +0530 Subject: [PATCH 057/331] readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3a4b9396..21b699dc 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,3 @@ # ml-core-service Centralised Service to support other Services. -It is used by ml-survey, ml-project +It is used by ml-survey and ml-project From 8ae281a3ca7169dd728903d54a4900420a4c8772 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Tue, 9 Nov 2021 15:22:27 +0530 Subject: [PATCH 058/331] index added --- models/programs.js | 8 ++++++-- models/solutions.js | 8 ++++++-- module/programs/helper.js | 11 +++++------ 3 files changed, 17 insertions(+), 10 deletions(-) diff --git a/models/programs.js b/models/programs.js index 4bc11f16..02bcdea9 100644 --- a/models/programs.js +++ b/models/programs.js @@ -7,7 +7,10 @@ module.exports = { owner: String, createdBy: String, updatedBy: String, - status: String, + status: { + type : String, + index : true + }, resourceType: [String], language: [String], keywords: [String], @@ -36,7 +39,8 @@ module.exports = { }, isDeleted: { default : false, - type : Boolean + type : Boolean, + index : true } } }; diff --git a/models/solutions.js b/models/solutions.js index d4291b95..26cf1fc5 100644 --- a/models/solutions.js +++ b/models/solutions.js @@ -27,7 +27,10 @@ module.exports = { programDescription: String, entityProfileFieldsPerEntityTypes: Object, startDate: Date, - endDate: Date, + endDate: { + type : Date, + index : true + }, status: String, evidenceMethods: Object, sections: Object, @@ -58,7 +61,8 @@ module.exports = { }, isDeleted: { default : false, - type : Boolean + type : Boolean, + index : true }, project : Object, referenceFrom : String, diff --git a/module/programs/helper.js b/module/programs/helper.js index 0559708d..7d643e16 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -10,6 +10,7 @@ const entityTypesHelper = require(MODULES_BASE_PATH + "/entityTypes/helper"); const entitiesHelper = require(MODULES_BASE_PATH + "/entities/helper"); const userRolesHelper = require(MODULES_BASE_PATH + "/user-roles/helper"); +const solutionsHelper = require(MODULES_BASE_PATH + "/solutions/helper"); /** * ProgramsHelper @@ -506,16 +507,14 @@ module.exports = class ProgramsHelper { let currentTargetedProgram = targetedPrograms.data.data[targetedProgram]; if( currentTargetedProgram.components.length > 0 ) { - - let solutions = await database.models.solutions.find({ + + let solutions = await solutionsHelper.solutionDocuments({ _id : { $in : currentTargetedProgram.components }, isDeleted : false, status : constants.common.ACTIVE - },{ - _id : 1 - }); + },["_id"]); - if( solutions.length > 0 ) { + if( solutions && solutions.length > 0 ) { currentTargetedProgram["solutions"] = solutions.length; delete currentTargetedProgram.components; } From 5464220a6fd7fcbeb2ca15631529576a1df3a4ab Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Mon, 15 Nov 2021 11:09:20 +0530 Subject: [PATCH 059/331] targeted solution fix --- module/programs/helper.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/module/programs/helper.js b/module/programs/helper.js index 7d643e16..e5dcf409 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -10,7 +10,6 @@ const entityTypesHelper = require(MODULES_BASE_PATH + "/entityTypes/helper"); const entitiesHelper = require(MODULES_BASE_PATH + "/entities/helper"); const userRolesHelper = require(MODULES_BASE_PATH + "/user-roles/helper"); -const solutionsHelper = require(MODULES_BASE_PATH + "/solutions/helper"); /** * ProgramsHelper @@ -389,6 +388,7 @@ module.exports = class ProgramsHelper { } if ( searchText !== "" ) { + matchQuery["$or"] = []; matchQuery["$or"].push( { @@ -522,7 +522,7 @@ module.exports = class ProgramsHelper { } } } - + return resolve({ success: true, message: constants.apiResponses.TARGETED_PROGRAMS_FETCHED, @@ -915,3 +915,5 @@ module.exports = class ProgramsHelper { } }; + +const solutionsHelper = require(MODULES_BASE_PATH + "/solutions/helper"); \ No newline at end of file From 1b8e66432480cd8bdab4a8e3e6782cdf874421ac Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Mon, 22 Nov 2021 16:54:54 +0530 Subject: [PATCH 060/331] observation mapped to task story --- controllers/v1/solutions.js | 4 +++- generics/constants/common.js | 3 ++- module/solutions/helper.js | 8 ++++++++ 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/controllers/v1/solutions.js b/controllers/v1/solutions.js index 33799348..bbb9951f 100644 --- a/controllers/v1/solutions.js +++ b/controllers/v1/solutions.js @@ -38,7 +38,9 @@ module.exports = class Solutions extends Abstract { "type" : "improvementProject", "subType" : "improvementProject", "isReusable" : false, - "externalId" : "01c04166-a65e-4e92-a87b-a9e4194e771d-1607936956167" + "externalId" : "01c04166-a65e-4e92-a87b-a9e4194e771d-1607936956167", + "noOfSubmissionsRequired" : 2, + "allowMultipleAssessemts" : true } * @apiHeader {String} internal-access-token internal access token * @apiHeader {String} X-authenticated-user-token Authenticity token diff --git a/generics/constants/common.js b/generics/constants/common.js index 8c2c42ec..7128ea5b 100644 --- a/generics/constants/common.js +++ b/generics/constants/common.js @@ -64,5 +64,6 @@ module.exports = { "CREATE_SURVEY" : "/create-survey/", "CREATE_PROJECT" : "/create-project/", "LINK" : "link", - "DISCOVERED_BY_ME" : "discoveredByMe" + "DISCOVERED_BY_ME" : "discoveredByMe", + "DEFAULT_SUBMISSION_REQUIRED" : 1 }; diff --git a/module/solutions/helper.js b/module/solutions/helper.js index cf4e10f6..215a4b7e 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -172,6 +172,10 @@ module.exports = class SolutionsHelper { solutionData.entities = entitiesData; } + if( !solutionData.noOfSubmissionsRequired || !solutionData.allowMultipleAssessemts ) { + solutionData.noOfSubmissionsRequired = constants.common.DEFAULT_SUBMISSION_REQUIRED; + } + solutionData.status = constants.common.ACTIVE; let solutionCreation = @@ -429,6 +433,10 @@ module.exports = class SolutionsHelper { "$set" : {} }; + if( !solutionData.noOfSubmissionsRequired || !solutionData.allowMultipleAssessemts ) { + solutionData.noOfSubmissionsRequired = constants.common.DEFAULT_SUBMISSION_REQUIRED; + } + let solutionUpdateData = solutionData; Object.keys(_.omit(solutionUpdateData,["scope"])).forEach(updationData=>{ From 93de0639faa0bc7558bfb7644cf0e7c5cb8f7249 Mon Sep 17 00:00:00 2001 From: Akash Shah Date: Mon, 22 Nov 2021 21:53:35 +0530 Subject: [PATCH 061/331] Multiple user sub roles. --- controllers/v1/users.js | 26 +++++++++++++++++++------- module/programs/helper.js | 2 +- module/solutions/helper.js | 2 +- 3 files changed, 21 insertions(+), 9 deletions(-) diff --git a/controllers/v1/users.js b/controllers/v1/users.js index dc8adffa..a0da89df 100644 --- a/controllers/v1/users.js +++ b/controllers/v1/users.js @@ -424,14 +424,26 @@ module.exports = class Users extends Abstract { try { - const entitiesMappingData = - await usersHelper.entityTypesByLocationAndRole( - req.params._id, - req.query.role - ); + let currentMaximumCountOfRequiredEntities = 0; + let requiredEntities = new Array; + + // Calculate required entities for each of the role and send the output of the role which has maximum length. + for (let roleCount = 0; roleCount < req.query.role.split(",").length; roleCount++) { + const eachRole = req.query.role.split(",")[roleCount]; + const entitiesMappingData = + await usersHelper.entityTypesByLocationAndRole( + req.params._id, + eachRole + ); + if(entitiesMappingData.data.length > currentMaximumCountOfRequiredEntities) { + currentMaximumCountOfRequiredEntities = entitiesMappingData.data.length; + requiredEntities = entitiesMappingData; + requiredEntities.result = entitiesMappingData.data; + } + } - entitiesMappingData["result"] = entitiesMappingData.data; - resolve(entitiesMappingData); + // entitiesMappingData["result"] = requiredEntities; + resolve(requiredEntities); } catch (error) { diff --git a/module/programs/helper.js b/module/programs/helper.js index e5dcf409..962e12f5 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -580,7 +580,7 @@ module.exports = class ProgramsHelper { }); let filterQuery = { - "scope.roles.code" : { $in : [constants.common.ALL_ROLES,data.role] }, + "scope.roles.code" : { $in : [constants.common.ALL_ROLES,...data.role.split(",")] }, "scope.entities" : { $in : entityIds }, "isDeleted" : false, status : constants.common.ACTIVE diff --git a/module/solutions/helper.js b/module/solutions/helper.js index cf4e10f6..9be381c6 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -756,7 +756,7 @@ module.exports = class SolutionsHelper { }); let filterQuery = { - "scope.roles.code" : { $in : [constants.common.ALL_ROLES,data.role] }, + "scope.roles.code" : { $in : [constants.common.ALL_ROLES,...data.role.split(",")] }, "scope.entities" : { $in : entityIds }, "scope.entityType" : { $in : entityTypes }, "isReusable" : false, From b06b0704440ae9502a1a1383a45ef508d82d1a70 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Tue, 23 Nov 2021 09:15:29 +0530 Subject: [PATCH 062/331] PR changes --- controllers/v1/solutions.js | 2 +- module/solutions/helper.js | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/controllers/v1/solutions.js b/controllers/v1/solutions.js index bbb9951f..56fcf3f6 100644 --- a/controllers/v1/solutions.js +++ b/controllers/v1/solutions.js @@ -39,7 +39,7 @@ module.exports = class Solutions extends Abstract { "subType" : "improvementProject", "isReusable" : false, "externalId" : "01c04166-a65e-4e92-a87b-a9e4194e771d-1607936956167", - "noOfSubmissionsRequired" : 2, + "minNoOfSubmissionsRequired" : 2, "allowMultipleAssessemts" : true } * @apiHeader {String} internal-access-token internal access token diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 215a4b7e..87b1777d 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -172,8 +172,8 @@ module.exports = class SolutionsHelper { solutionData.entities = entitiesData; } - if( !solutionData.noOfSubmissionsRequired || !solutionData.allowMultipleAssessemts ) { - solutionData.noOfSubmissionsRequired = constants.common.DEFAULT_SUBMISSION_REQUIRED; + if( !solutionData.minNoOfSubmissionsRequired || !solutionData.allowMultipleAssessemts ) { + solutionData.minNoOfSubmissionsRequired = constants.common.DEFAULT_SUBMISSION_REQUIRED; } solutionData.status = constants.common.ACTIVE; @@ -433,8 +433,8 @@ module.exports = class SolutionsHelper { "$set" : {} }; - if( !solutionData.noOfSubmissionsRequired || !solutionData.allowMultipleAssessemts ) { - solutionData.noOfSubmissionsRequired = constants.common.DEFAULT_SUBMISSION_REQUIRED; + if( !solutionData.minNoOfSubmissionsRequired || !solutionData.allowMultipleAssessemts ) { + solutionData.minNoOfSubmissionsRequired = constants.common.DEFAULT_SUBMISSION_REQUIRED; } let solutionUpdateData = solutionData; From b5bc6ba632843e9607da97f5bb0233fa997afe35 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Tue, 23 Nov 2021 19:13:34 +0530 Subject: [PATCH 063/331] pr changes --- module/solutions/helper.js | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 87b1777d..26ab4290 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -172,8 +172,12 @@ module.exports = class SolutionsHelper { solutionData.entities = entitiesData; } - if( !solutionData.minNoOfSubmissionsRequired || !solutionData.allowMultipleAssessemts ) { - solutionData.minNoOfSubmissionsRequired = constants.common.DEFAULT_SUBMISSION_REQUIRED; + if( solutionData.minNoOfSubmissionsRequired && + solutionData.minNoOfSubmissionsRequired > constants.common.DEFAULT_SUBMISSION_REQUIRED + ) { + if (!solutionData.allowMultipleAssessemts){ + solutionData.minNoOfSubmissionsRequired = constants.common.DEFAULT_SUBMISSION_REQUIRED; + } } solutionData.status = constants.common.ACTIVE; @@ -433,8 +437,12 @@ module.exports = class SolutionsHelper { "$set" : {} }; - if( !solutionData.minNoOfSubmissionsRequired || !solutionData.allowMultipleAssessemts ) { - solutionData.minNoOfSubmissionsRequired = constants.common.DEFAULT_SUBMISSION_REQUIRED; + if( solutionData.minNoOfSubmissionsRequired && + solutionData.minNoOfSubmissionsRequired > constants.common.DEFAULT_SUBMISSION_REQUIRED + ) { + if (!solutionData.allowMultipleAssessemts){ + solutionData.minNoOfSubmissionsRequired = constants.common.DEFAULT_SUBMISSION_REQUIRED; + } } let solutionUpdateData = solutionData; From 06dbb660ba1a5bb0266b963c69a898f478716c1e Mon Sep 17 00:00:00 2001 From: Akash Shah Date: Mon, 29 Nov 2021 19:59:24 +0530 Subject: [PATCH 064/331] Bug fix. --- module/solutions/helper.js | 3 ++- module/users/helper.js | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/module/solutions/helper.js b/module/solutions/helper.js index b7633575..2aa6476b 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -708,7 +708,8 @@ module.exports = class SolutionsHelper { "language", "creator", "endDate", - "link" + "link", + "referenceFrom" ] ); diff --git a/module/users/helper.js b/module/users/helper.js index c6ebd465..48454bb3 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -452,6 +452,8 @@ module.exports = class UsersHelper { delete targetedData.programName; return targetedData; }); + + mergedData = _.filter(mergedData, { 'referenceFrom': constants.common.PROJECT, 'type': constants.common.OBSERVATION }); } let importedProjects = await improvementProjectService.importedProjects( From ffe026a5358247a2238eeedfc89271db3b395509 Mon Sep 17 00:00:00 2001 From: Akash Shah Date: Mon, 29 Nov 2021 20:41:31 +0530 Subject: [PATCH 065/331] Bug fix. --- module/users/helper.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/module/users/helper.js b/module/users/helper.js index 48454bb3..29ad2420 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -443,6 +443,9 @@ module.exports = class UsersHelper { autoTargetedSolutions.data.data && autoTargetedSolutions.data.data.length > 0 ) { + + autoTargetedSolutions.data = _.remove(autoTargetedSolutions.data, { 'referenceFrom': constants.common.PROJECT, 'type': constants.common.OBSERVATION }); + totalCount = autoTargetedSolutions.data.count; mergedData = autoTargetedSolutions.data.data; @@ -453,7 +456,7 @@ module.exports = class UsersHelper { return targetedData; }); - mergedData = _.filter(mergedData, { 'referenceFrom': constants.common.PROJECT, 'type': constants.common.OBSERVATION }); + } let importedProjects = await improvementProjectService.importedProjects( From cec6bda38c5efd2861449461cfe10acab523505f Mon Sep 17 00:00:00 2001 From: Akash Shah Date: Mon, 29 Nov 2021 21:38:59 +0530 Subject: [PATCH 066/331] Bug fix. --- module/users/helper.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/module/users/helper.js b/module/users/helper.js index 29ad2420..0a962161 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -444,7 +444,7 @@ module.exports = class UsersHelper { autoTargetedSolutions.data.data.length > 0 ) { - autoTargetedSolutions.data = _.remove(autoTargetedSolutions.data, { 'referenceFrom': constants.common.PROJECT, 'type': constants.common.OBSERVATION }); + autoTargetedSolutions.data.data = _.remove(autoTargetedSolutions.data.data, { 'referenceFrom': constants.common.PROJECT, 'type': constants.common.OBSERVATION }); totalCount = autoTargetedSolutions.data.count; From b7de3989804f9ebbc6f3c6b0d197a3498773e7b8 Mon Sep 17 00:00:00 2001 From: Akash Shah Date: Mon, 29 Nov 2021 22:07:01 +0530 Subject: [PATCH 067/331] Bug fix. --- module/users/helper.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/module/users/helper.js b/module/users/helper.js index 0a962161..c757ad0d 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -444,7 +444,9 @@ module.exports = class UsersHelper { autoTargetedSolutions.data.data.length > 0 ) { - autoTargetedSolutions.data.data = _.remove(autoTargetedSolutions.data.data, { 'referenceFrom': constants.common.PROJECT, 'type': constants.common.OBSERVATION }); + autoTargetedSolutions.data.data = _.remove(autoTargetedSolutions.data.data, function(solution) { +   return solution.referenceFrom == constants.common.PROJECT && solution.type == constants.common.OBSERVATION; + }); totalCount = autoTargetedSolutions.data.count; From 557d24b9a28ce5c95d505079cc8433136d44cbb0 Mon Sep 17 00:00:00 2001 From: Akash Shah Date: Mon, 29 Nov 2021 22:24:56 +0530 Subject: [PATCH 068/331] Bug fix with comments. --- module/users/helper.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/module/users/helper.js b/module/users/helper.js index c757ad0d..e1d1459c 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -444,6 +444,8 @@ module.exports = class UsersHelper { autoTargetedSolutions.data.data.length > 0 ) { + // Remove observation solutions which for project tasks. + autoTargetedSolutions.data.data = _.remove(autoTargetedSolutions.data.data, function(solution) {   return solution.referenceFrom == constants.common.PROJECT && solution.type == constants.common.OBSERVATION; }); From 4638f33c46dd99cee90367fc4fdbd782034422f0 Mon Sep 17 00:00:00 2001 From: Akash Shah Date: Mon, 29 Nov 2021 22:37:13 +0530 Subject: [PATCH 069/331] Remove variable assignment. --- module/users/helper.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/module/users/helper.js b/module/users/helper.js index e1d1459c..dea6fde6 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -446,7 +446,7 @@ module.exports = class UsersHelper { // Remove observation solutions which for project tasks. - autoTargetedSolutions.data.data = _.remove(autoTargetedSolutions.data.data, function(solution) { + _.remove(autoTargetedSolutions.data.data, function(solution) {   return solution.referenceFrom == constants.common.PROJECT && solution.type == constants.common.OBSERVATION; }); From 7b48e817dd850c3c1d14e17bd5384f60c4d3c5f9 Mon Sep 17 00:00:00 2001 From: Akash Shah Date: Tue, 30 Nov 2021 12:51:04 +0530 Subject: [PATCH 070/331] Remove observation project solutions. --- module/solutions/helper.js | 8 +++++++- module/users/helper.js | 2 +- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 2aa6476b..173cbc05 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -1319,7 +1319,13 @@ module.exports = class SolutionsHelper { if( assignedSolutions.success && assignedSolutions.data ) { - totalCount = assignedSolutions.data.count; + // Remove observation solutions which for project tasks. + + _.remove(assignedSolutions.data.data, function(solution) { +   return solution.referenceFrom == constants.common.PROJECT && solution.type == constants.common.OBSERVATION; + }); + + totalCount = assignedSolutions.data.data.count; mergedData = assignedSolutions.data.data; if ( mergedData.length > 0 ) { diff --git a/module/users/helper.js b/module/users/helper.js index dea6fde6..6501d8cf 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -450,7 +450,7 @@ module.exports = class UsersHelper {   return solution.referenceFrom == constants.common.PROJECT && solution.type == constants.common.OBSERVATION; }); - totalCount = autoTargetedSolutions.data.count; + totalCount = autoTargetedSolutions.data.data.count; mergedData = autoTargetedSolutions.data.data; From b752594bea09490db5d0d93c2e8d737bbafa2ec0 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Tue, 7 Dec 2021 15:31:09 +0530 Subject: [PATCH 071/331] count fix --- module/solutions/helper.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 173cbc05..f3d4a597 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -1316,16 +1316,16 @@ module.exports = class SolutionsHelper { let totalCount = 0; let mergedData = []; let solutionIds = []; - + if( assignedSolutions.success && assignedSolutions.data ) { // Remove observation solutions which for project tasks. - _.remove(assignedSolutions.data.data, function(solution) { -   return solution.referenceFrom == constants.common.PROJECT && solution.type == constants.common.OBSERVATION; + _.remove(assignedSolutions.data.data, function(solution) { + return solution.referenceFrom == constants.common.PROJECT && solution.type == constants.common.OBSERVATION; }); - totalCount = assignedSolutions.data.data.count; + totalCount = assignedSolutions.data.data && assignedSolutions.data.data.length > 0 ? assignedSolutions.data.data.length : totalCount; mergedData = assignedSolutions.data.data; if ( mergedData.length > 0 ) { From 531bba48d99e4d8356e77b252501801fc11a63a3 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Thu, 9 Dec 2021 19:31:13 +0530 Subject: [PATCH 072/331] sub role story changes --- controllers/v1/entities.js | 25 ++++++++++---- controllers/v1/solutions.js | 6 ++-- controllers/v1/users.js | 52 +++++++++++++++++++++-------- generics/constants/api-responses.js | 1 + module/entities/helper.js | 5 +-- module/users/helper.js | 1 + 6 files changed, 66 insertions(+), 24 deletions(-) diff --git a/controllers/v1/entities.js b/controllers/v1/entities.js index 782890cc..15c52ffa 100644 --- a/controllers/v1/entities.js +++ b/controllers/v1/entities.js @@ -322,7 +322,7 @@ module.exports = class Entities extends Abstract { * @apiVersion 1.0.0 * @apiGroup Entities * @apiHeader {String} X-authenticated-user-token Authenticity token - * @apiSampleRequest /kendra/api/v1/entities/subEntityListBasedOnRoleAndLocation/236f5cff-c9af-4366-b0b6-253a1789766a?role=DEO + * @apiSampleRequest /kendra/api/v1/entities/subEntityListBasedOnRoleAndLocation/236f5cff-c9af-4366-b0b6-253a1789766a?role=DEO,HM * @apiUse successBody * @apiUse errorBody * @apiParamExample {json} Response: @@ -351,11 +351,24 @@ module.exports = class Entities extends Abstract { try { - const subEntityTypeListData = - await entitiesHelper.subEntityListBasedOnRoleAndLocation( - req.params._id, - req.query.role - ); + + let currentMaximumCountOfRequiredEntities = 0; + let subEntityTypeListData = new Array; + // Calculate required entity type for each of the role and send the output of the role which has maximum length. + for (let roleCount = 0; roleCount < req.query.role.split(",").length; roleCount++) { + const eachRole = req.query.role.split(",")[roleCount]; + const entityTypeMappingData = + await entitiesHelper.subEntityListBasedOnRoleAndLocation( + req.params._id, + eachRole + ); + + if(entityTypeMappingData.result && entityTypeMappingData.result.length > currentMaximumCountOfRequiredEntities) { + currentMaximumCountOfRequiredEntities = entityTypeMappingData.result.length; + subEntityTypeListData = entityTypeMappingData; + subEntityTypeListData.result = entityTypeMappingData.result; + } + } resolve(subEntityTypeListData); diff --git a/controllers/v1/solutions.js b/controllers/v1/solutions.js index 56fcf3f6..7374ad9d 100644 --- a/controllers/v1/solutions.js +++ b/controllers/v1/solutions.js @@ -679,7 +679,7 @@ module.exports = class Solutions extends Abstract { * @apiSampleRequest /kendra/api/v1/solutions/targetedSolutions?type=observation&page=1&limit=10&search=a&filter=assignedToMe * @apiParamExample {json} Request: * { - * "role" : "HM", + * "role" : "HM,DEO", "state" : "236f5cff-c9af-4366-b0b6-253a1789766a", "district" : "1dcbc362-ec4c-4559-9081-e0c2864c2931", "school" : "c5726207-4f9f-4f45-91f1-3e9e8e84d824" @@ -807,7 +807,7 @@ module.exports = class Solutions extends Abstract { * @apiUse errorBody * @apiParamExample {json} Request: * { - * "role" : "HM", + * "role" : "HM,DEO", "state" : "236f5cff-c9af-4366-b0b6-253a1789766a", "district" : "1dcbc362-ec4c-4559-9081-e0c2864c2931", "school" : "c5726207-4f9f-4f45-91f1-3e9e8e84d824" @@ -871,7 +871,7 @@ module.exports = class Solutions extends Abstract { * @apiUse errorBody * @apiParamExample {json} Request: * { - * "role" : "HM", + * "role" : "HM,DEO", "state" : "236f5cff-c9af-4366-b0b6-253a1789766a", "district" : "1dcbc362-ec4c-4559-9081-e0c2864c2931", "school" : "c5726207-4f9f-4f45-91f1-3e9e8e84d824" diff --git a/controllers/v1/users.js b/controllers/v1/users.js index a0da89df..36d27195 100644 --- a/controllers/v1/users.js +++ b/controllers/v1/users.js @@ -218,7 +218,7 @@ module.exports = class Users extends Abstract { * @apiSampleRequest /kendra/api/v1/users/solutions/5ff438b04698083dbfab7284?page=1&limit=10 * @apiParamExample {json} Request-Body: * { - "role" : "HM", + "role" : "HM,DEO", "state" : "236f5cff-c9af-4366-b0b6-253a1789766a", "district" : "1dcbc362-ec4c-4559-9081-e0c2864c2931", "school" : "c5726207-4f9f-4f45-91f1-3e9e8e84d824" @@ -310,7 +310,7 @@ module.exports = class Users extends Abstract { * @apiUse errorBody * @apiParamExample {json} Request: * { - "role" : "HM", + "role" : "HM,DEO", "state" : "236f5cff-c9af-4366-b0b6-253a1789766a", "district" : "1dcbc362-ec4c-4559-9081-e0c2864c2931", "school" : "c5726207-4f9f-4f45-91f1-3e9e8e84d824" @@ -435,7 +435,7 @@ module.exports = class Users extends Abstract { req.params._id, eachRole ); - if(entitiesMappingData.data.length > currentMaximumCountOfRequiredEntities) { + if(entitiesMappingData.data && entitiesMappingData.data.length > currentMaximumCountOfRequiredEntities) { currentMaximumCountOfRequiredEntities = entitiesMappingData.data.length; requiredEntities = entitiesMappingData; requiredEntities.result = entitiesMappingData.data; @@ -473,7 +473,7 @@ module.exports = class Users extends Abstract { "state" : "bc75cc99-9205-463e-a722-5326857838f8", "district" : "b54a5c6d-98be-4313-af1c-33040b1703aa", "school" : "2a128c91-a5a2-4e25-aa21-3d9196ad8203", - "role" : "DEO" + "role" : "DEO,HM" } * @apiHeader {String} X-authenticated-user-token Authenticity token * @apiSampleRequest /kendra/api/v1/users/targetedEntity/601d41607d4c835cf8b724ad @@ -502,15 +502,41 @@ module.exports = class Users extends Abstract { async targetedEntity(req) { return new Promise(async (resolve, reject) => { try { - - let detailEntity = await usersHelper.targetedEntity( - req.params._id, - req.body - ); - - detailEntity["result"] = detailEntity.data; - - return resolve(detailEntity); + + let targetedEntities = new Array; + targetedEntities["result"] = new Array; + targetedEntities["data"] = new Array; + + for ( let roleCount = 0; roleCount < req.body.role.split(",").length; roleCount++ ) { + + const eachRole = req.body.role.split(",")[roleCount]; + let bodyData = _.omit(req.body, ['role']); + bodyData.role = eachRole; + + const detailEntity = + await usersHelper.targetedEntity( + req.params._id, + bodyData + ); + + if ( detailEntity.data && Object.keys(detailEntity.data).length > 0 ) { + targetedEntities.message = detailEntity.message; + targetedEntities.success = detailEntity.success; + targetedEntities["data"].push(detailEntity.data); + } + + if ( !targetedEntities["data"].length > 0 ) { + targetedEntities.message = detailEntity.message; + targetedEntities.status = detailEntity.status + } + } + + if ( targetedEntities["data"].length > 0 ){ + targetedEntities["result"] = _.uniqBy(targetedEntities["data"], "entityName"); + delete targetedEntities["data"]; + } + + return resolve(targetedEntities); } catch (error) { return reject({ diff --git a/generics/constants/api-responses.js b/generics/constants/api-responses.js index cf6ae2ee..2b33f3da 100644 --- a/generics/constants/api-responses.js +++ b/generics/constants/api-responses.js @@ -178,5 +178,6 @@ module.exports = { "SOLUTION_DETAILS_VERIFIED": "Solution verified successfully", "SOLUTION_NOT_FOUND_OR_NOT_A_TARGETED": "Solution is not targeted to the role", "PROJECT_TEMPLATE_ID_NOT_FOUND": "Project templates not exists in solution", + "SOLUTION_TARGETED_ENTITY" : "Targeted Entity Types Fetched" }; diff --git a/module/entities/helper.js b/module/entities/helper.js index 9ccedb61..790b442a 100644 --- a/module/entities/helper.js +++ b/module/entities/helper.js @@ -745,8 +745,9 @@ module.exports = class EntitiesHelper { } return resolve({ - message : constants.apiResponses.ENTITIES_CHILD_HIERACHY_PATH, - result : result + success: true, + message : constants.apiResponses.ENTITIES_CHILD_HIERACHY_PATH, + result : result }); } catch (error) { diff --git a/module/users/helper.js b/module/users/helper.js index 6501d8cf..ca14694d 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -761,6 +761,7 @@ module.exports = class UsersHelper { success: true, data: entities[0] }); + } catch (error) { return resolve({ success: false, From 190c57b9830dd942f55d4885f27ec9559bb072fa Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Mon, 13 Dec 2021 18:39:55 +0530 Subject: [PATCH 073/331] targeted entity changes --- controllers/v1/solutions.js | 4 ++-- controllers/v1/users.js | 27 ++++++++++++--------------- generics/constants/common.js | 3 ++- 3 files changed, 16 insertions(+), 18 deletions(-) diff --git a/controllers/v1/solutions.js b/controllers/v1/solutions.js index 7374ad9d..9fcac0c7 100644 --- a/controllers/v1/solutions.js +++ b/controllers/v1/solutions.js @@ -208,7 +208,7 @@ module.exports = class Solutions extends Abstract { * @apiGroup Solutions * @apiParamExample {json} Request-Body: * { - "role" : "HM", + "role" : "HM,DEO", "state" : "236f5cff-c9af-4366-b0b6-253a1789766a", "district" : "1dcbc362-ec4c-4559-9081-e0c2864c2931", "school" : "c5726207-4f9f-4f45-91f1-3e9e8e84d824", @@ -277,7 +277,7 @@ module.exports = class Solutions extends Abstract { * @apiGroup Solutions * @apiParamExample {json} Request-Body: * { - "role" : "HM", + "role" : "HM,DEO", "state" : "236f5cff-c9af-4366-b0b6-253a1789766a", "district" : "1dcbc362-ec4c-4559-9081-e0c2864c2931", "school" : "c5726207-4f9f-4f45-91f1-3e9e8e84d824" diff --git a/controllers/v1/users.js b/controllers/v1/users.js index 36d27195..4ac95e7e 100644 --- a/controllers/v1/users.js +++ b/controllers/v1/users.js @@ -503,9 +503,7 @@ module.exports = class Users extends Abstract { return new Promise(async (resolve, reject) => { try { - let targetedEntities = new Array; - targetedEntities["result"] = new Array; - targetedEntities["data"] = new Array; + let targetedEntities = {}; for ( let roleCount = 0; roleCount < req.body.role.split(",").length; roleCount++ ) { @@ -519,21 +517,20 @@ module.exports = class Users extends Abstract { bodyData ); + targetedEntities.message = detailEntity.message; + targetedEntities.success = detailEntity.success; + targetedEntities.status = detailEntity.status; + if ( detailEntity.data && Object.keys(detailEntity.data).length > 0 ) { - targetedEntities.message = detailEntity.message; - targetedEntities.success = detailEntity.success; - targetedEntities["data"].push(detailEntity.data); - } - if ( !targetedEntities["data"].length > 0 ) { - targetedEntities.message = detailEntity.message; - targetedEntities.status = detailEntity.status - } - } + if ( roleCount == 0 ) { + targetedEntities.result = detailEntity.data; + } - if ( targetedEntities["data"].length > 0 ){ - targetedEntities["result"] = _.uniqBy(targetedEntities["data"], "entityName"); - delete targetedEntities["data"]; + if ( detailEntity.data.entityType !== constants.common.SCHOOL ) { + targetedEntities.result = detailEntity.data; + } + } } return resolve(targetedEntities); diff --git a/generics/constants/common.js b/generics/constants/common.js index 7128ea5b..4503f9b7 100644 --- a/generics/constants/common.js +++ b/generics/constants/common.js @@ -65,5 +65,6 @@ module.exports = { "CREATE_PROJECT" : "/create-project/", "LINK" : "link", "DISCOVERED_BY_ME" : "discoveredByMe", - "DEFAULT_SUBMISSION_REQUIRED" : 1 + "DEFAULT_SUBMISSION_REQUIRED" : 1, + "SCHOOL" : "school" }; From b1948509dc0d08b7da7c26e1b6fd32cff9986617 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Wed, 15 Dec 2021 12:41:39 +0530 Subject: [PATCH 074/331] hide inactive status --- module/user-extension/helper.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/module/user-extension/helper.js b/module/user-extension/helper.js index 4a049aea..0e83773d 100644 --- a/module/user-extension/helper.js +++ b/module/user-extension/helper.js @@ -654,7 +654,8 @@ module.exports = class UserExtensionHelper { const solutionDocuments = await solutionsHelper.solutionDocuments({ _id: {$in: programDocuments[0].components}, programId: programId, - isReusable: false + isReusable: false, + status: constants.common.ACTIVE },[ "externalId", "description", From cb3f7ef7ce96b29af57df16182c93a998160282b Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Thu, 16 Dec 2021 17:10:23 +0530 Subject: [PATCH 075/331] solution list --- module/user-extension/helper.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/module/user-extension/helper.js b/module/user-extension/helper.js index 0e83773d..60d2f347 100644 --- a/module/user-extension/helper.js +++ b/module/user-extension/helper.js @@ -655,7 +655,7 @@ module.exports = class UserExtensionHelper { _id: {$in: programDocuments[0].components}, programId: programId, isReusable: false, - status: constants.common.ACTIVE + isDeleted: false },[ "externalId", "description", From 937dd1a36ef5f27421e74cb2ea7d8c02211d99d0 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Fri, 17 Dec 2021 19:29:24 +0530 Subject: [PATCH 076/331] targeted entity fix --- controllers/v1/users.js | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/controllers/v1/users.js b/controllers/v1/users.js index 4ac95e7e..ccdea6c6 100644 --- a/controllers/v1/users.js +++ b/controllers/v1/users.js @@ -517,9 +517,6 @@ module.exports = class Users extends Abstract { bodyData ); - targetedEntities.message = detailEntity.message; - targetedEntities.success = detailEntity.success; - targetedEntities.status = detailEntity.status; if ( detailEntity.data && Object.keys(detailEntity.data).length > 0 ) { @@ -531,6 +528,12 @@ module.exports = class Users extends Abstract { targetedEntities.result = detailEntity.data; } } + + if ( !targetedEntities.result ) { + targetedEntities.message = detailEntity.message; + targetedEntities.success = detailEntity.success; + targetedEntities.status = detailEntity.status; + } } return resolve(targetedEntities); From 7343d4a3464345c2f840e6941b34507892692b5b Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Wed, 22 Dec 2021 04:08:43 +0530 Subject: [PATCH 077/331] targetedEntity fix --- controllers/v1/users.js | 74 +++++++++++++++++++++++++++++++++++------ 1 file changed, 63 insertions(+), 11 deletions(-) diff --git a/controllers/v1/users.js b/controllers/v1/users.js index ccdea6c6..c6cc58f7 100644 --- a/controllers/v1/users.js +++ b/controllers/v1/users.js @@ -11,6 +11,7 @@ */ const usersHelper = require(MODULES_BASE_PATH + "/users/helper.js"); +const entitiesHelper = require(MODULES_BASE_PATH + "/entities/helper.js"); /** * User @@ -504,6 +505,7 @@ module.exports = class Users extends Abstract { try { let targetedEntities = {}; + let matchingEntities = new Array(); for ( let roleCount = 0; roleCount < req.body.role.split(",").length; roleCount++ ) { @@ -517,23 +519,73 @@ module.exports = class Users extends Abstract { bodyData ); - if ( detailEntity.data && Object.keys(detailEntity.data).length > 0 ) { - if ( roleCount == 0 ) { - targetedEntities.result = detailEntity.data; - } + matchingEntities.push(detailEntity.data); - if ( detailEntity.data.entityType !== constants.common.SCHOOL ) { - targetedEntities.result = detailEntity.data; + }else{ + + if ( req.body.role.split(",").length - 1 === roleCount) { + targetedEntities.message = detailEntity.message; } } + } - if ( !targetedEntities.result ) { - targetedEntities.message = detailEntity.message; - targetedEntities.success = detailEntity.success; - targetedEntities.status = detailEntity.status; - } + if ( matchingEntities && matchingEntities.length == 1 ) { + targetedEntities.result = matchingEntities[0]; + return resolve(targetedEntities); + } + + let allTargetedEntities = {}; + if ( matchingEntities && matchingEntities.length > 1 ) { + + for( let pointerToEntities = 0 ; pointerToEntities < matchingEntities.length ; pointerToEntities++ ) { + + let currentEntity = matchingEntities[pointerToEntities]; + + if ( !allTargetedEntities.hasOwnProperty(currentEntity._id) ){ + allTargetedEntities[currentEntity._id] = new Array(); + } + let otherEntities = matchingEntities.filter((entity) => entity.entityType !== currentEntity.entityType); + + if ( !otherEntities || !otherEntities.length > 0 ) { + continue; + } + + let entitiesDocument = await entitiesHelper.entityDocuments({ + _id: ObjectId(currentEntity._id) + }, ["groups"]); + + if ( !entitiesDocument ) { + continue; + } + + entitiesDocument = entitiesDocument[0]; + + for( let entityCounter = 0 ; entityCounter < otherEntities.length ; entityCounter++ ) { + + let entityDoc = otherEntities[entityCounter]; + if ( !entitiesDocument.groups || !entitiesDocument.groups.hasOwnProperty(entityDoc.entityType)){ + continue; + } + + allTargetedEntities[currentEntity._id].push(true); + } + } + }else{ + + targetedEntities.status = httpStatusCode.bad_request.status; + } + + if ( Object.keys(allTargetedEntities).length > 0 ){ + + let entitiesCount = req.body.role.split(",").length - 1; + Object.keys(allTargetedEntities).forEach( entityMap => { + if ( allTargetedEntities[entityMap] && allTargetedEntities[entityMap].length === entitiesCount ) { + targetedEntities["result"] = matchingEntities.filter((entity) => entity._id == entityMap); + } + + }) } return resolve(targetedEntities); From 5ef433d7579f5e908dcee5efe03d14f54d01904f Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Wed, 22 Dec 2021 10:28:44 +0530 Subject: [PATCH 078/331] adding comments --- controllers/v1/users.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/controllers/v1/users.js b/controllers/v1/users.js index c6cc58f7..05cf2ddd 100644 --- a/controllers/v1/users.js +++ b/controllers/v1/users.js @@ -524,19 +524,21 @@ module.exports = class Users extends Abstract { matchingEntities.push(detailEntity.data); }else{ - + //setting error message if ( req.body.role.split(",").length - 1 === roleCount) { targetedEntities.message = detailEntity.message; } } } + //return when only one entity found if ( matchingEntities && matchingEntities.length == 1 ) { targetedEntities.result = matchingEntities[0]; return resolve(targetedEntities); } let allTargetedEntities = {}; + //finding the highest entity if ( matchingEntities && matchingEntities.length > 1 ) { for( let pointerToEntities = 0 ; pointerToEntities < matchingEntities.length ; pointerToEntities++ ) { @@ -577,6 +579,7 @@ module.exports = class Users extends Abstract { targetedEntities.status = httpStatusCode.bad_request.status; } + //check the count of allTargetedEntities with role count to get the targeted entity if ( Object.keys(allTargetedEntities).length > 0 ){ let entitiesCount = req.body.role.split(",").length - 1; From 1fe2f72ba05e1a283d6454e577e7b504705d23e9 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Wed, 22 Dec 2021 12:39:07 +0530 Subject: [PATCH 079/331] PR review --- controllers/v1/users.js | 114 +++++++++++++++++----------------------- module/users/helper.js | 77 +++++++++++++++++++++++++++ 2 files changed, 124 insertions(+), 67 deletions(-) diff --git a/controllers/v1/users.js b/controllers/v1/users.js index 05cf2ddd..b632fa17 100644 --- a/controllers/v1/users.js +++ b/controllers/v1/users.js @@ -504,91 +504,71 @@ module.exports = class Users extends Abstract { return new Promise(async (resolve, reject) => { try { + let roleArray = req.body.role.split(","); let targetedEntities = {}; - let matchingEntities = new Array(); - for ( let roleCount = 0; roleCount < req.body.role.split(",").length; roleCount++ ) { + if ( roleArray.length === 1 ) { - const eachRole = req.body.role.split(",")[roleCount]; - let bodyData = _.omit(req.body, ['role']); - bodyData.role = eachRole; - const detailEntity = await usersHelper.targetedEntity( req.params._id, - bodyData + req.body ); - if ( detailEntity.data && Object.keys(detailEntity.data).length > 0 ) { - - matchingEntities.push(detailEntity.data); - - }else{ - //setting error message - if ( req.body.role.split(",").length - 1 === roleCount) { - targetedEntities.message = detailEntity.message; - } - } - } + detailEntity["result"] = detailEntity.data; + + return resolve(detailEntity); - //return when only one entity found - if ( matchingEntities && matchingEntities.length == 1 ) { - targetedEntities.result = matchingEntities[0]; - return resolve(targetedEntities); - } + } else { - let allTargetedEntities = {}; - //finding the highest entity - if ( matchingEntities && matchingEntities.length > 1 ) { - - for( let pointerToEntities = 0 ; pointerToEntities < matchingEntities.length ; pointerToEntities++ ) { + let roleWiseTargetedEntities = new Array(); - let currentEntity = matchingEntities[pointerToEntities]; + for ( let roleCount = 0; roleCount < roleArray.length; roleCount++ ) { - if ( !allTargetedEntities.hasOwnProperty(currentEntity._id) ){ - allTargetedEntities[currentEntity._id] = new Array(); - } - let otherEntities = matchingEntities.filter((entity) => entity.entityType !== currentEntity.entityType); + const eachRole = roleArray[roleCount]; + let bodyData = _.omit(req.body, ['role']); + bodyData.role = eachRole; + + const detailEntity = + await usersHelper.targetedEntity( + req.params._id, + bodyData + ); - if ( !otherEntities || !otherEntities.length > 0 ) { - continue; + if ( detailEntity.data && Object.keys(detailEntity.data).length > 0 ) { + roleWiseTargetedEntities.push(detailEntity.data); } + } - let entitiesDocument = await entitiesHelper.entityDocuments({ - _id: ObjectId(currentEntity._id) - }, ["groups"]); + //no targeted entity + if ( roleWiseTargetedEntities.length == 0 ) { + throw { + status: httpStatusCode["bad_request"].status, + message: constants.apiResponses.ENTITIES_NOT_ALLOWED_IN_ROLE + }; + } + //one targeted entity + else if ( roleWiseTargetedEntities && roleWiseTargetedEntities.length == 1 ) { + + targetedEntities.result = roleWiseTargetedEntities[0]; - if ( !entitiesDocument ) { - continue; + } + // multiple targeted entity + else if ( roleWiseTargetedEntities && roleWiseTargetedEntities.length > 1 ) { + + let targetedEntity = await usersHelper.getHighestTargetedEntity( + roleWiseTargetedEntities + ); + + if ( !targetedEntity.data ) { + throw { + status: httpStatusCode["bad_request"].status, + message: constants.apiResponses.ENTITIES_NOT_ALLOWED_IN_ROLE + }; } - entitiesDocument = entitiesDocument[0]; - - for( let entityCounter = 0 ; entityCounter < otherEntities.length ; entityCounter++ ) { - - let entityDoc = otherEntities[entityCounter]; - if ( !entitiesDocument.groups || !entitiesDocument.groups.hasOwnProperty(entityDoc.entityType)){ - continue; - } - - allTargetedEntities[currentEntity._id].push(true); - } - } - }else{ - - targetedEntities.status = httpStatusCode.bad_request.status; - } - - //check the count of allTargetedEntities with role count to get the targeted entity - if ( Object.keys(allTargetedEntities).length > 0 ){ - - let entitiesCount = req.body.role.split(",").length - 1; - Object.keys(allTargetedEntities).forEach( entityMap => { - if ( allTargetedEntities[entityMap] && allTargetedEntities[entityMap].length === entitiesCount ) { - targetedEntities["result"] = matchingEntities.filter((entity) => entity._id == entityMap); - } - - }) + targetedEntities.result = targetedEntity.data; + } } return resolve(targetedEntities); diff --git a/module/users/helper.js b/module/users/helper.js index ca14694d..b2c26634 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -773,6 +773,83 @@ module.exports = class UsersHelper { } }); } + + /** + * Highest Targeted entity. + * @method + * @name getHighestTargetedEntity + * @param {Object} requestedData - requested data + * @returns {Object} - Entity. + */ + + static getHighestTargetedEntity( roleWiseTargetedEntities ) { + return new Promise(async (resolve, reject) => { + try { + + let allTargetedEntities = {}; + let targetedEntity = {}; + + for( let pointerToEntities = 0 ; pointerToEntities < roleWiseTargetedEntities.length ; pointerToEntities++ ) { + + let currentEntity = roleWiseTargetedEntities[pointerToEntities]; + + if ( !allTargetedEntities.hasOwnProperty(currentEntity._id) ) { + allTargetedEntities[currentEntity._id] = new Array(); + } + + let otherEntities = roleWiseTargetedEntities.filter((entity) => entity.entityType !== currentEntity.entityType); + + if ( !otherEntities || !otherEntities.length > 0 ) { + continue; + } + + let entitiesDocument = await entitiesHelper.entityDocuments({ + _id: ObjectId(currentEntity._id) + }, ["groups"]); + + if ( !entitiesDocument || !entitiesDocument.length > 0 ) { + continue; + } + + entitiesDocument = entitiesDocument[0]; + for( let entityCounter = 0 ; entityCounter < otherEntities.length ; entityCounter++ ) { + + let entityDoc = otherEntities[entityCounter]; + + if ( !entitiesDocument.groups || !entitiesDocument.groups.hasOwnProperty(entityDoc.entityType) ) { + break; + } + + allTargetedEntities[currentEntity._id].push(true); + + if ( allTargetedEntities[currentEntity._id].length == otherEntities.length ) { + targetedEntity = roleWiseTargetedEntities.filter((entity) => entity._id == currentEntity._id); + break; + } + } + + } + + return resolve({ + message: constants.apiResponses.SOLUTION_TARGETED_ENTITY, + success: true, + data: targetedEntity + }); + + } catch (error) { + return resolve({ + success: false, + status: error.status + ? error.status + : httpStatusCode['internal_server_error'].status, + message: error.message + }); + } + }); + } + + + }; /** From 8b0d460b004d8ba623c7f4de531753165524ea9c Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Wed, 22 Dec 2021 12:54:53 +0530 Subject: [PATCH 080/331] remove helper --- controllers/v1/users.js | 1 - 1 file changed, 1 deletion(-) diff --git a/controllers/v1/users.js b/controllers/v1/users.js index b632fa17..c4e58b43 100644 --- a/controllers/v1/users.js +++ b/controllers/v1/users.js @@ -11,7 +11,6 @@ */ const usersHelper = require(MODULES_BASE_PATH + "/users/helper.js"); -const entitiesHelper = require(MODULES_BASE_PATH + "/entities/helper.js"); /** * User From 5eabc7aba7c736dc44ba28c0a337f73d8efc99fe Mon Sep 17 00:00:00 2001 From: rakeshSgr Date: Thu, 30 Dec 2021 17:25:39 +0530 Subject: [PATCH 081/331] entity details api added --- controllers/v1/entities.js | 61 ++++++++++++++++++++++++++ generics/middleware/authenticator.js | 3 +- module/entities/helper.js | 65 ++++++++++++++++++++++++++++ 3 files changed, 128 insertions(+), 1 deletion(-) diff --git a/controllers/v1/entities.js b/controllers/v1/entities.js index 15c52ffa..598cfaab 100644 --- a/controllers/v1/entities.js +++ b/controllers/v1/entities.js @@ -386,5 +386,66 @@ module.exports = class Entities extends Abstract { } }); } + + /** + * @api {get} /kendra/api/v1/entities/details/:entityId + * Get entities details information + * @apiVersion 1.0.0 + * @apiGroup Entities + * @apiHeader {String} X-authenticated-user-token Authenticity token + * @apiSampleRequest /kendra/api/v1/entities/details/5db173598a8e070bedca6ba1 + * @apiUse successBody + * @apiUse errorBody + * @apiParamExample {json} Response: + * { + * "message": "Entity information fetched successfully", + * "status": 200, + * "result": { + "_id": "5db173598a8e070bedca6ba1", + "entityTypeId": "5d7a290e6371783ceb11064c", + "entityType": "state", + "metaInformation": { + "externalId": "DL", + "name": "Delhi", + "region": "NORTH", + "capital": "NEW DELHI" + }, + "updatedBy": "2be2fd94-f25e-4402-8e36-20907b45c650", + "createdBy": "2be2fd94-f25e-4402-8e36-20907b45c650", + "updatedAt": "2019-10-24T10:16:44.833Z", + "createdAt": "2019-10-24T09:48:09.005Z" + } + } + /** + * Entity details. + * @method + * @name details + * @param {Object} req - requested entity information. + * @param {String} req.params._id - entity id + * @returns {JSON} - Entity details information. + */ + + details(req) { + + return new Promise(async (resolve, reject) => { + + try { + + let result = await entitiesHelper.details( + req.params._id ? req.params._id :"",req.body ? req.body : {} + ); + + return resolve(result); + + } catch (error) { + + return reject({ + status: error.status || httpStatusCode.internal_server_error.status, + message: error.message || httpStatusCode.internal_server_error.message, + errorObject: error + }) + } + }) + } }; diff --git a/generics/middleware/authenticator.js b/generics/middleware/authenticator.js index 67d217a1..b664f2ed 100644 --- a/generics/middleware/authenticator.js +++ b/generics/middleware/authenticator.js @@ -69,7 +69,8 @@ module.exports = async function (req, res, next) { "/user-roles/list", "/forms/details", "/programs/list", - "/entities/getUsersByEntityAndRole/" + "/entities/getUsersByEntityAndRole/", + "/entities/details" ]; let performInternalAccessTokenCheck = false; diff --git a/module/entities/helper.js b/module/entities/helper.js index 790b442a..5ecfc561 100644 --- a/module/entities/helper.js +++ b/module/entities/helper.js @@ -757,4 +757,69 @@ module.exports = class EntitiesHelper { } + /** + * Entity details information. + * @method + * @name details + * @param {String} entityId - _id of entity. + * @param {Object} requestData - query details. + * @param {String} requestData.locationIds - array of location Ids + * @param {String} requestData.entityIds - array of entity Ids + * @return {Array} - consists of entity details information. + */ + + static details(entityId, requestData = {}) { + return new Promise(async (resolve, reject) => { + try { + + let entityIds = []; + let query = {}; + query["$or"] = []; + + if (entityId) { + entityIds.push(entityId) + } + if (requestData && requestData.entityIds) { + entityIds.push(...requestData.entityIds); + } + if (entityIds.length > 0) { + query["$or"].push({ + _id: { + $in: entityIds + } + }) + } + + if (requestData && requestData.locationIds) { + query["$or"].push({ + "registryDetails.locationId": { + $in: requestData.locationIds + } + }) + } + + let entityDocument = await this.entityDocuments( + query, + "all", + ["groups"] + ); + + if (entityDocument && entityDocument.length ==0 ) { + return resolve({ + status : httpStatusCode.bad_request.status, + message : constants.apiResponses.ENTITY_NOT_FOUND + }) + } + + resolve({ + message : constants.apiResponses.ENTITY_INFORMATION_FETCHED, + result : entityDocument + }); + + } catch (error) { + return reject(error); + } + }) + } + } From 4b5c3cb99e84ae01ad8561039487da2e64ac1d05 Mon Sep 17 00:00:00 2001 From: rakeshSgr Date: Thu, 30 Dec 2021 18:21:02 +0530 Subject: [PATCH 082/331] api validation added --- generics/constants/api-responses.js | 3 ++- module/entities/helper.js | 6 ++++++ module/entities/validator/v1.js | 30 ++++++++++++++++++++++++++++- 3 files changed, 37 insertions(+), 2 deletions(-) diff --git a/generics/constants/api-responses.js b/generics/constants/api-responses.js index 2b33f3da..45f4c5f8 100644 --- a/generics/constants/api-responses.js +++ b/generics/constants/api-responses.js @@ -178,6 +178,7 @@ module.exports = { "SOLUTION_DETAILS_VERIFIED": "Solution verified successfully", "SOLUTION_NOT_FOUND_OR_NOT_A_TARGETED": "Solution is not targeted to the role", "PROJECT_TEMPLATE_ID_NOT_FOUND": "Project templates not exists in solution", - "SOLUTION_TARGETED_ENTITY" : "Targeted Entity Types Fetched" + "SOLUTION_TARGETED_ENTITY" : "Targeted Entity Types Fetched", + "ENTITY_ID_OR_LOCATION_ID_NOT_FOUND" : "Entity id or location id not found" }; diff --git a/module/entities/helper.js b/module/entities/helper.js index 5ecfc561..6d0875b1 100644 --- a/module/entities/helper.js +++ b/module/entities/helper.js @@ -782,6 +782,12 @@ module.exports = class EntitiesHelper { if (requestData && requestData.entityIds) { entityIds.push(...requestData.entityIds); } + if(entityIds.length == 0 && !requestData.locationIds){ + throw { + message : constants.apiResponses.ENTITY_ID_OR_LOCATION_ID_NOT_FOUND, + } + } + if (entityIds.length > 0) { query["$or"].push({ _id: { diff --git a/module/entities/validator/v1.js b/module/entities/validator/v1.js index 0c6210ec..96bbddd0 100644 --- a/module/entities/validator/v1.js +++ b/module/entities/validator/v1.js @@ -22,7 +22,23 @@ module.exports = (req) => { subEntityListBasedOnRoleAndLocation : function () { req.checkParams('_id').exists().withMessage("required state location id"); req.checkQuery('role').exists().withMessage("required role code"); - } + }, + details : function () { + req.checkParams('_id').optional() + .isMongoId().withMessage("Invalid entity id"); + + req.checkBody('entityIds').optional() + .isArray().withMessage("entityIds should be array") + .custom(entities => + entitiesValidation(entities) + ).withMessage("invalid entity ids"); + + req.checkBody('locationIds').optional() + .isArray().withMessage("locationIds should be array") + .custom(location => + uuidValidation(location) + ).withMessage("invalid location ids"); + }, } if (entityValidator[req.params.method]) { @@ -42,4 +58,16 @@ module.exports = (req) => { return isObjectIds; } + function uuidValidation(locationIds) { + + let validateUUIDs = true; + if(Array.isArray(locationIds)){ + for (var i = 0; locationIds.length > i; i++) { + if(!gen.utils.checkValidUUID(locationIds[i])){ + validateUUIDs =false + } + } + } + return validateUUIDs; + } } \ No newline at end of file From 9cd5531ca2f2cb39e455ea6d25f7343d49270dba Mon Sep 17 00:00:00 2001 From: rakeshSgr Date: Thu, 30 Dec 2021 19:27:22 +0530 Subject: [PATCH 083/331] UUID validation function update --- generics/helpers/utils.js | 16 +++++++++++++--- module/entities/validator/v1.js | 14 +------------- 2 files changed, 14 insertions(+), 16 deletions(-) diff --git a/generics/helpers/utils.js b/generics/helpers/utils.js index 7e7281af..53d27c1d 100644 --- a/generics/helpers/utils.js +++ b/generics/helpers/utils.js @@ -200,12 +200,22 @@ function valueParser(dataToBeParsed) { * check whether string is valid uuid. * @function * @name checkValidUUID - * @param {String} str + * @param {String} uuids * @returns {Boolean} returns a Boolean value true/false */ -function checkValidUUID(str) { - var validateUUID = uuidValidate(str); +function checkValidUUID(uuids) { + + var validateUUID = true; + if(Array.isArray(uuids)){ + for (var i = 0; uuids.length > i; i++) { + if(!uuidValidate(uuids[i])){ + validateUUID = false + } + } + }else { + validateUUID = uuidValidate(uuids); + } return validateUUID; } diff --git a/module/entities/validator/v1.js b/module/entities/validator/v1.js index 96bbddd0..216c1a67 100644 --- a/module/entities/validator/v1.js +++ b/module/entities/validator/v1.js @@ -36,7 +36,7 @@ module.exports = (req) => { req.checkBody('locationIds').optional() .isArray().withMessage("locationIds should be array") .custom(location => - uuidValidation(location) + gen.utils.checkValidUUID(location) ).withMessage("invalid location ids"); }, } @@ -58,16 +58,4 @@ module.exports = (req) => { return isObjectIds; } - function uuidValidation(locationIds) { - - let validateUUIDs = true; - if(Array.isArray(locationIds)){ - for (var i = 0; locationIds.length > i; i++) { - if(!gen.utils.checkValidUUID(locationIds[i])){ - validateUUIDs =false - } - } - } - return validateUUIDs; - } } \ No newline at end of file From 686d6d4eae4c8ccadef93460f033f51f9f766f0f Mon Sep 17 00:00:00 2001 From: rakeshSgr Date: Wed, 5 Jan 2022 15:44:28 +0530 Subject: [PATCH 084/331] entity details can be fetch from registryDetaisl.code as well --- module/entities/helper.js | 7 +++++++ module/entities/validator/v1.js | 4 ++++ 2 files changed, 11 insertions(+) diff --git a/module/entities/helper.js b/module/entities/helper.js index 6d0875b1..77edecae 100644 --- a/module/entities/helper.js +++ b/module/entities/helper.js @@ -803,6 +803,13 @@ module.exports = class EntitiesHelper { } }) } + if (requestData && requestData.codes) { + query["$or"].push({ + "registryDetails.code": { + $in: requestData.codes + } + }) + } let entityDocument = await this.entityDocuments( query, diff --git a/module/entities/validator/v1.js b/module/entities/validator/v1.js index 216c1a67..2b6e228a 100644 --- a/module/entities/validator/v1.js +++ b/module/entities/validator/v1.js @@ -38,6 +38,10 @@ module.exports = (req) => { .custom(location => gen.utils.checkValidUUID(location) ).withMessage("invalid location ids"); + + req.checkBody('codes').optional() + .isArray().withMessage("codes should be array") + }, } From 2f64a7012c2d9dae6e6b70c1748a1e32c6a009bd Mon Sep 17 00:00:00 2001 From: rakeshSgr Date: Wed, 5 Jan 2022 15:51:35 +0530 Subject: [PATCH 085/331] codes check added --- module/entities/helper.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/module/entities/helper.js b/module/entities/helper.js index 77edecae..2ff6632e 100644 --- a/module/entities/helper.js +++ b/module/entities/helper.js @@ -782,7 +782,7 @@ module.exports = class EntitiesHelper { if (requestData && requestData.entityIds) { entityIds.push(...requestData.entityIds); } - if(entityIds.length == 0 && !requestData.locationIds){ + if(entityIds.length == 0 && !requestData.locationIds && !requestData.codes){ throw { message : constants.apiResponses.ENTITY_ID_OR_LOCATION_ID_NOT_FOUND, } From 53ea0532474e9e4cd4d6aa4b89645bc861090cfa Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Tue, 11 Jan 2022 13:19:20 +0530 Subject: [PATCH 086/331] solution model changes --- models/solutions.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/models/solutions.js b/models/solutions.js index 26cf1fc5..ee2a69d6 100644 --- a/models/solutions.js +++ b/models/solutions.js @@ -87,6 +87,10 @@ module.exports = { }, criteriaLevelReport : Boolean, license:Object, - link: String + link: String, + minNoOfSubmissionsRequired: { + type: Number, + default: 1 + } } }; \ No newline at end of file From b5ad3e90b50114be97919d08afa9d7983145f4f6 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Thu, 27 Jan 2022 18:19:52 +0530 Subject: [PATCH 087/331] verify Link --- controllers/v1/solutions.js | 6 +- controllers/v2/solutions.js | 84 ++++++++++++++++++++++ module/solutions/helper.js | 139 ++++++++++++++++++++++++++++++++++-- 3 files changed, 222 insertions(+), 7 deletions(-) create mode 100644 controllers/v2/solutions.js diff --git a/controllers/v1/solutions.js b/controllers/v1/solutions.js index 9fcac0c7..fbf3ac1d 100644 --- a/controllers/v1/solutions.js +++ b/controllers/v1/solutions.js @@ -787,7 +787,7 @@ module.exports = class Solutions extends Abstract { } catch (error) { - reject({ + return reject({ status: error.status || httpStatusCode.internal_server_error.status, message: error.message || httpStatusCode.internal_server_error.message, errorObject: error @@ -851,7 +851,7 @@ module.exports = class Solutions extends Abstract { } catch (error) { - reject({ + return reject({ status: error.status || httpStatusCode.internal_server_error.status, message: error.message || httpStatusCode.internal_server_error.message, errorObject: error @@ -976,7 +976,7 @@ module.exports = class Solutions extends Abstract { } catch (error) { - reject({ + return reject({ status: error.status || httpStatusCode.internal_server_error.status, message: error.message || httpStatusCode.internal_server_error.message, errorObject: error diff --git a/controllers/v2/solutions.js b/controllers/v2/solutions.js new file mode 100644 index 00000000..ef15d7a5 --- /dev/null +++ b/controllers/v2/solutions.js @@ -0,0 +1,84 @@ +/** + * name : solutions.js + * author : Priyanka Pradeep + * created-date : 27-jan-2022 + * Description : All solution v2 related information. + */ + + +/** + * dependencies + */ + +const solutionV1 = require(ROOT_PATH + "/controllers/v1/solutions"); +const solutionHelper = require(MODULES_BASE_PATH + "/solutions/helper"); + +/** + * SolutrioV2 + * @class +*/ + +module.exports = class SolutionsV2 extends solutionV1 { + /** + * @api {post} /kendra/api/v1/solutions/verifyLink/:link + * @apiVersion 1.0.0 + * @apiName verify Link + * @apiGroup Solutions + * @apiSampleRequest /kendra/api/v1/solutions/verifyLink/6f8d395f674dcb3146ade10f972da9d0 + * @apiHeader {String} X-authenticated-user-token Authenticity token + * @apiUse successBody + * @apiUse errorBody + * @apiParamExample {json} Request: + * { + * "role" : "HM,DEO", + "state" : "236f5cff-c9af-4366-b0b6-253a1789766a", + "district" : "1dcbc362-ec4c-4559-9081-e0c2864c2931", + "school" : "c5726207-4f9f-4f45-91f1-3e9e8e84d824" + } + * @apiParamExample {json} Response: + * { + "message": "Solution Link verified successfully", + "status": 200, + "result": { + isATargetedSolution : true/false, + type: improvementProject, + solutionId : “5f6853f293734140ccce90cf”, + projectId : “” + } + } + */ + + /** + * verify Link + * @method + * @name verifyLink + * @param {Object} req - requested data. + * @param {String} req.params._id - solution Id + * @returns {Array} + */ + + async verifyLink(req) { + return new Promise(async (resolve, reject) => { + try { + + let solutionData = await solutionHelper.verifyLinkV2( + req.params._id, + req.body, + req.userDetails.userId, + req.userDetails.userToken + ); + + return resolve(solutionData); + + } + catch (error) { + return reject({ + status: error.status || httpStatusCode.internal_server_error.status, + message: error.message || httpStatusCode.internal_server_error.message, + errorObject: error + }) + } + }) + } + +} \ No newline at end of file diff --git a/module/solutions/helper.js b/module/solutions/helper.js index f3d4a597..87be9350 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -1599,6 +1599,7 @@ module.exports = class SolutionsHelper { userId, userToken ); + let checkForTargetedSolution = await this.checkForTargetedSolution( link, bodyData, @@ -1812,7 +1813,8 @@ module.exports = class SolutionsHelper { "type", "_id", "programId", - "name" + "name", + "projectTemplateId" ]); let queryData = await this.queryBasedOnRoleAndLocation(bodyData); @@ -1828,26 +1830,29 @@ module.exports = class SolutionsHelper { "link", "type", "programId", - "name" + "name", + "projectTemplateId" ]); if ( !Array.isArray(solutionData) || solutionData.length < 1 ) { - + response.solutionId = solutionDetails[0]._id; response.type = solutionDetails[0].type; response.name = solutionDetails[0].name; response.programId = solutionDetails[0].programId; + return resolve({ success: true, message: constants.apiResponses.SOLUTION_NOT_FOUND_OR_NOT_A_TARGETED, - result: response, + result: response }); } response.isATargetedSolution = true; Object.assign(response, solutionData[0]); response.solutionId = solutionData[0]._id; + response.projectTemplateId = solutionDetails[0].projectTemplateId ? solutionDetails[0].projectTemplateId : ""; delete response._id; return resolve({ @@ -1938,6 +1943,132 @@ module.exports = class SolutionsHelper { } }); } + + /** + * Verify solution link V2 + * @method + * @name verifyLinkV2 + * @param {String} solutionId - solution Id. + * @param {String} userId - user Id. + * @param {Object} bodyData - Req Body. + * @returns {Object} - Details of the solution. + */ + + static verifyLinkV2(link = "", bodyData = {}, userId = "", userToken = "") { + return new Promise(async (resolve, reject) => { + try { + + let verifySolution = await this.verifySolutionDetails( + link, + userId, + userToken + ); + + let checkForTargetedSolution = await this.checkForTargetedSolution( + link, + bodyData, + userId, + userToken + ); + + if ( + checkForTargetedSolution && + Object.keys(checkForTargetedSolution.result).length > 0 + ) { + + let solutionData = checkForTargetedSolution.result; + //non targeted solution + if ( !checkForTargetedSolution.result.isATargetedSolution ) { + if ( solutionData.type === constants.common.IMPROVEMENT_PROJECT ) { + + let filterQuery = { + createdBy: userId, + referenceFrom: constants.common.LINK, + link: link, + }; + + let checkForProjectExist = + await improvementProjectService.projectDocuments( + userToken, + filterQuery, + ["_id"] + ); + if ( + checkForProjectExist.success && + checkForProjectExist.data && + checkForProjectExist.data.length > 0 && + checkForProjectExist.data[0]._id != "" + ) { + checkForTargetedSolution.result['projectId'] = + checkForProjectExist.data[0]._id; + } + } + + } else { + // targeted solution + let detailFromLink; + if ( solutionData.type == constants.common.IMPROVEMENT_PROJECT ) { + //return the project id if project is already exist for that user + let findQuery = { + userId: "de79e613-0d2f-4923-8431-db3534e69d3c", + projectTemplateId : solutionData.projectTemplateId, + referenceFrom: { + $ne : constants.common.LINK + }, + isDeleted : false + }; + + let checkTargetedProjectExist = + await improvementProjectService.projectDocuments( + userToken, + findQuery, + ["_id"] + ); + + if ( + checkTargetedProjectExist.success && + checkTargetedProjectExist.data && + checkTargetedProjectExist.data.length > 0 && + checkTargetedProjectExist.data[0]._id != "" + ) { + checkForTargetedSolution.result['projectId'] = + checkTargetedProjectExist.data[0]._id; + } + + } else if ( solutionData.type == constants.common.OBSERVATION ) { + + detailFromLink = await surveyService.getObservationDetail( + solutionData.solutionId, + userToken + ); + + if ( + solutionData.type == constants.common.OBSERVATION && detailFromLink.result && + detailFromLink.result._id != "" + ) { + checkForTargetedSolution.result["observationId"] = detailFromLink + .result._id + ? detailFromLink.result._id + : ""; + } + } + } + } + + return resolve(checkForTargetedSolution); + } catch (error) { + + return resolve({ + success: false, + status: error.status + ? error.status + : httpStatusCode['internal_server_error'].status, + message: error.message + }); + } + }); + } + }; /** From 10327d333f1e9785ac15800aec16593a3b725c67 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Thu, 27 Jan 2022 18:21:47 +0530 Subject: [PATCH 088/331] name fix --- controllers/v2/solutions.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/controllers/v2/solutions.js b/controllers/v2/solutions.js index ef15d7a5..9957be28 100644 --- a/controllers/v2/solutions.js +++ b/controllers/v2/solutions.js @@ -14,17 +14,17 @@ const solutionV1 = require(ROOT_PATH + "/controllers/v1/solutions"); const solutionHelper = require(MODULES_BASE_PATH + "/solutions/helper"); /** - * SolutrioV2 + * SolutionV2 * @class */ module.exports = class SolutionsV2 extends solutionV1 { /** - * @api {post} /kendra/api/v1/solutions/verifyLink/:link + * @api {post} /kendra/api/v2/solutions/verifyLink/:link * @apiVersion 1.0.0 * @apiName verify Link * @apiGroup Solutions - * @apiSampleRequest /kendra/api/v1/solutions/verifyLink/6f8d395f674dcb3146ade10f972da9d0 + * @apiSampleRequest /kendra/api/v2/solutions/verifyLink/6f8d395f674dcb3146ade10f972da9d0 * @apiHeader {String} X-authenticated-user-token Authenticity token * @apiUse successBody * @apiUse errorBody From d918ebc2b67f921d31e60598d4b29da0e0e6803b Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Thu, 27 Jan 2022 19:45:24 +0530 Subject: [PATCH 089/331] Pr changes --- controllers/v2/solutions.js | 5 +- module/solutions/helper.js | 192 ++++++++++-------------------------- 2 files changed, 53 insertions(+), 144 deletions(-) diff --git a/controllers/v2/solutions.js b/controllers/v2/solutions.js index 9957be28..d15fe186 100644 --- a/controllers/v2/solutions.js +++ b/controllers/v2/solutions.js @@ -61,11 +61,12 @@ module.exports = class SolutionsV2 extends solutionV1 { return new Promise(async (resolve, reject) => { try { - let solutionData = await solutionHelper.verifyLinkV2( + let solutionData = await solutionHelper.verifyLink( req.params._id, req.body, req.userDetails.userId, - req.userDetails.userToken + req.userDetails.userToken, + true ); return resolve(solutionData); diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 87be9350..0efaea84 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -1591,9 +1591,10 @@ module.exports = class SolutionsHelper { * @returns {Object} - Details of the solution. */ - static verifyLink(link = "", bodyData = {}, userId = "", userToken = "") { + static verifyLink(link = "", bodyData = {}, userId = "", userToken = "", doNotCreateProject = false ) { return new Promise(async (resolve, reject) => { try { + let verifySolution = await this.verifySolutionDetails( link, userId, @@ -1645,25 +1646,57 @@ module.exports = class SolutionsHelper { let detailFromLink; if ( solutionData.type == constants.common.IMPROVEMENT_PROJECT ) { - detailFromLink = await improvementProjectService.getProjectDetail( - solutionData.solutionId, - userToken, - bodyData - ); + if ( doNotCreateProject ) { + //return the project id if project is already exist for that user + let findQuery = { + userId: userId, + projectTemplateId : solutionData.projectTemplateId, + referenceFrom: { + $ne : constants.common.LINK + }, + isDeleted : false + }; - if ( !detailFromLink || !detailFromLink.data ) { - return resolve(detailFromLink); - } + let checkTargetedProjectExist = + await improvementProjectService.projectDocuments( + userToken, + findQuery, + ["_id"] + ); - if ( - solutionData.type == constants.common.IMPROVEMENT_PROJECT && - detailFromLink.data._id != "" - ) { - checkForTargetedSolution.result['projectId'] = detailFromLink - .data._id - ? detailFromLink.data._id - : ""; + if ( + checkTargetedProjectExist.success && + checkTargetedProjectExist.data && + checkTargetedProjectExist.data.length > 0 && + checkTargetedProjectExist.data[0]._id != "" + ) { + checkForTargetedSolution.result['projectId'] = + checkTargetedProjectExist.data[0]._id; + } + + } else { + + detailFromLink = await improvementProjectService.getProjectDetail( + solutionData.solutionId, + userToken, + bodyData + ); + + if ( !detailFromLink || !detailFromLink.data ) { + return resolve(detailFromLink); + } + + if ( + solutionData.type == constants.common.IMPROVEMENT_PROJECT && + detailFromLink.data._id != "" + ) { + checkForTargetedSolution.result['projectId'] = detailFromLink + .data._id + ? detailFromLink.data._id + : ""; + } } + } else if ( solutionData.type == constants.common.OBSERVATION ) { detailFromLink = await surveyService.getObservationDetail( @@ -1944,131 +1977,6 @@ module.exports = class SolutionsHelper { }); } - /** - * Verify solution link V2 - * @method - * @name verifyLinkV2 - * @param {String} solutionId - solution Id. - * @param {String} userId - user Id. - * @param {Object} bodyData - Req Body. - * @returns {Object} - Details of the solution. - */ - - static verifyLinkV2(link = "", bodyData = {}, userId = "", userToken = "") { - return new Promise(async (resolve, reject) => { - try { - - let verifySolution = await this.verifySolutionDetails( - link, - userId, - userToken - ); - - let checkForTargetedSolution = await this.checkForTargetedSolution( - link, - bodyData, - userId, - userToken - ); - - if ( - checkForTargetedSolution && - Object.keys(checkForTargetedSolution.result).length > 0 - ) { - - let solutionData = checkForTargetedSolution.result; - //non targeted solution - if ( !checkForTargetedSolution.result.isATargetedSolution ) { - if ( solutionData.type === constants.common.IMPROVEMENT_PROJECT ) { - - let filterQuery = { - createdBy: userId, - referenceFrom: constants.common.LINK, - link: link, - }; - - let checkForProjectExist = - await improvementProjectService.projectDocuments( - userToken, - filterQuery, - ["_id"] - ); - if ( - checkForProjectExist.success && - checkForProjectExist.data && - checkForProjectExist.data.length > 0 && - checkForProjectExist.data[0]._id != "" - ) { - checkForTargetedSolution.result['projectId'] = - checkForProjectExist.data[0]._id; - } - } - - } else { - // targeted solution - let detailFromLink; - if ( solutionData.type == constants.common.IMPROVEMENT_PROJECT ) { - //return the project id if project is already exist for that user - let findQuery = { - userId: "de79e613-0d2f-4923-8431-db3534e69d3c", - projectTemplateId : solutionData.projectTemplateId, - referenceFrom: { - $ne : constants.common.LINK - }, - isDeleted : false - }; - - let checkTargetedProjectExist = - await improvementProjectService.projectDocuments( - userToken, - findQuery, - ["_id"] - ); - - if ( - checkTargetedProjectExist.success && - checkTargetedProjectExist.data && - checkTargetedProjectExist.data.length > 0 && - checkTargetedProjectExist.data[0]._id != "" - ) { - checkForTargetedSolution.result['projectId'] = - checkTargetedProjectExist.data[0]._id; - } - - } else if ( solutionData.type == constants.common.OBSERVATION ) { - - detailFromLink = await surveyService.getObservationDetail( - solutionData.solutionId, - userToken - ); - - if ( - solutionData.type == constants.common.OBSERVATION && detailFromLink.result && - detailFromLink.result._id != "" - ) { - checkForTargetedSolution.result["observationId"] = detailFromLink - .result._id - ? detailFromLink.result._id - : ""; - } - } - } - } - - return resolve(checkForTargetedSolution); - } catch (error) { - - return resolve({ - success: false, - status: error.status - ? error.status - : httpStatusCode['internal_server_error'].status, - message: error.message - }); - } - }); - } - }; /** From e24e197b8bca84a6d60ad7bfe034fbd52207a37f Mon Sep 17 00:00:00 2001 From: Akash Shah Date: Thu, 27 Jan 2022 22:44:52 +0530 Subject: [PATCH 090/331] Code refactoring. --- controllers/v2/solutions.js | 2 +- module/solutions/helper.js | 155 ++++++++++++++---------------------- 2 files changed, 60 insertions(+), 97 deletions(-) diff --git a/controllers/v2/solutions.js b/controllers/v2/solutions.js index d15fe186..11889946 100644 --- a/controllers/v2/solutions.js +++ b/controllers/v2/solutions.js @@ -66,7 +66,7 @@ module.exports = class SolutionsV2 extends solutionV1 { req.body, req.userDetails.userId, req.userDetails.userToken, - true + false ); return resolve(solutionData); diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 0efaea84..e85d5d26 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -1587,11 +1587,13 @@ module.exports = class SolutionsHelper { * @name verifyLink * @param {String} solutionId - solution Id. * @param {String} userId - user Id. + * @param {String} userToken - user token. + * @param {Boolean} createProject - create project. * @param {Object} bodyData - Req Body. * @returns {Object} - Details of the solution. */ - static verifyLink(link = "", bodyData = {}, userId = "", userToken = "", doNotCreateProject = false ) { + static verifyLink(link = "", bodyData = {}, userId = "", userToken = "", createProject = true ) { return new Promise(async (resolve, reject) => { try { @@ -1608,116 +1610,77 @@ module.exports = class SolutionsHelper { userToken ); - if ( - checkForTargetedSolution && - Object.keys(checkForTargetedSolution.result).length > 0 - ) { + if(!checkForTargetedSolution || Object.keys(checkForTargetedSolution.result).length <= 0) { + return resolve(checkForTargetedSolution); + } - let solutionData = checkForTargetedSolution.result; - //non targeted solution - if ( !checkForTargetedSolution.result.isATargetedSolution ) { - if ( solutionData.type === constants.common.IMPROVEMENT_PROJECT ) { + let solutionData = checkForTargetedSolution.result; - let filterQuery = { - createdBy: userId, - referenceFrom: constants.common.LINK, - link: link, - }; + if(solutionData.type == constants.common.OBSERVATION) { + // Targeted solution + if(checkForTargetedSolution.result.isATargetedSolution) { - let checkForProjectExist = - await improvementProjectService.projectDocuments( - userToken, - filterQuery, - ["_id"] - ); - if ( - checkForProjectExist.success && - checkForProjectExist.data && - checkForProjectExist.data.length > 0 && - checkForProjectExist.data[0]._id != "" - ) { - checkForTargetedSolution.result['projectId'] = - checkForProjectExist.data[0]._id; - } - } + let observationDetailFromLink = await surveyService.getObservationDetail( + solutionData.solutionId, + userToken + ); - } else { - // targeted solution - let detailFromLink; - if ( solutionData.type == constants.common.IMPROVEMENT_PROJECT ) { - - if ( doNotCreateProject ) { - //return the project id if project is already exist for that user - let findQuery = { - userId: userId, - projectTemplateId : solutionData.projectTemplateId, - referenceFrom: { - $ne : constants.common.LINK - }, - isDeleted : false - }; - - let checkTargetedProjectExist = - await improvementProjectService.projectDocuments( - userToken, - findQuery, - ["_id"] - ); - - if ( - checkTargetedProjectExist.success && - checkTargetedProjectExist.data && - checkTargetedProjectExist.data.length > 0 && - checkTargetedProjectExist.data[0]._id != "" - ) { - checkForTargetedSolution.result['projectId'] = - checkTargetedProjectExist.data[0]._id; - } + checkForTargetedSolution.result["observationId"] = (observationDetailFromLink.result && observationDetailFromLink.result._id != "") + ? observationDetailFromLink.result._id + : ""; - } else { + } - detailFromLink = await improvementProjectService.getProjectDetail( - solutionData.solutionId, - userToken, - bodyData - ); + } else if (solutionData.type === constants.common.IMPROVEMENT_PROJECT) { + // Targeted solution + if(checkForTargetedSolution.result.isATargetedSolution && createProject) { - if ( !detailFromLink || !detailFromLink.data ) { - return resolve(detailFromLink); - } + let projectDetailFromLink = await improvementProjectService.getProjectDetail( + solutionData.solutionId, + userToken, + bodyData + ); - if ( - solutionData.type == constants.common.IMPROVEMENT_PROJECT && - detailFromLink.data._id != "" - ) { - checkForTargetedSolution.result['projectId'] = detailFromLink - .data._id - ? detailFromLink.data._id - : ""; - } - } - - } else if ( solutionData.type == constants.common.OBSERVATION ) { + if ( !projectDetailFromLink || !projectDetailFromLink.data ) { + return resolve(detailFromLink); + } - detailFromLink = await surveyService.getObservationDetail( - solutionData.solutionId, - userToken - ); + checkForTargetedSolution.result['projectId'] = projectDetailFromLink.data._id + ? projectDetailFromLink.data._id + : ""; - if ( - solutionData.type == constants.common.OBSERVATION && detailFromLink.result && - detailFromLink.result._id != "" - ) { - checkForTargetedSolution.result["observationId"] = detailFromLink - .result._id - ? detailFromLink.result._id - : ""; - } + } else { + + let checkIfUserProjectExistsQuery = { + createdBy: userId, + referenceFrom: constants.common.LINK, + link: link, + }; + + let checkForProjectExist = + await improvementProjectService.projectDocuments( + userToken, + checkIfUserProjectExistsQuery, + ["_id"] + ); + + if ( + checkForProjectExist.success && + checkForProjectExist.data && + checkForProjectExist.data.length > 0 && + checkForProjectExist.data[0]._id != "" + ) { + checkForTargetedSolution.result['projectId'] = + checkForProjectExist.data[0]._id; } + } + } + return resolve(checkForTargetedSolution); + } catch (error) { return resolve({ success: false, From c6ff9472126c562caf84d572af5b3a25a1a38024 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Fri, 28 Jan 2022 16:29:40 +0530 Subject: [PATCH 091/331] added targeted solution project check --- module/solutions/helper.js | 43 +++++++++++++++++++++++++++++++------- 1 file changed, 35 insertions(+), 8 deletions(-) diff --git a/module/solutions/helper.js b/module/solutions/helper.js index e85d5d26..323044c8 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -1610,13 +1610,13 @@ module.exports = class SolutionsHelper { userToken ); - if(!checkForTargetedSolution || Object.keys(checkForTargetedSolution.result).length <= 0) { + if( !checkForTargetedSolution || Object.keys(checkForTargetedSolution.result).length <= 0 ) { return resolve(checkForTargetedSolution); } let solutionData = checkForTargetedSolution.result; - if(solutionData.type == constants.common.OBSERVATION) { + if( solutionData.type == constants.common.OBSERVATION ) { // Targeted solution if(checkForTargetedSolution.result.isATargetedSolution) { @@ -1631,10 +1631,10 @@ module.exports = class SolutionsHelper { } - } else if (solutionData.type === constants.common.IMPROVEMENT_PROJECT) { + } else if ( solutionData.type === constants.common.IMPROVEMENT_PROJECT ) { // Targeted solution - if(checkForTargetedSolution.result.isATargetedSolution && createProject) { - + if( checkForTargetedSolution.result.isATargetedSolution && createProject ) { + //targeted user with project creation let projectDetailFromLink = await improvementProjectService.getProjectDetail( solutionData.solutionId, userToken, @@ -1642,15 +1642,43 @@ module.exports = class SolutionsHelper { ); if ( !projectDetailFromLink || !projectDetailFromLink.data ) { - return resolve(detailFromLink); + return resolve(projectDetailFromLink); } checkForTargetedSolution.result['projectId'] = projectDetailFromLink.data._id ? projectDetailFromLink.data._id : ""; - } else { + } if( checkForTargetedSolution.result.isATargetedSolution && !createProject ) { + //targeted user with no project creation + let findQuery = { + userId: "de79e613-0d2f-4923-8431-db3534e69d3c", + projectTemplateId : solutionData.projectTemplateId, + referenceFrom: { + $ne : constants.common.LINK + }, + isDeleted : false + }; + + let checkTargetedProjectExist = + await improvementProjectService.projectDocuments( + userToken, + findQuery, + ["_id"] + ); + + if ( + checkTargetedProjectExist.success && + checkTargetedProjectExist.data && + checkTargetedProjectExist.data.length > 0 && + checkTargetedProjectExist.data[0]._id != "" + ) { + checkForTargetedSolution.result['projectId'] = + checkTargetedProjectExist.data[0]._id; + } + } else { + //non targeted project exist let checkIfUserProjectExistsQuery = { createdBy: userId, referenceFrom: constants.common.LINK, @@ -1678,7 +1706,6 @@ module.exports = class SolutionsHelper { } - return resolve(checkForTargetedSolution); } catch (error) { From 2558203a9e5eb6b7da30be5cd28f3ef5531cc737 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Fri, 28 Jan 2022 16:36:01 +0530 Subject: [PATCH 092/331] userId change --- module/solutions/helper.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 323044c8..261fde95 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -1652,7 +1652,7 @@ module.exports = class SolutionsHelper { } if( checkForTargetedSolution.result.isATargetedSolution && !createProject ) { //targeted user with no project creation let findQuery = { - userId: "de79e613-0d2f-4923-8431-db3534e69d3c", + userId: userId, projectTemplateId : solutionData.projectTemplateId, referenceFrom: { $ne : constants.common.LINK From 28dcb1ce4ce233a846d6a8f5837d130ca1c18f69 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Fri, 28 Jan 2022 16:38:46 +0530 Subject: [PATCH 093/331] else if added --- module/solutions/helper.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 261fde95..f9571fd5 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -1649,7 +1649,7 @@ module.exports = class SolutionsHelper { ? projectDetailFromLink.data._id : ""; - } if( checkForTargetedSolution.result.isATargetedSolution && !createProject ) { + } else if( checkForTargetedSolution.result.isATargetedSolution && !createProject ) { //targeted user with no project creation let findQuery = { userId: userId, From 8de0ede8c0bd13190677282c96e18ca421c67e30 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Sun, 30 Jan 2022 19:24:05 +0530 Subject: [PATCH 094/331] remove v2 --- controllers/v1/solutions.js | 3 +- controllers/v2/solutions.js | 85 ------------------------------------- 2 files changed, 2 insertions(+), 86 deletions(-) delete mode 100644 controllers/v2/solutions.js diff --git a/controllers/v1/solutions.js b/controllers/v1/solutions.js index fbf3ac1d..bc72f017 100644 --- a/controllers/v1/solutions.js +++ b/controllers/v1/solutions.js @@ -844,7 +844,8 @@ module.exports = class Solutions extends Abstract { req.params._id, req.body, req.userDetails.userId, - req.userDetails.userToken + req.userDetails.userToken, + req.query.createProject ? req.query.createProject : true ); return resolve(solutionData); diff --git a/controllers/v2/solutions.js b/controllers/v2/solutions.js deleted file mode 100644 index 11889946..00000000 --- a/controllers/v2/solutions.js +++ /dev/null @@ -1,85 +0,0 @@ -/** - * name : solutions.js - * author : Priyanka Pradeep - * created-date : 27-jan-2022 - * Description : All solution v2 related information. - */ - - -/** - * dependencies - */ - -const solutionV1 = require(ROOT_PATH + "/controllers/v1/solutions"); -const solutionHelper = require(MODULES_BASE_PATH + "/solutions/helper"); - -/** - * SolutionV2 - * @class -*/ - -module.exports = class SolutionsV2 extends solutionV1 { - /** - * @api {post} /kendra/api/v2/solutions/verifyLink/:link - * @apiVersion 1.0.0 - * @apiName verify Link - * @apiGroup Solutions - * @apiSampleRequest /kendra/api/v2/solutions/verifyLink/6f8d395f674dcb3146ade10f972da9d0 - * @apiHeader {String} X-authenticated-user-token Authenticity token - * @apiUse successBody - * @apiUse errorBody - * @apiParamExample {json} Request: - * { - * "role" : "HM,DEO", - "state" : "236f5cff-c9af-4366-b0b6-253a1789766a", - "district" : "1dcbc362-ec4c-4559-9081-e0c2864c2931", - "school" : "c5726207-4f9f-4f45-91f1-3e9e8e84d824" - } - * @apiParamExample {json} Response: - * { - "message": "Solution Link verified successfully", - "status": 200, - "result": { - isATargetedSolution : true/false, - type: improvementProject, - solutionId : “5f6853f293734140ccce90cf”, - projectId : “” - } - } - */ - - /** - * verify Link - * @method - * @name verifyLink - * @param {Object} req - requested data. - * @param {String} req.params._id - solution Id - * @returns {Array} - */ - - async verifyLink(req) { - return new Promise(async (resolve, reject) => { - try { - - let solutionData = await solutionHelper.verifyLink( - req.params._id, - req.body, - req.userDetails.userId, - req.userDetails.userToken, - false - ); - - return resolve(solutionData); - - } - catch (error) { - return reject({ - status: error.status || httpStatusCode.internal_server_error.status, - message: error.message || httpStatusCode.internal_server_error.message, - errorObject: error - }) - } - }) - } - -} \ No newline at end of file From f5eb86da3408a3d2e32cf8d61f8f4f20579b2e33 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 4 Feb 2022 12:11:31 +0530 Subject: [PATCH 095/331] convert condition string to boolean --- controllers/v1/solutions.js | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/controllers/v1/solutions.js b/controllers/v1/solutions.js index bc72f017..29cb656b 100644 --- a/controllers/v1/solutions.js +++ b/controllers/v1/solutions.js @@ -4,6 +4,10 @@ * created-date : 03-Sep-2020 * Description : Solution related information. */ + +const { query } = require("express"); +const { utils } = require("mocha"); + // Dependencies const solutionsHelper = require(MODULES_BASE_PATH + "/solutions/helper"); module.exports = class Solutions extends Abstract { @@ -839,13 +843,13 @@ module.exports = class Solutions extends Abstract { async verifyLink(req) { return new Promise(async (resolve, reject) => { try { - + let solutionData = await solutionsHelper.verifyLink( req.params._id, req.body, req.userDetails.userId, req.userDetails.userToken, - req.query.createProject ? req.query.createProject : true + req.query.hasOwnProperty("createProject") ? gen.utils.convertStringToBoolean(req.query.createProject) : true ); return resolve(solutionData); From 4137f5c6d0b7e1dafbe29936eada61c62f98e560 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 4 Feb 2022 12:19:28 +0530 Subject: [PATCH 096/331] require removed --- controllers/v1/solutions.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/controllers/v1/solutions.js b/controllers/v1/solutions.js index 29cb656b..a93357f2 100644 --- a/controllers/v1/solutions.js +++ b/controllers/v1/solutions.js @@ -5,8 +5,7 @@ * Description : Solution related information. */ -const { query } = require("express"); -const { utils } = require("mocha"); + // Dependencies const solutionsHelper = require(MODULES_BASE_PATH + "/solutions/helper"); From 94b52078f13437c9b5620b798c8a4acf46ab6309 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Mon, 21 Feb 2022 13:49:08 +0530 Subject: [PATCH 097/331] cache file --- generics/helpers/cache.js | 62 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 generics/helpers/cache.js diff --git a/generics/helpers/cache.js b/generics/helpers/cache.js new file mode 100644 index 00000000..603d1a29 --- /dev/null +++ b/generics/helpers/cache.js @@ -0,0 +1,62 @@ +/** + * name : cache.js + * author : Priyanka Pradeep + * created-date : 21-Feb-2020 + * Description : Cache set , get and remove functionality. + */ + + const nodeCache = require( "node-cache" ); + const cache = new nodeCache(); + + /** + * Get cache data. + * @method + * @name get - Get specific cache data + * @params key - name of the cache key. + * @returns {Array} - return specific cache data. +*/ + +function getValue(key){ + let data = []; + + if (cache.has(key)) { + data = cache.get(key); + } + + return data; +} + + + /** + * Set new cache data + * @method + * @name set + * @params key - name of the cache key. + * @params value - cache data to set. + * @returns {Array} - cache updated data. +*/ + +function setValue(key, value, timeout){ + let data = cache.set( key, value, timeout ); + return data; +} + +/** + * delete cache data + * @method + * @name remove + * @params key - cache key need to be removed. + * @returns +*/ + +function removeKey(key){ + + let data = cache.del(key); + return; +} + +module.exports = { + getValue : getValue, + setValue : setValue, + removeKey : removeKey +} \ No newline at end of file From 9c05f73c6b6cf2f731465e36ee5950ca3fce2701 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Tue, 22 Feb 2022 10:20:32 +0530 Subject: [PATCH 098/331] package.json --- package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/package.json b/package.json index 4e50fb37..08459a30 100644 --- a/package.json +++ b/package.json @@ -61,6 +61,7 @@ "mongoose-delete": "^0.5.3", "mongoose-timestamp": "^0.6.0", "mongoose-ttl": "0.0.3", + "node-cache": "^5.1.2", "node-schedule": "^1.3.2", "nodemailer": "^6.4.1", "nyc": "^15.1.0", From cf6f53ed1fd605538e66deac3afa3862aac19e19 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 24 Feb 2022 22:50:02 +0530 Subject: [PATCH 099/331] eG chenges --- generics/constants/api-responses.js | 3 +- generics/constants/endpoints.js | 3 +- generics/services/sunbird.js | 68 ++++++++++++++++++++ module/programs/helper.js | 99 ++++++++++++++--------------- module/solutions/helper.js | 65 +++++++------------ module/user-roles/helper.js | 2 +- 6 files changed, 144 insertions(+), 96 deletions(-) create mode 100644 generics/services/sunbird.js diff --git a/generics/constants/api-responses.js b/generics/constants/api-responses.js index 45f4c5f8..04ef7606 100644 --- a/generics/constants/api-responses.js +++ b/generics/constants/api-responses.js @@ -179,6 +179,7 @@ module.exports = { "SOLUTION_NOT_FOUND_OR_NOT_A_TARGETED": "Solution is not targeted to the role", "PROJECT_TEMPLATE_ID_NOT_FOUND": "Project templates not exists in solution", "SOLUTION_TARGETED_ENTITY" : "Targeted Entity Types Fetched", - "ENTITY_ID_OR_LOCATION_ID_NOT_FOUND" : "Entity id or location id not found" + "ENTITY_ID_OR_LOCATION_ID_NOT_FOUND" : "Entity id or location id not found", + "NO_LOCATION_ID_FOUND_IN_DATA" : "Location Id not found in data" }; diff --git a/generics/constants/endpoints.js b/generics/constants/endpoints.js index bc52a941..53f71a13 100644 --- a/generics/constants/endpoints.js +++ b/generics/constants/endpoints.js @@ -30,5 +30,6 @@ module.exports = { GET_TEMPLATE_DETAILS : "/v1/project/templates/details", LIST_PROJECT : "/v1/userProjects/list", GET_QUESTIONS : "/v1/solutions/questions", - GET_OBSERVATION : "/v1/observations/details" + GET_OBSERVATION : "/v1/observations/details", + GET_LOCATION_DATA : "/api/data/v1/location/search" } \ No newline at end of file diff --git a/generics/services/sunbird.js b/generics/services/sunbird.js new file mode 100644 index 00000000..ee521c49 --- /dev/null +++ b/generics/services/sunbird.js @@ -0,0 +1,68 @@ +/** + * name : sunbird.js + * author : Vishnudas + * Date : 22-Feb-2022 + * Description : All Sunbird learner related api call. + */ + +//dependencies + + +const request = require('request'); +const sunbirdBaseUrl = process.env.SUNBIRD_SERVICE_URL; + +/** + * + * @function + * @name learnerLocationSearch + * @param {String} bearerToken - autherization token. + * @param {object} bodyData - bodydata . + * @returns {Promise} returns a promise. +*/ + +const learnerLocationSearch = function ( bodyData ) { + return new Promise(async (resolve, reject) => { + try { + + const url = + sunbirdBaseUrl + constants.endpoints.GET_LOCATION_DATA; + const options = { + headers : { + "Authorization" : process.env.SUNBIRD_SERVICE_AUTHERIZATION, + "content-type": "application/json" + }, + json : bodyData + }; + + request.post(url,options,kendraCallback); + + function kendraCallback(err, data) { + + let result = { + success : true + }; + + if (err) { + result.success = false; + } else { + + let response = data.body; + + if( response.responseCode === constants.common.OK) { + result["data"] = response.result; + } else { + result.success = false; + } + } + return resolve(result); + } + + } catch (error) { + return reject(error); + } + }) +} + +module.exports = { + learnerLocationSearch : learnerLocationSearch +}; \ No newline at end of file diff --git a/module/programs/helper.js b/module/programs/helper.js index 962e12f5..cbc5d306 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -10,6 +10,7 @@ const entityTypesHelper = require(MODULES_BASE_PATH + "/entityTypes/helper"); const entitiesHelper = require(MODULES_BASE_PATH + "/entities/helper"); const userRolesHelper = require(MODULES_BASE_PATH + "/user-roles/helper"); +const sunbirdService = require(ROOT_PATH + '/generics/services/sunbird'); /** * ProgramsHelper @@ -50,7 +51,7 @@ module.exports = class ProgramsHelper { projection[field] = 0; }) } - + let programData = await database.models.programs.find( queryObject, projection @@ -483,7 +484,7 @@ module.exports = class ProgramsHelper { let queryData = await this.queryBasedOnRoleAndLocation( bodyData ); - + if( !queryData.success ) { return resolve(queryData); } @@ -553,35 +554,21 @@ module.exports = class ProgramsHelper { static queryBasedOnRoleAndLocation( data ) { return new Promise(async (resolve, reject) => { try { - + let locationIds = Object.values(_.omit(data,["role","filter"])).map(locationId => { return locationId; }); - - let filterData = { - $or : [{ - "registryDetails.code" : { $in : locationIds } - },{ - "registryDetails.locationId" : { $in : locationIds } - }] - }; - - let entities = await entitiesHelper.entityDocuments(filterData,["_id"]); - - if( !entities.length > 0 ) { + if( !locationIds.length > 0 ) { throw { - message : constants.apiResponses.NO_ENTITY_FOUND_IN_LOCATION + message : constants.apiResponses.NO_LOCATION_ID_FOUND_IN_DATA } } - let entityIds = entities.map(entity => { - return entity._id; - }); - + let filterQuery = { "scope.roles.code" : { $in : [constants.common.ALL_ROLES,...data.role.split(",")] }, - "scope.entities" : { $in : entityIds }, + "scope.entities" : { $in : locationIds }, "isDeleted" : false, status : constants.common.ACTIVE } @@ -721,37 +708,50 @@ module.exports = class ProgramsHelper { _id : programId, scope : { $exists : true }, isAPrivateProgram : false - },["_id","scope.entityTypeId"]); - + },["_id"]); + if( !programData.length > 0 ) { throw { message : constants.apiResponses.PROGRAM_NOT_FOUND }; } + - let entitiesData = - await entitiesHelper.entityDocuments({ - _id : { $in : entities }, - entityTypeId : programData[0].scope.entityTypeId - },["_id"]); - - if( !entitiesData.length > 0 ) { + let locationIds = []; + let bodyData={}; + bodyData["request"] = {}; + bodyData["request"]["filters"] = {}; + bodyData["request"]["filters"]["id"] = ""; + + entities.forEach(entity=>{ + if (gen.utils.checkValidUUID(entity)) { + locationIds.push(entity); + } + }); + + bodyData["request"]["filters"]["id"] = locationIds; + let entitiesData = await sunbirdService.learnerLocationSearch( bodyData ); + + + if( !entitiesData.data.count > 0 ) { throw { message : constants.apiResponses.ENTITIES_NOT_FOUND }; } - let entityIds = []; - entitiesData.forEach(entity => { - entityIds.push(entity._id); + let entityIds = []; + entitiesData.data.response.forEach(entityResult => { + entityIds.push(entityResult.id); }); + let updateProgram = await database.models.programs.findOneAndUpdate({ _id : programId },{ $addToSet : { "scope.entities" : { $each : entityIds } } },{ new : true }).lean(); + if( !updateProgram || !updateProgram._id ) { throw { @@ -854,50 +854,47 @@ module.exports = class ProgramsHelper { static removeEntitiesInScope( programId,entities ) { return new Promise(async (resolve, reject) => { try { - let programData = await this.programDocuments({ _id : programId, scope : { $exists : true }, isAPrivateProgram : false - },["_id","scope.entityTypeId"]); - + },["_id","scope.entities"]); + if( !programData.length > 0 ) { throw { message : constants.apiResponses.PROGRAM_NOT_FOUND }; } - - let entitiesData = - await entitiesHelper.entityDocuments({ - _id : { $in : entities }, - entityTypeId : programData[0].scope.entityTypeId - },["_id"]); - + let entitiesData = []; + entitiesData = programData[0].scope.entities; + if( !entitiesData.length > 0 ) { throw { message : constants.apiResponses.ENTITIES_NOT_FOUND }; } - + let entityIds = []; - - entitiesData.forEach(entity => { - entityIds.push(entity._id); + entities.forEach(entity => { + if (gen.utils.checkValidUUID(entity)) { + entityIds.push(entity); + } + }); - + let updateProgram = await database.models.programs.findOneAndUpdate({ _id : programId },{ - $pull : { "scope.entities" : { $in : entityIds } } + $pull : { "scope.entities" : { $in : entityIds} } },{ new : true }).lean(); - + if( !updateProgram || !updateProgram._id ) { throw { message : constants.apiResponses.PROGRAM_NOT_UPDATED } } - + return resolve({ message : constants.apiResponses.ENTITIES_REMOVED_IN_PROGRAM, success : true diff --git a/module/solutions/helper.js b/module/solutions/helper.js index f9571fd5..00452e42 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -590,7 +590,7 @@ module.exports = class SolutionsHelper { $arrayElemAt: ["$totalCount.count", 0] } }; - + let solutionDocuments = await database.models.solutions.aggregate([ { $match : matchQuery }, @@ -650,7 +650,7 @@ module.exports = class SolutionsHelper { subType, programId ); - + if( !queryData.success ) { return resolve(queryData); } @@ -751,30 +751,15 @@ module.exports = class SolutionsHelper { registryIds.push(data[requestedDataKey]); entityTypes.push(requestedDataKey); }) - - let filterData = { - $or : [{ - "registryDetails.code" : { $in : registryIds } - },{ - "registryDetails.locationId" : { $in : registryIds } - }] - }; - - let entities = await entitiesHelper.entityDocuments(filterData,["_id"]); - - if( !entities.length > 0 ) { + if( !registryIds.length > 0 ) { throw { - message : constants.apiResponses.NO_ENTITY_FOUND_IN_LOCATION + message : constants.apiResponses.NO_LOCATION_ID_FOUND_IN_DATA } } - - let entityIds = entities.map(entity => { - return entity._id; - }); - + let filterQuery = { "scope.roles.code" : { $in : [constants.common.ALL_ROLES,...data.role.split(",")] }, - "scope.entities" : { $in : entityIds }, + "scope.entities" : { $in : registryIds }, "scope.entityType" : { $in : entityTypes }, "isReusable" : false, "isDeleted" : false @@ -1180,7 +1165,7 @@ module.exports = class SolutionsHelper { isReusable: false, isDeleted: false, }, - ["_id", "scope.entityTypeId"] + ["_id", "scope.entities"] ); if (!solutionData.length > 0) { @@ -1189,27 +1174,23 @@ module.exports = class SolutionsHelper { message: constants.apiResponses.SOLUTION_NOT_FOUND, }); } - - let entitiesData = await entitiesHelper.entityDocuments( - { - _id: { $in: entities }, - entityTypeId: solutionData[0].scope.entityTypeId, - }, - ["_id"] - ); - - if (!entitiesData.length > 0) { + let entitiesData = []; + entitiesData = solutionData[0].scope.entities; + if( !entitiesData.length > 0 ) { throw { - message: constants.apiResponses.ENTITIES_NOT_FOUND, + message : constants.apiResponses.ENTITIES_NOT_FOUND }; } let entityIds = []; - - entitiesData.forEach((entity) => { - entityIds.push(entity._id); + entities.forEach(entity => { + if (gen.utils.checkValidUUID(entity)) { + entityIds.push(entity); + } + }); + let updateSolution = await database.models.solutions .findOneAndUpdate( { @@ -1596,30 +1577,29 @@ module.exports = class SolutionsHelper { static verifyLink(link = "", bodyData = {}, userId = "", userToken = "", createProject = true ) { return new Promise(async (resolve, reject) => { try { - + let verifySolution = await this.verifySolutionDetails( link, userId, userToken ); - + let checkForTargetedSolution = await this.checkForTargetedSolution( link, bodyData, userId, userToken ); - if( !checkForTargetedSolution || Object.keys(checkForTargetedSolution.result).length <= 0 ) { return resolve(checkForTargetedSolution); } - + let solutionData = checkForTargetedSolution.result; if( solutionData.type == constants.common.OBSERVATION ) { // Targeted solution if(checkForTargetedSolution.result.isATargetedSolution) { - + let observationDetailFromLink = await surveyService.getObservationDetail( solutionData.solutionId, userToken @@ -1635,6 +1615,7 @@ module.exports = class SolutionsHelper { // Targeted solution if( checkForTargetedSolution.result.isATargetedSolution && createProject ) { //targeted user with project creation + let projectDetailFromLink = await improvementProjectService.getProjectDetail( solutionData.solutionId, userToken, @@ -1912,7 +1893,7 @@ module.exports = class SolutionsHelper { "type", "projectTemplateId", ]); - + if ( !Array.isArray(solutionData) || solutionData.length < 1 ) { return resolve({ message: constants.apiResponses.SOLUTION_NOT_FOUND, diff --git a/module/user-roles/helper.js b/module/user-roles/helper.js index 45f893af..ef466555 100644 --- a/module/user-roles/helper.js +++ b/module/user-roles/helper.js @@ -50,7 +50,7 @@ module.exports = class UserRolesHelper { queryObject, projection ).lean(); - + return resolve(userRolesData); } catch (error) { From f96dc2b9f401362bc52c95b38d3b1f20b2e49547 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 25 Feb 2022 15:08:16 +0530 Subject: [PATCH 100/331] 4.7 issue --- module/users/helper.js | 1 + 1 file changed, 1 insertion(+) diff --git a/module/users/helper.js b/module/users/helper.js index b2c26634..0deb2cb5 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -476,6 +476,7 @@ module.exports = class UsersHelper { let data = importedProject.solutionInformation; data['projectTemplateId'] = importedProject.projectTemplateId; data["type"] = constants.common.IMPROVEMENT_PROJECT; + data["projectId"] = importedProject._id; mergedData.push(data); }); } From efd3532b47ea55207e239eee3e6db59a6ee222e7 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 25 Feb 2022 15:34:52 +0530 Subject: [PATCH 101/331] stash conflict --- controllers/v1/users.js | 2 +- module/solutions/helper.js | 6 +++--- module/users/helper.js | 5 +++-- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/controllers/v1/users.js b/controllers/v1/users.js index c4e58b43..13dc2fcc 100644 --- a/controllers/v1/users.js +++ b/controllers/v1/users.js @@ -270,7 +270,7 @@ module.exports = class Users extends Abstract { solutions(req) { return new Promise(async (resolve, reject) => { try { - + let targetedSolutions = await usersHelper.solutions( req.params._id, req.body, diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 00452e42..9a2b989c 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -650,7 +650,7 @@ module.exports = class SolutionsHelper { subType, programId ); - + console.log("queryData:",queryData) if( !queryData.success ) { return resolve(queryData); } @@ -689,7 +689,7 @@ module.exports = class SolutionsHelper { if ( programId !== "" ) { matchQuery["programId"] = ObjectId(programId); } - + console.log("matchQuery:",matchQuery) let targetedSolutions = await this.list( type, subType, @@ -712,7 +712,7 @@ module.exports = class SolutionsHelper { "referenceFrom" ] ); - + console.log("targetedSolutions: ######",targetedSolutions.data) return resolve({ success: true, message: constants.apiResponses.TARGETED_SOLUTIONS_FETCHED, diff --git a/module/users/helper.js b/module/users/helper.js index b2c26634..2d6d6754 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -410,6 +410,7 @@ module.exports = class UsersHelper { static solutions(programId, requestedData, pageSize, pageNo, search, token) { return new Promise(async (resolve, reject) => { + token="b110b42b-d016-48b5-b10a-6529ac903c44" try { let programData = await programsHelper.programDocuments( { @@ -462,12 +463,12 @@ module.exports = class UsersHelper { } - + console.log("controll here yeah#############",token); let importedProjects = await improvementProjectService.importedProjects( token, programId ); - + console.log("importedProjects:",mergedData); if (importedProjects.success) { if (importedProjects.data && importedProjects.data.length > 0) { totalCount += importedProjects.data.length; From 927f353a7f012619c6a2a2106ecd1a210e1acc27 Mon Sep 17 00:00:00 2001 From: Akash Shah Date: Fri, 25 Feb 2022 19:33:52 +0530 Subject: [PATCH 102/331] Add projectId to the solution object if the user has already started a project for the improvement project solution. --- module/users/helper.js | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/module/users/helper.js b/module/users/helper.js index 0deb2cb5..143a9ec6 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -439,6 +439,8 @@ module.exports = class UsersHelper { let totalCount = 0; let mergedData = []; + let projectSolutionIdIndexMap = {} + if ( autoTargetedSolutions.data.data && autoTargetedSolutions.data.data.length > 0 @@ -454,30 +456,30 @@ module.exports = class UsersHelper { mergedData = autoTargetedSolutions.data.data; - mergedData = mergedData.map((targetedData) => { + mergedData = mergedData.map((targetedData, index) => { + if(targetedData.type == constants.common.IMPROVEMENT_PROJECT) { + projectSolutionIdIndexMap[targetedData._id.toString()] = index; + } delete targetedData.programId; delete targetedData.programName; return targetedData; }); - } + // Get projects already started by a user in a given program let importedProjects = await improvementProjectService.importedProjects( token, programId ); + // Add projectId to the solution object if the user has already started a project for the improvement project solution. if (importedProjects.success) { if (importedProjects.data && importedProjects.data.length > 0) { - totalCount += importedProjects.data.length; - importedProjects.data.forEach((importedProject) => { - let data = importedProject.solutionInformation; - data['projectTemplateId'] = importedProject.projectTemplateId; - data["type"] = constants.common.IMPROVEMENT_PROJECT; - data["projectId"] = importedProject._id; - mergedData.push(data); + if(projectSolutionIdIndexMap[importedProject.solutionInformation._id]) { + mergedData[projectSolutionIdIndexMap[importedProject.solutionInformation._id]].projectId = importedProject._id; + } }); } } From 5e61e09a9d8a35c6d41162f719d8eb86813aca92 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 25 Feb 2022 20:49:43 +0530 Subject: [PATCH 103/331] entity Generalisation ml-core --- controllers/v1/solutions.js | 4 +- controllers/v1/users.js | 2 +- module/entities/helper.js | 1 + module/programs/helper.js | 38 ++++++---- module/users/helper.js | 137 ++++++++++++++++++------------------ 5 files changed, 97 insertions(+), 85 deletions(-) diff --git a/controllers/v1/solutions.js b/controllers/v1/solutions.js index a93357f2..5e7b7839 100644 --- a/controllers/v1/solutions.js +++ b/controllers/v1/solutions.js @@ -28,9 +28,7 @@ module.exports = class Solutions extends Abstract { * "concepts" : [], "themes" : [], "flattenedThemes" : [], - "entities" : [ - "5beaa888af0065f0e0a10515" - ], + "entities" : ["bc75cc99-9205-463e-a722-5326857838f8","8ac1efe9-0415-4313-89ef-884e1c8eee34"] "registry" : [], "isRubricDriven" : false, "enableQuestionReadOut" : false, diff --git a/controllers/v1/users.js b/controllers/v1/users.js index 13dc2fcc..1bb8cecc 100644 --- a/controllers/v1/users.js +++ b/controllers/v1/users.js @@ -538,7 +538,7 @@ module.exports = class Users extends Abstract { roleWiseTargetedEntities.push(detailEntity.data); } } - + //no targeted entity if ( roleWiseTargetedEntities.length == 0 ) { throw { diff --git a/module/entities/helper.js b/module/entities/helper.js index 2ff6632e..f8dcd204 100644 --- a/module/entities/helper.js +++ b/module/entities/helper.js @@ -72,6 +72,7 @@ module.exports = class EntitiesHelper { .skip(skippingValue) .lean(); } + return resolve(entitiesDocuments); } catch (error) { return reject(error); diff --git a/module/programs/helper.js b/module/programs/helper.js index cbc5d306..bc2de2fa 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -105,17 +105,17 @@ module.exports = class ProgramsHelper { "components" : [], "isAPrivateProgram" : data.isAPrivateProgram ? data.isAPrivateProgram : false } - + let program = await database.models.programs.create( programData ); - + if( !program._id ) { throw { message : constants.apiResponses.PROGRAM_NOT_CREATED }; } - + if( data.scope ) { let programScopeUpdated = await this.setScope( @@ -212,7 +212,7 @@ module.exports = class ProgramsHelper { { name : scopeData.entityType }, - ["name","_id"] + ["name"] ); if( !entityTypeData.length > 0 ) { @@ -223,19 +223,31 @@ module.exports = class ProgramsHelper { } scope["entityType"] = entityTypeData[0].name; - scope["entityTypeId"] = entityTypeData[0]._id; } if( scopeData.entities && scopeData.entities.length > 0 ) { + + //call learners api for search + + let locationIds = []; + let bodyData={}; + bodyData["request"] = {}; + bodyData["request"]["filters"] = {}; + bodyData["request"]["filters"]["id"] = ""; + + scopeData.entities.forEach(entity=>{ + if (gen.utils.checkValidUUID(entity)) { + locationIds.push(entity); + } + }); + + bodyData["request"]["filters"]["id"] = locationIds; + + + let entityData = await sunbirdService.learnerLocationSearch( bodyData ); - let entities = - await entitiesHelper.entityDocuments( - { - _id : { $in : scopeData.entities }, - entityTypeId : scope.entityTypeId - },["_id"] - ); + let entities = entityData.data.response; if( !entities.length > 0 ) { return resolve({ status : httpStatusCode.bad_request.status, @@ -244,7 +256,7 @@ module.exports = class ProgramsHelper { } scope["entities"] = entities.map(entity => { - return entity._id; + return entity.id; }); } diff --git a/module/users/helper.js b/module/users/helper.js index 2d6d6754..48c0641e 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -12,6 +12,7 @@ const userRolesHelper = require(MODULES_BASE_PATH + "/user-roles/helper"); const entitiesHelper = require(MODULES_BASE_PATH + "/entities/helper"); const improvementProjectService = require(ROOT_PATH + "/generics/services/improvement-project"); const userService = require(ROOT_PATH + "/generics/services/users"); +const sunbirdService = require(ROOT_PATH + '/generics/services/sunbird'); /** @@ -32,7 +33,7 @@ module.exports = class UsersHelper { static privatePrograms(userId) { return new Promise(async (resolve, reject) => { try { - + let userPrivatePrograms = await programsHelper.userPrivatePrograms( userId @@ -67,7 +68,7 @@ module.exports = class UsersHelper { ) { return new Promise(async (resolve, reject) => { try { - + let userPrivateProgram = {}; let dateFormat = gen.utils.epochTime(); let parentSolutionInformation = {}; @@ -91,7 +92,7 @@ module.exports = class UsersHelper { "all", ["__v"] ); - + if ( !checkforProgramExist.length > 0 ) { return resolve({ status: httpStatusCode["bad_request"].status, @@ -134,8 +135,9 @@ module.exports = class UsersHelper { : data.programName, userId ); - + userPrivateProgram = await programsHelper.create(programData); + } let solutionDataToBeUpdated = { @@ -152,15 +154,24 @@ module.exports = class UsersHelper { data.entities && data.entities.length > 0 ) { + - let entityData = await entitiesHelper.entityDocuments( - { - _id: { $in: data.entities } - }, - ["entityType", "entityTypeId"] - ); + let locationIds = []; + let bodyData={}; + bodyData["request"] = {}; + bodyData["request"]["filters"] = {}; + bodyData["request"]["filters"]["id"] = ""; - if ( !entityData.length > 0 ) { + data.entities.forEach(entity=>{ + if (gen.utils.checkValidUUID(entity)) { + locationIds.push(entity); + } + }); + + bodyData["request"]["filters"]["id"] = locationIds; + let entityData = await sunbirdService.learnerLocationSearch( bodyData ); + + if ( !entityData.data.count > 0 ) { return resolve({ status: httpStatusCode["bad_request"].status, message: constants.apiResponses.ENTITY_NOT_FOUND, @@ -169,13 +180,14 @@ module.exports = class UsersHelper { } if ( data.type && data.type !== constants.common.IMPROVEMENT_PROJECT ) { - solutionDataToBeUpdated["entities"] = entityData.map( - (entity) => entity._id + solutionDataToBeUpdated["entities"] = entityData.data.response.map( + + (entity) => entity.id ); } - solutionDataToBeUpdated["entityType"] = entityData[0].entityType; - solutionDataToBeUpdated["entityTypeId"] = entityData[0].entityTypeId; + solutionDataToBeUpdated["entityType"] = entityData.data.response[0].type; + } //solution part @@ -418,7 +430,7 @@ module.exports = class UsersHelper { }, ["name"] ); - + if (!programData.length > 0) { return resolve({ status: httpStatusCode["bad_request"].status, @@ -670,7 +682,7 @@ module.exports = class UsersHelper { message: constants.apiResponses.SOLUTION_NOT_FOUND }); } - + console.log("solutionData:",solutionData) let rolesDocument = await userRolesHelper.roleDocuments( { code: requestedData.role @@ -687,80 +699,69 @@ module.exports = class UsersHelper { let requestedEntityTypes = Object.keys(_.omit(requestedData, ['role'])); let targetedEntityType = ""; - + rolesDocument[0].entityTypes.forEach((singleEntityType) => { if (requestedEntityTypes.includes(singleEntityType.entityType)) { targetedEntityType = singleEntityType.entityType; } }); - + console.log("targetedEntityType:",targetedEntityType) + console.log("requestedData[targetedEntityType]:",requestedData[targetedEntityType]) if (!requestedData[targetedEntityType]) { throw { status: httpStatusCode["bad_request"].status, message: constants.apiResponses.ENTITIES_NOT_ALLOWED_IN_ROLE }; } - + console.log("##############") if (solutionData[0].entityType === targetedEntityType) { - let filterQuery = { - "registryDetails.code": requestedData[targetedEntityType] - }; - + let bodyData={}; + bodyData["request"] = {}; + bodyData["request"]["filters"] = {}; + bodyData["request"]["filters"]["parentId"] = ""; + if (gen.utils.checkValidUUID(requestedData[targetedEntityType])) { - filterQuery = { - "registryDetails.locationId": requestedData[targetedEntityType] - }; - } - - let entities = await entitiesHelper.entityDocuments(filterQuery, [ - "groups", - ]); - - if (!entities.length > 0) { - throw { - message: constants.apiResponses.ENTITY_NOT_FOUND - }; + bodyData["request"]["filters"]["parentId"] = requestedData[targetedEntityType]; } - - if ( - entities[0] && - entities[0].groups && - Object.keys(entities[0].groups).length > 0 - ) { + + let entitiesData = await sunbirdService.learnerLocationSearch( bodyData ); + if( entitiesData.count > 0 ){ targetedEntityType = constants.common.STATE_ENTITY_TYPE; - } + } } - - let filterData = { - "registryDetails.code": requestedData[targetedEntityType] - }; - + console.log("targetedEntityTypeUpdated:",targetedEntityType) + let filterData={}; + filterData["request"] = {}; + filterData["request"]["filters"] = {}; + if (gen.utils.checkValidUUID(requestedData[targetedEntityType])) { - filterData = { - "registryDetails.locationId": requestedData[targetedEntityType] + filterData["request"]["filters"] = { + "id" : requestedData[targetedEntityType] + }; + } else { + filterData["request"]["filters"] = { + "code" : requestedData[targetedEntityType] }; } - - let entities = await entitiesHelper.entityDocuments(filterData, [ - "metaInformation.name", - "entityType" - ]); - - if (!entities.length > 0) { + + let entitiesDocument = await sunbirdService.learnerLocationSearch( filterData ); + if (!entitiesDocument.data.count > 0) { throw { message: constants.apiResponses.ENTITY_NOT_FOUND }; } - if (entities[0].metaInformation && entities[0].metaInformation.name) { - entities[0]['entityName'] = entities[0].metaInformation.name; - delete entities[0].metaInformation; + let entityData = entitiesDocument.data.response; + let entityDataFormated = { + "_id" : entityData[0].id, + "entityType" : entityData[0].type, + "entityName" : entityData[0].name } - + console.log("entityDataFormated:",entityDataFormated) return resolve({ message: constants.apiResponses.SOLUTION_TARGETED_ENTITY, success: true, - data: entities[0] + data: entityDataFormated }); } catch (error) { @@ -793,17 +794,17 @@ module.exports = class UsersHelper { for( let pointerToEntities = 0 ; pointerToEntities < roleWiseTargetedEntities.length ; pointerToEntities++ ) { let currentEntity = roleWiseTargetedEntities[pointerToEntities]; - + console.log("currentEntity:",currentEntity) if ( !allTargetedEntities.hasOwnProperty(currentEntity._id) ) { allTargetedEntities[currentEntity._id] = new Array(); } - + //add entity _id if already not there to allTargetedEntities let otherEntities = roleWiseTargetedEntities.filter((entity) => entity.entityType !== currentEntity.entityType); - + console.log("otherEntities:",otherEntities) if ( !otherEntities || !otherEntities.length > 0 ) { continue; } - + console.log("i am here***********") let entitiesDocument = await entitiesHelper.entityDocuments({ _id: ObjectId(currentEntity._id) }, ["groups"]); @@ -811,7 +812,7 @@ module.exports = class UsersHelper { if ( !entitiesDocument || !entitiesDocument.length > 0 ) { continue; } - + console.log("i am on next ***********") entitiesDocument = entitiesDocument[0]; for( let entityCounter = 0 ; entityCounter < otherEntities.length ; entityCounter++ ) { From 9e0c426c475c796718b4ca1c93ac8f1a8a4d58ed Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 28 Feb 2022 09:18:17 +0530 Subject: [PATCH 104/331] change --- module/programs/helper.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/module/programs/helper.js b/module/programs/helper.js index bc2de2fa..63b3eee1 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -259,7 +259,7 @@ module.exports = class ProgramsHelper { return entity.id; }); - } + } if( scopeData.roles ) { From 3d4b9a5e01e0544b618b310e8a18dedf689473d5 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 28 Feb 2022 09:23:10 +0530 Subject: [PATCH 105/331] console removed --- module/users/helper.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/module/users/helper.js b/module/users/helper.js index 48c0641e..c8175fb9 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -475,7 +475,7 @@ module.exports = class UsersHelper { } - console.log("controll here yeah#############",token); + let importedProjects = await improvementProjectService.importedProjects( token, programId From c0d05f60d965ae6d0ed6919ae0de473dfdbd41e8 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 28 Feb 2022 09:34:11 +0530 Subject: [PATCH 106/331] console removed --- module/users/helper.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/module/users/helper.js b/module/users/helper.js index c8175fb9..a9c0b2f8 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -422,7 +422,7 @@ module.exports = class UsersHelper { static solutions(programId, requestedData, pageSize, pageNo, search, token) { return new Promise(async (resolve, reject) => { - token="b110b42b-d016-48b5-b10a-6529ac903c44" + try { let programData = await programsHelper.programDocuments( { @@ -480,7 +480,7 @@ module.exports = class UsersHelper { token, programId ); - console.log("importedProjects:",mergedData); + if (importedProjects.success) { if (importedProjects.data && importedProjects.data.length > 0) { totalCount += importedProjects.data.length; From 5c5cd1f7b48950b9f8a847dd4807e6c163e3c23f Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 4 Mar 2022 18:08:07 +0530 Subject: [PATCH 107/331] commited to change branch need to recheck for commands --- controllers/v1/entities.js | 2 + controllers/v1/users.js | 5 +- generics/constants/common.js | 3 +- generics/constants/endpoints.js | 3 +- generics/services/form.js | 49 ++++ generics/services/sunbird.js | 63 ++++- module/entities/helper.js | 83 +++--- module/solutions/helper.js | 354 ++++++++++++++++++++++---- module/user-roles/helper.js | 3 +- module/users/helper.js | 431 +++++++++++++++++++++++++------- 10 files changed, 816 insertions(+), 180 deletions(-) create mode 100644 generics/services/form.js diff --git a/controllers/v1/entities.js b/controllers/v1/entities.js index 598cfaab..e5b18ea8 100644 --- a/controllers/v1/entities.js +++ b/controllers/v1/entities.js @@ -154,7 +154,9 @@ module.exports = class Entities extends Abstract { subEntityList(req) { return new Promise(async (resolve, reject) => { + console.log("request : ",req.params._id, req.body.entities) + //if condition is not working if( !(req.params._id || req.body.entities) ) { return resolve({ status : httpStatusCode.bad_request.status, diff --git a/controllers/v1/users.js b/controllers/v1/users.js index 1bb8cecc..a6ecc915 100644 --- a/controllers/v1/users.js +++ b/controllers/v1/users.js @@ -423,7 +423,7 @@ module.exports = class Users extends Abstract { return new Promise(async (resolve, reject) => { try { - + let currentMaximumCountOfRequiredEntities = 0; let requiredEntities = new Array; @@ -502,7 +502,7 @@ module.exports = class Users extends Abstract { async targetedEntity(req) { return new Promise(async (resolve, reject) => { try { - + console.log("request : ", req.params._id,req.body) let roleArray = req.body.role.split(","); let targetedEntities = {}; @@ -573,6 +573,7 @@ module.exports = class Users extends Abstract { return resolve(targetedEntities); } catch (error) { + console.log(error) return reject({ status: error.status || httpStatusCode.internal_server_error.status, message: error.message || httpStatusCode.internal_server_error.message, diff --git a/generics/constants/common.js b/generics/constants/common.js index 4503f9b7..2dcbaa99 100644 --- a/generics/constants/common.js +++ b/generics/constants/common.js @@ -66,5 +66,6 @@ module.exports = { "LINK" : "link", "DISCOVERED_BY_ME" : "discoveredByMe", "DEFAULT_SUBMISSION_REQUIRED" : 1, - "SCHOOL" : "school" + "SCHOOL" : "school", + "SUBENTITY" :"subEntity_" }; diff --git a/generics/constants/endpoints.js b/generics/constants/endpoints.js index 53f71a13..5fe46387 100644 --- a/generics/constants/endpoints.js +++ b/generics/constants/endpoints.js @@ -31,5 +31,6 @@ module.exports = { LIST_PROJECT : "/v1/userProjects/list", GET_QUESTIONS : "/v1/solutions/questions", GET_OBSERVATION : "/v1/observations/details", - GET_LOCATION_DATA : "/api/data/v1/location/search" + GET_LOCATION_DATA : "/api/data/v1/location/search", + GET_FORM_DATA : "/api/data/v1/form/read" } \ No newline at end of file diff --git a/generics/services/form.js b/generics/services/form.js new file mode 100644 index 00000000..ea9188f4 --- /dev/null +++ b/generics/services/form.js @@ -0,0 +1,49 @@ +/** + * name : form.js + * author : Vishnudas + * Date : 02-Mar-2022 + * Description : calling sunbird form api and setting cache. + */ + +//dependencies +const sunbirdService = require(ROOT_PATH + '/generics/services/sunbird'); +let cache = require(ROOT_PATH+"/generics/helpers/cache"); + +/** + * + * @function + * @name formData + * @param {String} stateLocationCode - state location code. + * @param {object} entityKey - key to store data in cache + * @returns {Promise} returns a promise. +*/ + + +const formData = function ( stateLocationCode, entityKey ) { + return new Promise(async (resolve, reject) => { + try { + console.log("requestData:",stateLocationCode,entityKey) + let subEntitiesDetails = await sunbirdService.formRead( stateLocationCode ); + let subEntityData = subEntitiesDetails.data.form.data.fields[1].children.teacher; + + let subEntities = subEntityData.map( subEntity => { + return subEntity.code; + }) + if( !subEntitiesDetails.data || !subEntityData.length > 0 ) { + return resolve({ + message : constants.apiResponses.ENTITY_NOT_FOUND, + result : [] + }) + } + let setCache = cache.setValue(entityKey, subEntities, 43200); + console.log("setCache",setCache) + return resolve(subEntities); + + } catch (error) { + return reject(error); + } + }) +} +module.exports = { + formData : formData +} \ No newline at end of file diff --git a/generics/services/sunbird.js b/generics/services/sunbird.js index ee521c49..9e49e032 100644 --- a/generics/services/sunbird.js +++ b/generics/services/sunbird.js @@ -63,6 +63,67 @@ const learnerLocationSearch = function ( bodyData ) { }) } +/** + * + * @function + * @name formRead + * @param {String} bearerToken - autherization token. + * @param {object} bodyData - subType data. + * @returns {Promise} returns a promise. +*/ +const formRead = function ( subTypeData ) { + return new Promise(async (resolve, reject) => { + try { + console.log("subTypeData:",subTypeData) + let bodyData = { + request : { + type: "profileConfig", + subType: subTypeData, + action: "get" + } + } + console.log("bodyData:",bodyData.request) + const url = + sunbirdBaseUrl + constants.endpoints.GET_FORM_DATA; + const options = { + headers : { + "Authorization" : process.env.SUNBIRD_SERVICE_AUTHERIZATION, + "content-type": "application/json" + }, + json : bodyData + }; + + request.post(url,options,kendraCallback); + + function kendraCallback(err, data) { + + let result = { + success : true + }; + + if (err) { + result.success = false; + } else { + + let response = data.body; + + if( response.responseCode === constants.common.OK) { + result["data"] = response.result; + } else { + result.success = false; + } + } + return resolve(result); + } + + } catch (error) { + return reject(error); + } + }) +} + + module.exports = { - learnerLocationSearch : learnerLocationSearch + learnerLocationSearch : learnerLocationSearch, + formRead : formRead }; \ No newline at end of file diff --git a/module/entities/helper.js b/module/entities/helper.js index f8dcd204..7acb27f6 100644 --- a/module/entities/helper.js +++ b/module/entities/helper.js @@ -1,7 +1,9 @@ const entityTypesHelper = require(MODULES_BASE_PATH + "/entityTypes/helper"); const userRolesHelper = require(MODULES_BASE_PATH + "/user-roles/helper"); // const elasticSearch = require(GENERIC_HELPERS_PATH + "/elastic-search"); - +const sunbirdService = require(ROOT_PATH + '/generics/services/sunbird'); +let cache = require(ROOT_PATH+"/generics/helpers/cache"); +const formService = require(ROOT_PATH + '/generics/services/form'); module.exports = class EntitiesHelper { @@ -319,7 +321,7 @@ module.exports = class EntitiesHelper { return new Promise(async (resolve, reject) => { try { - + console.log("req in helper : ",entities,entityId,type,search,limit,pageNo) let result = []; let obj = { entityId : entityId, @@ -379,9 +381,9 @@ module.exports = class EntitiesHelper { static subEntities( entitiesData ) { return new Promise(async (resolve, reject) => { - + try { - + console.log("#entitiesData : ",entitiesData) let entitiesDocument; if( entitiesData.type !== "" ) { @@ -686,7 +688,8 @@ module.exports = class EntitiesHelper { static subEntityListBasedOnRoleAndLocation( stateLocationId,role ) { return new Promise(async (resolve, reject) => { try { - + let entityKey = constants.common.SUBENTITY + stateLocationId; + let rolesDocument = await userRolesHelper.roleDocuments({ code : role },["entityTypes.entityType"]); @@ -697,44 +700,52 @@ module.exports = class EntitiesHelper { message: constants.apiResponses.USER_ROLES_NOT_FOUND } } + + let subEntities = await cache.getValue(entityKey); + console.log("subEntitiesDetails from cache:",subEntities) + if( !subEntities.length > 0 ) { + let bodyData={}; + bodyData["request"] = {}; + bodyData["request"]["filters"] = {}; + bodyData["request"]["filters"]["id"] = stateLocationId; + + let entitiesData = await sunbirdService.learnerLocationSearch( bodyData ); + + if( !entitiesData.data.response.length > 0 ) { + return resolve({ + message : constants.apiResponses.ENTITY_NOT_FOUND, + result : [] + }) + } + + let stateLocationCode = entitiesData.data.response[0].code; + subEntities = await formService.formData( stateLocationCode,entityKey ); + if( !subEntities.length > 0 ) { + return resolve({ + message : constants.apiResponses.ENTITY_NOT_FOUND, + result : [] + }) + } + } + + + let result = []; - let filterQuery = { - "registryDetails.code" : stateLocationId - }; - - if( gen.utils.checkValidUUID(stateLocationId) ) { - filterQuery = { - "registryDetails.locationId" : stateLocationId - }; - } - - const entityDocuments = await this.entityDocuments(filterQuery,["childHierarchyPath"]); - - if( !entityDocuments.length > 0 ) { - return resolve({ - message : constants.apiResponses.ENTITY_NOT_FOUND, - result : [] - }) - } - - let result = []; - - if( rolesDocument[0].entityTypes[0].entityType === constants.common.STATE_ENTITY_TYPE ) { - result = entityDocuments[0].childHierarchyPath; + if( rolesDocument[0].entityTypes[0].entityType === constants.common.STATE_ENTITY_TYPE ) { + result = subEntities; result.unshift(constants.common.STATE_ENTITY_TYPE); - } else { + } else { let targetedEntityType = ""; rolesDocument[0].entityTypes.forEach(singleEntityType => { - if( entityDocuments[0].childHierarchyPath.includes(singleEntityType.entityType) ) { + if( subEntities.includes(singleEntityType.entityType) ) { targetedEntityType = singleEntityType.entityType; } }); let findTargetedEntityIndex = - entityDocuments[0].childHierarchyPath.findIndex(element => element === targetedEntityType); - + subEntities.findIndex(element => element === targetedEntityType); if( findTargetedEntityIndex < 0 ) { throw { message : constants.apiResponses.SUB_ENTITY_NOT_FOUND, @@ -742,14 +753,14 @@ module.exports = class EntitiesHelper { } } - result = entityDocuments[0].childHierarchyPath.slice(findTargetedEntityIndex); - } + result = subEntities.slice(findTargetedEntityIndex); + } - return resolve({ + return resolve({ success: true, message : constants.apiResponses.ENTITIES_CHILD_HIERACHY_PATH, result : result - }); + }); } catch (error) { return reject(error); diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 9a2b989c..4091b35c 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -5,6 +5,8 @@ * Description : Solution related helper functionality. */ +const { header } = require("express-validator/check"); + // Dependencies const programsHelper = require(MODULES_BASE_PATH + "/programs/helper"); @@ -14,6 +16,7 @@ const userRolesHelper = require(MODULES_BASE_PATH + "/user-roles/helper"); const surveyService = require(ROOT_PATH + '/generics/services/survey'); const improvementProjectService = require(ROOT_PATH + '/generics/services/improvement-project'); const appsPortalBaseUrl = process.env.APP_PORTAL_BASE_URL + "/" ; +const sunbirdService = require(ROOT_PATH + '/generics/services/sunbird'); /** * SolutionsHelper @@ -114,64 +117,103 @@ module.exports = class SolutionsHelper { message : constants.apiResponses.PROGRAM_NOT_FOUND } } - + console.log("programData:",programData) solutionData.programId = programData[0]._id; solutionData.programName = programData[0].name; solutionData.programDescription = programData[0].description; - if( solutionData.type == constants.common.COURSE ) { + // if( solutionData.type == constants.common.COURSE ) { - if( !solutionData.link ) { - return resolve({ - status : httpStatusCode.bad_request.status, - message : constants.apiResponses.COURSE_LINK_REQUIRED - }); - } - } else { + // if( !solutionData.link ) { + // return resolve({ + // status : httpStatusCode.bad_request.status, + // message : constants.apiResponses.COURSE_LINK_REQUIRED + // }); + // } + // } else { - if( !solutionData.entityType ){ + // if( !solutionData.entityType ){ - return resolve({ - status : httpStatusCode.bad_request.status, - message : constants.apiResponses.ENTITY_TYPE_REQUIRED - }); + // return resolve({ + // status : httpStatusCode.bad_request.status, + // message : constants.apiResponses.ENTITY_TYPE_REQUIRED + // }); - } + // } - let entityTypeData = - await entityTypesHelper.entityTypesDocument({ - name : solutionData.entityType - },["_id"]); + // let entityTypeData = + // await entityTypesHelper.entityTypesDocument({ + // name : solutionData.entityType + // },["_id"]); + // console.log("entityTypeData:",entityTypeData) + // if( !entityTypeData.length > 0 ) { + // throw { + // message : constants.apiResponses.ENTITY_TYPES_NOT_FOUND + // } + // } - if( !entityTypeData.length > 0 ) { - throw { - message : constants.apiResponses.ENTITY_TYPES_NOT_FOUND - } - } + // solutionData.entityTypeId = entityTypeData[0]._id; + // } + + + //eG code begining -------------------------- + if( solutionData.type == constants.common.COURSE && !solutionData.link ) { - solutionData.entityTypeId = entityTypeData[0]._id; + return resolve({ + status : httpStatusCode.bad_request.status, + message : constants.apiResponses.COURSE_LINK_REQUIRED + }); + } + //eG code ending -------------------------- - if( solutionData.entities && solutionData.entities.length > 0 ) { + + // if( solutionData.entities && solutionData.entities.length > 0 ) { - let entitiesData = - await entitiesHelper.entityDocuments({ - _id : { $in : solutionData.entities } - },["_id"]); + // let entitiesData = + // await entitiesHelper.entityDocuments({ + // _id : { $in : solutionData.entities } + // },["_id"]); + + // if( !entitiesData.length > 0 ) { + // throw { + // message : constants.apiResponses.ENTITIES_NOT_FOUND + // } + // } + + // entitiesData = entitiesData.map( entity => { + // return entity._id; + // }) + + // solutionData.entities = entitiesData; + // } + //eG code Start --------------------------- + if( solutionData.entities && solutionData.entities.length > 0 ) { + let bodyData={}; + bodyData["request"] = {}; + bodyData["request"]["filters"] = {}; + bodyData["request"]["filters"]["id"] = solutionData.entities; + console.log("bodyData :",bodyData) + + let entitiesDetails = await sunbirdService.learnerLocationSearch( bodyData ); + console.log("entitiesDetails:",entitiesDetails) + let entitiesData = entitiesDetails.data.response; if( !entitiesData.length > 0 ) { throw { message : constants.apiResponses.ENTITIES_NOT_FOUND } } - entitiesData = entitiesData.map( entity => { - return entity._id; + return entity.id; }) - + console.log("entitiesData:",entitiesData) solutionData.entities = entitiesData; + } + //eG code Ends --------------------------- + if( solutionData.minNoOfSubmissionsRequired && solutionData.minNoOfSubmissionsRequired > constants.common.DEFAULT_SUBMISSION_REQUIRED ) { @@ -240,9 +282,182 @@ module.exports = class SolutionsHelper { static setScope( programId,solutionId,scopeData ) { return new Promise(async (resolve, reject) => { - + console.log("data reached here") try { + // let programData = + // await programsHelper.programDocuments({ _id : programId },["_id","scope"]); + + // if( !programData.length > 0 ) { + // return resolve({ + // status : httpStatusCode.bad_request.status, + // message : constants.apiResponses.PROGRAM_NOT_FOUND + // }); + // } + + // let solutionData = await this.solutionDocuments({ _id : solutionId },["_id"]); + + // if( !solutionData.length > 0 ) { + // return resolve({ + // status : httpStatusCode.bad_request.status, + // message : constants.apiResponses.SOLUTION_NOT_FOUND + // }); + // } + // console.log("programData[0].scope:",programData[0].scope) + // console.log("scopeData",scopeData) + // if( programData[0].scope ) { + + // let currentSolutionScope = JSON.parse(JSON.stringify(programData[0].scope)); + + // if( Object.keys(scopeData).length > 0 ) { + + // if( scopeData.entityType ) { + // currentSolutionScope.entityType = scopeData.entityType; + // } + // console.log(" currentSolutionScope.entityType:", currentSolutionScope.entityType); + // if( scopeData.entities && scopeData.entities.length > 0 ) { + // let bodyData={}; + // bodyData["request"] = {}; + // bodyData["request"]["filters"] = {}; + // let entityLocationIds = []; + // scopeData.entities.forEach(entity => { + // if (gen.utils.checkValidUUID(entity)) { + // entityLocationIds.push(entity); + // } + // }); + // bodyData["request"]["filters"]["id"] = entityLocationIds; + // console.log(" bodyData:", bodyData["request"]["filters"]) + // let entityDetails = await sunbirdService.learnerLocationSearch(bodyData); + // if( !entityDetails.data.response.length > 0 ) { + // return resolve({ + // status : httpStatusCode.bad_request.status, + // message : constants.apiResponses.ENTITIES_NOT_FOUND + // }); + // } + // console.log("Data from learner:",entityDetails.data.response) + // let entityData = entityDetails.data.response; + // let entities = []; + // entityData.map(entity => { + // console.log("entity inside map:",entity.type); + // if( entity.type == currentSolutionScope.entityType ) { + // entities.push(entity.id) + // } + // }) + // console.log ("entityData:",entities.length) + // if( !entities.length > 0 ) { + // return resolve({ + // status : httpStatusCode.bad_request.status, + // message : constants.apiResponses.ENTITIES_NOT_FOUND + // }); + // } + + // let entityIds = []; + // //check from here + // console.log("inside the condition") + // if( currentSolutionScope.entityType !== programData[0].scope.entityType ) { + // console.log("inside the condition 1:",currentSolutionScope.entityType ,currentSolutionScope.entities) + // entitiesInParent(currentSolutionScope.entities,currentSolutionScope.entityType); + + + + + // for( let entity = 0; entity < entities.length; entity ++ ) { + + // let entityQuery = { + // _id : { $in : currentSolutionScope.entities }, + // [`groups.${currentSolutionScope.entityType}`] : entities[entity]._id + // } + + // let entityInParent = + // await entitiesHelper.entityDocuments(entityQuery); + + // if( entityInParent.length > 0 ) { + // entityIds.push(ObjectId(entities[entity]._id)); + // } + // } + + // } else { + // console.log("inside the condition") + // entityIds = entities.map(entity => { + // return ObjectId(entity._id); + // }) + // } + + // if( !entityIds.length > 0 ) { + + // return resolve({ + // status : httpStatusCode.bad_request.status, + // message : constants.apiResponses.SCOPE_ENTITY_INVALID + // }); + + // } + + // currentSolutionScope.entities = entityIds; + // } + + // if( scopeData.roles ) { + // if( Array.isArray(scopeData.roles) && scopeData.roles.length > 0 ) { + + // let userRoles = await userRolesHelper.roleDocuments({ + // code : { $in : scopeData.roles } + // },["_id","code"]); + + // if( !userRoles.length > 0 ) { + // return resolve({ + // status : httpStatusCode.bad_request.status, + // message : constants.apiResponses.INVALID_ROLE_CODE + // }); + // } + + // currentSolutionScope["roles"] = userRoles; + + // } else { + // if( scopeData.roles === constants.common.ALL_ROLES ) { + // currentSolutionScope["roles"] = [{ + // "code" : constants.common.ALL_ROLES + // }]; + // } + // } + // } + // } + // console.log("currentSolutionScope:",currentSolutionScope) + // if( currentSolutionScope && currentSolutionScope.entities.length > 0 ){ + // console.log("**************inside") + // let entitiesIds = currentSolutionScope.entities; + // console.log("entitiesIds:",entitiesIds) + // for( let eachEntity in entitiesIds ) { + // if( entitiesIds[eachEntity].toString() == entitiesIds[eachEntity] ) { + // entitiesIds[eachEntity] = ObjectId(entitiesIds[eachEntity]); + // } + // } + // console.log("currentSolutionScope After:",entitiesIds) + // delete currentSolutionScope.entities; + // currentSolutionScope["entities"] = entitiesIds; + + // } + // console.log("currentSolutionScope After:",currentSolutionScope) + // let updateSolution = + // await database.models.solutions.findOneAndUpdate( + // { + // _id : solutionId + // }, + // { $set : { scope : currentSolutionScope }},{ new: true } + // ).lean(); + + // if( !updateSolution._id ) { + // throw { + // status : constants.apiResponses.SOLUTION_SCOPE_NOT_ADDED + // }; + // } + // solutionData = updateSolution; + + // } + + // return resolve({ + // success : true, + // message : constants.apiResponses.SOLUTION_UPDATED + // }); +//----------------------------------------------------------------------------------- let programData = await programsHelper.programDocuments({ _id : programId },["_id","scope"]); @@ -261,7 +476,8 @@ module.exports = class SolutionsHelper { message : constants.apiResponses.SOLUTION_NOT_FOUND }); } - + console.log("programData[0].scope:",programData[0].scope) + console.log("scopeData",scopeData) if( programData[0].scope ) { let currentSolutionScope = JSON.parse(JSON.stringify(programData[0].scope)); @@ -278,11 +494,14 @@ module.exports = class SolutionsHelper { ); currentSolutionScope.entityType = entityType[0].name; + //remove entity type id currentSolutionScope.entityTypeId = entityType[0]._id; } - + if( scopeData.entities && scopeData.entities.length > 0 ) { + + //get all entity details from learner api let entities = await entitiesHelper.entityDocuments( { @@ -290,16 +509,16 @@ module.exports = class SolutionsHelper { entityTypeId : currentSolutionScope.entityTypeId },["_id"] ); - + console.log ("entities:",entities) if( !entities.length > 0 ) { return resolve({ status : httpStatusCode.bad_request.status, message : constants.apiResponses.ENTITIES_NOT_FOUND }); } - + let entityIds = []; - + console.log("condition data:",currentSolutionScope.entityType, programData[0].scope.entityType) if( currentSolutionScope.entityType !== programData[0].scope.entityType ) { for( let entity = 0; entity < entities.length; entity ++ ) { @@ -307,10 +526,10 @@ module.exports = class SolutionsHelper { _id : { $in : currentSolutionScope.entities }, [`groups.${currentSolutionScope.entityType}`] : entities[entity]._id } - + console.log("query:",entityQuery) let entityInParent = await entitiesHelper.entityDocuments(entityQuery); - + console.log("entityInParent:",entityInParent); if( entityInParent.length > 0 ) { entityIds.push(ObjectId(entities[entity]._id)); } @@ -359,22 +578,22 @@ module.exports = class SolutionsHelper { } } } - + console.log("currentSolutionScope:",currentSolutionScope) if( currentSolutionScope && currentSolutionScope.entities.length > 0 ){ - + console.log("**************inside") let entitiesIds = currentSolutionScope.entities; - + console.log("entitiesIds:",entitiesIds) for( let eachEntity in entitiesIds ) { if( entitiesIds[eachEntity].toString() == entitiesIds[eachEntity] ) { entitiesIds[eachEntity] = ObjectId(entitiesIds[eachEntity]); } } - + console.log("currentSolutionScope After:",entitiesIds) delete currentSolutionScope.entities; currentSolutionScope["entities"] = entitiesIds; } - + console.log("currentSolutionScope After:",currentSolutionScope) let updateSolution = await database.models.solutions.findOneAndUpdate( { @@ -1991,3 +2210,46 @@ function _generateLink(appsPortalBaseUrl, prefix, solutionLink, solutionType) { return link; } + +/** + * get entitiesData of matching type by recursion. + * @method + * @name entitiesInParent + * @returns {Array} - Entities matching the type under the parent. + */ + +async function entitiesInParent( solutionEntities,currentEntityType ){ + //console.log("inside recursive function : ",solutionEntities,currentEntityType) + let bodyData={}; + bodyData["request"] = {}; + bodyData["request"]["filters"] = {}; + bodyData["request"]["filters"]["parentId"] = solutionEntities; + //console.log(" bodyData:", bodyData["request"]["filters"]) + let entityDetails = await sunbirdService.learnerLocationSearch(bodyData); + if( !entityDetails.data.response.length > 0 ) { + return resolve({ + status : httpStatusCode.bad_request.status, + message : constants.apiResponses.ENTITIES_NOT_FOUND + }); + } + //console.log("Data from learner inside recursion:",entityDetails.data.response) + let entityData = entityDetails.data.response; + //let entities = []; + entities = ( typeof entities != 'undefined' && entities instanceof Array ) ? entities : [] + let mismatchEntities = []; + entityData.map(entity => { + //console.log("entity inside map:",entity.type); + if( entity.type == currentEntityType ) { + entities.push(entity.id) + } else { + mismatchEntities.push(entity.id) + } + }); + console.log("mismatchEntities:",mismatchEntities.length) + if( mismatchEntities.length > 0 ){ + entitiesInParent(mismatchEntities,currentEntityType) + } + console.log("matched entities:",entities.length); + +} + diff --git a/module/user-roles/helper.js b/module/user-roles/helper.js index ef466555..a0bfafd2 100644 --- a/module/user-roles/helper.js +++ b/module/user-roles/helper.js @@ -29,7 +29,6 @@ module.exports = class UserRolesHelper { ) { return new Promise(async (resolve, reject) => { try { - let queryObject = (filterQuery != "all") ? filterQuery : {}; let projection = {} @@ -50,7 +49,7 @@ module.exports = class UserRolesHelper { queryObject, projection ).lean(); - + return resolve(userRolesData); } catch (error) { diff --git a/module/users/helper.js b/module/users/helper.js index a9c0b2f8..0a6543a3 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -13,6 +13,8 @@ const entitiesHelper = require(MODULES_BASE_PATH + "/entities/helper"); const improvementProjectService = require(ROOT_PATH + "/generics/services/improvement-project"); const userService = require(ROOT_PATH + "/generics/services/users"); const sunbirdService = require(ROOT_PATH + '/generics/services/sunbird'); +let cache = require(ROOT_PATH+"/generics/helpers/cache"); +const formService = require(ROOT_PATH + '/generics/services/form'); /** @@ -322,15 +324,15 @@ module.exports = class UsersHelper { * Entities mapping form data. * @method * @name entitiesMappingForm - * @param {String} stateId - state id. + * @param {String} stateCode - state code. * @param {String} roleId - role id. * @returns {Object} returns a list of entitiesMappingForm. */ - static entitiesMappingForm(stateId, roleId) { + static entitiesMappingForm(stateCode, roleId, entityKey) { return new Promise(async (resolve, reject) => { try { - + console.log("data in request:",stateCode,roleId,entityKey) const rolesData = await userRolesHelper.roleDocuments({ _id: roleId }, ["entityTypes.entityType"]); @@ -341,31 +343,31 @@ module.exports = class UsersHelper { result: [] }) } - - const entitiesData = await entitiesHelper.entityDocuments( - { - _id: stateId - }, ["childHierarchyPath"] - ); - - if (!entitiesData.length > 0) { - return resolve({ - message: constants.apiResponses.ENTITY_NOT_FOUND, - result: [] - }) + console.log("#rolesData:",rolesData) + let subEntities = await cache.getValue(entityKey); + console.log("subEntitiesDetails from cache:",subEntities) + if( !subEntities.length > 0 ) { + subEntities = await formService.formData( stateCode,entityKey ); + if( !subEntities.length > 0 ) { + return resolve({ + message : constants.apiResponses.ENTITY_NOT_FOUND, + result : [] + }) + } } - + console.log("subEntitiesDetails from cache:",subEntities); + let roleEntityType = ""; rolesData[0].entityTypes.forEach(roleData => { - if (entitiesData[0].childHierarchyPath.includes(roleData.entityType)) { + if (subEntities.includes(roleData.entityType)) { roleEntityType = roleData.entityType; } }) - + console.log("roleEntityType",roleEntityType) let entityTypeIndex = - entitiesData[0].childHierarchyPath.findIndex(path => path === roleEntityType); - + subEntities.findIndex(path => path === roleEntityType); + console.log("entityTypeIndex",entityTypeIndex) let form = { "field": "", "label": "", @@ -381,12 +383,12 @@ module.exports = class UsersHelper { let forms = []; for ( - let pointerToChildHierarchy = 0; + let pointerToChildHierarchy = 1; pointerToChildHierarchy < entityTypeIndex + 1; pointerToChildHierarchy++ ) { let cloneForm = JSON.parse(JSON.stringify(form)); - let entityType = entitiesData[0].childHierarchyPath[pointerToChildHierarchy]; + let entityType = subEntities[pointerToChildHierarchy]; cloneForm["field"] = entityType; cloneForm["label"] = `Select ${gen.utils.camelCaseToTitleCase(entityType)}`; @@ -402,6 +404,79 @@ module.exports = class UsersHelper { result: forms }); + + //============= + // const rolesData = await userRolesHelper.roleDocuments({ + // _id: roleId + // }, ["entityTypes.entityType"]); + + // if (!rolesData.length > 0) { + // return resolve({ + // message: constants.apiResponses.USER_ROLES_NOT_FOUND, + // result: [] + // }) + // } + + // const entitiesData = await entitiesHelper.entityDocuments( + // { + // _id: stateId, + // }, ["childHierarchyPath"] + // ); + // console.log("entitiesData##",entitiesData) + // if (!entitiesData.length > 0) { + // return resolve({ + // message: constants.apiResponses.ENTITY_NOT_FOUND, + // result: [] + // }) + // } + + // let roleEntityType = ""; + + // rolesData[0].entityTypes.forEach(roleData => { + // if (entitiesData[0].childHierarchyPath.includes(roleData.entityType)) { + // roleEntityType = roleData.entityType; + // } + // }) + // console.log("roleEntityType##",roleEntityType) + // let entityTypeIndex = + // entitiesData[0].childHierarchyPath.findIndex(path => path === roleEntityType); + // console.log("entityTypeIndex##",entityTypeIndex) + // let form = { + // "field": "", + // "label": "", + // "value": "", + // "visible": true, + // "editable": true, + // "input": "text", + // "validation": { + // "required": false + // } + // }; + + // let forms = []; + + // for ( + // let pointerToChildHierarchy = 0; + // pointerToChildHierarchy < entityTypeIndex + 1; + // pointerToChildHierarchy++ + // ) { + // let cloneForm = JSON.parse(JSON.stringify(form)); + // let entityType = entitiesData[0].childHierarchyPath[pointerToChildHierarchy]; + // cloneForm["field"] = entityType; + // cloneForm["label"] = `Select ${gen.utils.camelCaseToTitleCase(entityType)}`; + + // if (roleEntityType === entityType) { + // cloneForm.validation.required = true; + // } + + // forms.push(cloneForm); + // } + // console.log("form",forms) + // return resolve({ + // message: constants.apiResponses.ENTITIES_MAPPING_FORM_FETCHED, + // result: forms + // }); + } catch (error) { return reject(error); } @@ -583,58 +658,60 @@ module.exports = class UsersHelper { * @param {String} role - role. * @returns {Object} returns a list of entity type by location and role. */ - - static entityTypesByLocationAndRole(stateLocationId, role) { + static entityTypesByLocationAndRole(stateLocationId, role) { return new Promise(async (resolve, reject) => { try { - let filterQuery = { - "registryDetails.code": stateLocationId, - }; - - if (gen.utils.checkValidUUID(stateLocationId)) { - filterQuery = { - "registryDetails.locationId": stateLocationId, - }; - } - - const entitiesData = await entitiesHelper.entityDocuments(filterQuery, [ - "_id", - ]); - - if (!entitiesData.length > 0) { - throw { - message: constants.apiResponses.ENTITIES_NOT_EXIST_IN_LOCATION, - }; - } - + let entityKey = constants.common.SUBENTITY + stateLocationId; const rolesDocument = await userRolesHelper.roleDocuments( { code: role.toUpperCase(), }, ["_id", "entityTypes.entityType"] ); - + console.log("role:",rolesDocument[0]) if (!rolesDocument.length > 0) { throw { message: constants.apiResponses.USER_ROLES_NOT_FOUND }; } + + + let bodyData={}; + bodyData["request"] = {}; + bodyData["request"]["filters"] = {}; + if (gen.utils.checkValidUUID(stateLocationId)) { + bodyData["request"]["filters"]["id"] = stateLocationId; + } else { + bodyData["request"]["filters"]["code"] = stateLocationId; + } + console.log("querybody:",bodyData["request"]["filters"]) + let entityData = await sunbirdService.learnerLocationSearch( bodyData ); + console.log("entityData:",entityData.data.response) + if ( !entityData.data.response.length > 0) { + throw { + message: constants.apiResponses.ENTITIES_NOT_EXIST_IN_LOCATION, + }; + } + console.log("entityData After:",entityData.data.response[0].code) + let entityTypes = []; let stateEntityExists = false; rolesDocument[0].entityTypes.forEach((roleDocument) => { + console.log("inside roleDocument",roleDocument) if (roleDocument.entityType === constants.common.STATE_ENTITY_TYPE) { stateEntityExists = true; } }); - + console.log("******entityTypes",entityTypes) if (stateEntityExists) { entityTypes = [constants.common.STATE_ENTITY_TYPE]; } else { let entitiesMappingForm = await this.entitiesMappingForm( - entitiesData[0]._id, - rolesDocument[0]._id + entityData.data.response[0].code, + rolesDocument[0]._id, + entityKey ); entitiesMappingForm.result.forEach((entitiesMappingData) => { @@ -647,6 +724,68 @@ module.exports = class UsersHelper { message: constants.apiResponses.ENTITY_TYPES_FETCHED, data: entityTypes }); + + //============ + // let filterQuery = { + // "registryDetails.code": stateLocationId, + // }; + + // if (gen.utils.checkValidUUID(stateLocationId)) { + // filterQuery = { + // "registryDetails.locationId": stateLocationId, + // }; + // } + + // const entitiesData = await entitiesHelper.entityDocuments(filterQuery, [ + // "_id", + // ]); + + // if (!entitiesData.length > 0) { + // throw { + // message: constants.apiResponses.ENTITIES_NOT_EXIST_IN_LOCATION, + // }; + // } + // console.log("entitiesData:",entitiesData) + // const rolesDocument = await userRolesHelper.roleDocuments( + // { + // code: role.toUpperCase(), + // }, + // ["_id", "entityTypes.entityType"] + // ); + + // if (!rolesDocument.length > 0) { + // throw { + // message: constants.apiResponses.USER_ROLES_NOT_FOUND + // }; + // } + // console.log("rolesDocument:",rolesDocument) + // let entityTypes = []; + // let stateEntityExists = false; + + // rolesDocument[0].entityTypes.forEach((roleDocument) => { + // if (roleDocument.entityType === constants.common.STATE_ENTITY_TYPE) { + // stateEntityExists = true; + // } + // }); + + // if (stateEntityExists) { + // entityTypes = [constants.common.STATE_ENTITY_TYPE]; + // } else { + // let entitiesMappingForm = await this.entitiesMappingForm( + // entitiesData[0]._id, + // rolesDocument[0]._id + // ); + + // entitiesMappingForm.result.forEach((entitiesMappingData) => { + // entityTypes.push(entitiesMappingData.field); + // }); + // } + + // return resolve({ + // success: true, + // message: constants.apiResponses.ENTITY_TYPES_FETCHED, + // data: entityTypes + // }); } catch (error) { return resolve({ success: false, @@ -655,6 +794,7 @@ module.exports = class UsersHelper { } }); } + /** * User Targeted entity. @@ -668,6 +808,101 @@ module.exports = class UsersHelper { static targetedEntity(solutionId, requestedData) { return new Promise(async (resolve, reject) => { try { + // let solutionData = await solutionsHelper.solutionDocuments( + // { + // _id: solutionId, + // isDeleted: false + // }, + // ["entityType", "type"] + // ); + + // if (!solutionData.length > 0) { + // return resolve({ + // status: httpStatusCode.bad_request.status, + // message: constants.apiResponses.SOLUTION_NOT_FOUND + // }); + // } + // console.log("solutionData:",solutionData) + // let rolesDocument = await userRolesHelper.roleDocuments( + // { + // code: requestedData.role + // }, + // ["entityTypes.entityType"] + // ); + + // if (!rolesDocument.length > 0) { + // throw { + // status: httpStatusCode["bad_request"].status, + // message: constants.apiResponses.USER_ROLES_NOT_FOUND + // }; + // } + + // let requestedEntityTypes = Object.keys(_.omit(requestedData, ['role'])); + // let targetedEntityType = ""; + + // rolesDocument[0].entityTypes.forEach((singleEntityType) => { + // if (requestedEntityTypes.includes(singleEntityType.entityType)) { + // targetedEntityType = singleEntityType.entityType; + // } + // }); + // console.log("targetedEntityType:",targetedEntityType) + // console.log("requestedData[targetedEntityType]:",requestedData[targetedEntityType]) + // if (!requestedData[targetedEntityType]) { + // throw { + // status: httpStatusCode["bad_request"].status, + // message: constants.apiResponses.ENTITIES_NOT_ALLOWED_IN_ROLE + // }; + // } + // console.log("##############") + // if (solutionData[0].entityType === targetedEntityType) { + // let bodyData={}; + // bodyData["request"] = {}; + // bodyData["request"]["filters"] = {}; + // bodyData["request"]["filters"]["parentId"] = ""; + + // if (gen.utils.checkValidUUID(requestedData[targetedEntityType])) { + // bodyData["request"]["filters"]["parentId"] = requestedData[targetedEntityType]; + // } + + // let entitiesData = await sunbirdService.learnerLocationSearch( bodyData ); + // if( entitiesData.count > 0 ){ + // targetedEntityType = constants.common.STATE_ENTITY_TYPE; + // } + // } + // console.log("targetedEntityTypeUpdated:",targetedEntityType) + // let filterData={}; + // filterData["request"] = {}; + // filterData["request"]["filters"] = {}; + + // if (gen.utils.checkValidUUID(requestedData[targetedEntityType])) { + // filterData["request"]["filters"] = { + // "id" : requestedData[targetedEntityType] + // }; + // } else { + // filterData["request"]["filters"] = { + // "code" : requestedData[targetedEntityType] + // }; + // } + + // let entitiesDocument = await sunbirdService.learnerLocationSearch( filterData ); + // if (!entitiesDocument.data.count > 0) { + // throw { + // message: constants.apiResponses.ENTITY_NOT_FOUND + // }; + // } + + // let entityData = entitiesDocument.data.response; + // let entityDataFormated = { + // "_id" : entityData[0].id, + // "entityType" : entityData[0].type, + // "entityName" : entityData[0].name + // } + // console.log("entityDataFormated:",entityDataFormated) + // return resolve({ + // message: constants.apiResponses.SOLUTION_TARGETED_ENTITY, + // success: true, + // data: entityDataFormated + // }); let solutionData = await solutionsHelper.solutionDocuments( { _id: solutionId, @@ -682,7 +917,7 @@ module.exports = class UsersHelper { message: constants.apiResponses.SOLUTION_NOT_FOUND }); } - console.log("solutionData:",solutionData) + let rolesDocument = await userRolesHelper.roleDocuments( { code: requestedData.role @@ -699,69 +934,80 @@ module.exports = class UsersHelper { let requestedEntityTypes = Object.keys(_.omit(requestedData, ['role'])); let targetedEntityType = ""; - + rolesDocument[0].entityTypes.forEach((singleEntityType) => { if (requestedEntityTypes.includes(singleEntityType.entityType)) { targetedEntityType = singleEntityType.entityType; } }); - console.log("targetedEntityType:",targetedEntityType) - console.log("requestedData[targetedEntityType]:",requestedData[targetedEntityType]) + console.log("targetedEntityType :",targetedEntityType) if (!requestedData[targetedEntityType]) { throw { status: httpStatusCode["bad_request"].status, message: constants.apiResponses.ENTITIES_NOT_ALLOWED_IN_ROLE }; } - console.log("##############") + if (solutionData[0].entityType === targetedEntityType) { - let bodyData={}; - bodyData["request"] = {}; - bodyData["request"]["filters"] = {}; - bodyData["request"]["filters"]["parentId"] = ""; - + let filterQuery = { + "registryDetails.code": requestedData[targetedEntityType] + }; + if (gen.utils.checkValidUUID(requestedData[targetedEntityType])) { - bodyData["request"]["filters"]["parentId"] = requestedData[targetedEntityType]; + filterQuery = { + "registryDetails.locationId": requestedData[targetedEntityType] + }; } - - let entitiesData = await sunbirdService.learnerLocationSearch( bodyData ); - if( entitiesData.count > 0 ){ + + let entities = await entitiesHelper.entityDocuments(filterQuery, [ + "groups", + ]); + + if (!entities.length > 0) { + throw { + message: constants.apiResponses.ENTITY_NOT_FOUND + }; + } + + if ( + entities[0] && + entities[0].groups && + Object.keys(entities[0].groups).length > 0 + ) { targetedEntityType = constants.common.STATE_ENTITY_TYPE; - } + } } - console.log("targetedEntityTypeUpdated:",targetedEntityType) - let filterData={}; - filterData["request"] = {}; - filterData["request"]["filters"] = {}; - + + let filterData = { + "registryDetails.code": requestedData[targetedEntityType] + }; + if (gen.utils.checkValidUUID(requestedData[targetedEntityType])) { - filterData["request"]["filters"] = { - "id" : requestedData[targetedEntityType] - }; - } else { - filterData["request"]["filters"] = { - "code" : requestedData[targetedEntityType] + filterData = { + "registryDetails.locationId": requestedData[targetedEntityType] }; } - - let entitiesDocument = await sunbirdService.learnerLocationSearch( filterData ); - if (!entitiesDocument.data.count > 0) { + + let entities = await entitiesHelper.entityDocuments(filterData, [ + "metaInformation.name", + "entityType" + ]); + + if (!entities.length > 0) { throw { message: constants.apiResponses.ENTITY_NOT_FOUND }; } - let entityData = entitiesDocument.data.response; - let entityDataFormated = { - "_id" : entityData[0].id, - "entityType" : entityData[0].type, - "entityName" : entityData[0].name + if (entities[0].metaInformation && entities[0].metaInformation.name) { + entities[0]['entityName'] = entities[0].metaInformation.name; + delete entities[0].metaInformation; } - console.log("entityDataFormated:",entityDataFormated) + return resolve({ message: constants.apiResponses.SOLUTION_TARGETED_ENTITY, success: true, - data: entityDataFormated + data: entities[0] }); } catch (error) { @@ -787,7 +1033,7 @@ module.exports = class UsersHelper { static getHighestTargetedEntity( roleWiseTargetedEntities ) { return new Promise(async (resolve, reject) => { try { - + console.log("roleWiseTargetedEntities:",roleWiseTargetedEntities) let allTargetedEntities = {}; let targetedEntity = {}; @@ -798,13 +1044,14 @@ module.exports = class UsersHelper { if ( !allTargetedEntities.hasOwnProperty(currentEntity._id) ) { allTargetedEntities[currentEntity._id] = new Array(); } + console.log("allTargetedEntities:",allTargetedEntities) //add entity _id if already not there to allTargetedEntities let otherEntities = roleWiseTargetedEntities.filter((entity) => entity.entityType !== currentEntity.entityType); console.log("otherEntities:",otherEntities) if ( !otherEntities || !otherEntities.length > 0 ) { continue; } - console.log("i am here***********") + let entitiesDocument = await entitiesHelper.entityDocuments({ _id: ObjectId(currentEntity._id) }, ["groups"]); @@ -812,26 +1059,28 @@ module.exports = class UsersHelper { if ( !entitiesDocument || !entitiesDocument.length > 0 ) { continue; } - console.log("i am on next ***********") + entitiesDocument = entitiesDocument[0]; for( let entityCounter = 0 ; entityCounter < otherEntities.length ; entityCounter++ ) { let entityDoc = otherEntities[entityCounter]; - + console.log("entityDoc:",entityDoc) if ( !entitiesDocument.groups || !entitiesDocument.groups.hasOwnProperty(entityDoc.entityType) ) { + console.log(entityDoc.entityType,"entity type not exists") break; } allTargetedEntities[currentEntity._id].push(true); - + console.log("allTargetedEntities in entity counter:",allTargetedEntities) if ( allTargetedEntities[currentEntity._id].length == otherEntities.length ) { targetedEntity = roleWiseTargetedEntities.filter((entity) => entity._id == currentEntity._id); break; } + console.log("targetedEntity in entity counter:",targetedEntity) } - + } - + console.log("targetedEntity in entity counter:",targetedEntity) return resolve({ message: constants.apiResponses.SOLUTION_TARGETED_ENTITY, success: true, From 6810779caba8597acac7ee57f56b54a0127e2ab6 Mon Sep 17 00:00:00 2001 From: rakeshSgr Date: Wed, 9 Mar 2022 12:33:43 +0530 Subject: [PATCH 108/331] program dashboard changes --- module/user-extension/helper.js | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/module/user-extension/helper.js b/module/user-extension/helper.js index 60d2f347..6a6095d9 100644 --- a/module/user-extension/helper.js +++ b/module/user-extension/helper.js @@ -571,7 +571,13 @@ module.exports = class UserExtensionHelper { } for( let program = 0; program < currentRole.programs.length;program++) { - programMapToRole[currentRole.programs[program].toString()] = currentRole.code; + + if(programMapToRole[currentRole.programs[program].toString()] && programMapToRole[currentRole.programs[program].toString()].length > 0){ + programMapToRole[currentRole.programs[program].toString()].push(currentRole.code); + }else { + programMapToRole[currentRole.programs[program].toString()] = [currentRole.code]; + } + programIds.push(currentRole.programs[program]); } From d738948f6fd69612a4a45df599ab4598842c5a0d Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Wed, 9 Mar 2022 12:55:26 +0530 Subject: [PATCH 109/331] user solutions list fix --- module/users/helper.js | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/module/users/helper.js b/module/users/helper.js index 143a9ec6..5e8aaa08 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -452,8 +452,7 @@ module.exports = class UsersHelper {   return solution.referenceFrom == constants.common.PROJECT && solution.type == constants.common.OBSERVATION; }); - totalCount = autoTargetedSolutions.data.data.count; - + totalCount = autoTargetedSolutions.data.data.length; mergedData = autoTargetedSolutions.data.data; mergedData = mergedData.map((targetedData, index) => { @@ -476,10 +475,22 @@ module.exports = class UsersHelper { // Add projectId to the solution object if the user has already started a project for the improvement project solution. if (importedProjects.success) { if (importedProjects.data && importedProjects.data.length > 0) { + importedProjects.data.forEach((importedProject) => { - if(projectSolutionIdIndexMap[importedProject.solutionInformation._id]) { + + if( projectSolutionIdIndexMap[importedProject.solutionInformation._id] ) { mergedData[projectSolutionIdIndexMap[importedProject.solutionInformation._id]].projectId = importedProject._id; + } else { + + let data = importedProject.solutionInformation; + data['projectTemplateId'] = importedProject.projectTemplateId; + data['projectId'] = importedProject._id; + data["type"] = constants.common.IMPROVEMENT_PROJECT; + mergedData.push(data); + totalCount = totalCount + 1; + } + }); } } From 3c8f6bc4e0437b6a34814ab431495a9ca7453bb4 Mon Sep 17 00:00:00 2001 From: Akash Shah Date: Wed, 9 Mar 2022 13:26:15 +0530 Subject: [PATCH 110/331] Revert "program dashboard changes" --- module/user-extension/helper.js | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/module/user-extension/helper.js b/module/user-extension/helper.js index 6a6095d9..60d2f347 100644 --- a/module/user-extension/helper.js +++ b/module/user-extension/helper.js @@ -571,13 +571,7 @@ module.exports = class UserExtensionHelper { } for( let program = 0; program < currentRole.programs.length;program++) { - - if(programMapToRole[currentRole.programs[program].toString()] && programMapToRole[currentRole.programs[program].toString()].length > 0){ - programMapToRole[currentRole.programs[program].toString()].push(currentRole.code); - }else { - programMapToRole[currentRole.programs[program].toString()] = [currentRole.code]; - } - + programMapToRole[currentRole.programs[program].toString()] = currentRole.code; programIds.push(currentRole.programs[program]); } From 809ed10749d282ad9e3bce8ec267309ea0bbcce0 Mon Sep 17 00:00:00 2001 From: rakeshSgr Date: Wed, 9 Mar 2022 13:50:27 +0530 Subject: [PATCH 111/331] programsByPlatformRoles api changes --- module/user-extension/helper.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/module/user-extension/helper.js b/module/user-extension/helper.js index 6a6095d9..72bb7db7 100644 --- a/module/user-extension/helper.js +++ b/module/user-extension/helper.js @@ -571,7 +571,6 @@ module.exports = class UserExtensionHelper { } for( let program = 0; program < currentRole.programs.length;program++) { - if(programMapToRole[currentRole.programs[program].toString()] && programMapToRole[currentRole.programs[program].toString()].length > 0){ programMapToRole[currentRole.programs[program].toString()].push(currentRole.code); }else { @@ -584,6 +583,8 @@ module.exports = class UserExtensionHelper { } } + console.log("programMapToRole",programMapToRole); + const programData = await programsHelper.programDocuments({ _id: {$in: programIds}, status: constants.common.ACTIVE From bebc4f33a82254d41b8d5f9bde935694596c2b2b Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 11 Mar 2022 09:46:38 +0530 Subject: [PATCH 112/331] eG comments and console need to remove --- controllers/v1/entities.js | 2 +- controllers/v1/users.js | 5 +- generics/constants/common.js | 4 +- generics/services/sunbird.js | 66 ++-- module/entities/helper.js | 9 +- module/solutions/helper.js | 566 ++++++++++++++++++++--------------- module/users/helper.js | 409 +++++++++++++------------ 7 files changed, 602 insertions(+), 459 deletions(-) diff --git a/controllers/v1/entities.js b/controllers/v1/entities.js index e5b18ea8..d2c42955 100644 --- a/controllers/v1/entities.js +++ b/controllers/v1/entities.js @@ -156,7 +156,7 @@ module.exports = class Entities extends Abstract { return new Promise(async (resolve, reject) => { console.log("request : ",req.params._id, req.body.entities) - //if condition is not working + if( !(req.params._id || req.body.entities) ) { return resolve({ status : httpStatusCode.bad_request.status, diff --git a/controllers/v1/users.js b/controllers/v1/users.js index a6ecc915..c7ae76f3 100644 --- a/controllers/v1/users.js +++ b/controllers/v1/users.js @@ -502,7 +502,7 @@ module.exports = class Users extends Abstract { async targetedEntity(req) { return new Promise(async (resolve, reject) => { try { - console.log("request : ", req.params._id,req.body) + let roleArray = req.body.role.split(","); let targetedEntities = {}; @@ -556,7 +556,7 @@ module.exports = class Users extends Abstract { else if ( roleWiseTargetedEntities && roleWiseTargetedEntities.length > 1 ) { let targetedEntity = await usersHelper.getHighestTargetedEntity( - roleWiseTargetedEntities + roleWiseTargetedEntities, req.body ); if ( !targetedEntity.data ) { @@ -573,7 +573,6 @@ module.exports = class Users extends Abstract { return resolve(targetedEntities); } catch (error) { - console.log(error) return reject({ status: error.status || httpStatusCode.internal_server_error.status, message: error.message || httpStatusCode.internal_server_error.message, diff --git a/generics/constants/common.js b/generics/constants/common.js index 2dcbaa99..734e5886 100644 --- a/generics/constants/common.js +++ b/generics/constants/common.js @@ -67,5 +67,7 @@ module.exports = { "DISCOVERED_BY_ME" : "discoveredByMe", "DEFAULT_SUBMISSION_REQUIRED" : 1, "SCHOOL" : "school", - "SUBENTITY" :"subEntity_" + "SUBENTITY" :"subEntity_", + "SUNBIRD_SERVER_TIMEOUT" : 5000, + "TIMEOUT_ERROR" : "Server timeout error" }; diff --git a/generics/services/sunbird.js b/generics/services/sunbird.js index 9e49e032..7c1d9357 100644 --- a/generics/services/sunbird.js +++ b/generics/services/sunbird.js @@ -24,38 +24,43 @@ const learnerLocationSearch = function ( bodyData ) { return new Promise(async (resolve, reject) => { try { - const url = - sunbirdBaseUrl + constants.endpoints.GET_LOCATION_DATA; - const options = { - headers : { - "Authorization" : process.env.SUNBIRD_SERVICE_AUTHERIZATION, - "content-type": "application/json" - }, - json : bodyData - }; - - request.post(url,options,kendraCallback); - - function kendraCallback(err, data) { - - let result = { - success : true - }; - - if (err) { - result.success = false; - } else { + const url = + sunbirdBaseUrl + constants.endpoints.GET_LOCATION_DATA; + const options = { + headers : { + "Authorization" : process.env.SUNBIRD_SERVICE_AUTHERIZATION, + "content-type": "application/json" + }, + json : bodyData + }; + + request.post(url,options,kendraCallback); + + function kendraCallback(err, data) { + + let result = { + success : true + }; + + if (err) { + result.success = false; + } else { - let response = data.body; + let response = data.body; - if( response.responseCode === constants.common.OK) { - result["data"] = response.result; - } else { + if( response.responseCode === constants.common.OK) { + result["data"] = response.result; + } else { result.success = false; - } - } - return resolve(result); - } + } + } + return resolve(result); + } + + setTimeout(function () { + return reject (constants.common.TIMEOUT_ERROR) + }, constants.common.SUNBIRD_SERVER_TIMEOUT); + } catch (error) { return reject(error); @@ -115,6 +120,9 @@ const formRead = function ( subTypeData ) { } return resolve(result); } + setTimeout(function () { + return reject (constants.common.TIMEOUT_ERROR) + }, constants.common.SUNBIRD_SERVER_TIMEOUT); } catch (error) { return reject(error); diff --git a/module/entities/helper.js b/module/entities/helper.js index 7acb27f6..35fa87de 100644 --- a/module/entities/helper.js +++ b/module/entities/helper.js @@ -144,7 +144,7 @@ module.exports = class EntitiesHelper { } } ]); - + console.log("entityDocuments : ",entityDocuments) return resolve(entityDocuments); } catch (error) { @@ -295,7 +295,7 @@ module.exports = class EntitiesHelper { immediateEntities = searchImmediateData[0]; } } - + console.log("immediateEntities : ",immediateEntities) return resolve(immediateEntities); } catch(error) { @@ -322,6 +322,7 @@ module.exports = class EntitiesHelper { try { console.log("req in helper : ",entities,entityId,type,search,limit,pageNo) + let result = []; let obj = { entityId : entityId, @@ -330,7 +331,7 @@ module.exports = class EntitiesHelper { limit : limit, pageNo : pageNo } - + if ( entityId !== "" ) { result = await this.subEntities( obj @@ -396,7 +397,7 @@ module.exports = class EntitiesHelper { entitiesData.pageNo ); } else { - + //type is empty call learner search with parentId entitiesDocument = await this.immediateEntities( entitiesData.entityId, entitiesData.search, diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 4091b35c..9af0e5cd 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -5,7 +5,7 @@ * Description : Solution related helper functionality. */ -const { header } = require("express-validator/check"); + // Dependencies @@ -117,7 +117,7 @@ module.exports = class SolutionsHelper { message : constants.apiResponses.PROGRAM_NOT_FOUND } } - console.log("programData:",programData) + console.log(programData,"programData") solutionData.programId = programData[0]._id; solutionData.programName = programData[0].name; solutionData.programDescription = programData[0].description; @@ -197,7 +197,6 @@ module.exports = class SolutionsHelper { console.log("bodyData :",bodyData) let entitiesDetails = await sunbirdService.learnerLocationSearch( bodyData ); - console.log("entitiesDetails:",entitiesDetails) let entitiesData = entitiesDetails.data.response; if( !entitiesData.length > 0 ) { throw { @@ -207,7 +206,6 @@ module.exports = class SolutionsHelper { entitiesData = entitiesData.map( entity => { return entity.id; }) - console.log("entitiesData:",entitiesData) solutionData.entities = entitiesData; } @@ -285,6 +283,158 @@ module.exports = class SolutionsHelper { console.log("data reached here") try { + let programData = + await programsHelper.programDocuments({ _id : programId },["_id","scope"]); + + if( !programData.length > 0 ) { + return resolve({ + status : httpStatusCode.bad_request.status, + message : constants.apiResponses.PROGRAM_NOT_FOUND + }); + } + console.log(programData,"programData") + let solutionData = await this.solutionDocuments({ _id : solutionId },["_id"]); + + if( !solutionData.length > 0 ) { + return resolve({ + status : httpStatusCode.bad_request.status, + message : constants.apiResponses.SOLUTION_NOT_FOUND + }); + } + if( programData[0].scope ) { + + let currentSolutionScope = JSON.parse(JSON.stringify(programData[0].scope)); + console.log("currentSolutionScope",currentSolutionScope) + if( Object.keys(scopeData).length > 0 ) { + //if scope data passed with request body + if( scopeData.entityType ) { + currentSolutionScope.entityType = scopeData.entityType; + } + console.log(" currentSolutionScope.entityType:", currentSolutionScope.entityType); + if( scopeData.entities && scopeData.entities.length > 0 ) { + let bodyData={}; + bodyData["request"] = {}; + bodyData["request"]["filters"] = {}; + let entityLocationIds = []; + scopeData.entities.forEach(entity => { + if (gen.utils.checkValidUUID(entity)) { + entityLocationIds.push(entity); + } + }); + bodyData["request"]["filters"]["id"] = entityLocationIds; + console.log(" bodyData:", bodyData["request"]["filters"]) + let entityDetails = await sunbirdService.learnerLocationSearch(bodyData); + if( !entityDetails.data.response.length > 0 ) { + return resolve({ + status : httpStatusCode.bad_request.status, + message : constants.apiResponses.ENTITIES_NOT_FOUND + }); + } + console.log("Data from learner:",entityDetails.data.response) + let entityData = entityDetails.data.response; + let entities = []; + entityData.map(entity => { + console.log("entity inside map:",entity.type); + if( entity.type == currentSolutionScope.entityType ) { + entities.push(entity.id) + } + }) + console.log("entityData to check from:",entities) + if( !entities.length > 0 ) { + return resolve({ + status : httpStatusCode.bad_request.status, + message : constants.apiResponses.ENTITIES_NOT_FOUND + }); + } + + let entityIds = []; + //check from here + console.log("inside the condition") + if( currentSolutionScope.entityType !== programData[0].scope.entityType ) { + let matchData = []; + console.log("inside the condition 1:",currentSolutionScope.entityType ,currentSolutionScope.entities) + let childList = await entitiesInParent(currentSolutionScope.entities,currentSolutionScope.entityType,matchData); + console.log("childList : ",childList.length); + if( childList.length > 0) { + for( let entitiesIndex = 0; entitiesIndex < entities.length; entitiesIndex++ ) { + for( let childListIndex = 0; childListIndex < childList.length; childListIndex++) { + if( childList[childListIndex] == entities[entitiesIndex]){ + entityIds.push(entities[entitiesIndex]); + entitiesIndex++; + } + } + } + } + console.log("entityIds : ",entityIds); + + } else { + console.log("inside the condition+___++++") + entityIds = entities.map(entity => { + return entity._id; + }) + } + + if( !entityIds.length > 0 ) { + + return resolve({ + status : httpStatusCode.bad_request.status, + message : constants.apiResponses.SCOPE_ENTITY_INVALID + }); + + } + + currentSolutionScope.entities = entityIds; + } + + if( scopeData.roles ) { + if( Array.isArray(scopeData.roles) && scopeData.roles.length > 0 ) { + + let userRoles = await userRolesHelper.roleDocuments({ + code : { $in : scopeData.roles } + },["_id","code"]); + + if( !userRoles.length > 0 ) { + return resolve({ + status : httpStatusCode.bad_request.status, + message : constants.apiResponses.INVALID_ROLE_CODE + }); + } + + currentSolutionScope["roles"] = userRoles; + + } else { + if( scopeData.roles === constants.common.ALL_ROLES ) { + currentSolutionScope["roles"] = [{ + "code" : constants.common.ALL_ROLES + }]; + } + } + } + } + console.log("currentSolutionScope:",currentSolutionScope) + console.log("currentSolutionScope After:",currentSolutionScope) + let updateSolution = + await database.models.solutions.findOneAndUpdate( + { + _id : solutionId + }, + { $set : { scope : currentSolutionScope }},{ new: true } + ).lean(); + + if( !updateSolution._id ) { + throw { + status : constants.apiResponses.SOLUTION_SCOPE_NOT_ADDED + }; + } + solutionData = updateSolution; + + } + + return resolve({ + success : true, + message : constants.apiResponses.SOLUTION_UPDATED + }); +//----------------------------------------------------------------------------------- // let programData = // await programsHelper.programDocuments({ _id : programId },["_id","scope"]); @@ -312,72 +462,57 @@ module.exports = class SolutionsHelper { // if( Object.keys(scopeData).length > 0 ) { // if( scopeData.entityType ) { - // currentSolutionScope.entityType = scopeData.entityType; + + // let entityType = await entityTypesHelper.entityTypesDocument( + // { + // name : scopeData.entityType + // }, + // ["name","_id"] + // ); + + // currentSolutionScope.entityType = entityType[0].name; + // //remove entity type id + // currentSolutionScope.entityTypeId = entityType[0]._id; + // } - // console.log(" currentSolutionScope.entityType:", currentSolutionScope.entityType); + // if( scopeData.entities && scopeData.entities.length > 0 ) { - // let bodyData={}; - // bodyData["request"] = {}; - // bodyData["request"]["filters"] = {}; - // let entityLocationIds = []; - // scopeData.entities.forEach(entity => { - // if (gen.utils.checkValidUUID(entity)) { - // entityLocationIds.push(entity); - // } - // }); - // bodyData["request"]["filters"]["id"] = entityLocationIds; - // console.log(" bodyData:", bodyData["request"]["filters"]) - // let entityDetails = await sunbirdService.learnerLocationSearch(bodyData); - // if( !entityDetails.data.response.length > 0 ) { - // return resolve({ - // status : httpStatusCode.bad_request.status, - // message : constants.apiResponses.ENTITIES_NOT_FOUND - // }); - // } - // console.log("Data from learner:",entityDetails.data.response) - // let entityData = entityDetails.data.response; - // let entities = []; - // entityData.map(entity => { - // console.log("entity inside map:",entity.type); - // if( entity.type == currentSolutionScope.entityType ) { - // entities.push(entity.id) - // } - // }) - // console.log ("entityData:",entities.length) + + // //get all entity details from learner api + // let entities = + // await entitiesHelper.entityDocuments( + // { + // _id : { $in : scopeData.entities }, + // entityTypeId : currentSolutionScope.entityTypeId + // },["_id"] + // ); + // console.log ("entities:",entities) // if( !entities.length > 0 ) { // return resolve({ // status : httpStatusCode.bad_request.status, // message : constants.apiResponses.ENTITIES_NOT_FOUND // }); // } - - // let entityIds = []; - // //check from here - // console.log("inside the condition") - // if( currentSolutionScope.entityType !== programData[0].scope.entityType ) { - // console.log("inside the condition 1:",currentSolutionScope.entityType ,currentSolutionScope.entities) - // entitiesInParent(currentSolutionScope.entities,currentSolutionScope.entityType); - - - - - // for( let entity = 0; entity < entities.length; entity ++ ) { - // let entityQuery = { - // _id : { $in : currentSolutionScope.entities }, - // [`groups.${currentSolutionScope.entityType}`] : entities[entity]._id - // } - - // let entityInParent = - // await entitiesHelper.entityDocuments(entityQuery); - - // if( entityInParent.length > 0 ) { - // entityIds.push(ObjectId(entities[entity]._id)); - // } - // } + // let entityIds = []; + // console.log("condition data:",currentSolutionScope.entityType, programData[0].scope.entityType) + // if( currentSolutionScope.entityType !== programData[0].scope.entityType ) { + // for( let entity = 0; entity < entities.length; entity ++ ) { + + // let entityQuery = { + // _id : { $in : currentSolutionScope.entities }, + // [`groups.${currentSolutionScope.entityType}`] : entities[entity]._id + // } + // console.log("query:",entityQuery) + // let entityInParent = + // await entitiesHelper.entityDocuments(entityQuery); + // console.log("entityInParent:",entityInParent); + // if( entityInParent.length > 0 ) { + // entityIds.push(ObjectId(entities[entity]._id)); + // } + // } // } else { - // console.log("inside the condition") // entityIds = entities.map(entity => { // return ObjectId(entity._id); // }) @@ -457,164 +592,6 @@ module.exports = class SolutionsHelper { // success : true, // message : constants.apiResponses.SOLUTION_UPDATED // }); -//----------------------------------------------------------------------------------- - let programData = - await programsHelper.programDocuments({ _id : programId },["_id","scope"]); - - if( !programData.length > 0 ) { - return resolve({ - status : httpStatusCode.bad_request.status, - message : constants.apiResponses.PROGRAM_NOT_FOUND - }); - } - - let solutionData = await this.solutionDocuments({ _id : solutionId },["_id"]); - - if( !solutionData.length > 0 ) { - return resolve({ - status : httpStatusCode.bad_request.status, - message : constants.apiResponses.SOLUTION_NOT_FOUND - }); - } - console.log("programData[0].scope:",programData[0].scope) - console.log("scopeData",scopeData) - if( programData[0].scope ) { - - let currentSolutionScope = JSON.parse(JSON.stringify(programData[0].scope)); - - if( Object.keys(scopeData).length > 0 ) { - - if( scopeData.entityType ) { - - let entityType = await entityTypesHelper.entityTypesDocument( - { - name : scopeData.entityType - }, - ["name","_id"] - ); - - currentSolutionScope.entityType = entityType[0].name; - //remove entity type id - currentSolutionScope.entityTypeId = entityType[0]._id; - - } - - if( scopeData.entities && scopeData.entities.length > 0 ) { - - //get all entity details from learner api - let entities = - await entitiesHelper.entityDocuments( - { - _id : { $in : scopeData.entities }, - entityTypeId : currentSolutionScope.entityTypeId - },["_id"] - ); - console.log ("entities:",entities) - if( !entities.length > 0 ) { - return resolve({ - status : httpStatusCode.bad_request.status, - message : constants.apiResponses.ENTITIES_NOT_FOUND - }); - } - - let entityIds = []; - console.log("condition data:",currentSolutionScope.entityType, programData[0].scope.entityType) - if( currentSolutionScope.entityType !== programData[0].scope.entityType ) { - for( let entity = 0; entity < entities.length; entity ++ ) { - - let entityQuery = { - _id : { $in : currentSolutionScope.entities }, - [`groups.${currentSolutionScope.entityType}`] : entities[entity]._id - } - console.log("query:",entityQuery) - let entityInParent = - await entitiesHelper.entityDocuments(entityQuery); - console.log("entityInParent:",entityInParent); - if( entityInParent.length > 0 ) { - entityIds.push(ObjectId(entities[entity]._id)); - } - } - - } else { - entityIds = entities.map(entity => { - return ObjectId(entity._id); - }) - } - - if( !entityIds.length > 0 ) { - - return resolve({ - status : httpStatusCode.bad_request.status, - message : constants.apiResponses.SCOPE_ENTITY_INVALID - }); - - } - - currentSolutionScope.entities = entityIds; - } - - if( scopeData.roles ) { - if( Array.isArray(scopeData.roles) && scopeData.roles.length > 0 ) { - - let userRoles = await userRolesHelper.roleDocuments({ - code : { $in : scopeData.roles } - },["_id","code"]); - - if( !userRoles.length > 0 ) { - return resolve({ - status : httpStatusCode.bad_request.status, - message : constants.apiResponses.INVALID_ROLE_CODE - }); - } - - currentSolutionScope["roles"] = userRoles; - - } else { - if( scopeData.roles === constants.common.ALL_ROLES ) { - currentSolutionScope["roles"] = [{ - "code" : constants.common.ALL_ROLES - }]; - } - } - } - } - console.log("currentSolutionScope:",currentSolutionScope) - if( currentSolutionScope && currentSolutionScope.entities.length > 0 ){ - console.log("**************inside") - let entitiesIds = currentSolutionScope.entities; - console.log("entitiesIds:",entitiesIds) - for( let eachEntity in entitiesIds ) { - if( entitiesIds[eachEntity].toString() == entitiesIds[eachEntity] ) { - entitiesIds[eachEntity] = ObjectId(entitiesIds[eachEntity]); - } - } - console.log("currentSolutionScope After:",entitiesIds) - delete currentSolutionScope.entities; - currentSolutionScope["entities"] = entitiesIds; - - } - console.log("currentSolutionScope After:",currentSolutionScope) - let updateSolution = - await database.models.solutions.findOneAndUpdate( - { - _id : solutionId - }, - { $set : { scope : currentSolutionScope }},{ new: true } - ).lean(); - - if( !updateSolution._id ) { - throw { - status : constants.apiResponses.SOLUTION_SCOPE_NOT_ADDED - }; - } - solutionData = updateSolution; - - } - - return resolve({ - success : true, - message : constants.apiResponses.SOLUTION_UPDATED - }); } catch (error) { return resolve({ @@ -2167,6 +2144,108 @@ module.exports = class SolutionsHelper { }); } + /** + * get entitiesData of matching type by recursion. + * @method + * @name entitiesInParent + * @returns {Array} - Entities matching the type under the parent. + */ + + static matchingTypeEntities( solutionEntities,currentEntityType,matchingData ){ + return new Promise ( async (resolve, reject)=>{ + try{ + console.log("######################inside recursive parent:",matchingData) + + let mismatchEntities = []; + let bodyData={}; + bodyData["request"] = {}; + bodyData["request"]["filters"] = {}; + bodyData["request"]["filters"]["parentId"] = solutionEntities; + console.log(" bodyData inside recursive fn : ", bodyData["request"]["filters"]) + console.log("array entities : ",matchingData.length) + let entityDetails = await sunbirdService.learnerLocationSearch(bodyData); + if( !entityDetails.data.response.length > 0 && !entities.length > 0 ) { + return ({ + status : httpStatusCode.bad_request.status, + message : constants.apiResponses.ENTITIES_NOT_FOUND + }); + } + console.log("Data from learner inside recursion:",entityDetails.data.response.length) + let entityData = entityDetails.data.response; + //let mismatchEntities = []; + entityData.map(entity => { + //console.log("entity inside map:",entity.type); + if( entity.type == currentEntityType ) { + matchingData.push(entity.id) + }else { + mismatchEntities.push(entity.id) + } + }); + console.log("mismatchEntities:",mismatchEntities.length) + if( mismatchEntities.length > 0 ){ + console.log("+++++++caling recursion") + await matchingTypeEntities(mismatchEntities,currentEntityType,matchingData) + } + + return resolve (matchingData); + // console.log(typeof (entities)) + // if (typeof entities === 'undefined' || !Array.isArray(entities)) { + // console.log("############yeeeaah") + // var entities = []; + // } else { + // console.log("############noooo") + // entities = entities; + // } + + // console.log(typeof (entities)) + // console.log("Array Entities : ",entities.length) + // let bodyData={}; + // bodyData["request"] = {}; + // bodyData["request"]["filters"] = {}; + // bodyData["request"]["filters"]["parentId"] = solutionEntities; + + // console.log(" bodyData inside recursive fn : ", solutionEntities.length) + // let entityDetails = await sunbirdService.learnerLocationSearch(bodyData); + // if( !entityDetails.data.response.length > 0 && !entities.length > 0 ) { + // return resolve({ + // status : httpStatusCode.bad_request.status, + // message : constants.apiResponses.ENTITIES_NOT_FOUND + // }); + // } + // console.log("Data from learner inside recursion:",entityDetails.data.response) + // let entityData = entityDetails.data.response; + // //entities = ( typeof entities != 'undefined' && entities instanceof Array ) ? entities : []; + // let mismatchEntities = []; + // entityData.map(entity => { + // if( entity.type == currentEntityType ) { + // entities.push(entity.id) + // } else { + // mismatchEntities.push(entity.id) + // } + // }); + // console.log("mismatchEntities:",mismatchEntities.length) + // console.log("Real data length:",entities.length); + // if( !mismatchEntities.length > 0 ){ + // console.log("send data length:",entities.length); + // return resolve(entities); + // }else{ + // await this.matchingTypeEntities(mismatchEntities,currentEntityType) + // } + + + } catch(err) { + console.log("error : ",err) + return resolve({ + success : false + }); + } + }); + } + + + + + }; /** @@ -2211,45 +2290,60 @@ function _generateLink(appsPortalBaseUrl, prefix, solutionLink, solutionType) { } -/** - * get entitiesData of matching type by recursion. - * @method - * @name entitiesInParent - * @returns {Array} - Entities matching the type under the parent. - */ - -async function entitiesInParent( solutionEntities,currentEntityType ){ - //console.log("inside recursive function : ",solutionEntities,currentEntityType) +// /** +// * get entitiesData of matching type by recursion. +// * @method +// * @name entitiesInParent +// * @returns {Array} - Entities matching the type under the parent. +// */ + +async function entitiesInParent( solutionEntities,currentEntityType,matchingData ){ + //console.log("inside recursive function : ",matchingData) + //console.log("inside recursive function solutionEntities: ",solutionEntities) + if( !solutionEntities.length > 0 ){ + return matchingData; + } let bodyData={}; bodyData["request"] = {}; bodyData["request"]["filters"] = {}; bodyData["request"]["filters"]["parentId"] = solutionEntities; - //console.log(" bodyData:", bodyData["request"]["filters"]) + //console.log(" bodyData inside recursive fn : ", bodyData["request"]["filters"]) + //let entities = []; + //entities = ( typeof entities != 'undefined' && entities instanceof Array ) ? entities : [] + //console.log("array entities : ",matchingData.length) let entityDetails = await sunbirdService.learnerLocationSearch(bodyData); - if( !entityDetails.data.response.length > 0 ) { - return resolve({ + if( !entityDetails.data.response.length > 0 && !entities.length > 0 ) { + return ({ status : httpStatusCode.bad_request.status, message : constants.apiResponses.ENTITIES_NOT_FOUND }); } //console.log("Data from learner inside recursion:",entityDetails.data.response) let entityData = entityDetails.data.response; - //let entities = []; - entities = ( typeof entities != 'undefined' && entities instanceof Array ) ? entities : [] + + let mismatchEntities = []; entityData.map(entity => { //console.log("entity inside map:",entity.type); if( entity.type == currentEntityType ) { - entities.push(entity.id) + matchingData.push(entity.id) + //if (matchingData.includes(entity.type) === false) matchingData.push(entity.type); } else { mismatchEntities.push(entity.id) } }); console.log("mismatchEntities:",mismatchEntities.length) + console.log("matching---------:",matchingData.length) if( mismatchEntities.length > 0 ){ - entitiesInParent(mismatchEntities,currentEntityType) - } - console.log("matched entities:",entities.length); + console.log("++++recursive calling") + await entitiesInParent(mismatchEntities,currentEntityType,matchingData) + } + let uniqueEntities = []; + matchingData.map( data => { + if (uniqueEntities.includes(data) === false) uniqueEntities.push(data); + }); + return uniqueEntities; -} + + } \ No newline at end of file diff --git a/module/users/helper.js b/module/users/helper.js index 0a6543a3..6e1bad85 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -808,101 +808,6 @@ module.exports = class UsersHelper { static targetedEntity(solutionId, requestedData) { return new Promise(async (resolve, reject) => { try { - // let solutionData = await solutionsHelper.solutionDocuments( - // { - // _id: solutionId, - // isDeleted: false - // }, - // ["entityType", "type"] - // ); - - // if (!solutionData.length > 0) { - // return resolve({ - // status: httpStatusCode.bad_request.status, - // message: constants.apiResponses.SOLUTION_NOT_FOUND - // }); - // } - // console.log("solutionData:",solutionData) - // let rolesDocument = await userRolesHelper.roleDocuments( - // { - // code: requestedData.role - // }, - // ["entityTypes.entityType"] - // ); - - // if (!rolesDocument.length > 0) { - // throw { - // status: httpStatusCode["bad_request"].status, - // message: constants.apiResponses.USER_ROLES_NOT_FOUND - // }; - // } - - // let requestedEntityTypes = Object.keys(_.omit(requestedData, ['role'])); - // let targetedEntityType = ""; - - // rolesDocument[0].entityTypes.forEach((singleEntityType) => { - // if (requestedEntityTypes.includes(singleEntityType.entityType)) { - // targetedEntityType = singleEntityType.entityType; - // } - // }); - // console.log("targetedEntityType:",targetedEntityType) - // console.log("requestedData[targetedEntityType]:",requestedData[targetedEntityType]) - // if (!requestedData[targetedEntityType]) { - // throw { - // status: httpStatusCode["bad_request"].status, - // message: constants.apiResponses.ENTITIES_NOT_ALLOWED_IN_ROLE - // }; - // } - // console.log("##############") - // if (solutionData[0].entityType === targetedEntityType) { - // let bodyData={}; - // bodyData["request"] = {}; - // bodyData["request"]["filters"] = {}; - // bodyData["request"]["filters"]["parentId"] = ""; - - // if (gen.utils.checkValidUUID(requestedData[targetedEntityType])) { - // bodyData["request"]["filters"]["parentId"] = requestedData[targetedEntityType]; - // } - - // let entitiesData = await sunbirdService.learnerLocationSearch( bodyData ); - // if( entitiesData.count > 0 ){ - // targetedEntityType = constants.common.STATE_ENTITY_TYPE; - // } - // } - // console.log("targetedEntityTypeUpdated:",targetedEntityType) - // let filterData={}; - // filterData["request"] = {}; - // filterData["request"]["filters"] = {}; - - // if (gen.utils.checkValidUUID(requestedData[targetedEntityType])) { - // filterData["request"]["filters"] = { - // "id" : requestedData[targetedEntityType] - // }; - // } else { - // filterData["request"]["filters"] = { - // "code" : requestedData[targetedEntityType] - // }; - // } - - // let entitiesDocument = await sunbirdService.learnerLocationSearch( filterData ); - // if (!entitiesDocument.data.count > 0) { - // throw { - // message: constants.apiResponses.ENTITY_NOT_FOUND - // }; - // } - - // let entityData = entitiesDocument.data.response; - // let entityDataFormated = { - // "_id" : entityData[0].id, - // "entityType" : entityData[0].type, - // "entityName" : entityData[0].name - // } - // console.log("entityDataFormated:",entityDataFormated) - // return resolve({ - // message: constants.apiResponses.SOLUTION_TARGETED_ENTITY, - // success: true, - // data: entityDataFormated - // }); let solutionData = await solutionsHelper.solutionDocuments( { _id: solutionId, @@ -917,7 +822,6 @@ module.exports = class UsersHelper { message: constants.apiResponses.SOLUTION_NOT_FOUND }); } - let rolesDocument = await userRolesHelper.roleDocuments( { code: requestedData.role @@ -934,81 +838,170 @@ module.exports = class UsersHelper { let requestedEntityTypes = Object.keys(_.omit(requestedData, ['role'])); let targetedEntityType = ""; - + rolesDocument[0].entityTypes.forEach((singleEntityType) => { if (requestedEntityTypes.includes(singleEntityType.entityType)) { targetedEntityType = singleEntityType.entityType; } }); - console.log("targetedEntityType :",targetedEntityType) if (!requestedData[targetedEntityType]) { throw { status: httpStatusCode["bad_request"].status, message: constants.apiResponses.ENTITIES_NOT_ALLOWED_IN_ROLE }; } - if (solutionData[0].entityType === targetedEntityType) { - let filterQuery = { - "registryDetails.code": requestedData[targetedEntityType] - }; - + let bodyData={}; + bodyData["request"] = {}; + bodyData["request"]["filters"] = {}; + bodyData["request"]["filters"]["parentId"] = ""; + if (gen.utils.checkValidUUID(requestedData[targetedEntityType])) { - filterQuery = { - "registryDetails.locationId": requestedData[targetedEntityType] - }; + bodyData["request"]["filters"]["parentId"] = requestedData[targetedEntityType]; } - - let entities = await entitiesHelper.entityDocuments(filterQuery, [ - "groups", - ]); - - if (!entities.length > 0) { - throw { - message: constants.apiResponses.ENTITY_NOT_FOUND - }; - } - - if ( - entities[0] && - entities[0].groups && - Object.keys(entities[0].groups).length > 0 - ) { + + let entitiesData = await sunbirdService.learnerLocationSearch( bodyData ); + if( entitiesData.count > 0 ){ targetedEntityType = constants.common.STATE_ENTITY_TYPE; - } + } } - - let filterData = { - "registryDetails.code": requestedData[targetedEntityType] - }; - + let filterData={}; + filterData["request"] = {}; + filterData["request"]["filters"] = {}; + if (gen.utils.checkValidUUID(requestedData[targetedEntityType])) { - filterData = { - "registryDetails.locationId": requestedData[targetedEntityType] + filterData["request"]["filters"] = { + "id" : requestedData[targetedEntityType] + }; + } else { + filterData["request"]["filters"] = { + "code" : requestedData[targetedEntityType] }; } - - let entities = await entitiesHelper.entityDocuments(filterData, [ - "metaInformation.name", - "entityType" - ]); - - if (!entities.length > 0) { + let entitiesDocument = await sunbirdService.learnerLocationSearch( filterData ); + if (!entitiesDocument.data.count > 0) { throw { message: constants.apiResponses.ENTITY_NOT_FOUND }; } - if (entities[0].metaInformation && entities[0].metaInformation.name) { - entities[0]['entityName'] = entities[0].metaInformation.name; - delete entities[0].metaInformation; + let entityData = entitiesDocument.data.response; + let entityDataFormated = { + "_id" : entityData[0].id, + "entityType" : entityData[0].type, + "entityName" : entityData[0].name } - return resolve({ message: constants.apiResponses.SOLUTION_TARGETED_ENTITY, success: true, - data: entities[0] + data: entityDataFormated }); + // let solutionData = await solutionsHelper.solutionDocuments( + // { + // _id: solutionId, + // isDeleted: false + // }, + // ["entityType", "type"] + // ); + + // if (!solutionData.length > 0) { + // return resolve({ + // status: httpStatusCode.bad_request.status, + // message: constants.apiResponses.SOLUTION_NOT_FOUND + // }); + // } + + // let rolesDocument = await userRolesHelper.roleDocuments( + // { + // code: requestedData.role + // }, + // ["entityTypes.entityType"] + // ); + + // if (!rolesDocument.length > 0) { + // throw { + // status: httpStatusCode["bad_request"].status, + // message: constants.apiResponses.USER_ROLES_NOT_FOUND + // }; + // } + + // let requestedEntityTypes = Object.keys(_.omit(requestedData, ['role'])); + // let targetedEntityType = ""; + + // rolesDocument[0].entityTypes.forEach((singleEntityType) => { + // if (requestedEntityTypes.includes(singleEntityType.entityType)) { + // targetedEntityType = singleEntityType.entityType; + // } + // }); + // console.log("targetedEntityType :",targetedEntityType) + // if (!requestedData[targetedEntityType]) { + // throw { + // status: httpStatusCode["bad_request"].status, + // message: constants.apiResponses.ENTITIES_NOT_ALLOWED_IN_ROLE + // }; + // } + + // if (solutionData[0].entityType === targetedEntityType) { + // let filterQuery = { + // "registryDetails.code": requestedData[targetedEntityType] + // }; + + // if (gen.utils.checkValidUUID(requestedData[targetedEntityType])) { + // filterQuery = { + // "registryDetails.locationId": requestedData[targetedEntityType] + // }; + // } + + // let entities = await entitiesHelper.entityDocuments(filterQuery, [ + // "groups", + // ]); + + // if (!entities.length > 0) { + // throw { + // message: constants.apiResponses.ENTITY_NOT_FOUND + // }; + // } + + // if ( + // entities[0] && + // entities[0].groups && + // Object.keys(entities[0].groups).length > 0 + // ) { + // targetedEntityType = constants.common.STATE_ENTITY_TYPE; + // } + // } + + // let filterData = { + // "registryDetails.code": requestedData[targetedEntityType] + // }; + + // if (gen.utils.checkValidUUID(requestedData[targetedEntityType])) { + // filterData = { + // "registryDetails.locationId": requestedData[targetedEntityType] + // }; + // } + + // let entities = await entitiesHelper.entityDocuments(filterData, [ + // "metaInformation.name", + // "entityType" + // ]); + + // if (!entities.length > 0) { + // throw { + // message: constants.apiResponses.ENTITY_NOT_FOUND + // }; + // } + + // if (entities[0].metaInformation && entities[0].metaInformation.name) { + // entities[0]['entityName'] = entities[0].metaInformation.name; + // delete entities[0].metaInformation; + // } + + // return resolve({ + // message: constants.apiResponses.SOLUTION_TARGETED_ENTITY, + // success: true, + // data: entities[0] + // }); } catch (error) { return resolve({ @@ -1030,62 +1023,108 @@ module.exports = class UsersHelper { * @returns {Object} - Entity. */ - static getHighestTargetedEntity( roleWiseTargetedEntities ) { + static getHighestTargetedEntity( roleWiseTargetedEntities,requestedData ) { return new Promise(async (resolve, reject) => { try { - console.log("roleWiseTargetedEntities:",roleWiseTargetedEntities) - let allTargetedEntities = {}; - let targetedEntity = {}; + let entityKey = constants.common.SUBENTITY + requestedData.state; + let subEntities = await cache.getValue(entityKey); + if( !subEntities.length > 0 ) { + let bodyData={}; + bodyData["request"] = {}; + bodyData["request"]["filters"] = {}; + bodyData["request"]["filters"]["id"] = requestedData.state; - for( let pointerToEntities = 0 ; pointerToEntities < roleWiseTargetedEntities.length ; pointerToEntities++ ) { - - let currentEntity = roleWiseTargetedEntities[pointerToEntities]; - console.log("currentEntity:",currentEntity) - if ( !allTargetedEntities.hasOwnProperty(currentEntity._id) ) { - allTargetedEntities[currentEntity._id] = new Array(); - } - console.log("allTargetedEntities:",allTargetedEntities) - //add entity _id if already not there to allTargetedEntities - let otherEntities = roleWiseTargetedEntities.filter((entity) => entity.entityType !== currentEntity.entityType); - console.log("otherEntities:",otherEntities) - if ( !otherEntities || !otherEntities.length > 0 ) { - continue; - } - - let entitiesDocument = await entitiesHelper.entityDocuments({ - _id: ObjectId(currentEntity._id) - }, ["groups"]); + let entitiesData = await sunbirdService.learnerLocationSearch( bodyData ); - if ( !entitiesDocument || !entitiesDocument.length > 0 ) { - continue; - } - - entitiesDocument = entitiesDocument[0]; - for( let entityCounter = 0 ; entityCounter < otherEntities.length ; entityCounter++ ) { - - let entityDoc = otherEntities[entityCounter]; - console.log("entityDoc:",entityDoc) - if ( !entitiesDocument.groups || !entitiesDocument.groups.hasOwnProperty(entityDoc.entityType) ) { - console.log(entityDoc.entityType,"entity type not exists") - break; + if( !entitiesData.data.response.length > 0 ) { + return resolve({ + message : constants.apiResponses.ENTITY_NOT_FOUND, + result : [] + }) } - - allTargetedEntities[currentEntity._id].push(true); - console.log("allTargetedEntities in entity counter:",allTargetedEntities) - if ( allTargetedEntities[currentEntity._id].length == otherEntities.length ) { - targetedEntity = roleWiseTargetedEntities.filter((entity) => entity._id == currentEntity._id); - break; + let stateLocationCode = entitiesData.data.response[0].code; + subEntities = await formService.formData( stateLocationCode,entityKey ); + if( !subEntities.length > 0 ) { + return resolve({ + message : constants.apiResponses.ENTITY_NOT_FOUND, + result : [] + }) + } + } + let targetedIndex = subEntities.length; + let roleWiseTarget; + for( let roleWiseEntityIndex = 0; roleWiseEntityIndex < roleWiseTargetedEntities.length; roleWiseEntityIndex++ ) { + for( let subEntitiesIndex = 0; subEntitiesIndex < subEntities.length; subEntitiesIndex++ ) { + if( roleWiseTargetedEntities[roleWiseEntityIndex].entityType == subEntities[subEntitiesIndex] ) { + if( subEntitiesIndex < targetedIndex) { + targetedIndex = subEntitiesIndex; + roleWiseTarget = roleWiseEntityIndex; + } } - console.log("targetedEntity in entity counter:",targetedEntity) } - } - console.log("targetedEntity in entity counter:",targetedEntity) + + let targetedEntity = roleWiseTargetedEntities[roleWiseTarget]; return resolve({ message: constants.apiResponses.SOLUTION_TARGETED_ENTITY, success: true, data: targetedEntity }); + + + // console.log("roleWiseTargetedEntities:",roleWiseTargetedEntities) + // let allTargetedEntities = {}; + // let targetedEntity = {}; + + // for( let pointerToEntities = 0 ; pointerToEntities < roleWiseTargetedEntities.length ; pointerToEntities++ ) { + + // let currentEntity = roleWiseTargetedEntities[pointerToEntities]; + // console.log("currentEntity:",currentEntity) + // if ( !allTargetedEntities.hasOwnProperty(currentEntity._id) ) { + // allTargetedEntities[currentEntity._id] = new Array(); + // } + // console.log("allTargetedEntities:",allTargetedEntities) + // //add entity _id if already not there to allTargetedEntities + // let otherEntities = roleWiseTargetedEntities.filter((entity) => entity.entityType !== currentEntity.entityType); + // console.log("otherEntities:",otherEntities) + // if ( !otherEntities || !otherEntities.length > 0 ) { + // continue; + // } + + // let entitiesDocument = await entitiesHelper.entityDocuments({ + // _id: ObjectId(currentEntity._id) + // }, ["groups"]); + + // if ( !entitiesDocument || !entitiesDocument.length > 0 ) { + // continue; + // } + + // entitiesDocument = entitiesDocument[0]; + // for( let entityCounter = 0 ; entityCounter < otherEntities.length ; entityCounter++ ) { + + // let entityDoc = otherEntities[entityCounter]; + // console.log("entityDoc:",entityDoc) + // if ( !entitiesDocument.groups || !entitiesDocument.groups.hasOwnProperty(entityDoc.entityType) ) { + // console.log(entityDoc.entityType,"entity type not exists") + // break; + // } + + // allTargetedEntities[currentEntity._id].push(true); + // console.log("allTargetedEntities in entity counter:",allTargetedEntities) + // if ( allTargetedEntities[currentEntity._id].length == otherEntities.length ) { + // targetedEntity = roleWiseTargetedEntities.filter((entity) => entity._id == currentEntity._id); + // break; + // } + // console.log("targetedEntity in entity counter:",targetedEntity) + // } + + // } + // console.log("targetedEntity in entity counter:",targetedEntity) + // return resolve({ + // message: constants.apiResponses.SOLUTION_TARGETED_ENTITY, + // success: true, + // data: targetedEntity + // }); } catch (error) { return resolve({ From 4438dafb4bf2378034a437eac509885cf2a2b6d8 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Wed, 16 Mar 2022 13:27:59 +0530 Subject: [PATCH 113/331] eG changes march 16 --- controllers/v1/entities.js | 6 +- generics/services/sunbird.js | 1 - module/entities/helper.js | 373 +++++++++++++++++++++++++---------- module/solutions/helper.js | 149 +++++++++++--- 4 files changed, 394 insertions(+), 135 deletions(-) diff --git a/controllers/v1/entities.js b/controllers/v1/entities.js index d2c42955..624edc4f 100644 --- a/controllers/v1/entities.js +++ b/controllers/v1/entities.js @@ -152,11 +152,9 @@ module.exports = class Entities extends Abstract { */ subEntityList(req) { - + return new Promise(async (resolve, reject) => { - console.log("request : ",req.params._id, req.body.entities) - - + if( !(req.params._id || req.body.entities) ) { return resolve({ status : httpStatusCode.bad_request.status, diff --git a/generics/services/sunbird.js b/generics/services/sunbird.js index 7c1d9357..b044d388 100644 --- a/generics/services/sunbird.js +++ b/generics/services/sunbird.js @@ -130,7 +130,6 @@ const formRead = function ( subTypeData ) { }) } - module.exports = { learnerLocationSearch : learnerLocationSearch, formRead : formRead diff --git a/module/entities/helper.js b/module/entities/helper.js index 35fa87de..9dbcf11e 100644 --- a/module/entities/helper.js +++ b/module/entities/helper.js @@ -104,7 +104,7 @@ module.exports = class EntitiesHelper { queryObject["$match"]["_id"] = {}; queryObject["$match"]["_id"]["$in"] = entityIds; } - + console.log("query inside search : ",queryObject) if( searchText !== "") { queryObject["$match"]["$or"] = [ { "metaInformation.name": new RegExp(searchText, 'i') }, @@ -144,7 +144,7 @@ module.exports = class EntitiesHelper { } } ]); - console.log("entityDocuments : ",entityDocuments) + console.log("entityDocuments : ",entityDocuments.result) return resolve(entityDocuments); } catch (error) { @@ -244,59 +244,102 @@ module.exports = class EntitiesHelper { return new Promise(async (resolve, reject) => { try { + let bodyData={}; + bodyData["request"] = {}; + bodyData["request"]["filters"] = {}; + bodyData["request"]["filters"]["parentId"] = entityId; - let projection = [ - constants.schema.ENTITYTYPE, - constants.schema.GROUPS - ]; - - let entitiesDocument = await this.entityDocuments({ - _id: entityId - }, projection); + let entitiesData = await sunbirdService.learnerLocationSearch( bodyData ); + + if( !entitiesData.data.response.length > 0 ) { + return resolve(entitiesData.data.response) + } + + let immediateLocation = entitiesData.data.response; + + if( searchText !== "" ){ + let matchEntities = []; + immediateLocation.map( entityData => { + if( entityData.name.match(new RegExp(searchText, 'i')) || entityData.code.match(new RegExp("^" + searchText, 'm')) ) { + matchEntities.push(entityData) + } + }); + immediateLocation = []; + immediateLocation = matchEntities; + } + + let formatedEntities = []; + + immediateLocation.map( entityData => { + let data = {}; + data._id = entityData.id; + data.entityType = entityData.type; + data.name = entityData.name; + data.externalId = entityData.code; + data.label = entityData.name; + data.value = entityData.id + formatedEntities.push(data) + } ); + + immediateLocation = []; + immediateLocation = formatedEntities; + + return resolve(immediateLocation); + + + + // let projection = [ + // constants.schema.ENTITYTYPE, + // constants.schema.GROUPS + // ]; - let immediateEntities = []; + // let entitiesDocument = await this.entityDocuments({ + // _id: entityId + // }, projection); - if (entitiesDocument[0] && - entitiesDocument[0].groups && - Object.keys(entitiesDocument[0].groups).length > 0 - ) { + // let immediateEntities = []; - let getImmediateEntityTypes = - await entityTypesHelper.entityTypesDocument({ - name : entitiesDocument[0].entityType - },["immediateChildrenEntityType"] - ); + // if (entitiesDocument[0] && + // entitiesDocument[0].groups && + // Object.keys(entitiesDocument[0].groups).length > 0 + // ) { - let immediateEntitiesIds; + // let getImmediateEntityTypes = + // await entityTypesHelper.entityTypesDocument({ + // name : entitiesDocument[0].entityType + // },["immediateChildrenEntityType"] + // ); - Object.keys(entitiesDocument[0].groups).forEach(entityGroup => { - if ( - getImmediateEntityTypes[0].immediateChildrenEntityType && - getImmediateEntityTypes[0].immediateChildrenEntityType.length > 0 && - getImmediateEntityTypes[0].immediateChildrenEntityType.includes(entityGroup) - ) { - immediateEntitiesIds = - entitiesDocument[0].groups[entityGroup]; - } - }) + // let immediateEntitiesIds; - if ( - Array.isArray(immediateEntitiesIds) && - immediateEntitiesIds.length > 0 - ) { + // Object.keys(entitiesDocument[0].groups).forEach(entityGroup => { + // if ( + // getImmediateEntityTypes[0].immediateChildrenEntityType && + // getImmediateEntityTypes[0].immediateChildrenEntityType.length > 0 && + // getImmediateEntityTypes[0].immediateChildrenEntityType.includes(entityGroup) + // ) { + // immediateEntitiesIds = + // entitiesDocument[0].groups[entityGroup]; + // } + // }) + // console.log("Immediate entities before : ",immediateEntitiesIds) + // if ( + // Array.isArray(immediateEntitiesIds) && + // immediateEntitiesIds.length > 0 + // ) { - let searchImmediateData = await this.search( - searchText, - pageSize, - pageNo, - immediateEntitiesIds - ); + // let searchImmediateData = await this.search( + // searchText, + // pageSize, + // pageNo, + // immediateEntitiesIds + // ); - immediateEntities = searchImmediateData[0]; - } - } - console.log("immediateEntities : ",immediateEntities) - return resolve(immediateEntities); + // immediateEntities = searchImmediateData[0]; + // } + // } + // console.log("immediateEntities : ",immediateEntities) + // return resolve(immediateEntities); } catch(error) { return reject(error); @@ -321,46 +364,58 @@ module.exports = class EntitiesHelper { return new Promise(async (resolve, reject) => { try { - console.log("req in helper : ",entities,entityId,type,search,limit,pageNo) - let result = []; + let result = {}; + let aggregateEntitiesData = []; + let uniqueEntities = []; let obj = { entityId : entityId, type : type, - search : search, - limit : limit, - pageNo : pageNo + search : search } if ( entityId !== "" ) { - result = await this.subEntities( + uniqueEntities = await this.subEntities( obj ); } else { - await Promise.all(entities.map(async (entity)=> { obj["entityId"] = entity; let entitiesDocument = await this.subEntities( obj ); - - if( Array.isArray(entitiesDocument.data) && - entitiesDocument.data.length > 0 + if( Array.isArray(entitiesDocument) && + entitiesDocument.length > 0 ) { - result = entitiesDocument; - } + entitiesDocument.forEach(entityData => { + aggregateEntitiesData.push(entityData); + }); + } })); + aggregateEntitiesData.map( data => { + if (uniqueEntities.includes(data) === false) uniqueEntities.push(data); + }); } - - if( result.data && result.data.length > 0 ) { - result.data = result.data.map(data=>{ - let cloneData = {...data}; - cloneData["label"] = cloneData.name; - cloneData["value"] = cloneData._id; - return cloneData; - }) + + let totalcount = uniqueEntities.length; + if (uniqueEntities.length > 0) { + let startIndex = limit * (pageNo - 1); + let endIndex = startIndex + limit; + uniqueEntities = uniqueEntities.slice(startIndex, endIndex); } + result.data = uniqueEntities; + result.count = totalcount; + + + // if( result.data && result.data.length > 0 ) { + // result.data = result.data.map(data=>{ + // let cloneData = {...data}; + // cloneData["label"] = cloneData.name; + // cloneData["value"] = cloneData._id; + // return cloneData; + // }) + // } resolve({ message: constants.apiResponses.ENTITIES_FETCHED, @@ -384,29 +439,45 @@ module.exports = class EntitiesHelper { return new Promise(async (resolve, reject) => { try { - console.log("#entitiesData : ",entitiesData) + let entitiesDocument; - + if( entitiesData.type !== "" ) { entitiesDocument = await this.entityTraversal( entitiesData.entityId, entitiesData.type, - entitiesData.search, - entitiesData.limit, - entitiesData.pageNo + entitiesData.search ); } else { - //type is empty call learner search with parentId entitiesDocument = await this.immediateEntities( entitiesData.entityId, - entitiesData.search, - entitiesData.limit, - entitiesData.pageNo + entitiesData.search ); } - return resolve(entitiesDocument); + + // if( entitiesData.type !== "" ) { + + // entitiesDocument = await this.entityTraversal( + // entitiesData.entityId, + // entitiesData.type, + // entitiesData.search, + // entitiesData.limit, + // entitiesData.pageNo + // ); + // } else { + // console.log("working in else part") + // //type is empty call learner search with parentId + // entitiesDocument = await this.immediateEntities( + // entitiesData.entityId, + // entitiesData.search, + // entitiesData.limit, + // entitiesData.pageNo + // ); + // } + + } catch(error) { return reject(error); } @@ -424,45 +495,82 @@ module.exports = class EntitiesHelper { static entityTraversal( entityId, entityTraversalType = "", - searchText = "", - pageSize, - pageNo + searchText = "" ) { return new Promise(async (resolve, reject) => { try { - - let entityTraversal = `groups.${entityTraversalType}`; - - let entitiesDocument = - await this.entityDocuments( - { - _id: entityId, - "groups" : { $exists : true }, - [entityTraversal] : { $exists: true } - }, - [ entityTraversal ] - ); - - if( !entitiesDocument[0] ) { - return resolve([]); + let subEntitiesMatchingType = []; + let parentId = []; + parentId.push(entityId); + let subEntities = await subEntitiesWithMatchingType( parentId,entityTraversalType,subEntitiesMatchingType ) + + if( !subEntities.length > 0 ) { + return resolve(subEntities) } - let result = []; + if( searchText !== "" ){ + let matchEntities = []; + subEntities.map( entityData => { + if( entityData.name.match(new RegExp(searchText, 'i')) || entityData.code.match(new RegExp("^" + searchText, 'm')) ) { + matchEntities.push(entityData) + } + }); + subEntities = []; + subEntities = matchEntities; + } + + let formatedEntities = []; + + subEntities.map( entityData => { + let data = {}; + data._id = entityData.id; + data.entityType = entityData.type; + data.name = entityData.name; + data.externalId = entityData.code; + data.label = entityData.name; + data.value = entityData.id + formatedEntities.push(data) + } ); + + subEntities = []; + subEntities = formatedEntities; + + return resolve(subEntities); + - if( entitiesDocument[0].groups[entityTraversalType].length > 0 ) { + + // let entityTraversal = `groups.${entityTraversalType}`; + + // let entitiesDocument = + // await this.entityDocuments( + // { + // _id: entityId, + // "groups" : { $exists : true }, + // [entityTraversal] : { $exists: true } + // }, + // [ entityTraversal ] + // ); + + // if( !entitiesDocument[0] ) { + // return resolve([]); + // } + + // let result = []; + + // if( entitiesDocument[0].groups[entityTraversalType].length > 0 ) { - let entityTraversalData = await this.search( - searchText, - pageSize, - pageNo, - entitiesDocument[0].groups[entityTraversalType] - ); + // let entityTraversalData = await this.search( + // searchText, + // pageSize, + // pageNo, + // entitiesDocument[0].groups[entityTraversalType] + // ); - result = entityTraversalData[0]; + // result = entityTraversalData[0]; - } + // } - return resolve(result); + // return resolve(result); } catch(error) { return reject(error); @@ -849,3 +957,58 @@ module.exports = class EntitiesHelper { } } + +// /** +// * get subEntities of matching type by recursion. +// * @method +// * @name subEntitiesWithMatchingType +// * @returns {Array} - Sub entities matching the type . +// */ + +async function subEntitiesWithMatchingType( parentIds,entityType,matchingData ){ + //console.log("inside recursive function : ",matchingData) + //console.log("inside recursive function solutionEntities: ",parentIds,entityType,matchingData) + if( !parentIds.length > 0 ){ + return matchingData; + } + + let bodyData={}; + bodyData["request"] = {}; + bodyData["request"]["filters"] = {}; + bodyData["request"]["filters"]["parentId"] = parentIds; + //console.log(" bodyData inside recursive fn : ", bodyData["request"]["filters"]) + + let entityDetails = await sunbirdService.learnerLocationSearch(bodyData); + + if( !entityDetails.data.response.length > 0 && !matchingData.length > 0 ) { + return matchingData; + } + //console.log("Data from learner inside recursion:",entityDetails.data.response) + let entityData = entityDetails.data.response; + + + let mismatchEntities = []; + entityData.map(entity => { + //console.log("entity inside map:",entity.type); + if( entity.type == entityType ) { + matchingData.push(entity) + //if (matchingData.includes(entity.type) === false) matchingData.push(entity.type); + } else { + mismatchEntities.push(entity.id) + } + }); + console.log("mismatchEntities:",mismatchEntities.length) + console.log("matching---------:",matchingData.length) + if( mismatchEntities.length > 0 ){ + console.log("++++recursive calling") + await subEntitiesWithMatchingType(mismatchEntities,entityType,matchingData) + } + let uniqueEntities = []; + matchingData.map( data => { + if (uniqueEntities.includes(data) === false) uniqueEntities.push(data); + }); + return uniqueEntities; + + + + } \ No newline at end of file diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 9af0e5cd..85d12cca 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -1031,7 +1031,7 @@ module.exports = class SolutionsHelper { } queryData.data["_id"] = solutionId; - + console.log("queryData : ",queryData) let targetedSolutionDetails = await this.solutionDocuments( queryData.data, @@ -1052,7 +1052,7 @@ module.exports = class SolutionsHelper { "link" ] ); - + console.log("targetedSolutionDetails[0] : ",targetedSolutionDetails[0]) if( !targetedSolutionDetails.length > 0 ) { throw { status : httpStatusCode["bad_request"].status, @@ -1177,7 +1177,6 @@ module.exports = class SolutionsHelper { static addEntitiesInScope( solutionId,entities ) { return new Promise(async (resolve, reject) => { try { - let solutionData = await this.solutionDocuments({ _id : solutionId, @@ -1192,7 +1191,6 @@ module.exports = class SolutionsHelper { message : constants.apiResponses.SOLUTION_NOT_FOUND }); } - let programData = await programsHelper.programDocuments({ _id : solutionData[0].programId },["scope.entities","scope.entityType"]); @@ -1203,14 +1201,26 @@ module.exports = class SolutionsHelper { message : constants.apiResponses.PROGRAM_NOT_FOUND }); } - if( solutionData[0].scope.entityType !== programData[0].scope.entityType ) { - let checkEntityInParent = - await entitiesHelper.entityDocuments({ - _id : programData[0].scope.entities, - [`groups.${solutionData[0].entityType}`] : entities - },["_id"]); + let matchData = []; + let checkEntityInParent = []; + let childList = await entitiesInParent(programData[0].scope.entities,solutionData[0].scope.entityType,matchData); + + if( !childList.length > 0 ) { + throw { + message : constants.apiResponses.ENTITY_NOT_EXISTS_IN_PARENT + } + } + + for( let entitiesIndex = 0; entitiesIndex < entities.length; entitiesIndex++ ) { + for( let childListIndex = 0; childListIndex < childList.length; childListIndex++) { + if( childList[childListIndex] == entities[entitiesIndex]){ + checkEntityInParent.push(entities[entitiesIndex]); + entitiesIndex++; + } + } + } if( !checkEntityInParent.length > 0 ) { throw { @@ -1218,25 +1228,35 @@ module.exports = class SolutionsHelper { } } } + let bodyData={}; + bodyData["request"] = {}; + bodyData["request"]["filters"] = {}; + bodyData["request"]["filters"]["id"] = entities; + + let entitiesDetails = await sunbirdService.learnerLocationSearch( bodyData ); + + if( !entitiesDetails.data.response.length > 0 ) { + return resolve({ + status : httpStatusCode.bad_request.status, + message : constants.apiResponses.ENTITIES_NOT_FOUND + }); + } - let entitiesData = - await entitiesHelper.entityDocuments({ - _id : { $in : entities }, - entityType : solutionData[0].scope.entityType - },["_id"]); + let entitiesData = entitiesDetails.data.response; + let entityIds = []; + + entitiesData.map(entity => { + if( entity.type == solutionData[0].scope.entityType ) { + entityIds.push(entity.id) + } + }); - if( !entitiesData.length > 0 ) { + if( !entityIds.length > 0 ) { throw { message : constants.apiResponses.ENTITIES_NOT_FOUND }; } - let entityIds = []; - - entitiesData.forEach(entity => { - entityIds.push(entity._id); - }); - let updateSolution = await database.models.solutions.findOneAndUpdate({ _id : solutionId },{ @@ -1254,6 +1274,85 @@ module.exports = class SolutionsHelper { success : true }); + // let solutionData = + // await this.solutionDocuments({ + // _id : solutionId, + // scope : { $exists : true }, + // isReusable : false, + // isDeleted : false + // },["_id","programId","scope.entityType"]); + + // if( !solutionData.length > 0 ) { + // return resolve({ + // status : httpStatusCode.bad_request.status, + // message : constants.apiResponses.SOLUTION_NOT_FOUND + // }); + // } + // console.log("solutionData : ",solutionData) + // let programData = await programsHelper.programDocuments({ + // _id : solutionData[0].programId + // },["scope.entities","scope.entityType"]); + + // if( !programData.length > 0 ) { + // return resolve({ + // status : httpStatusCode.bad_request.status, + // message : constants.apiResponses.PROGRAM_NOT_FOUND + // }); + // } + // console.log("programData : ",programData) + // if( solutionData[0].scope.entityType !== programData[0].scope.entityType ) { + // console.log("inside condition") + // console.log("_id ; ",programData[0].scope.entities) + // console.log("group : ",solutionData[0].scope.entityType) + // console.log("entities : ",entities) + // let checkEntityInParent = + // await entitiesHelper.entityDocuments({ + // _id : programData[0].scope.entities, + // [`groups.${solutionData[0].scope.entityType}`] : entities + // },["_id"]); + // console.log("checkEntityInParent : ",checkEntityInParent) + // if( !checkEntityInParent.length > 0 ) { + // throw { + // message : constants.apiResponses.ENTITY_NOT_EXISTS_IN_PARENT + // } + // } + // } + + // let entitiesData = + // await entitiesHelper.entityDocuments({ + // _id : { $in : entities }, + // entityType : solutionData[0].scope.entityType + // },["_id"]); + // console.log("entities data with same type : ",entitiesData) + // if( !entitiesData.length > 0 ) { + // throw { + // message : constants.apiResponses.ENTITIES_NOT_FOUND + // }; + // } + + // let entityIds = []; + + // entitiesData.forEach(entity => { + // entityIds.push(entity._id); + // }); + + // let updateSolution = await database.models.solutions.findOneAndUpdate({ + // _id : solutionId + // },{ + // $addToSet : { "scope.entities" : { $each : entityIds } } + // },{ new : true }).lean(); + + // if( !updateSolution || !updateSolution._id ) { + // throw { + // message : constants.apiResponses.SOLUTION_NOT_UPDATED + // } + // } + + // return resolve({ + // message : constants.apiResponses.ENTITIES_ADDED_IN_SOLUTION, + // success : true + // }); + } catch(error) { return resolve({ success : false, @@ -2299,7 +2398,7 @@ function _generateLink(appsPortalBaseUrl, prefix, solutionLink, solutionType) { async function entitiesInParent( solutionEntities,currentEntityType,matchingData ){ //console.log("inside recursive function : ",matchingData) - //console.log("inside recursive function solutionEntities: ",solutionEntities) + console.log("inside recursive function solutionEntities: ",solutionEntities,currentEntityType,matchingData) if( !solutionEntities.length > 0 ){ return matchingData; } @@ -2307,12 +2406,12 @@ async function entitiesInParent( solutionEntities,currentEntityType,matchingData bodyData["request"] = {}; bodyData["request"]["filters"] = {}; bodyData["request"]["filters"]["parentId"] = solutionEntities; - //console.log(" bodyData inside recursive fn : ", bodyData["request"]["filters"]) + console.log(" bodyData inside recursive fn : ", bodyData["request"]["filters"]) //let entities = []; //entities = ( typeof entities != 'undefined' && entities instanceof Array ) ? entities : [] //console.log("array entities : ",matchingData.length) let entityDetails = await sunbirdService.learnerLocationSearch(bodyData); - if( !entityDetails.data.response.length > 0 && !entities.length > 0 ) { + if( !entityDetails.data.response.length > 0 && !matchingData.length > 0 ) { return ({ status : httpStatusCode.bad_request.status, message : constants.apiResponses.ENTITIES_NOT_FOUND From 5cbb956d3731477a4d86e41d7d178888c64586c2 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Wed, 16 Mar 2022 14:10:55 +0530 Subject: [PATCH 114/331] SB_29227 --- module/users/helper.js | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/module/users/helper.js b/module/users/helper.js index 5e8aaa08..021724de 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -417,7 +417,7 @@ module.exports = class UsersHelper { }, ["name"] ); - + if (!programData.length > 0) { return resolve({ status: httpStatusCode["bad_request"].status, @@ -435,7 +435,7 @@ module.exports = class UsersHelper { constants.common.DEFAULT_PAGE_NO, search ); - + let totalCount = 0; let mergedData = []; @@ -471,24 +471,26 @@ module.exports = class UsersHelper { token, programId ); - + // Add projectId to the solution object if the user has already started a project for the improvement project solution. if (importedProjects.success) { + if (importedProjects.data && importedProjects.data.length > 0) { importedProjects.data.forEach((importedProject) => { + + + if( projectSolutionIdIndexMap[importedProject.solutionInformation._id] !== undefined ) { - if( projectSolutionIdIndexMap[importedProject.solutionInformation._id] ) { + mergedData[projectSolutionIdIndexMap[importedProject.solutionInformation._id]].projectId = importedProject._id; } else { - let data = importedProject.solutionInformation; data['projectTemplateId'] = importedProject.projectTemplateId; data['projectId'] = importedProject._id; data["type"] = constants.common.IMPROVEMENT_PROJECT; mergedData.push(data); totalCount = totalCount + 1; - } }); From 4ff4c95a355bdb3db2fc15abd0c1a7cafd687e3a Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Wed, 16 Mar 2022 14:26:51 +0530 Subject: [PATCH 115/331] program duplicate --- module/users/helper.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/module/users/helper.js b/module/users/helper.js index 5e8aaa08..2497f8e3 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -478,7 +478,7 @@ module.exports = class UsersHelper { importedProjects.data.forEach((importedProject) => { - if( projectSolutionIdIndexMap[importedProject.solutionInformation._id] ) { + if( projectSolutionIdIndexMap[importedProject.solutionInformation._id] !== undefined ) { mergedData[projectSolutionIdIndexMap[importedProject.solutionInformation._id]].projectId = importedProject._id; } else { From aa7fa0309786a91f402f474d3d0fa28219f2d7f6 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 21 Mar 2022 09:46:53 +0530 Subject: [PATCH 116/331] entity generalization monday march22 --- generics/constants/endpoints.js | 3 +- generics/services/sunbird.js | 66 ++++++++++++- module/entities/helper.js | 165 ++++++++++++++++++++++++-------- 3 files changed, 194 insertions(+), 40 deletions(-) diff --git a/generics/constants/endpoints.js b/generics/constants/endpoints.js index 5fe46387..00a48946 100644 --- a/generics/constants/endpoints.js +++ b/generics/constants/endpoints.js @@ -32,5 +32,6 @@ module.exports = { GET_QUESTIONS : "/v1/solutions/questions", GET_OBSERVATION : "/v1/observations/details", GET_LOCATION_DATA : "/api/data/v1/location/search", - GET_FORM_DATA : "/api/data/v1/form/read" + GET_FORM_DATA : "/api/data/v1/form/read", + GET_SCHOOL_DATA : "/api/org/v1/search" } \ No newline at end of file diff --git a/generics/services/sunbird.js b/generics/services/sunbird.js index b044d388..14c7472e 100644 --- a/generics/services/sunbird.js +++ b/generics/services/sunbird.js @@ -10,6 +10,7 @@ const request = require('request'); const sunbirdBaseUrl = process.env.SUNBIRD_SERVICE_URL; +const sunbirdOrgBaseUrl = process.env.SUNBIRD_ORG_URL; /** * @@ -130,7 +131,70 @@ const formRead = function ( subTypeData ) { }) } +/** + * + * @function + * @name schoolData + * @param {String} bearerToken - autherization token. + * @param {object} bodyData - location id + * @returns {Promise} returns a promise. +*/ +const schoolData = function ( locationIds ) { + return new Promise(async (resolve, reject) => { + try { + console.log("locationIds:",locationIds) + let bodyData = { + request : { + filters :{ + "orgLocation.id" : locationIds + } + } + } + console.log("bodyData:",bodyData.request) + const url = + sunbirdBaseUrl + constants.endpoints.GET_SCHOOL_DATA; + const options = { + headers : { + "Authorization" : process.env.SUNBIRD_SERVICE_AUTHERIZATION, + "content-type": "application/json" + }, + json : bodyData + }; + + request.post(url,options,kendraCallback); + + function kendraCallback(err, data) { + + let result = { + success : true + }; + + if (err) { + result.success = false; + } else { + + let response = data.body; + + if( response.responseCode === constants.common.OK) { + result["data"] = response.result; + } else { + result.success = false; + } + } + return resolve(result); + } + setTimeout(function () { + return reject (constants.common.TIMEOUT_ERROR) + }, constants.common.SUNBIRD_SERVER_TIMEOUT); + + } catch (error) { + return reject(error); + } + }) +} + module.exports = { learnerLocationSearch : learnerLocationSearch, - formRead : formRead + formRead : formRead, + schoolData :schoolData }; \ No newline at end of file diff --git a/module/entities/helper.js b/module/entities/helper.js index 9dbcf11e..5e0bfca1 100644 --- a/module/entities/helper.js +++ b/module/entities/helper.js @@ -1,3 +1,5 @@ + + const entityTypesHelper = require(MODULES_BASE_PATH + "/entityTypes/helper"); const userRolesHelper = require(MODULES_BASE_PATH + "/user-roles/helper"); // const elasticSearch = require(GENERIC_HELPERS_PATH + "/elastic-search"); @@ -268,21 +270,21 @@ module.exports = class EntitiesHelper { immediateLocation = matchEntities; } - let formatedEntities = []; + // let formatedEntities = []; - immediateLocation.map( entityData => { - let data = {}; - data._id = entityData.id; - data.entityType = entityData.type; - data.name = entityData.name; - data.externalId = entityData.code; - data.label = entityData.name; - data.value = entityData.id - formatedEntities.push(data) - } ); + // immediateLocation.map( entityData => { + // let data = {}; + // data._id = entityData.id; + // data.entityType = entityData.type; + // data.name = entityData.name; + // data.externalId = entityData.code; + // data.label = entityData.name; + // data.value = entityData.id + // formatedEntities.push(data) + // } ); - immediateLocation = []; - immediateLocation = formatedEntities; + // immediateLocation = []; + // immediateLocation = formatedEntities; return resolve(immediateLocation); @@ -397,6 +399,22 @@ module.exports = class EntitiesHelper { if (uniqueEntities.includes(data) === false) uniqueEntities.push(data); }); } + let formatedEntities = []; + + uniqueEntities.map( entityData => { + let data = {}; + data._id = entityData.id; + data.entityType = entityData.type; + data.name = entityData.name; + data.externalId = entityData.code; + data.label = entityData.name; + data.value = entityData.id + formatedEntities.push(data) + } ); + + uniqueEntities = []; + uniqueEntities = formatedEntities; + let totalcount = uniqueEntities.length; if (uniqueEntities.length > 0) { @@ -499,43 +517,114 @@ module.exports = class EntitiesHelper { ) { return new Promise(async (resolve, reject) => { try { - let subEntitiesMatchingType = []; - let parentId = []; - parentId.push(entityId); - let subEntities = await subEntitiesWithMatchingType( parentId,entityTraversalType,subEntitiesMatchingType ) + let subentitiesData = []; + if( entityTraversalType == constants.common.SCHOOL) { + let subentitiesCode = await sunbirdService.schoolData( entityId ); + let schoolDetails = subentitiesCode.data.response.content; + if( !schoolDetails.length > 0 ) { + return resolve(schoolDetails) + } + //console.log("subentitiesData : ",subentitiesCode.data.response.content) + //get code from all data + let schoolCodes = []; + schoolDetails.map(schoolData=> { + schoolCodes.push(schoolData.externalId); + }); + //console.log("schoolDetails : ",schoolCodes) + + let bodyData={}; + bodyData["request"] = {}; + bodyData["request"]["filters"] = {}; + bodyData["request"]["filters"]["code"] = schoolCodes; + + let entitiesData = await sunbirdService.learnerLocationSearch( bodyData ); + + if( !entitiesData.data.response.length > 0 ) { + return resolve(entitiesData.data.response) + } + + console.log("schoolData : ",entitiesData.data.response.length) + subentitiesData = entitiesData.data.response; + + } else { + let subEntitiesMatchingType = []; + let parentId = []; + parentId.push(entityId); + let subEntities = await subEntitiesWithMatchingType( parentId,entityTraversalType,subEntitiesMatchingType ) - if( !subEntities.length > 0 ) { - return resolve(subEntities) + if( !subEntities.length > 0 ) { + return resolve(subEntities) + } + subentitiesData = subEntities + + } - + console.log("schoolData : ",subentitiesData) if( searchText !== "" ){ let matchEntities = []; - subEntities.map( entityData => { + subentitiesData.map( entityData => { if( entityData.name.match(new RegExp(searchText, 'i')) || entityData.code.match(new RegExp("^" + searchText, 'm')) ) { matchEntities.push(entityData) } }); - subEntities = []; - subEntities = matchEntities; - } + subentitiesData = []; + subentitiesData = matchEntities; + } + // let formatedEntities = []; + + // subentitiesData.map( entityData => { + // let data = {}; + // data._id = entityData.id; + // data.entityType = entityData.type; + // data.name = entityData.name; + // data.externalId = entityData.code; + // data.label = entityData.name; + // data.value = entityData.id + // formatedEntities.push(data) + // } ); + + // subentitiesData = []; + // subentitiesData = formatedEntities; + + return resolve(subentitiesData); + + // let subEntitiesMatchingType = []; + // let parentId = []; + // parentId.push(entityId); + // let subEntities = await subEntitiesWithMatchingType( parentId,entityTraversalType,subEntitiesMatchingType ) + + // if( !subEntities.length > 0 ) { + // return resolve(subEntities) + // } - let formatedEntities = []; + // if( searchText !== "" ){ + // let matchEntities = []; + // subEntities.map( entityData => { + // if( entityData.name.match(new RegExp(searchText, 'i')) || entityData.code.match(new RegExp("^" + searchText, 'm')) ) { + // matchEntities.push(entityData) + // } + // }); + // subEntities = []; + // subEntities = matchEntities; + // } - subEntities.map( entityData => { - let data = {}; - data._id = entityData.id; - data.entityType = entityData.type; - data.name = entityData.name; - data.externalId = entityData.code; - data.label = entityData.name; - data.value = entityData.id - formatedEntities.push(data) - } ); + // let formatedEntities = []; + + // subEntities.map( entityData => { + // let data = {}; + // data._id = entityData.id; + // data.entityType = entityData.type; + // data.name = entityData.name; + // data.externalId = entityData.code; + // data.label = entityData.name; + // data.value = entityData.id + // formatedEntities.push(data) + // } ); - subEntities = []; - subEntities = formatedEntities; + // subEntities = []; + // subEntities = formatedEntities; - return resolve(subEntities); + // return resolve(subEntities); From 82a080c97aa663983ff246aad753cef2d0f92417 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Tue, 22 Mar 2022 18:18:12 +0530 Subject: [PATCH 117/331] eg march 23 --- generics/services/form.js | 3 +- generics/services/sunbird.js | 23 +- module/entities/helper.js | 60 ++--- module/programs/helper.js | 17 +- module/solutions/helper.js | 504 +++-------------------------------- module/users/helper.js | 376 +++----------------------- 6 files changed, 133 insertions(+), 850 deletions(-) diff --git a/generics/services/form.js b/generics/services/form.js index ea9188f4..9df7fb79 100644 --- a/generics/services/form.js +++ b/generics/services/form.js @@ -22,7 +22,7 @@ let cache = require(ROOT_PATH+"/generics/helpers/cache"); const formData = function ( stateLocationCode, entityKey ) { return new Promise(async (resolve, reject) => { try { - console.log("requestData:",stateLocationCode,entityKey) + let subEntitiesDetails = await sunbirdService.formRead( stateLocationCode ); let subEntityData = subEntitiesDetails.data.form.data.fields[1].children.teacher; @@ -36,7 +36,6 @@ const formData = function ( stateLocationCode, entityKey ) { }) } let setCache = cache.setValue(entityKey, subEntities, 43200); - console.log("setCache",setCache) return resolve(subEntities); } catch (error) { diff --git a/generics/services/sunbird.js b/generics/services/sunbird.js index 14c7472e..6b08e490 100644 --- a/generics/services/sunbird.js +++ b/generics/services/sunbird.js @@ -17,13 +17,24 @@ const sunbirdOrgBaseUrl = process.env.SUNBIRD_ORG_URL; * @function * @name learnerLocationSearch * @param {String} bearerToken - autherization token. - * @param {object} bodyData - bodydata . + * @param {object} filterData - bodydata . * @returns {Promise} returns a promise. */ -const learnerLocationSearch = function ( bodyData ) { +const learnerLocationSearch = function ( filterData, limit = "", offset = "" ) { return new Promise(async (resolve, reject) => { try { + + let bodyData={}; + bodyData["request"] = {}; + bodyData["request"]["filters"] = filterData; + if( limit !== "" ) { + bodyData["request"]["limit"] = limit; + } + if( limit !== "" ) { + bodyData["request"]["offset"] = offset; + } + const url = sunbirdBaseUrl + constants.endpoints.GET_LOCATION_DATA; @@ -80,7 +91,7 @@ const learnerLocationSearch = function ( bodyData ) { const formRead = function ( subTypeData ) { return new Promise(async (resolve, reject) => { try { - console.log("subTypeData:",subTypeData) + let bodyData = { request : { type: "profileConfig", @@ -88,7 +99,7 @@ const formRead = function ( subTypeData ) { action: "get" } } - console.log("bodyData:",bodyData.request) + const url = sunbirdBaseUrl + constants.endpoints.GET_FORM_DATA; const options = { @@ -142,7 +153,7 @@ const formRead = function ( subTypeData ) { const schoolData = function ( locationIds ) { return new Promise(async (resolve, reject) => { try { - console.log("locationIds:",locationIds) + let bodyData = { request : { filters :{ @@ -150,7 +161,7 @@ const schoolData = function ( locationIds ) { } } } - console.log("bodyData:",bodyData.request) + const url = sunbirdBaseUrl + constants.endpoints.GET_SCHOOL_DATA; const options = { diff --git a/module/entities/helper.js b/module/entities/helper.js index 5e0bfca1..8cb68671 100644 --- a/module/entities/helper.js +++ b/module/entities/helper.js @@ -106,7 +106,7 @@ module.exports = class EntitiesHelper { queryObject["$match"]["_id"] = {}; queryObject["$match"]["_id"]["$in"] = entityIds; } - console.log("query inside search : ",queryObject) + if( searchText !== "") { queryObject["$match"]["$or"] = [ { "metaInformation.name": new RegExp(searchText, 'i') }, @@ -146,7 +146,7 @@ module.exports = class EntitiesHelper { } } ]); - console.log("entityDocuments : ",entityDocuments.result) + return resolve(entityDocuments); } catch (error) { @@ -246,10 +246,9 @@ module.exports = class EntitiesHelper { return new Promise(async (resolve, reject) => { try { - let bodyData={}; - bodyData["request"] = {}; - bodyData["request"]["filters"] = {}; - bodyData["request"]["filters"]["parentId"] = entityId; + let bodyData={ + "parentId" : entityId + }; let entitiesData = await sunbirdService.learnerLocationSearch( bodyData ); @@ -524,18 +523,18 @@ module.exports = class EntitiesHelper { if( !schoolDetails.length > 0 ) { return resolve(schoolDetails) } - //console.log("subentitiesData : ",subentitiesCode.data.response.content) + //get code from all data let schoolCodes = []; schoolDetails.map(schoolData=> { schoolCodes.push(schoolData.externalId); }); - //console.log("schoolDetails : ",schoolCodes) + - let bodyData={}; - bodyData["request"] = {}; - bodyData["request"]["filters"] = {}; - bodyData["request"]["filters"]["code"] = schoolCodes; + let bodyData={ + "code" : schoolCodes + }; + let entitiesData = await sunbirdService.learnerLocationSearch( bodyData ); @@ -543,7 +542,7 @@ module.exports = class EntitiesHelper { return resolve(entitiesData.data.response) } - console.log("schoolData : ",entitiesData.data.response.length) + subentitiesData = entitiesData.data.response; } else { @@ -559,7 +558,7 @@ module.exports = class EntitiesHelper { } - console.log("schoolData : ",subentitiesData) + if( searchText !== "" ){ let matchEntities = []; subentitiesData.map( entityData => { @@ -900,13 +899,12 @@ module.exports = class EntitiesHelper { } let subEntities = await cache.getValue(entityKey); - console.log("subEntitiesDetails from cache:",subEntities) + if( !subEntities.length > 0 ) { - let bodyData={}; - bodyData["request"] = {}; - bodyData["request"]["filters"] = {}; - bodyData["request"]["filters"]["id"] = stateLocationId; - + let bodyData={ + "id" : stateLocationId + }; + let entitiesData = await sunbirdService.learnerLocationSearch( bodyData ); if( !entitiesData.data.response.length > 0 ) { @@ -1055,41 +1053,37 @@ module.exports = class EntitiesHelper { // */ async function subEntitiesWithMatchingType( parentIds,entityType,matchingData ){ - //console.log("inside recursive function : ",matchingData) - //console.log("inside recursive function solutionEntities: ",parentIds,entityType,matchingData) + if( !parentIds.length > 0 ){ return matchingData; } - let bodyData={}; - bodyData["request"] = {}; - bodyData["request"]["filters"] = {}; - bodyData["request"]["filters"]["parentId"] = parentIds; - //console.log(" bodyData inside recursive fn : ", bodyData["request"]["filters"]) + let bodyData={ + "parentId" : parentIds + }; let entityDetails = await sunbirdService.learnerLocationSearch(bodyData); if( !entityDetails.data.response.length > 0 && !matchingData.length > 0 ) { return matchingData; } - //console.log("Data from learner inside recursion:",entityDetails.data.response) + let entityData = entityDetails.data.response; let mismatchEntities = []; entityData.map(entity => { - //console.log("entity inside map:",entity.type); + if( entity.type == entityType ) { matchingData.push(entity) - //if (matchingData.includes(entity.type) === false) matchingData.push(entity.type); + } else { mismatchEntities.push(entity.id) } }); - console.log("mismatchEntities:",mismatchEntities.length) - console.log("matching---------:",matchingData.length) + if( mismatchEntities.length > 0 ){ - console.log("++++recursive calling") + await subEntitiesWithMatchingType(mismatchEntities,entityType,matchingData) } let uniqueEntities = []; diff --git a/module/programs/helper.js b/module/programs/helper.js index 63b3eee1..d7cd50b6 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -231,17 +231,15 @@ module.exports = class ProgramsHelper { let locationIds = []; let bodyData={}; - bodyData["request"] = {}; - bodyData["request"]["filters"] = {}; - bodyData["request"]["filters"]["id"] = ""; scopeData.entities.forEach(entity=>{ if (gen.utils.checkValidUUID(entity)) { locationIds.push(entity); } }); - - bodyData["request"]["filters"]["id"] = locationIds; + bodyData = { + "id" : locationIds + } let entityData = await sunbirdService.learnerLocationSearch( bodyData ); @@ -731,17 +729,16 @@ module.exports = class ProgramsHelper { let locationIds = []; let bodyData={}; - bodyData["request"] = {}; - bodyData["request"]["filters"] = {}; - bodyData["request"]["filters"]["id"] = ""; - + entities.forEach(entity=>{ if (gen.utils.checkValidUUID(entity)) { locationIds.push(entity); } }); + bodyData = { + "id" : locationIds + } - bodyData["request"]["filters"]["id"] = locationIds; let entitiesData = await sunbirdService.learnerLocationSearch( bodyData ); diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 85d12cca..051e20af 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -117,46 +117,12 @@ module.exports = class SolutionsHelper { message : constants.apiResponses.PROGRAM_NOT_FOUND } } - console.log(programData,"programData") + solutionData.programId = programData[0]._id; solutionData.programName = programData[0].name; solutionData.programDescription = programData[0].description; - // if( solutionData.type == constants.common.COURSE ) { - - // if( !solutionData.link ) { - // return resolve({ - // status : httpStatusCode.bad_request.status, - // message : constants.apiResponses.COURSE_LINK_REQUIRED - // }); - // } - // } else { - - // if( !solutionData.entityType ){ - - // return resolve({ - // status : httpStatusCode.bad_request.status, - // message : constants.apiResponses.ENTITY_TYPE_REQUIRED - // }); - - // } - - // let entityTypeData = - // await entityTypesHelper.entityTypesDocument({ - // name : solutionData.entityType - // },["_id"]); - // console.log("entityTypeData:",entityTypeData) - // if( !entityTypeData.length > 0 ) { - // throw { - // message : constants.apiResponses.ENTITY_TYPES_NOT_FOUND - // } - // } - - // solutionData.entityTypeId = entityTypeData[0]._id; - // } - - - //eG code begining -------------------------- + if( solutionData.type == constants.common.COURSE && !solutionData.link ) { return resolve({ @@ -165,39 +131,16 @@ module.exports = class SolutionsHelper { }); } - //eG code ending -------------------------- - - - // if( solutionData.entities && solutionData.entities.length > 0 ) { - - // let entitiesData = - // await entitiesHelper.entityDocuments({ - // _id : { $in : solutionData.entities } - // },["_id"]); - - // if( !entitiesData.length > 0 ) { - // throw { - // message : constants.apiResponses.ENTITIES_NOT_FOUND - // } - // } - - // entitiesData = entitiesData.map( entity => { - // return entity._id; - // }) - - // solutionData.entities = entitiesData; - // } - - //eG code Start --------------------------- + if( solutionData.entities && solutionData.entities.length > 0 ) { - let bodyData={}; - bodyData["request"] = {}; - bodyData["request"]["filters"] = {}; - bodyData["request"]["filters"]["id"] = solutionData.entities; - console.log("bodyData :",bodyData) + let bodyData={ + "id" : solutionData.entities + }; + let entitiesDetails = await sunbirdService.learnerLocationSearch( bodyData ); let entitiesData = entitiesDetails.data.response; + if( !entitiesData.length > 0 ) { throw { message : constants.apiResponses.ENTITIES_NOT_FOUND @@ -210,8 +153,6 @@ module.exports = class SolutionsHelper { } - //eG code Ends --------------------------- - if( solutionData.minNoOfSubmissionsRequired && solutionData.minNoOfSubmissionsRequired > constants.common.DEFAULT_SUBMISSION_REQUIRED ) { @@ -280,7 +221,6 @@ module.exports = class SolutionsHelper { static setScope( programId,solutionId,scopeData ) { return new Promise(async (resolve, reject) => { - console.log("data reached here") try { let programData = @@ -292,7 +232,7 @@ module.exports = class SolutionsHelper { message : constants.apiResponses.PROGRAM_NOT_FOUND }); } - console.log(programData,"programData") + let solutionData = await this.solutionDocuments({ _id : solutionId },["_id"]); if( !solutionData.length > 0 ) { @@ -304,25 +244,24 @@ module.exports = class SolutionsHelper { if( programData[0].scope ) { let currentSolutionScope = JSON.parse(JSON.stringify(programData[0].scope)); - console.log("currentSolutionScope",currentSolutionScope) + if( Object.keys(scopeData).length > 0 ) { //if scope data passed with request body if( scopeData.entityType ) { currentSolutionScope.entityType = scopeData.entityType; } - console.log(" currentSolutionScope.entityType:", currentSolutionScope.entityType); + if( scopeData.entities && scopeData.entities.length > 0 ) { - let bodyData={}; - bodyData["request"] = {}; - bodyData["request"]["filters"] = {}; let entityLocationIds = []; scopeData.entities.forEach(entity => { if (gen.utils.checkValidUUID(entity)) { entityLocationIds.push(entity); } }); - bodyData["request"]["filters"]["id"] = entityLocationIds; - console.log(" bodyData:", bodyData["request"]["filters"]) + let bodyData = { + "id" : entityLocationIds + }; + let entityDetails = await sunbirdService.learnerLocationSearch(bodyData); if( !entityDetails.data.response.length > 0 ) { return resolve({ @@ -330,16 +269,16 @@ module.exports = class SolutionsHelper { message : constants.apiResponses.ENTITIES_NOT_FOUND }); } - console.log("Data from learner:",entityDetails.data.response) + let entityData = entityDetails.data.response; let entities = []; entityData.map(entity => { - console.log("entity inside map:",entity.type); + if( entity.type == currentSolutionScope.entityType ) { entities.push(entity.id) } }) - console.log("entityData to check from:",entities) + if( !entities.length > 0 ) { return resolve({ status : httpStatusCode.bad_request.status, @@ -348,13 +287,11 @@ module.exports = class SolutionsHelper { } let entityIds = []; - //check from here - console.log("inside the condition") + if( currentSolutionScope.entityType !== programData[0].scope.entityType ) { let matchData = []; - console.log("inside the condition 1:",currentSolutionScope.entityType ,currentSolutionScope.entities) let childList = await entitiesInParent(currentSolutionScope.entities,currentSolutionScope.entityType,matchData); - console.log("childList : ",childList.length); + if( childList.length > 0) { for( let entitiesIndex = 0; entitiesIndex < entities.length; entitiesIndex++ ) { for( let childListIndex = 0; childListIndex < childList.length; childListIndex++) { @@ -365,13 +302,11 @@ module.exports = class SolutionsHelper { } } } - console.log("entityIds : ",entityIds); - - } else { - console.log("inside the condition+___++++") - entityIds = entities.map(entity => { - return entity._id; - }) + + } else { + entityIds = entities.map(entity => { + return entity._id; + }); } if( !entityIds.length > 0 ) { @@ -411,8 +346,7 @@ module.exports = class SolutionsHelper { } } } - console.log("currentSolutionScope:",currentSolutionScope) - console.log("currentSolutionScope After:",currentSolutionScope) + let updateSolution = await database.models.solutions.findOneAndUpdate( { @@ -434,164 +368,6 @@ module.exports = class SolutionsHelper { success : true, message : constants.apiResponses.SOLUTION_UPDATED }); -//----------------------------------------------------------------------------------- - // let programData = - // await programsHelper.programDocuments({ _id : programId },["_id","scope"]); - - // if( !programData.length > 0 ) { - // return resolve({ - // status : httpStatusCode.bad_request.status, - // message : constants.apiResponses.PROGRAM_NOT_FOUND - // }); - // } - - // let solutionData = await this.solutionDocuments({ _id : solutionId },["_id"]); - - // if( !solutionData.length > 0 ) { - // return resolve({ - // status : httpStatusCode.bad_request.status, - // message : constants.apiResponses.SOLUTION_NOT_FOUND - // }); - // } - // console.log("programData[0].scope:",programData[0].scope) - // console.log("scopeData",scopeData) - // if( programData[0].scope ) { - - // let currentSolutionScope = JSON.parse(JSON.stringify(programData[0].scope)); - - // if( Object.keys(scopeData).length > 0 ) { - - // if( scopeData.entityType ) { - - // let entityType = await entityTypesHelper.entityTypesDocument( - // { - // name : scopeData.entityType - // }, - // ["name","_id"] - // ); - - // currentSolutionScope.entityType = entityType[0].name; - // //remove entity type id - // currentSolutionScope.entityTypeId = entityType[0]._id; - - // } - - // if( scopeData.entities && scopeData.entities.length > 0 ) { - - // //get all entity details from learner api - // let entities = - // await entitiesHelper.entityDocuments( - // { - // _id : { $in : scopeData.entities }, - // entityTypeId : currentSolutionScope.entityTypeId - // },["_id"] - // ); - // console.log ("entities:",entities) - // if( !entities.length > 0 ) { - // return resolve({ - // status : httpStatusCode.bad_request.status, - // message : constants.apiResponses.ENTITIES_NOT_FOUND - // }); - // } - - // let entityIds = []; - // console.log("condition data:",currentSolutionScope.entityType, programData[0].scope.entityType) - // if( currentSolutionScope.entityType !== programData[0].scope.entityType ) { - // for( let entity = 0; entity < entities.length; entity ++ ) { - - // let entityQuery = { - // _id : { $in : currentSolutionScope.entities }, - // [`groups.${currentSolutionScope.entityType}`] : entities[entity]._id - // } - // console.log("query:",entityQuery) - // let entityInParent = - // await entitiesHelper.entityDocuments(entityQuery); - // console.log("entityInParent:",entityInParent); - // if( entityInParent.length > 0 ) { - // entityIds.push(ObjectId(entities[entity]._id)); - // } - // } - - // } else { - // entityIds = entities.map(entity => { - // return ObjectId(entity._id); - // }) - // } - - // if( !entityIds.length > 0 ) { - - // return resolve({ - // status : httpStatusCode.bad_request.status, - // message : constants.apiResponses.SCOPE_ENTITY_INVALID - // }); - - // } - - // currentSolutionScope.entities = entityIds; - // } - - // if( scopeData.roles ) { - // if( Array.isArray(scopeData.roles) && scopeData.roles.length > 0 ) { - - // let userRoles = await userRolesHelper.roleDocuments({ - // code : { $in : scopeData.roles } - // },["_id","code"]); - - // if( !userRoles.length > 0 ) { - // return resolve({ - // status : httpStatusCode.bad_request.status, - // message : constants.apiResponses.INVALID_ROLE_CODE - // }); - // } - - // currentSolutionScope["roles"] = userRoles; - - // } else { - // if( scopeData.roles === constants.common.ALL_ROLES ) { - // currentSolutionScope["roles"] = [{ - // "code" : constants.common.ALL_ROLES - // }]; - // } - // } - // } - // } - // console.log("currentSolutionScope:",currentSolutionScope) - // if( currentSolutionScope && currentSolutionScope.entities.length > 0 ){ - // console.log("**************inside") - // let entitiesIds = currentSolutionScope.entities; - // console.log("entitiesIds:",entitiesIds) - // for( let eachEntity in entitiesIds ) { - // if( entitiesIds[eachEntity].toString() == entitiesIds[eachEntity] ) { - // entitiesIds[eachEntity] = ObjectId(entitiesIds[eachEntity]); - // } - // } - // console.log("currentSolutionScope After:",entitiesIds) - // delete currentSolutionScope.entities; - // currentSolutionScope["entities"] = entitiesIds; - - // } - // console.log("currentSolutionScope After:",currentSolutionScope) - // let updateSolution = - // await database.models.solutions.findOneAndUpdate( - // { - // _id : solutionId - // }, - // { $set : { scope : currentSolutionScope }},{ new: true } - // ).lean(); - - // if( !updateSolution._id ) { - // throw { - // status : constants.apiResponses.SOLUTION_SCOPE_NOT_ADDED - // }; - // } - // solutionData = updateSolution; - - // } - - // return resolve({ - // success : true, - // message : constants.apiResponses.SOLUTION_UPDATED - // }); } catch (error) { return resolve({ @@ -846,7 +622,7 @@ module.exports = class SolutionsHelper { subType, programId ); - console.log("queryData:",queryData) + if( !queryData.success ) { return resolve(queryData); } @@ -885,7 +661,7 @@ module.exports = class SolutionsHelper { if ( programId !== "" ) { matchQuery["programId"] = ObjectId(programId); } - console.log("matchQuery:",matchQuery) + let targetedSolutions = await this.list( type, subType, @@ -908,7 +684,7 @@ module.exports = class SolutionsHelper { "referenceFrom" ] ); - console.log("targetedSolutions: ######",targetedSolutions.data) + return resolve({ success: true, message: constants.apiResponses.TARGETED_SOLUTIONS_FETCHED, @@ -1031,7 +807,7 @@ module.exports = class SolutionsHelper { } queryData.data["_id"] = solutionId; - console.log("queryData : ",queryData) + let targetedSolutionDetails = await this.solutionDocuments( queryData.data, @@ -1052,7 +828,7 @@ module.exports = class SolutionsHelper { "link" ] ); - console.log("targetedSolutionDetails[0] : ",targetedSolutionDetails[0]) + if( !targetedSolutionDetails.length > 0 ) { throw { status : httpStatusCode["bad_request"].status, @@ -1228,10 +1004,10 @@ module.exports = class SolutionsHelper { } } } - let bodyData={}; - bodyData["request"] = {}; - bodyData["request"]["filters"] = {}; - bodyData["request"]["filters"]["id"] = entities; + let bodyData={ + "id" : entities + }; + let entitiesDetails = await sunbirdService.learnerLocationSearch( bodyData ); @@ -1273,86 +1049,6 @@ module.exports = class SolutionsHelper { message : constants.apiResponses.ENTITIES_ADDED_IN_SOLUTION, success : true }); - - // let solutionData = - // await this.solutionDocuments({ - // _id : solutionId, - // scope : { $exists : true }, - // isReusable : false, - // isDeleted : false - // },["_id","programId","scope.entityType"]); - - // if( !solutionData.length > 0 ) { - // return resolve({ - // status : httpStatusCode.bad_request.status, - // message : constants.apiResponses.SOLUTION_NOT_FOUND - // }); - // } - // console.log("solutionData : ",solutionData) - // let programData = await programsHelper.programDocuments({ - // _id : solutionData[0].programId - // },["scope.entities","scope.entityType"]); - - // if( !programData.length > 0 ) { - // return resolve({ - // status : httpStatusCode.bad_request.status, - // message : constants.apiResponses.PROGRAM_NOT_FOUND - // }); - // } - // console.log("programData : ",programData) - // if( solutionData[0].scope.entityType !== programData[0].scope.entityType ) { - // console.log("inside condition") - // console.log("_id ; ",programData[0].scope.entities) - // console.log("group : ",solutionData[0].scope.entityType) - // console.log("entities : ",entities) - // let checkEntityInParent = - // await entitiesHelper.entityDocuments({ - // _id : programData[0].scope.entities, - // [`groups.${solutionData[0].scope.entityType}`] : entities - // },["_id"]); - // console.log("checkEntityInParent : ",checkEntityInParent) - // if( !checkEntityInParent.length > 0 ) { - // throw { - // message : constants.apiResponses.ENTITY_NOT_EXISTS_IN_PARENT - // } - // } - // } - - // let entitiesData = - // await entitiesHelper.entityDocuments({ - // _id : { $in : entities }, - // entityType : solutionData[0].scope.entityType - // },["_id"]); - // console.log("entities data with same type : ",entitiesData) - // if( !entitiesData.length > 0 ) { - // throw { - // message : constants.apiResponses.ENTITIES_NOT_FOUND - // }; - // } - - // let entityIds = []; - - // entitiesData.forEach(entity => { - // entityIds.push(entity._id); - // }); - - // let updateSolution = await database.models.solutions.findOneAndUpdate({ - // _id : solutionId - // },{ - // $addToSet : { "scope.entities" : { $each : entityIds } } - // },{ new : true }).lean(); - - // if( !updateSolution || !updateSolution._id ) { - // throw { - // message : constants.apiResponses.SOLUTION_NOT_UPDATED - // } - // } - - // return resolve({ - // message : constants.apiResponses.ENTITIES_ADDED_IN_SOLUTION, - // success : true - // }); - } catch(error) { return resolve({ success : false, @@ -2243,107 +1939,6 @@ module.exports = class SolutionsHelper { }); } - /** - * get entitiesData of matching type by recursion. - * @method - * @name entitiesInParent - * @returns {Array} - Entities matching the type under the parent. - */ - - static matchingTypeEntities( solutionEntities,currentEntityType,matchingData ){ - return new Promise ( async (resolve, reject)=>{ - try{ - console.log("######################inside recursive parent:",matchingData) - - let mismatchEntities = []; - let bodyData={}; - bodyData["request"] = {}; - bodyData["request"]["filters"] = {}; - bodyData["request"]["filters"]["parentId"] = solutionEntities; - console.log(" bodyData inside recursive fn : ", bodyData["request"]["filters"]) - console.log("array entities : ",matchingData.length) - let entityDetails = await sunbirdService.learnerLocationSearch(bodyData); - if( !entityDetails.data.response.length > 0 && !entities.length > 0 ) { - return ({ - status : httpStatusCode.bad_request.status, - message : constants.apiResponses.ENTITIES_NOT_FOUND - }); - } - console.log("Data from learner inside recursion:",entityDetails.data.response.length) - let entityData = entityDetails.data.response; - //let mismatchEntities = []; - entityData.map(entity => { - //console.log("entity inside map:",entity.type); - if( entity.type == currentEntityType ) { - matchingData.push(entity.id) - }else { - mismatchEntities.push(entity.id) - } - }); - console.log("mismatchEntities:",mismatchEntities.length) - if( mismatchEntities.length > 0 ){ - console.log("+++++++caling recursion") - await matchingTypeEntities(mismatchEntities,currentEntityType,matchingData) - } - - return resolve (matchingData); - // console.log(typeof (entities)) - // if (typeof entities === 'undefined' || !Array.isArray(entities)) { - // console.log("############yeeeaah") - // var entities = []; - // } else { - // console.log("############noooo") - // entities = entities; - // } - - // console.log(typeof (entities)) - // console.log("Array Entities : ",entities.length) - // let bodyData={}; - // bodyData["request"] = {}; - // bodyData["request"]["filters"] = {}; - // bodyData["request"]["filters"]["parentId"] = solutionEntities; - - // console.log(" bodyData inside recursive fn : ", solutionEntities.length) - // let entityDetails = await sunbirdService.learnerLocationSearch(bodyData); - // if( !entityDetails.data.response.length > 0 && !entities.length > 0 ) { - // return resolve({ - // status : httpStatusCode.bad_request.status, - // message : constants.apiResponses.ENTITIES_NOT_FOUND - // }); - // } - // console.log("Data from learner inside recursion:",entityDetails.data.response) - // let entityData = entityDetails.data.response; - // //entities = ( typeof entities != 'undefined' && entities instanceof Array ) ? entities : []; - // let mismatchEntities = []; - // entityData.map(entity => { - // if( entity.type == currentEntityType ) { - // entities.push(entity.id) - // } else { - // mismatchEntities.push(entity.id) - // } - // }); - // console.log("mismatchEntities:",mismatchEntities.length) - // console.log("Real data length:",entities.length); - // if( !mismatchEntities.length > 0 ){ - // console.log("send data length:",entities.length); - // return resolve(entities); - // }else{ - // await this.matchingTypeEntities(mismatchEntities,currentEntityType) - // } - - - } catch(err) { - console.log("error : ",err) - return resolve({ - success : false - }); - } - }); - } - - - - }; @@ -2397,52 +1992,41 @@ function _generateLink(appsPortalBaseUrl, prefix, solutionLink, solutionType) { // */ async function entitiesInParent( solutionEntities,currentEntityType,matchingData ){ - //console.log("inside recursive function : ",matchingData) - console.log("inside recursive function solutionEntities: ",solutionEntities,currentEntityType,matchingData) + if( !solutionEntities.length > 0 ){ return matchingData; } - let bodyData={}; - bodyData["request"] = {}; - bodyData["request"]["filters"] = {}; - bodyData["request"]["filters"]["parentId"] = solutionEntities; - console.log(" bodyData inside recursive fn : ", bodyData["request"]["filters"]) - //let entities = []; - //entities = ( typeof entities != 'undefined' && entities instanceof Array ) ? entities : [] - //console.log("array entities : ",matchingData.length) + let bodyData={ + "parentId" : solutionEntities + }; + let entityDetails = await sunbirdService.learnerLocationSearch(bodyData); + if( !entityDetails.data.response.length > 0 && !matchingData.length > 0 ) { return ({ status : httpStatusCode.bad_request.status, message : constants.apiResponses.ENTITIES_NOT_FOUND }); } - //console.log("Data from learner inside recursion:",entityDetails.data.response) + let entityData = entityDetails.data.response; - let mismatchEntities = []; entityData.map(entity => { - //console.log("entity inside map:",entity.type); if( entity.type == currentEntityType ) { matchingData.push(entity.id) - //if (matchingData.includes(entity.type) === false) matchingData.push(entity.type); } else { mismatchEntities.push(entity.id) } }); - console.log("mismatchEntities:",mismatchEntities.length) - console.log("matching---------:",matchingData.length) + if( mismatchEntities.length > 0 ){ - console.log("++++recursive calling") await entitiesInParent(mismatchEntities,currentEntityType,matchingData) } let uniqueEntities = []; matchingData.map( data => { if (uniqueEntities.includes(data) === false) uniqueEntities.push(data); }); - return uniqueEntities; - - + return uniqueEntities; } \ No newline at end of file diff --git a/module/users/helper.js b/module/users/helper.js index 6e1bad85..6d01be1f 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -160,9 +160,7 @@ module.exports = class UsersHelper { let locationIds = []; let bodyData={}; - bodyData["request"] = {}; - bodyData["request"]["filters"] = {}; - bodyData["request"]["filters"]["id"] = ""; + data.entities.forEach(entity=>{ if (gen.utils.checkValidUUID(entity)) { @@ -170,7 +168,9 @@ module.exports = class UsersHelper { } }); - bodyData["request"]["filters"]["id"] = locationIds; + bodyData = { + "id" : locationIds + } let entityData = await sunbirdService.learnerLocationSearch( bodyData ); if ( !entityData.data.count > 0 ) { @@ -332,7 +332,7 @@ module.exports = class UsersHelper { static entitiesMappingForm(stateCode, roleId, entityKey) { return new Promise(async (resolve, reject) => { try { - console.log("data in request:",stateCode,roleId,entityKey) + const rolesData = await userRolesHelper.roleDocuments({ _id: roleId }, ["entityTypes.entityType"]); @@ -343,9 +343,9 @@ module.exports = class UsersHelper { result: [] }) } - console.log("#rolesData:",rolesData) + let subEntities = await cache.getValue(entityKey); - console.log("subEntitiesDetails from cache:",subEntities) + if( !subEntities.length > 0 ) { subEntities = await formService.formData( stateCode,entityKey ); if( !subEntities.length > 0 ) { @@ -355,7 +355,7 @@ module.exports = class UsersHelper { }) } } - console.log("subEntitiesDetails from cache:",subEntities); + let roleEntityType = ""; @@ -364,10 +364,10 @@ module.exports = class UsersHelper { roleEntityType = roleData.entityType; } }) - console.log("roleEntityType",roleEntityType) + let entityTypeIndex = subEntities.findIndex(path => path === roleEntityType); - console.log("entityTypeIndex",entityTypeIndex) + let form = { "field": "", "label": "", @@ -403,80 +403,6 @@ module.exports = class UsersHelper { message: constants.apiResponses.ENTITIES_MAPPING_FORM_FETCHED, result: forms }); - - - //============= - // const rolesData = await userRolesHelper.roleDocuments({ - // _id: roleId - // }, ["entityTypes.entityType"]); - - // if (!rolesData.length > 0) { - // return resolve({ - // message: constants.apiResponses.USER_ROLES_NOT_FOUND, - // result: [] - // }) - // } - - // const entitiesData = await entitiesHelper.entityDocuments( - // { - // _id: stateId, - // }, ["childHierarchyPath"] - // ); - // console.log("entitiesData##",entitiesData) - // if (!entitiesData.length > 0) { - // return resolve({ - // message: constants.apiResponses.ENTITY_NOT_FOUND, - // result: [] - // }) - // } - - // let roleEntityType = ""; - - // rolesData[0].entityTypes.forEach(roleData => { - // if (entitiesData[0].childHierarchyPath.includes(roleData.entityType)) { - // roleEntityType = roleData.entityType; - // } - // }) - // console.log("roleEntityType##",roleEntityType) - // let entityTypeIndex = - // entitiesData[0].childHierarchyPath.findIndex(path => path === roleEntityType); - // console.log("entityTypeIndex##",entityTypeIndex) - // let form = { - // "field": "", - // "label": "", - // "value": "", - // "visible": true, - // "editable": true, - // "input": "text", - // "validation": { - // "required": false - // } - // }; - - // let forms = []; - - // for ( - // let pointerToChildHierarchy = 0; - // pointerToChildHierarchy < entityTypeIndex + 1; - // pointerToChildHierarchy++ - // ) { - // let cloneForm = JSON.parse(JSON.stringify(form)); - // let entityType = entitiesData[0].childHierarchyPath[pointerToChildHierarchy]; - // cloneForm["field"] = entityType; - // cloneForm["label"] = `Select ${gen.utils.camelCaseToTitleCase(entityType)}`; - - // if (roleEntityType === entityType) { - // cloneForm.validation.required = true; - // } - - // forms.push(cloneForm); - // } - // console.log("form",forms) - // return resolve({ - // message: constants.apiResponses.ENTITIES_MAPPING_FORM_FETCHED, - // result: forms - // }); - } catch (error) { return reject(error); } @@ -668,7 +594,7 @@ module.exports = class UsersHelper { }, ["_id", "entityTypes.entityType"] ); - console.log("role:",rolesDocument[0]) + if (!rolesDocument.length > 0) { throw { message: constants.apiResponses.USER_ROLES_NOT_FOUND @@ -677,34 +603,36 @@ module.exports = class UsersHelper { - let bodyData={}; - bodyData["request"] = {}; - bodyData["request"]["filters"] = {}; + let bodyData={}; if (gen.utils.checkValidUUID(stateLocationId)) { - bodyData["request"]["filters"]["id"] = stateLocationId; + bodyData = { + "id" : stateLocationId + }; } else { - bodyData["request"]["filters"]["code"] = stateLocationId; + bodyData = { + "code" : stateLocationId + }; } - console.log("querybody:",bodyData["request"]["filters"]) + let entityData = await sunbirdService.learnerLocationSearch( bodyData ); - console.log("entityData:",entityData.data.response) + if ( !entityData.data.response.length > 0) { throw { message: constants.apiResponses.ENTITIES_NOT_EXIST_IN_LOCATION, }; } - console.log("entityData After:",entityData.data.response[0].code) + let entityTypes = []; let stateEntityExists = false; rolesDocument[0].entityTypes.forEach((roleDocument) => { - console.log("inside roleDocument",roleDocument) + if (roleDocument.entityType === constants.common.STATE_ENTITY_TYPE) { stateEntityExists = true; } }); - console.log("******entityTypes",entityTypes) + if (stateEntityExists) { entityTypes = [constants.common.STATE_ENTITY_TYPE]; } else { @@ -724,68 +652,6 @@ module.exports = class UsersHelper { message: constants.apiResponses.ENTITY_TYPES_FETCHED, data: entityTypes }); - - //============ - // let filterQuery = { - // "registryDetails.code": stateLocationId, - // }; - - // if (gen.utils.checkValidUUID(stateLocationId)) { - // filterQuery = { - // "registryDetails.locationId": stateLocationId, - // }; - // } - - // const entitiesData = await entitiesHelper.entityDocuments(filterQuery, [ - // "_id", - // ]); - - // if (!entitiesData.length > 0) { - // throw { - // message: constants.apiResponses.ENTITIES_NOT_EXIST_IN_LOCATION, - // }; - // } - // console.log("entitiesData:",entitiesData) - // const rolesDocument = await userRolesHelper.roleDocuments( - // { - // code: role.toUpperCase(), - // }, - // ["_id", "entityTypes.entityType"] - // ); - - // if (!rolesDocument.length > 0) { - // throw { - // message: constants.apiResponses.USER_ROLES_NOT_FOUND - // }; - // } - // console.log("rolesDocument:",rolesDocument) - // let entityTypes = []; - // let stateEntityExists = false; - - // rolesDocument[0].entityTypes.forEach((roleDocument) => { - // if (roleDocument.entityType === constants.common.STATE_ENTITY_TYPE) { - // stateEntityExists = true; - // } - // }); - - // if (stateEntityExists) { - // entityTypes = [constants.common.STATE_ENTITY_TYPE]; - // } else { - // let entitiesMappingForm = await this.entitiesMappingForm( - // entitiesData[0]._id, - // rolesDocument[0]._id - // ); - - // entitiesMappingForm.result.forEach((entitiesMappingData) => { - // entityTypes.push(entitiesMappingData.field); - // }); - // } - - // return resolve({ - // success: true, - // message: constants.apiResponses.ENTITY_TYPES_FETCHED, - // data: entityTypes - // }); } catch (error) { return resolve({ success: false, @@ -844,37 +710,33 @@ module.exports = class UsersHelper { targetedEntityType = singleEntityType.entityType; } }); + if (!requestedData[targetedEntityType]) { throw { status: httpStatusCode["bad_request"].status, message: constants.apiResponses.ENTITIES_NOT_ALLOWED_IN_ROLE }; } + let filterData ={}; if (solutionData[0].entityType === targetedEntityType) { - let bodyData={}; - bodyData["request"] = {}; - bodyData["request"]["filters"] = {}; - bodyData["request"]["filters"]["parentId"] = ""; - + if (gen.utils.checkValidUUID(requestedData[targetedEntityType])) { - bodyData["request"]["filters"]["parentId"] = requestedData[targetedEntityType]; + filterData = { + "parentId" : requestedData[targetedEntityType] + } } - - let entitiesData = await sunbirdService.learnerLocationSearch( bodyData ); + let entitiesData = await sunbirdService.learnerLocationSearch( filterData ); if( entitiesData.count > 0 ){ targetedEntityType = constants.common.STATE_ENTITY_TYPE; } } - let filterData={}; - filterData["request"] = {}; - filterData["request"]["filters"] = {}; if (gen.utils.checkValidUUID(requestedData[targetedEntityType])) { - filterData["request"]["filters"] = { + filterData = { "id" : requestedData[targetedEntityType] }; - } else { - filterData["request"]["filters"] = { + } else { + filterData = { "code" : requestedData[targetedEntityType] }; } @@ -896,113 +758,6 @@ module.exports = class UsersHelper { success: true, data: entityDataFormated }); - // let solutionData = await solutionsHelper.solutionDocuments( - // { - // _id: solutionId, - // isDeleted: false - // }, - // ["entityType", "type"] - // ); - - // if (!solutionData.length > 0) { - // return resolve({ - // status: httpStatusCode.bad_request.status, - // message: constants.apiResponses.SOLUTION_NOT_FOUND - // }); - // } - - // let rolesDocument = await userRolesHelper.roleDocuments( - // { - // code: requestedData.role - // }, - // ["entityTypes.entityType"] - // ); - - // if (!rolesDocument.length > 0) { - // throw { - // status: httpStatusCode["bad_request"].status, - // message: constants.apiResponses.USER_ROLES_NOT_FOUND - // }; - // } - - // let requestedEntityTypes = Object.keys(_.omit(requestedData, ['role'])); - // let targetedEntityType = ""; - - // rolesDocument[0].entityTypes.forEach((singleEntityType) => { - // if (requestedEntityTypes.includes(singleEntityType.entityType)) { - // targetedEntityType = singleEntityType.entityType; - // } - // }); - // console.log("targetedEntityType :",targetedEntityType) - // if (!requestedData[targetedEntityType]) { - // throw { - // status: httpStatusCode["bad_request"].status, - // message: constants.apiResponses.ENTITIES_NOT_ALLOWED_IN_ROLE - // }; - // } - - // if (solutionData[0].entityType === targetedEntityType) { - // let filterQuery = { - // "registryDetails.code": requestedData[targetedEntityType] - // }; - - // if (gen.utils.checkValidUUID(requestedData[targetedEntityType])) { - // filterQuery = { - // "registryDetails.locationId": requestedData[targetedEntityType] - // }; - // } - - // let entities = await entitiesHelper.entityDocuments(filterQuery, [ - // "groups", - // ]); - - // if (!entities.length > 0) { - // throw { - // message: constants.apiResponses.ENTITY_NOT_FOUND - // }; - // } - - // if ( - // entities[0] && - // entities[0].groups && - // Object.keys(entities[0].groups).length > 0 - // ) { - // targetedEntityType = constants.common.STATE_ENTITY_TYPE; - // } - // } - - // let filterData = { - // "registryDetails.code": requestedData[targetedEntityType] - // }; - - // if (gen.utils.checkValidUUID(requestedData[targetedEntityType])) { - // filterData = { - // "registryDetails.locationId": requestedData[targetedEntityType] - // }; - // } - - // let entities = await entitiesHelper.entityDocuments(filterData, [ - // "metaInformation.name", - // "entityType" - // ]); - - // if (!entities.length > 0) { - // throw { - // message: constants.apiResponses.ENTITY_NOT_FOUND - // }; - // } - - // if (entities[0].metaInformation && entities[0].metaInformation.name) { - // entities[0]['entityName'] = entities[0].metaInformation.name; - // delete entities[0].metaInformation; - // } - - // return resolve({ - // message: constants.apiResponses.SOLUTION_TARGETED_ENTITY, - // success: true, - // data: entities[0] - // }); - } catch (error) { return resolve({ success: false, @@ -1029,12 +784,11 @@ module.exports = class UsersHelper { let entityKey = constants.common.SUBENTITY + requestedData.state; let subEntities = await cache.getValue(entityKey); if( !subEntities.length > 0 ) { - let bodyData={}; - bodyData["request"] = {}; - bodyData["request"]["filters"] = {}; - bodyData["request"]["filters"]["id"] = requestedData.state; + let filterData = { + "id" : requestedData.state + }; - let entitiesData = await sunbirdService.learnerLocationSearch( bodyData ); + let entitiesData = await sunbirdService.learnerLocationSearch( filterData ); if( !entitiesData.data.response.length > 0 ) { return resolve({ @@ -1070,62 +824,6 @@ module.exports = class UsersHelper { success: true, data: targetedEntity }); - - - // console.log("roleWiseTargetedEntities:",roleWiseTargetedEntities) - // let allTargetedEntities = {}; - // let targetedEntity = {}; - - // for( let pointerToEntities = 0 ; pointerToEntities < roleWiseTargetedEntities.length ; pointerToEntities++ ) { - - // let currentEntity = roleWiseTargetedEntities[pointerToEntities]; - // console.log("currentEntity:",currentEntity) - // if ( !allTargetedEntities.hasOwnProperty(currentEntity._id) ) { - // allTargetedEntities[currentEntity._id] = new Array(); - // } - // console.log("allTargetedEntities:",allTargetedEntities) - // //add entity _id if already not there to allTargetedEntities - // let otherEntities = roleWiseTargetedEntities.filter((entity) => entity.entityType !== currentEntity.entityType); - // console.log("otherEntities:",otherEntities) - // if ( !otherEntities || !otherEntities.length > 0 ) { - // continue; - // } - - // let entitiesDocument = await entitiesHelper.entityDocuments({ - // _id: ObjectId(currentEntity._id) - // }, ["groups"]); - - // if ( !entitiesDocument || !entitiesDocument.length > 0 ) { - // continue; - // } - - // entitiesDocument = entitiesDocument[0]; - // for( let entityCounter = 0 ; entityCounter < otherEntities.length ; entityCounter++ ) { - - // let entityDoc = otherEntities[entityCounter]; - // console.log("entityDoc:",entityDoc) - // if ( !entitiesDocument.groups || !entitiesDocument.groups.hasOwnProperty(entityDoc.entityType) ) { - // console.log(entityDoc.entityType,"entity type not exists") - // break; - // } - - // allTargetedEntities[currentEntity._id].push(true); - // console.log("allTargetedEntities in entity counter:",allTargetedEntities) - // if ( allTargetedEntities[currentEntity._id].length == otherEntities.length ) { - // targetedEntity = roleWiseTargetedEntities.filter((entity) => entity._id == currentEntity._id); - // break; - // } - // console.log("targetedEntity in entity counter:",targetedEntity) - // } - - // } - // console.log("targetedEntity in entity counter:",targetedEntity) - // return resolve({ - // message: constants.apiResponses.SOLUTION_TARGETED_ENTITY, - // success: true, - // data: targetedEntity - // }); - } catch (error) { return resolve({ success: false, From bdfc02794daaa39c2ec0e3b350533a32814fd906 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Wed, 23 Mar 2022 17:04:18 +0530 Subject: [PATCH 118/331] entity Generalization comment resolve lvl 1 --- generics/constants/common.js | 4 +- generics/services/form.js | 16 ++++---- generics/services/sunbird.js | 51 +++++++++++++------------ module/entities/helper.js | 11 ++++-- module/programs/helper.js | 28 +++++++------- module/solutions/helper.js | 29 ++++++++------- module/users/helper.js | 72 +++++++++++++++++++++++++----------- 7 files changed, 125 insertions(+), 86 deletions(-) diff --git a/generics/constants/common.js b/generics/constants/common.js index 734e5886..45c9da77 100644 --- a/generics/constants/common.js +++ b/generics/constants/common.js @@ -69,5 +69,7 @@ module.exports = { "SCHOOL" : "school", "SUBENTITY" :"subEntity_", "SUNBIRD_SERVER_TIMEOUT" : 5000, - "TIMEOUT_ERROR" : "Server timeout error" + "CACHE_TIME_PERIOD" : 43200, + "FORM_API_TYPE" : "profileConfig" + }; diff --git a/generics/services/form.js b/generics/services/form.js index 9df7fb79..0a1dc765 100644 --- a/generics/services/form.js +++ b/generics/services/form.js @@ -24,18 +24,20 @@ const formData = function ( stateLocationCode, entityKey ) { try { let subEntitiesDetails = await sunbirdService.formRead( stateLocationCode ); - let subEntityData = subEntitiesDetails.data.form.data.fields[1].children.teacher; - - let subEntities = subEntityData.map( subEntity => { - return subEntity.code; - }) - if( !subEntitiesDetails.data || !subEntityData.length > 0 ) { + if( !subEntitiesDetails.success) { return resolve({ message : constants.apiResponses.ENTITY_NOT_FOUND, result : [] }) } - let setCache = cache.setValue(entityKey, subEntities, 43200); + + let subEntityData = subEntitiesDetails.data.form.data.fields[1].children.teacher; + + let subEntities = subEntityData.map( subEntity => { + return subEntity.code; + }) + + let setCache = cache.setValue(entityKey, subEntities, constants.common.CACHE_TIME_PERIOD); return resolve(subEntities); } catch (error) { diff --git a/generics/services/sunbird.js b/generics/services/sunbird.js index 6b08e490..86331db2 100644 --- a/generics/services/sunbird.js +++ b/generics/services/sunbird.js @@ -31,7 +31,7 @@ const learnerLocationSearch = function ( filterData, limit = "", offset = "" ) if( limit !== "" ) { bodyData["request"]["limit"] = limit; } - if( limit !== "" ) { + if( offset !== "" ) { bodyData["request"]["offset"] = offset; } @@ -48,18 +48,18 @@ const learnerLocationSearch = function ( filterData, limit = "", offset = "" ) request.post(url,options,kendraCallback); - function kendraCallback(err, data) { + let result = { + success : true + }; - let result = { - success : true - }; + function kendraCallback(err, data) { + if (err) { result.success = false; } else { let response = data.body; - if( response.responseCode === constants.common.OK) { result["data"] = response.result; } else { @@ -70,7 +70,9 @@ const learnerLocationSearch = function ( filterData, limit = "", offset = "" ) } setTimeout(function () { - return reject (constants.common.TIMEOUT_ERROR) + return reject (result = { + success : false + }); }, constants.common.SUNBIRD_SERVER_TIMEOUT); @@ -94,9 +96,9 @@ const formRead = function ( subTypeData ) { let bodyData = { request : { - type: "profileConfig", + type: constants.common.FORM_API_TYPE, subType: subTypeData, - action: "get" + action: constants.common.GET_METHOD } } @@ -111,13 +113,12 @@ const formRead = function ( subTypeData ) { }; request.post(url,options,kendraCallback); - + let result = { + success : true + }; function kendraCallback(err, data) { - let result = { - success : true - }; - + if (err) { result.success = false; } else { @@ -126,6 +127,7 @@ const formRead = function ( subTypeData ) { if( response.responseCode === constants.common.OK) { result["data"] = response.result; + result.success = true; } else { result.success = false; } @@ -133,7 +135,9 @@ const formRead = function ( subTypeData ) { return resolve(result); } setTimeout(function () { - return reject (constants.common.TIMEOUT_ERROR) + return reject (result = { + success : false + }); }, constants.common.SUNBIRD_SERVER_TIMEOUT); } catch (error) { @@ -150,15 +154,13 @@ const formRead = function ( subTypeData ) { * @param {object} bodyData - location id * @returns {Promise} returns a promise. */ -const schoolData = function ( locationIds ) { +const schoolData = function ( filterData ) { return new Promise(async (resolve, reject) => { try { let bodyData = { request : { - filters :{ - "orgLocation.id" : locationIds - } + filters : filterData } } @@ -173,12 +175,13 @@ const schoolData = function ( locationIds ) { }; request.post(url,options,kendraCallback); + let result = { + success : true + }; function kendraCallback(err, data) { - let result = { - success : true - }; + if (err) { result.success = false; @@ -195,7 +198,9 @@ const schoolData = function ( locationIds ) { return resolve(result); } setTimeout(function () { - return reject (constants.common.TIMEOUT_ERROR) + return reject (result = { + success : false + }); }, constants.common.SUNBIRD_SERVER_TIMEOUT); } catch (error) { diff --git a/module/entities/helper.js b/module/entities/helper.js index 8cb68671..e93c5fce 100644 --- a/module/entities/helper.js +++ b/module/entities/helper.js @@ -252,7 +252,7 @@ module.exports = class EntitiesHelper { let entitiesData = await sunbirdService.learnerLocationSearch( bodyData ); - if( !entitiesData.data.response.length > 0 ) { + if( !entitiesData.success ||!entitiesData.data.response.length > 0 ) { return resolve(entitiesData.data.response) } @@ -518,7 +518,10 @@ module.exports = class EntitiesHelper { try { let subentitiesData = []; if( entityTraversalType == constants.common.SCHOOL) { - let subentitiesCode = await sunbirdService.schoolData( entityId ); + let filterData = { + "orgLocation.id" : entityId + } + let subentitiesCode = await sunbirdService.schoolData( filterData ); let schoolDetails = subentitiesCode.data.response.content; if( !schoolDetails.length > 0 ) { return resolve(schoolDetails) @@ -907,7 +910,7 @@ module.exports = class EntitiesHelper { let entitiesData = await sunbirdService.learnerLocationSearch( bodyData ); - if( !entitiesData.data.response.length > 0 ) { + if( !entitiesData.success || !entitiesData.data.response.length > 0 ) { return resolve({ message : constants.apiResponses.ENTITY_NOT_FOUND, result : [] @@ -1064,7 +1067,7 @@ async function subEntitiesWithMatchingType( parentIds,entityType,matchingData ){ let entityDetails = await sunbirdService.learnerLocationSearch(bodyData); - if( !entityDetails.data.response.length > 0 && !matchingData.length > 0 ) { + if( ( !entityDetails.success || !entityDetails.data.response.length > 0 ) && !matchingData.length > 0 ) { return matchingData; } diff --git a/module/programs/helper.js b/module/programs/helper.js index d7cd50b6..8e3a7d90 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -207,22 +207,21 @@ module.exports = class ProgramsHelper { let scope = {}; if( scopeData.entityType ) { + + let bodyData = { + "type" : scopeData.entityType + } + let entityTypeData = await sunbirdService.learnerLocationSearch( bodyData ); - let entityTypeData = await entityTypesHelper.entityTypesDocument( - { - name : scopeData.entityType - }, - ["name"] - ); - - if( !entityTypeData.length > 0 ) { + if( !entityTypeData.success || !entityTypeData.data.response.length > 0 ) { return resolve({ status : httpStatusCode.bad_request.status, message : constants.apiResponses.ENTITY_TYPES_NOT_FOUND }); } - scope["entityType"] = entityTypeData[0].name; + scope["entityType"] = entityTypeData.data.response[0].type; + } if( scopeData.entities && scopeData.entities.length > 0 ) { @@ -243,15 +242,14 @@ module.exports = class ProgramsHelper { let entityData = await sunbirdService.learnerLocationSearch( bodyData ); - - - let entities = entityData.data.response; - if( !entities.length > 0 ) { + if( !entityData.success || !entityData.data.response.length > 0 ) { return resolve({ status : httpStatusCode.bad_request.status, message : constants.apiResponses.ENTITIES_NOT_FOUND }); } + + let entities = entityData.data.response; scope["entities"] = entities.map(entity => { return entity.id; @@ -741,8 +739,8 @@ module.exports = class ProgramsHelper { let entitiesData = await sunbirdService.learnerLocationSearch( bodyData ); - - if( !entitiesData.data.count > 0 ) { + + if( !entitiesData.success || !entitiesData.data.count > 0 ) { throw { message : constants.apiResponses.ENTITIES_NOT_FOUND }; diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 051e20af..747e2000 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -139,13 +139,14 @@ module.exports = class SolutionsHelper { let entitiesDetails = await sunbirdService.learnerLocationSearch( bodyData ); - let entitiesData = entitiesDetails.data.response; - - if( !entitiesData.length > 0 ) { + if( !entitiesDetails.success || !entitiesDetails.data.response.length > 0 ) { throw { message : constants.apiResponses.ENTITIES_NOT_FOUND } } + + let entitiesData = entitiesDetails.data.response; + entitiesData = entitiesData.map( entity => { return entity.id; }) @@ -263,7 +264,7 @@ module.exports = class SolutionsHelper { }; let entityDetails = await sunbirdService.learnerLocationSearch(bodyData); - if( !entityDetails.data.response.length > 0 ) { + if( !entityDetails.success || !entityDetails.data.response.length > 0 ) { return resolve({ status : httpStatusCode.bad_request.status, message : constants.apiResponses.ENTITIES_NOT_FOUND @@ -290,12 +291,12 @@ module.exports = class SolutionsHelper { if( currentSolutionScope.entityType !== programData[0].scope.entityType ) { let matchData = []; - let childList = await entitiesInParent(currentSolutionScope.entities,currentSolutionScope.entityType,matchData); + let childEntities = await entitiesInParent(currentSolutionScope.entities,currentSolutionScope.entityType,matchData); - if( childList.length > 0) { + if( childEntities.length > 0) { for( let entitiesIndex = 0; entitiesIndex < entities.length; entitiesIndex++ ) { - for( let childListIndex = 0; childListIndex < childList.length; childListIndex++) { - if( childList[childListIndex] == entities[entitiesIndex]){ + for( let childListIndex = 0; childListIndex < childEntities.length; childListIndex++) { + if( childEntities[childListIndex] == entities[entitiesIndex]){ entityIds.push(entities[entitiesIndex]); entitiesIndex++; } @@ -981,17 +982,17 @@ module.exports = class SolutionsHelper { let matchData = []; let checkEntityInParent = []; - let childList = await entitiesInParent(programData[0].scope.entities,solutionData[0].scope.entityType,matchData); + let childEntities = await entitiesInParent(programData[0].scope.entities,solutionData[0].scope.entityType,matchData); - if( !childList.length > 0 ) { + if( !childEntities.length > 0 ) { throw { message : constants.apiResponses.ENTITY_NOT_EXISTS_IN_PARENT } } for( let entitiesIndex = 0; entitiesIndex < entities.length; entitiesIndex++ ) { - for( let childListIndex = 0; childListIndex < childList.length; childListIndex++) { - if( childList[childListIndex] == entities[entitiesIndex]){ + for( let childListIndex = 0; childListIndex < childEntities.length; childListIndex++) { + if( childEntities[childListIndex] == entities[entitiesIndex]){ checkEntityInParent.push(entities[entitiesIndex]); entitiesIndex++; } @@ -1011,7 +1012,7 @@ module.exports = class SolutionsHelper { let entitiesDetails = await sunbirdService.learnerLocationSearch( bodyData ); - if( !entitiesDetails.data.response.length > 0 ) { + if( !entitiesDetails.success || !entitiesDetails.data.response.length > 0 ) { return resolve({ status : httpStatusCode.bad_request.status, message : constants.apiResponses.ENTITIES_NOT_FOUND @@ -2002,7 +2003,7 @@ async function entitiesInParent( solutionEntities,currentEntityType,matchingData let entityDetails = await sunbirdService.learnerLocationSearch(bodyData); - if( !entityDetails.data.response.length > 0 && !matchingData.length > 0 ) { + if( ( !entityDetails.success || !entityDetails.data.response.length > 0) && !matchingData.length > 0 ) { return ({ status : httpStatusCode.bad_request.status, message : constants.apiResponses.ENTITIES_NOT_FOUND diff --git a/module/users/helper.js b/module/users/helper.js index 6d01be1f..8e58d80d 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -159,37 +159,65 @@ module.exports = class UsersHelper { let locationIds = []; + let orgExternalId = []; + let entitiesData = []; let bodyData={}; data.entities.forEach(entity=>{ if (gen.utils.checkValidUUID(entity)) { locationIds.push(entity); + } else { + orgExternalId.push(entity) } }); - - bodyData = { - "id" : locationIds - } - let entityData = await sunbirdService.learnerLocationSearch( bodyData ); - - if ( !entityData.data.count > 0 ) { - return resolve({ - status: httpStatusCode["bad_request"].status, - message: constants.apiResponses.ENTITY_NOT_FOUND, - result: {} + + if( locationIds.length > 0 ){ + + bodyData = { + "id" : locationIds + } + let entityData = await sunbirdService.learnerLocationSearch( bodyData ); + + if ( !entityData.success || !entityData.data.count > 0 ) { + return resolve({ + status: httpStatusCode["bad_request"].status, + message: constants.apiResponses.ENTITY_NOT_FOUND, + result: {} + }); + } + + entityData.data.response.forEach(entity =>{ + entitiesData.push(entity.id) }); + + solutionDataToBeUpdated["entityType"] = entityData.data.response[0].type; + } - if ( data.type && data.type !== constants.common.IMPROVEMENT_PROJECT ) { - solutionDataToBeUpdated["entities"] = entityData.data.response.map( - - (entity) => entity.id - ); + if( orgExternalId.length > 0 ) { + let filterData = { + "externalId" : orgExternalId + } + let schoolDetails = await sunbirdService.schoolData( filterData ); + if( !schoolDetails.success || !schoolDetails.data.response.content > 0 ) { + return resolve({ + status: httpStatusCode["bad_request"].status, + message: constants.apiResponses.ENTITY_NOT_FOUND, + result: {} + }); + } + let schoolData = schoolDetails.data.response.content; + schoolData.forEach(entity =>{ + entitiesData.push(entity.identifier) + }); + + solutionDataToBeUpdated["entityType"] = constants.common.SCHOOL; } - solutionDataToBeUpdated["entityType"] = entityData.data.response[0].type; - + if ( data.type && data.type !== constants.common.IMPROVEMENT_PROJECT ) { + solutionDataToBeUpdated["entities"] = entitiesData; + } } //solution part @@ -616,7 +644,7 @@ module.exports = class UsersHelper { let entityData = await sunbirdService.learnerLocationSearch( bodyData ); - if ( !entityData.data.response.length > 0) { + if ( !entityData.success || !entityData.data.response.length > 0) { throw { message: constants.apiResponses.ENTITIES_NOT_EXIST_IN_LOCATION, }; @@ -726,7 +754,7 @@ module.exports = class UsersHelper { } } let entitiesData = await sunbirdService.learnerLocationSearch( filterData ); - if( entitiesData.count > 0 ){ + if( !entitiesData.success || entitiesData.count > 0 ){ targetedEntityType = constants.common.STATE_ENTITY_TYPE; } } @@ -741,7 +769,7 @@ module.exports = class UsersHelper { }; } let entitiesDocument = await sunbirdService.learnerLocationSearch( filterData ); - if (!entitiesDocument.data.count > 0) { + if ( !entitiesDocument.success || !entitiesDocument.data.count > 0) { throw { message: constants.apiResponses.ENTITY_NOT_FOUND }; @@ -790,7 +818,7 @@ module.exports = class UsersHelper { let entitiesData = await sunbirdService.learnerLocationSearch( filterData ); - if( !entitiesData.data.response.length > 0 ) { + if( !entitiesData.success || !entitiesData.data.response.length > 0 ) { return resolve({ message : constants.apiResponses.ENTITY_NOT_FOUND, result : [] From 4de70fbf8374609309283c1ba1b28b54a5214cfb Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 24 Mar 2022 13:10:06 +0530 Subject: [PATCH 119/331] 4.7 hotfix --- controllers/v1/solutions.js | 2 +- controllers/v1/users.js | 5 ++-- models/programs.js | 13 +++++++--- models/solutions.js | 15 +++++++++--- models/user-roles.js | 4 ++- module/programs/helper.js | 49 +++++++++++++++++++++---------------- module/solutions/helper.js | 28 +++++++++------------ module/users/helper.js | 25 +++++++++++++------ 8 files changed, 86 insertions(+), 55 deletions(-) diff --git a/controllers/v1/solutions.js b/controllers/v1/solutions.js index a93357f2..2b518c0b 100644 --- a/controllers/v1/solutions.js +++ b/controllers/v1/solutions.js @@ -835,7 +835,7 @@ module.exports = class Solutions extends Abstract { * @method * @name verifyLink * @param {Object} req - requested data. - * @param {String} req.params._id - solution Id + * @param {String} req.params._id - solution link * @returns {Array} */ diff --git a/controllers/v1/users.js b/controllers/v1/users.js index c4e58b43..c983fe5f 100644 --- a/controllers/v1/users.js +++ b/controllers/v1/users.js @@ -426,10 +426,11 @@ module.exports = class Users extends Abstract { let currentMaximumCountOfRequiredEntities = 0; let requiredEntities = new Array; + let roleArray = req.query.role.split(","); // Calculate required entities for each of the role and send the output of the role which has maximum length. - for (let roleCount = 0; roleCount < req.query.role.split(",").length; roleCount++) { - const eachRole = req.query.role.split(",")[roleCount]; + for (let roleCount = 0; roleCount < roleArray.length; roleCount++) { + const eachRole = roleArray[roleCount]; const entitiesMappingData = await usersHelper.entityTypesByLocationAndRole( req.params._id, diff --git a/models/programs.js b/models/programs.js index 02bcdea9..dcacd41b 100644 --- a/models/programs.js +++ b/models/programs.js @@ -2,8 +2,14 @@ module.exports = { name: "programs", schema: { externalId: String, - name: String, - description: String, + name: { + type : String, + index : true + }, + description: { + type : String, + index : true + }, owner: String, createdBy: String, updatedBy: String, @@ -20,7 +26,8 @@ module.exports = { components: ["json"], isAPrivateProgram : { default : false, - type : Boolean + type : Boolean, + index : true }, scope : { entityType : String, diff --git a/models/solutions.js b/models/solutions.js index ee2a69d6..8d02825b 100644 --- a/models/solutions.js +++ b/models/solutions.js @@ -3,8 +3,14 @@ module.exports = { schema: { externalId: String, isReusable: Boolean, - name: String, - description: String, + name: { + type : String, + index : true + }, + description: { + type : String, + index : true + }, author: String, parentSolutionId: "ObjectId", resourceType: Array, @@ -87,7 +93,10 @@ module.exports = { }, criteriaLevelReport : Boolean, license:Object, - link: String, + link: { + type : String, + index : true + }, minNoOfSubmissionsRequired: { type: Number, default: 1 diff --git a/models/user-roles.js b/models/user-roles.js index bf9dce95..455f3ca7 100644 --- a/models/user-roles.js +++ b/models/user-roles.js @@ -10,7 +10,9 @@ module.exports = { schema: { code: { type: String, - required: true + required: true, + index: true, + unique: true }, title: { type: String, diff --git a/module/programs/helper.js b/module/programs/helper.js index 962e12f5..8ef01fe7 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -498,29 +498,36 @@ module.exports = class ProgramsHelper { if ( targetedPrograms.success && targetedPrograms.data && targetedPrograms.data.data.length > 0) { - for ( - let targetedProgram = 0; - targetedProgram < targetedPrograms.data.data.length; - targetedProgram ++ - ) { - - let currentTargetedProgram = targetedPrograms.data.data[targetedProgram]; - - if( currentTargetedProgram.components.length > 0 ) { - - let solutions = await solutionsHelper.solutionDocuments({ - _id : { $in : currentTargetedProgram.components }, - isDeleted : false, - status : constants.common.ACTIVE - },["_id"]); - - if( solutions && solutions.length > 0 ) { - currentTargetedProgram["solutions"] = solutions.length; - delete currentTargetedProgram.components; - } + let componentsIds = []; + targetedPrograms.data.data.forEach(targetedProgram => { + if( targetedProgram.components.length > 0 ) { + componentsIds = componentsIds.concat(targetedProgram.components); + } + }); + + let solutions = await solutionsHelper.solutionDocuments({ + _id : { $in : componentsIds }, + isDeleted : false, + status : constants.common.ACTIVE + },["_id"]); + + const solutionsIds = [] + solutions.forEach(solution => solutionsIds.push(solution._id.toString())); + + targetedPrograms.data.data.forEach(targetedProgram => { + if( targetedProgram.components.length > 0 ) { + + let countSolutions = 0; + targetedProgram.components.forEach(component => { + if (solutionsIds.includes(component.toString())) { + countSolutions++; } - } + }); + targetedProgram.solutions = countSolutions; + delete targetedProgram.components; + } + }); } return resolve({ diff --git a/module/solutions/helper.js b/module/solutions/helper.js index f9571fd5..0970a832 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -1379,15 +1379,13 @@ module.exports = class SolutionsHelper { } let targetedSolutions = { - success: false, + success: false }; let getTargetedSolution = true; if ( filter === constants.common.DISCOVERED_BY_ME ) { getTargetedSolution = false; - } else if ( solutionType === constants.common.COURSE ) { - getTargetedSolution = true; } else if ( gen.utils.convertStringToBoolean(surveyReportPage) === true ) { getTargetedSolution = false; } @@ -1407,11 +1405,12 @@ module.exports = class SolutionsHelper { if( targetedSolutions.success ) { - if( targetedSolutions.data.data && targetedSolutions.data.data.length > 0 ) { - totalCount += targetedSolutions.data.count; - targetedSolutions.data.data.forEach(targetedSolution => { - targetedSolution.solutionId = targetedSolution._id; - targetedSolution._id = ""; + if( targetedSolutions.success && targetedSolutions.data.data && targetedSolutions.data.data.length > 0 ) { + + totalCount += targetedSolutions.data.count; + targetedSolutions.data.data.forEach(targetedSolution => { + targetedSolution.solutionId = targetedSolution._id; + targetedSolution._id = ""; if( solutionType !== constants.common.COURSE ) { targetedSolution["creator"] = targetedSolution.creator ? targetedSolution.creator : ""; @@ -1420,7 +1419,7 @@ module.exports = class SolutionsHelper { if ( solutionType === constants.common.SURVEY ) { targetedSolution.isCreator = false; } - + mergedData.push(targetedSolution); delete targetedSolution.type; delete targetedSolution.externalId; @@ -1440,8 +1439,8 @@ module.exports = class SolutionsHelper { message: constants.apiResponses.TARGETED_OBSERVATION_FETCHED, data: { data: mergedData, - count: totalCount, - }, + count: totalCount + } }); } catch (error) { return reject({ @@ -1735,10 +1734,6 @@ module.exports = class SolutionsHelper { verified: false, }; - if ( link == "" ) { - throw new Error(constants.apiResponses.LINK_REQUIRED_CHECK); - } - if ( userToken == "" ) { throw new Error(constants.apiResponses.REQUIRED_USER_AUTH_TOKEN); } @@ -1798,7 +1793,8 @@ module.exports = class SolutionsHelper { message: constants.apiResponses.LINK_VERIFIED, result: response, }); - } catch (error) { + } + catch (error) { return resolve({ success: false, status: error.status diff --git a/module/users/helper.js b/module/users/helper.js index 5e8aaa08..58e4fd6a 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -599,7 +599,7 @@ module.exports = class UsersHelper { } const entitiesData = await entitiesHelper.entityDocuments(filterQuery, [ - "_id", + "_id", "childHierarchyPath" ]); if (!entitiesData.length > 0) { @@ -623,24 +623,33 @@ module.exports = class UsersHelper { let entityTypes = []; let stateEntityExists = false; + let roleEntityType = ""; rolesDocument[0].entityTypes.forEach((roleDocument) => { if (roleDocument.entityType === constants.common.STATE_ENTITY_TYPE) { stateEntityExists = true; } + if (entitiesData[0].childHierarchyPath.includes(roleDocument.entityType)) { + roleEntityType = roleDocument.entityType; + } + }); + let entityTypeIndex = + entitiesData[0].childHierarchyPath.findIndex(path => path === roleEntityType); + if (stateEntityExists) { entityTypes = [constants.common.STATE_ENTITY_TYPE]; } else { - let entitiesMappingForm = await this.entitiesMappingForm( - entitiesData[0]._id, - rolesDocument[0]._id - ); + for ( + let pointerToChildHierarchy = 0; + pointerToChildHierarchy < entityTypeIndex + 1; + pointerToChildHierarchy++ + ) { - entitiesMappingForm.result.forEach((entitiesMappingData) => { - entityTypes.push(entitiesMappingData.field); - }); + let entityType = entitiesData[0].childHierarchyPath[pointerToChildHierarchy]; + entityTypes.push(entityType); + } } return resolve({ From 06be0ca63061cd11df258ffd86b1e7bde8471128 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 24 Mar 2022 14:10:51 +0530 Subject: [PATCH 120/331] users change --- module/users/helper.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/module/users/helper.js b/module/users/helper.js index 8e58d80d..5a64779a 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -172,7 +172,7 @@ module.exports = class UsersHelper { } }); - if( locationIds.length > 0 ){ + if ( locationIds.length > 0 ){ bodyData = { "id" : locationIds @@ -187,7 +187,7 @@ module.exports = class UsersHelper { }); } - entityData.data.response.forEach(entity =>{ + entityData.data.response.forEach( entity => { entitiesData.push(entity.id) }); @@ -195,7 +195,7 @@ module.exports = class UsersHelper { } - if( orgExternalId.length > 0 ) { + if ( orgExternalId.length > 0 ) { let filterData = { "externalId" : orgExternalId } From 7e49cafa42bf04b7b94d3b35919c0ed5eeb1a540 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 24 Mar 2022 14:20:43 +0530 Subject: [PATCH 121/331] targetedEntity - multiple role case hotfix --- controllers/v1/users.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/controllers/v1/users.js b/controllers/v1/users.js index c983fe5f..487b2235 100644 --- a/controllers/v1/users.js +++ b/controllers/v1/users.js @@ -566,8 +566,8 @@ module.exports = class Users extends Abstract { message: constants.apiResponses.ENTITIES_NOT_ALLOWED_IN_ROLE }; } - - targetedEntities.result = targetedEntity.data; + + targetedEntities.result = targetedEntity.data[0]; } } From 831f5f7b5e556529e78895f42e3c8de22843a1b4 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Tue, 29 Mar 2022 09:52:47 +0530 Subject: [PATCH 122/331] callback name change --- generics/services/sunbird.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/generics/services/sunbird.js b/generics/services/sunbird.js index 86331db2..dcc6e0bb 100644 --- a/generics/services/sunbird.js +++ b/generics/services/sunbird.js @@ -46,13 +46,13 @@ const learnerLocationSearch = function ( filterData, limit = "", offset = "" ) json : bodyData }; - request.post(url,options,kendraCallback); + request.post(url,options,sunbirdCallback); let result = { success : true }; - function kendraCallback(err, data) { + function sunbirdCallback(err, data) { if (err) { @@ -112,11 +112,11 @@ const formRead = function ( subTypeData ) { json : bodyData }; - request.post(url,options,kendraCallback); + request.post(url,options,sunbirdCallback); let result = { success : true }; - function kendraCallback(err, data) { + function sunbirdCallback(err, data) { if (err) { @@ -174,12 +174,12 @@ const schoolData = function ( filterData ) { json : bodyData }; - request.post(url,options,kendraCallback); + request.post(url,options,sunbirdCallback); let result = { success : true }; - function kendraCallback(err, data) { + function sunbirdCallback(err, data) { From 072f662fcbe2dc95232c18b6495796a751dae3ac Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Wed, 30 Mar 2022 18:48:34 +0530 Subject: [PATCH 123/331] env added --- envVariables.js | 4 ++++ module/solutions/helper.js | 1 - 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/envVariables.js b/envVariables.js index ee9f0312..4b842053 100644 --- a/envVariables.js +++ b/envVariables.js @@ -129,6 +129,10 @@ let enviromentVariables = { "message" : "App Portal base url", "optional" : true, "default": "https://dev.sunbirded.org" + }, + "SUNBIRD_SERVICE_URL" : { + "message" : "Required sunbird service url", + "optional" : false } } diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 747e2000..65458c87 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -808,7 +808,6 @@ module.exports = class SolutionsHelper { } queryData.data["_id"] = solutionId; - let targetedSolutionDetails = await this.solutionDocuments( queryData.data, From aaffad007d879f91ef78b323ea29808b61f5704e Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 31 Mar 2022 11:14:44 +0530 Subject: [PATCH 124/331] response.data check --- generics/services/sunbird.js | 8 ++++---- module/entities/helper.js | 8 ++++---- module/programs/helper.js | 6 +++--- module/solutions/helper.js | 8 ++++---- module/users/helper.js | 13 +++++++------ 5 files changed, 22 insertions(+), 21 deletions(-) diff --git a/generics/services/sunbird.js b/generics/services/sunbird.js index dcc6e0bb..78466eda 100644 --- a/generics/services/sunbird.js +++ b/generics/services/sunbird.js @@ -10,7 +10,7 @@ const request = require('request'); const sunbirdBaseUrl = process.env.SUNBIRD_SERVICE_URL; -const sunbirdOrgBaseUrl = process.env.SUNBIRD_ORG_URL; +const serverTimeout = process.env.SUNBIRD_SERVER_TIMEOUT ? parseInt(process.env.SUNBIRD_SERVER_TIMEOUT) : 500; /** * @@ -73,7 +73,7 @@ const learnerLocationSearch = function ( filterData, limit = "", offset = "" ) return reject (result = { success : false }); - }, constants.common.SUNBIRD_SERVER_TIMEOUT); + }, serverTimeout); } catch (error) { @@ -138,7 +138,7 @@ const formRead = function ( subTypeData ) { return reject (result = { success : false }); - }, constants.common.SUNBIRD_SERVER_TIMEOUT); + }, serverTimeout); } catch (error) { return reject(error); @@ -201,7 +201,7 @@ const schoolData = function ( filterData ) { return reject (result = { success : false }); - }, constants.common.SUNBIRD_SERVER_TIMEOUT); + }, serverTimeout); } catch (error) { return reject(error); diff --git a/module/entities/helper.js b/module/entities/helper.js index e93c5fce..d5fb42af 100644 --- a/module/entities/helper.js +++ b/module/entities/helper.js @@ -252,7 +252,7 @@ module.exports = class EntitiesHelper { let entitiesData = await sunbirdService.learnerLocationSearch( bodyData ); - if( !entitiesData.success ||!entitiesData.data.response.length > 0 ) { + if( !entitiesData.success || !entitiesData.data || !entitiesData.data.response.length > 0 ) { return resolve(entitiesData.data.response) } @@ -523,7 +523,7 @@ module.exports = class EntitiesHelper { } let subentitiesCode = await sunbirdService.schoolData( filterData ); let schoolDetails = subentitiesCode.data.response.content; - if( !schoolDetails.length > 0 ) { + if( !subentitiesCode.success || !schoolDetails.length > 0 ) { return resolve(schoolDetails) } @@ -910,7 +910,7 @@ module.exports = class EntitiesHelper { let entitiesData = await sunbirdService.learnerLocationSearch( bodyData ); - if( !entitiesData.success || !entitiesData.data.response.length > 0 ) { + if( !entitiesData.success || !entitiesData.data || !entitiesData.data.response.length > 0 ) { return resolve({ message : constants.apiResponses.ENTITY_NOT_FOUND, result : [] @@ -1067,7 +1067,7 @@ async function subEntitiesWithMatchingType( parentIds,entityType,matchingData ){ let entityDetails = await sunbirdService.learnerLocationSearch(bodyData); - if( ( !entityDetails.success || !entityDetails.data.response.length > 0 ) && !matchingData.length > 0 ) { + if( ( !entityDetails.success || !entityDetails.data || !entityDetails.data.response.length > 0 ) && !matchingData.length > 0 ) { return matchingData; } diff --git a/module/programs/helper.js b/module/programs/helper.js index 8e3a7d90..72715676 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -213,7 +213,7 @@ module.exports = class ProgramsHelper { } let entityTypeData = await sunbirdService.learnerLocationSearch( bodyData ); - if( !entityTypeData.success || !entityTypeData.data.response.length > 0 ) { + if( !entityTypeData.success || !entityTypeData.data || !entityTypeData.data.response.length > 0 ) { return resolve({ status : httpStatusCode.bad_request.status, message : constants.apiResponses.ENTITY_TYPES_NOT_FOUND @@ -242,7 +242,7 @@ module.exports = class ProgramsHelper { let entityData = await sunbirdService.learnerLocationSearch( bodyData ); - if( !entityData.success || !entityData.data.response.length > 0 ) { + if( !entityData.success || !entityData.data || !entityData.data.response.length > 0 ) { return resolve({ status : httpStatusCode.bad_request.status, message : constants.apiResponses.ENTITIES_NOT_FOUND @@ -740,7 +740,7 @@ module.exports = class ProgramsHelper { let entitiesData = await sunbirdService.learnerLocationSearch( bodyData ); - if( !entitiesData.success || !entitiesData.data.count > 0 ) { + if( !entitiesData.success || !entitiesData.data || !entitiesData.data.count > 0 ) { throw { message : constants.apiResponses.ENTITIES_NOT_FOUND }; diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 65458c87..43c32fb4 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -139,7 +139,7 @@ module.exports = class SolutionsHelper { let entitiesDetails = await sunbirdService.learnerLocationSearch( bodyData ); - if( !entitiesDetails.success || !entitiesDetails.data.response.length > 0 ) { + if( !entitiesDetails.success || !entitiesDetails.data || !entitiesDetails.data.response.length > 0 ) { throw { message : constants.apiResponses.ENTITIES_NOT_FOUND } @@ -264,7 +264,7 @@ module.exports = class SolutionsHelper { }; let entityDetails = await sunbirdService.learnerLocationSearch(bodyData); - if( !entityDetails.success || !entityDetails.data.response.length > 0 ) { + if( !entityDetails.success || !entityDetails.data || !entityDetails.data.response.length > 0 ) { return resolve({ status : httpStatusCode.bad_request.status, message : constants.apiResponses.ENTITIES_NOT_FOUND @@ -1011,7 +1011,7 @@ module.exports = class SolutionsHelper { let entitiesDetails = await sunbirdService.learnerLocationSearch( bodyData ); - if( !entitiesDetails.success || !entitiesDetails.data.response.length > 0 ) { + if( !entitiesDetails.success || !entitiesDetails.data || !entitiesDetails.data.response.length > 0 ) { return resolve({ status : httpStatusCode.bad_request.status, message : constants.apiResponses.ENTITIES_NOT_FOUND @@ -2002,7 +2002,7 @@ async function entitiesInParent( solutionEntities,currentEntityType,matchingData let entityDetails = await sunbirdService.learnerLocationSearch(bodyData); - if( ( !entityDetails.success || !entityDetails.data.response.length > 0) && !matchingData.length > 0 ) { + if( ( !entityDetails.success || !entityDetails.data || !entityDetails.data.response.length > 0) && !matchingData.length > 0 ) { return ({ status : httpStatusCode.bad_request.status, message : constants.apiResponses.ENTITIES_NOT_FOUND diff --git a/module/users/helper.js b/module/users/helper.js index 5a64779a..dc43c976 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -179,7 +179,7 @@ module.exports = class UsersHelper { } let entityData = await sunbirdService.learnerLocationSearch( bodyData ); - if ( !entityData.success || !entityData.data.count > 0 ) { + if ( !entityData.success || !entityData.data || !entityData.data.count > 0 ) { return resolve({ status: httpStatusCode["bad_request"].status, message: constants.apiResponses.ENTITY_NOT_FOUND, @@ -200,7 +200,8 @@ module.exports = class UsersHelper { "externalId" : orgExternalId } let schoolDetails = await sunbirdService.schoolData( filterData ); - if( !schoolDetails.success || !schoolDetails.data.response.content > 0 ) { + let schoolDocuments = schoolDetails.data.response.content; + if( !schoolDetails.success || !schoolDocuments.length > 0 ) { return resolve({ status: httpStatusCode["bad_request"].status, message: constants.apiResponses.ENTITY_NOT_FOUND, @@ -644,7 +645,7 @@ module.exports = class UsersHelper { let entityData = await sunbirdService.learnerLocationSearch( bodyData ); - if ( !entityData.success || !entityData.data.response.length > 0) { + if ( !entityData.success || !entityData.data || !entityData.data.response.length > 0) { throw { message: constants.apiResponses.ENTITIES_NOT_EXIST_IN_LOCATION, }; @@ -754,7 +755,7 @@ module.exports = class UsersHelper { } } let entitiesData = await sunbirdService.learnerLocationSearch( filterData ); - if( !entitiesData.success || entitiesData.count > 0 ){ + if( !entitiesData.success ||!entityData.data || !entityData.data.response.length > 0 ){ targetedEntityType = constants.common.STATE_ENTITY_TYPE; } } @@ -769,7 +770,7 @@ module.exports = class UsersHelper { }; } let entitiesDocument = await sunbirdService.learnerLocationSearch( filterData ); - if ( !entitiesDocument.success || !entitiesDocument.data.count > 0) { + if ( !entitiesDocument.success || !entitiesDocument.data || !entitiesDocument.data.count > 0) { throw { message: constants.apiResponses.ENTITY_NOT_FOUND }; @@ -818,7 +819,7 @@ module.exports = class UsersHelper { let entitiesData = await sunbirdService.learnerLocationSearch( filterData ); - if( !entitiesData.success || !entitiesData.data.response.length > 0 ) { + if( !entitiesData.success || !entitiesData.data || !entitiesData.data.response.length > 0 ) { return resolve({ message : constants.apiResponses.ENTITY_NOT_FOUND, result : [] From df9f82a509f835f4eed346a85aa14bdfd6454edf Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 1 Apr 2022 15:25:32 +0530 Subject: [PATCH 125/331] subentity api changes --- generics/services/sunbird.js | 48 +++++-- module/entities/helper.js | 241 ++++++++++++++++++++++------------- 2 files changed, 190 insertions(+), 99 deletions(-) diff --git a/generics/services/sunbird.js b/generics/services/sunbird.js index 78466eda..057cabef 100644 --- a/generics/services/sunbird.js +++ b/generics/services/sunbird.js @@ -11,7 +11,7 @@ const request = require('request'); const sunbirdBaseUrl = process.env.SUNBIRD_SERVICE_URL; const serverTimeout = process.env.SUNBIRD_SERVER_TIMEOUT ? parseInt(process.env.SUNBIRD_SERVER_TIMEOUT) : 500; - +const dataLimit = process.env.SUNBIRD_RESPONSE_DATA_LIMIT ? parseInt(process.env.SUNBIRD_RESPONSE_DATA_LIMIT) : 10000; /** * * @function @@ -21,18 +21,27 @@ const serverTimeout = process.env.SUNBIRD_SERVER_TIMEOUT ? parseInt(process.env. * @returns {Promise} returns a promise. */ -const learnerLocationSearch = function ( filterData, limit = "", offset = "" ) { +const learnerLocationSearch = function ( filterData, pageSize = "", pageNo = "", searchKey = "" ) { return new Promise(async (resolve, reject) => { try { - - let bodyData={}; + + let bodyData = {}; bodyData["request"] = {}; bodyData["request"]["filters"] = filterData; - if( limit !== "" ) { - bodyData["request"]["limit"] = limit; + + if ( pageSize !== "" ) { + bodyData["request"]["limit"] = pageSize; + } else { + bodyData["request"]["limit"] = dataLimit; } - if( offset !== "" ) { - bodyData["request"]["offset"] = offset; + + if ( pageNo !== "" ) { + let offsetValue = pageSize * ( pageNo - 1 ); + bodyData["request"]["offset"] = offsetValue; + } + + if ( searchKey !== "" ) { + bodyData["request"]["query"] = searchKey } @@ -154,15 +163,28 @@ const formRead = function ( subTypeData ) { * @param {object} bodyData - location id * @returns {Promise} returns a promise. */ -const schoolData = function ( filterData ) { +const schoolData = function ( filterData, pageSize = "", pageNo = "", searchKey = "" ) { return new Promise(async (resolve, reject) => { try { - let bodyData = { - request : { - filters : filterData - } + let bodyData = {}; + bodyData["request"] = {}; + bodyData["request"]["filters"] = filterData; + + if ( pageSize !== "" ) { + bodyData["request"]["limit"] = pageSize; + } + + if ( pageNo !== "" ) { + let offsetValue = pageSize * ( pageNo - 1 ); + bodyData["request"]["offset"] = offsetValue; } + + if ( searchKey !== "" ) { + bodyData["request"]["query"] = searchKey + } + + const url = sunbirdBaseUrl + constants.endpoints.GET_SCHOOL_DATA; diff --git a/module/entities/helper.js b/module/entities/helper.js index d5fb42af..4fcee693 100644 --- a/module/entities/helper.js +++ b/module/entities/helper.js @@ -250,24 +250,39 @@ module.exports = class EntitiesHelper { "parentId" : entityId }; - let entitiesData = await sunbirdService.learnerLocationSearch( bodyData ); + let entitiesData = await sunbirdService.learnerLocationSearch( + bodyData, + pageSize, + pageNo, + searchText + ); if( !entitiesData.success || !entitiesData.data || !entitiesData.data.response.length > 0 ) { - return resolve(entitiesData.data.response) + return resolve({ + data : entitiesData.data.response, + count : entitiesData.data.count + }); } let immediateLocation = entitiesData.data.response; - if( searchText !== "" ){ - let matchEntities = []; - immediateLocation.map( entityData => { - if( entityData.name.match(new RegExp(searchText, 'i')) || entityData.code.match(new RegExp("^" + searchText, 'm')) ) { - matchEntities.push(entityData) - } - }); - immediateLocation = []; - immediateLocation = matchEntities; - } + + return resolve({ + data : immediateLocation, + count : entitiesData.data.count + }); + + + // if( searchText !== "" ){ + // let matchEntities = []; + // immediateLocation.map( entityData => { + // if( entityData.name.match(new RegExp(searchText, 'i')) || entityData.code.match(new RegExp("^" + searchText, 'm')) ) { + // matchEntities.push(entityData) + // } + // }); + // immediateLocation = []; + // immediateLocation = matchEntities; + // } // let formatedEntities = []; @@ -285,7 +300,7 @@ module.exports = class EntitiesHelper { // immediateLocation = []; // immediateLocation = formatedEntities; - return resolve(immediateLocation); + @@ -367,64 +382,87 @@ module.exports = class EntitiesHelper { try { let result = {}; - let aggregateEntitiesData = []; + let subentitiesResult = {}; let uniqueEntities = []; let obj = { entityId : entityId, type : type, - search : search + search : search, + limit :limit, + pageNo : pageNo } if ( entityId !== "" ) { - uniqueEntities = await this.subEntities( + subentitiesResult = await this.subEntities( obj ); } else { - await Promise.all(entities.map(async (entity)=> { - - obj["entityId"] = entity; - let entitiesDocument = await this.subEntities( + obj["entityId"] = entities; + subentitiesResult = await this.subEntities( obj ); - if( Array.isArray(entitiesDocument) && - entitiesDocument.length > 0 - ) { - entitiesDocument.forEach(entityData => { - aggregateEntitiesData.push(entityData); - }); - } - })); - aggregateEntitiesData.map( data => { - if (uniqueEntities.includes(data) === false) uniqueEntities.push(data); - }); + } - let formatedEntities = []; - - uniqueEntities.map( entityData => { - let data = {}; - data._id = entityData.id; - data.entityType = entityData.type; - data.name = entityData.name; - data.externalId = entityData.code; - data.label = entityData.name; - data.value = entityData.id - formatedEntities.push(data) - } ); - - uniqueEntities = []; - uniqueEntities = formatedEntities; - - let totalcount = uniqueEntities.length; - if (uniqueEntities.length > 0) { - let startIndex = limit * (pageNo - 1); - let endIndex = startIndex + limit; - uniqueEntities = uniqueEntities.slice(startIndex, endIndex); + + if ( subentitiesResult && subentitiesResult.data && subentitiesResult.data.length > 0 ) { + let formatedEntities = []; + uniqueEntities = subentitiesResult.data + uniqueEntities.map( entityData => { + let data = {}; + data._id = entityData.id; + data.entityType = entityData.type; + data.name = entityData.name; + data.externalId = entityData.code; + data.label = entityData.name; + data.value = entityData.id + formatedEntities.push(data) + } ); + uniqueEntities = []; + uniqueEntities = formatedEntities; } + result.data = uniqueEntities; - result.count = totalcount; + result.count = subentitiesResult.count; + + resolve({ + message: constants.apiResponses.ENTITIES_FETCHED, + result: result + }); + //remove when new code confirmed. + + //let totalcount = uniqueEntities.length; + // if (uniqueEntities.length > 0) { + // let startIndex = limit * (pageNo - 1); + // let endIndex = startIndex + limit; + // uniqueEntities = uniqueEntities.slice(startIndex, endIndex); + // } + + // if ( entityId !== "" ) { + // uniqueEntities = await this.subEntities( + // obj + // ); + // } else { + // await Promise.all(entities.map(async (entity)=> { + + // obj["entityId"] = entity; + // let entitiesDocument = await this.subEntities( + // obj + // ); + // if( Array.isArray(entitiesDocument) && + // entitiesDocument.length > 0 + // ) { + // entitiesDocument.forEach(entityData => { + // aggregateEntitiesData.push(entityData); + // }); + // } + // })); + // aggregateEntitiesData.map( data => { + // if (uniqueEntities.includes(data) === false) uniqueEntities.push(data); + // }); + // } // if( result.data && result.data.length > 0 ) { // result.data = result.data.map(data=>{ // let cloneData = {...data}; @@ -434,10 +472,7 @@ module.exports = class EntitiesHelper { // }) // } - resolve({ - message: constants.apiResponses.ENTITIES_FETCHED, - result: result - }); + } catch(error) { return reject(error); } @@ -464,14 +499,19 @@ module.exports = class EntitiesHelper { entitiesDocument = await this.entityTraversal( entitiesData.entityId, entitiesData.type, - entitiesData.search + entitiesData.search, + entitiesData.limit, + entitiesData.pageNo ); } else { entitiesDocument = await this.immediateEntities( entitiesData.entityId, - entitiesData.search + entitiesData.search, + entitiesData.limit, + entitiesData.pageNo ); } + return resolve(entitiesDocument); // if( entitiesData.type !== "" ) { @@ -512,21 +552,30 @@ module.exports = class EntitiesHelper { static entityTraversal( entityId, entityTraversalType = "", - searchText = "" + searchText = "", + pageSize = "", + pageNo = "", ) { return new Promise(async (resolve, reject) => { try { - let subentitiesData = []; + if( entityTraversalType == constants.common.SCHOOL) { let filterData = { "orgLocation.id" : entityId } - let subentitiesCode = await sunbirdService.schoolData( filterData ); - let schoolDetails = subentitiesCode.data.response.content; - if( !subentitiesCode.success || !schoolDetails.length > 0 ) { - return resolve(schoolDetails) - } + let subentitiesCode = await sunbirdService.schoolData( filterData, pageSize, pageNo, searchText ); + if( !subentitiesCode.success || + !subentitiesCode.data || + !subentitiesCode.data.response || + !subentitiesCode.data.response.content || + !subentitiesCode.data.response.content.length > 0 ) { + return resolve({ + data : [], + count : subentitiesCode.data.response.count + }) + } + let schoolDetails = subentitiesCode.data.response.content; //get code from all data let schoolCodes = []; schoolDetails.map(schoolData=> { @@ -541,37 +590,57 @@ module.exports = class EntitiesHelper { let entitiesData = await sunbirdService.learnerLocationSearch( bodyData ); - if( !entitiesData.data.response.length > 0 ) { - return resolve(entitiesData.data.response) + if( !entitiesData.success || !entitiesData.data || !entitiesData.data.response.length > 0 ) { + return resolve({ + data : [], + count : 0 + }) } - - subentitiesData = entitiesData.data.response; + return resolve({ + data : subentitiesData, + count : subentitiesCode.data.response.count + }) + } else { let subEntitiesMatchingType = []; - let parentId = []; - parentId.push(entityId); - let subEntities = await subEntitiesWithMatchingType( parentId,entityTraversalType,subEntitiesMatchingType ) + + let subEntities = await subEntitiesWithMatchingType( entityId,entityTraversalType,subEntitiesMatchingType ) if( !subEntities.length > 0 ) { - return resolve(subEntities) + return resolve({ + data : subEntities, + count : 0 + }) } - subentitiesData = subEntities + let subentitiesData = subEntities + let count = subentitiesData.length; + if( searchText !== "" ){ + let matchEntities = []; + subentitiesData.map( entityData => { + if( entityData.name.match(new RegExp(searchText, 'i')) || entityData.code.match(new RegExp("^" + searchText, 'm')) ) { + matchEntities.push(entityData) + } + }); + subentitiesData = []; + subentitiesData = matchEntities; + } + + if (subentitiesData.length > 0) { + let startIndex = pageSize * (pageNo - 1); + let endIndex = startIndex + pageSize; + subentitiesData = subentitiesData.slice(startIndex, endIndex); + } + return resolve({ + data : subentitiesData, + count : count + }) } - if( searchText !== "" ){ - let matchEntities = []; - subentitiesData.map( entityData => { - if( entityData.name.match(new RegExp(searchText, 'i')) || entityData.code.match(new RegExp("^" + searchText, 'm')) ) { - matchEntities.push(entityData) - } - }); - subentitiesData = []; - subentitiesData = matchEntities; - } + // let formatedEntities = []; // subentitiesData.map( entityData => { @@ -588,7 +657,7 @@ module.exports = class EntitiesHelper { // subentitiesData = []; // subentitiesData = formatedEntities; - return resolve(subentitiesData); + // let subEntitiesMatchingType = []; // let parentId = []; From ad6db383618c2d9ebfc81aabd04705f9ac2aee5a Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Mon, 18 Apr 2022 11:18:34 +0530 Subject: [PATCH 126/331] solution read api --- controllers/v1/solutions.js | 62 +++++++++++++++++++++++++++++++++++++ models/solutions.js | 19 +++++++++++- module/solutions/helper.js | 45 +++++++++++++++++++++++++++ 3 files changed, 125 insertions(+), 1 deletion(-) diff --git a/controllers/v1/solutions.js b/controllers/v1/solutions.js index a93357f2..431cc934 100644 --- a/controllers/v1/solutions.js +++ b/controllers/v1/solutions.js @@ -989,4 +989,66 @@ module.exports = class Solutions extends Abstract { }) } + /** + * @api {get} /kendra/api/v1/solutions/read/:solutionId Read Solution Report Informations + * @apiVersion 1.0.0 + * @apiName Read Solution Report Informations + * @apiGroup Solutions + * @apiSampleRequest /kendra/api/v1/solutions/read/5ff9d50f9259097d48017bbb + * @apiHeader {String} X-authenticated-user-token Authenticity token + * @apiUse successBody + * @apiUse errorBody + * @apiParamExample {json} Response: + * { + "message": "Solution details fetched successfully", + "status": 200, + "result": { + "districts": [ + "2f76dcf5-e43b-4f71-a3f2-c8f19e1fce03", + "aecac7ab-15e4-45c9-ac7b-d716444cd652" + ], + "organisations": [ + { + "orgName": "TAMILNADU", + "organisationId": "01269878797503692810" + }, + { + "orgName": "JHS NARHARPUR", + "organisationId": "0869878797503692810" + } + ] + } + } + */ + + /** + * Read Solution Report Informations. + * @method + * @name read + * @param {Object} req - requested data. + * @param {String} req.params._id - solution id. + * @returns {JSON} + */ + + async read(req) { + return new Promise(async (resolve, reject) => { + try { + + let solutionData = await solutionsHelper.read( + req.params._id, + req.userDetails.id + ); + + return resolve(solutionData); + } + catch (error) { + reject({ + status: error.status || httpStatusCode.internal_server_error.status, + message: error.message || httpStatusCode.internal_server_error.message, + errorObject: error + }) + } + }) + } + } \ No newline at end of file diff --git a/models/solutions.js b/models/solutions.js index ee2a69d6..1cf3c1c4 100644 --- a/models/solutions.js +++ b/models/solutions.js @@ -91,6 +91,23 @@ module.exports = { minNoOfSubmissionsRequired: { type: Number, default: 1 - } + }, + reportInformation : { + districts : { + type : Array, + index : true + }, + organisations : [{ + orgName : { + type : String, + index : true + }, + organisationId : { + type : String, + index : true + } + }] + } + } }; \ No newline at end of file diff --git a/module/solutions/helper.js b/module/solutions/helper.js index f9571fd5..ad175fcb 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -1967,6 +1967,51 @@ module.exports = class SolutionsHelper { }); } + /** + * Solution Report Information. + * @method + * @name read + * @param {String} solutionId - Solution Id. + * @returns {Object} - Report Information of the solution. + */ + + static read(solutionId) { + return new Promise(async (resolve, reject) => { + try { + let solutionData = await this.solutionDocuments({ + _id: solutionId, + isDeleted: false + },["reportInformation"]); + + if ( !Array.isArray(solutionData) || solutionData.length < 1 ) { + return resolve({ + message: constants.apiResponses.SOLUTION_NOT_FOUND, + result: {}, + }); + } + + solutionData = solutionData[0]; + + return resolve({ + message: constants.apiResponses.SOLUTION_DETAILS_FETCHED, + success: true, + result: solutionData.reportInformation ? solutionData.reportInformation : {}, + }); + + } catch (error) { + return resolve({ + success: false, + status: error.status + ? error.status + : httpStatusCode['internal_server_error'].status, + message: error.message, + }); + } + }); + } + + + }; /** From d751f681c8926a563938c2ab054176a595082b2e Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Wed, 20 Apr 2022 11:13:15 +0530 Subject: [PATCH 127/331] PR comments resolved --- controllers/v1/solutions.js | 9 +++++++-- generics/constants/api-responses.js | 4 ++-- models/solutions.js | 18 +----------------- module/solutions/helper.js | 20 +++++++++++++++++++- 4 files changed, 29 insertions(+), 22 deletions(-) diff --git a/controllers/v1/solutions.js b/controllers/v1/solutions.js index 431cc934..03dd7442 100644 --- a/controllers/v1/solutions.js +++ b/controllers/v1/solutions.js @@ -1004,8 +1004,13 @@ module.exports = class Solutions extends Abstract { "status": 200, "result": { "districts": [ - "2f76dcf5-e43b-4f71-a3f2-c8f19e1fce03", - "aecac7ab-15e4-45c9-ac7b-d716444cd652" + { + "name" : "ANANTAPUR", + "locationId" : "2f76dcf5-e43b-4f71-a3f2-c8f19e1fce03", + },{ + "name" : "EAST GODAVARI", + "locationId" : "aecac7ab-15e4-45c9-ac7b-d716444cd652", + } ], "organisations": [ { diff --git a/generics/constants/api-responses.js b/generics/constants/api-responses.js index 45f4c5f8..de65ac3f 100644 --- a/generics/constants/api-responses.js +++ b/generics/constants/api-responses.js @@ -179,6 +179,6 @@ module.exports = { "SOLUTION_NOT_FOUND_OR_NOT_A_TARGETED": "Solution is not targeted to the role", "PROJECT_TEMPLATE_ID_NOT_FOUND": "Project templates not exists in solution", "SOLUTION_TARGETED_ENTITY" : "Targeted Entity Types Fetched", - "ENTITY_ID_OR_LOCATION_ID_NOT_FOUND" : "Entity id or location id not found" - + "ENTITY_ID_OR_LOCATION_ID_NOT_FOUND" : "Entity id or location id not found", + "NOT_AUTHORIZED_TO_ACCESS" :"The program Manager and Designer can only access this resource" }; diff --git a/models/solutions.js b/models/solutions.js index 1cf3c1c4..6ba182a1 100644 --- a/models/solutions.js +++ b/models/solutions.js @@ -92,22 +92,6 @@ module.exports = { type: Number, default: 1 }, - reportInformation : { - districts : { - type : Array, - index : true - }, - organisations : [{ - orgName : { - type : String, - index : true - }, - organisationId : { - type : String, - index : true - } - }] - } - + reportInformation : Object } }; \ No newline at end of file diff --git a/module/solutions/helper.js b/module/solutions/helper.js index ad175fcb..d81f0fd5 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -14,6 +14,7 @@ const userRolesHelper = require(MODULES_BASE_PATH + "/user-roles/helper"); const surveyService = require(ROOT_PATH + '/generics/services/survey'); const improvementProjectService = require(ROOT_PATH + '/generics/services/improvement-project'); const appsPortalBaseUrl = process.env.APP_PORTAL_BASE_URL + "/" ; +const userExtensionsHelper = require(MODULES_BASE_PATH + "/user-extension/helper"); /** * SolutionsHelper @@ -1972,12 +1973,28 @@ module.exports = class SolutionsHelper { * @method * @name read * @param {String} solutionId - Solution Id. + * @param {String} userId - User Id. * @returns {Object} - Report Information of the solution. */ - static read(solutionId) { + static read(solutionId, userId) { return new Promise(async (resolve, reject) => { try { + + let userInformation = await userExtensionsHelper.userExtensionDocument({ + userId: userId, + "programRoles.code" : { $in : ["PROGRAM_MANAGER","PROGRAM_DESIGNER"]}, + status: constants.common.ACTIVE, + isDeleted: false + }, { _id: 1 }); + + if (!userInformation) { + return resolve({ + status: httpStatusCode.bad_request.status, + message: constants.apiResponses.NOT_AUTHORIZED_TO_ACCESS + }) + } + let solutionData = await this.solutionDocuments({ _id: solutionId, isDeleted: false @@ -2055,3 +2072,4 @@ function _generateLink(appsPortalBaseUrl, prefix, solutionLink, solutionType) { return link; } + From 2b806dc74e14de826aced56777f41924a375a184 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Wed, 20 Apr 2022 11:17:12 +0530 Subject: [PATCH 128/331] chanage id to userid --- controllers/v1/solutions.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/controllers/v1/solutions.js b/controllers/v1/solutions.js index 03dd7442..d67c416a 100644 --- a/controllers/v1/solutions.js +++ b/controllers/v1/solutions.js @@ -1041,7 +1041,7 @@ module.exports = class Solutions extends Abstract { let solutionData = await solutionsHelper.read( req.params._id, - req.userDetails.id + req.userDetails.userId ); return resolve(solutionData); From a27593b1e0de915681e2cc68e98543b2b47ddb26 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Thu, 21 Apr 2022 18:23:35 +0530 Subject: [PATCH 129/331] PR changes --- generics/constants/api-responses.js | 2 +- module/solutions/helper.js | 40 +++++++++++++++++++++++------ 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/generics/constants/api-responses.js b/generics/constants/api-responses.js index de65ac3f..6309b4a1 100644 --- a/generics/constants/api-responses.js +++ b/generics/constants/api-responses.js @@ -180,5 +180,5 @@ module.exports = { "PROJECT_TEMPLATE_ID_NOT_FOUND": "Project templates not exists in solution", "SOLUTION_TARGETED_ENTITY" : "Targeted Entity Types Fetched", "ENTITY_ID_OR_LOCATION_ID_NOT_FOUND" : "Entity id or location id not found", - "NOT_AUTHORIZED_TO_ACCESS" :"The program Manager and Designer can only access this resource" + "NOT_AUTHORIZED_TO_ACCESS" :"You are not authorised to access this resource" }; diff --git a/module/solutions/helper.js b/module/solutions/helper.js index d81f0fd5..11395ada 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -6,7 +6,7 @@ */ // Dependencies - +let _ = require("lodash"); const programsHelper = require(MODULES_BASE_PATH + "/programs/helper"); const entityTypesHelper = require(MODULES_BASE_PATH + "/entityTypes/helper"); const entitiesHelper = require(MODULES_BASE_PATH + "/entities/helper"); @@ -1986,18 +1986,42 @@ module.exports = class SolutionsHelper { "programRoles.code" : { $in : ["PROGRAM_MANAGER","PROGRAM_DESIGNER"]}, status: constants.common.ACTIVE, isDeleted: false - }, { _id: 1 }); + }, { _id: 1, "programRoles.programs" :1}); + + if ( !userInformation ) { + return resolve({ + status: httpStatusCode.bad_request.status, + message: constants.apiResponses.NOT_AUTHORIZED_TO_ACCESS + }) + } + + let userPrograms = userInformation.programRoles ? userInformation.programRoles : []; + let programs = []; + + if ( !userPrograms.length > 0 ) { + return resolve({ + status: httpStatusCode.bad_request.status, + message: constants.apiResponses.NOT_AUTHORIZED_TO_ACCESS + }) + } + + userPrograms.map(eachProgram => { + if ( eachProgram["programs"] && eachProgram["programs"].length > 0 ) { + programs.push(...eachProgram["programs"]); + } + }); - if (!userInformation) { - return resolve({ - status: httpStatusCode.bad_request.status, - message: constants.apiResponses.NOT_AUTHORIZED_TO_ACCESS - }) + if ( !programs.length > 0 ) { + return resolve({ + status: httpStatusCode.bad_request.status, + message: constants.apiResponses.NOT_AUTHORIZED_TO_ACCESS + }) } let solutionData = await this.solutionDocuments({ _id: solutionId, - isDeleted: false + isDeleted: false, + programId : { $in : programs } },["reportInformation"]); if ( !Array.isArray(solutionData) || solutionData.length < 1 ) { From adace1faf909bb68e3ed88487aea3ca3184d16ea Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Fri, 22 Apr 2022 01:06:20 +0530 Subject: [PATCH 130/331] PR changes --- module/solutions/helper.js | 1 - 1 file changed, 1 deletion(-) diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 11395ada..c4f0fb47 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -6,7 +6,6 @@ */ // Dependencies -let _ = require("lodash"); const programsHelper = require(MODULES_BASE_PATH + "/programs/helper"); const entityTypesHelper = require(MODULES_BASE_PATH + "/entityTypes/helper"); const entitiesHelper = require(MODULES_BASE_PATH + "/entities/helper"); From 01a7bafaac3cf2ab50c313cdafeb68675a87929e Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Fri, 22 Apr 2022 17:13:37 +0530 Subject: [PATCH 131/331] fixing helper dependency --- module/solutions/helper.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/module/solutions/helper.js b/module/solutions/helper.js index c4f0fb47..70984974 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -13,7 +13,6 @@ const userRolesHelper = require(MODULES_BASE_PATH + "/user-roles/helper"); const surveyService = require(ROOT_PATH + '/generics/services/survey'); const improvementProjectService = require(ROOT_PATH + '/generics/services/improvement-project'); const appsPortalBaseUrl = process.env.APP_PORTAL_BASE_URL + "/" ; -const userExtensionsHelper = require(MODULES_BASE_PATH + "/user-extension/helper"); /** * SolutionsHelper @@ -1980,7 +1979,7 @@ module.exports = class SolutionsHelper { return new Promise(async (resolve, reject) => { try { - let userInformation = await userExtensionsHelper.userExtensionDocument({ + let userInformation = await database.models.userExtension.findOne({ userId: userId, "programRoles.code" : { $in : ["PROGRAM_MANAGER","PROGRAM_DESIGNER"]}, status: constants.common.ACTIVE, From 5300786100ac88cce629b77db6f110df9b36c2ad Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Fri, 22 Apr 2022 17:24:55 +0530 Subject: [PATCH 132/331] added new helper --- module/solutions/helper.js | 3 ++- module/user-extension/helperv2.js | 45 +++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 module/user-extension/helperv2.js diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 70984974..8d2d258e 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -13,6 +13,7 @@ const userRolesHelper = require(MODULES_BASE_PATH + "/user-roles/helper"); const surveyService = require(ROOT_PATH + '/generics/services/survey'); const improvementProjectService = require(ROOT_PATH + '/generics/services/improvement-project'); const appsPortalBaseUrl = process.env.APP_PORTAL_BASE_URL + "/" ; +const userExtensionsHelperV2 = require(MODULES_BASE_PATH + "/user-extension/helperv2"); /** * SolutionsHelper @@ -1979,7 +1980,7 @@ module.exports = class SolutionsHelper { return new Promise(async (resolve, reject) => { try { - let userInformation = await database.models.userExtension.findOne({ + let userInformation = await userExtensionsHelperV2.userExtensionDocument({ userId: userId, "programRoles.code" : { $in : ["PROGRAM_MANAGER","PROGRAM_DESIGNER"]}, status: constants.common.ACTIVE, diff --git a/module/user-extension/helperv2.js b/module/user-extension/helperv2.js new file mode 100644 index 00000000..49de8d84 --- /dev/null +++ b/module/user-extension/helperv2.js @@ -0,0 +1,45 @@ +/** + * name : module//user-extension/helper.js + * author : Priyanka Pradeep + * Date : 22-Apr-2022 + * Description : User extension helper. + */ + + +/** + * UserExtensionHelperV2 + * @class +*/ + +module.exports = class UserExtensionHelperV2 { + + /** + * Get userExtension document based on userid. + * @method + * @name userExtensionDocument + * @name userExtensionDocument + * @param {Object} filterQueryObject - filter query data. + * @param {Object} [projection = {}] - projected data. + * @returns {Promise} returns a promise. + */ + + static userExtensionDocument(filterQueryObject, projection = {}) { + return new Promise(async (resolve, reject) => { + try { + + let userExtensionData = await database.models.userExtension.findOne(filterQueryObject, projection).lean(); + + return resolve(userExtensionData); + + } catch (error) { + return reject(error); + } + }) + + + } +}; + + + + From 15ae2943869dcf2417a2f967aaea9520d2a17478 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Mon, 25 Apr 2022 11:05:36 +0530 Subject: [PATCH 133/331] checking with userInformation.platformRoles --- module/solutions/helper.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 8d2d258e..09234d47 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -1982,10 +1982,10 @@ module.exports = class SolutionsHelper { let userInformation = await userExtensionsHelperV2.userExtensionDocument({ userId: userId, - "programRoles.code" : { $in : ["PROGRAM_MANAGER","PROGRAM_DESIGNER"]}, + "platformRoles.code" : { $in : ["PROGRAM_MANAGER","PROGRAM_DESIGNER"]}, status: constants.common.ACTIVE, isDeleted: false - }, { _id: 1, "programRoles.programs" :1}); + }, { _id: 1, "platformRoles.programs" :1}); if ( !userInformation ) { return resolve({ @@ -1994,7 +1994,7 @@ module.exports = class SolutionsHelper { }) } - let userPrograms = userInformation.programRoles ? userInformation.programRoles : []; + let userPrograms = userInformation.platformRoles ? userInformation.platformRoles : []; let programs = []; if ( !userPrograms.length > 0 ) { From 3060e183136ecf746348aa8a5cc0b9816520a1f8 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 20 Jun 2022 13:28:49 +0530 Subject: [PATCH 134/331] change with fuzzy search --- generics/services/sunbird.js | 15 +++- module/entities/helper.js | 168 ++--------------------------------- 2 files changed, 19 insertions(+), 164 deletions(-) diff --git a/generics/services/sunbird.js b/generics/services/sunbird.js index 057cabef..da3ddb4b 100644 --- a/generics/services/sunbird.js +++ b/generics/services/sunbird.js @@ -161,9 +161,11 @@ const formRead = function ( subTypeData ) { * @name schoolData * @param {String} bearerToken - autherization token. * @param {object} bodyData - location id + * @param {array} fields - set of data keys need to be fetched. + * @param {String} searchKey - search key for fuzzy search. * @returns {Promise} returns a promise. */ -const schoolData = function ( filterData, pageSize = "", pageNo = "", searchKey = "" ) { +const schoolData = function ( filterData, pageSize = "", pageNo = "", searchKey = "", fields) { return new Promise(async (resolve, reject) => { try { @@ -181,10 +183,17 @@ const schoolData = function ( filterData, pageSize = "", pageNo = "", searchKey } if ( searchKey !== "" ) { - bodyData["request"]["query"] = searchKey + bodyData["request"]["fuzzy"] = { + "orgName" : searchKey + } } - + //for getting specified key data only. + if ( fields.length > 0 ) { + bodyData["request"]["fields"] = fields; + } + + const url = sunbirdBaseUrl + constants.endpoints.GET_SCHOOL_DATA; diff --git a/module/entities/helper.js b/module/entities/helper.js index 4fcee693..e059eab1 100644 --- a/module/entities/helper.js +++ b/module/entities/helper.js @@ -429,50 +429,7 @@ module.exports = class EntitiesHelper { message: constants.apiResponses.ENTITIES_FETCHED, result: result }); - - //remove when new code confirmed. - - //let totalcount = uniqueEntities.length; - // if (uniqueEntities.length > 0) { - // let startIndex = limit * (pageNo - 1); - // let endIndex = startIndex + limit; - // uniqueEntities = uniqueEntities.slice(startIndex, endIndex); - // } - - - // if ( entityId !== "" ) { - // uniqueEntities = await this.subEntities( - // obj - // ); - // } else { - // await Promise.all(entities.map(async (entity)=> { - - // obj["entityId"] = entity; - // let entitiesDocument = await this.subEntities( - // obj - // ); - // if( Array.isArray(entitiesDocument) && - // entitiesDocument.length > 0 - // ) { - // entitiesDocument.forEach(entityData => { - // aggregateEntitiesData.push(entityData); - // }); - // } - // })); - // aggregateEntitiesData.map( data => { - // if (uniqueEntities.includes(data) === false) uniqueEntities.push(data); - // }); - // } - // if( result.data && result.data.length > 0 ) { - // result.data = result.data.map(data=>{ - // let cloneData = {...data}; - // cloneData["label"] = cloneData.name; - // cloneData["value"] = cloneData._id; - // return cloneData; - // }) - // } - - + } catch(error) { return reject(error); } @@ -513,27 +470,6 @@ module.exports = class EntitiesHelper { } return resolve(entitiesDocument); - - // if( entitiesData.type !== "" ) { - - // entitiesDocument = await this.entityTraversal( - // entitiesData.entityId, - // entitiesData.type, - // entitiesData.search, - // entitiesData.limit, - // entitiesData.pageNo - // ); - // } else { - // console.log("working in else part") - // //type is empty call learner search with parentId - // entitiesDocument = await this.immediateEntities( - // entitiesData.entityId, - // entitiesData.search, - // entitiesData.limit, - // entitiesData.pageNo - // ); - // } - } catch(error) { return reject(error); @@ -558,12 +494,13 @@ module.exports = class EntitiesHelper { ) { return new Promise(async (resolve, reject) => { try { - + if( entityTraversalType == constants.common.SCHOOL) { let filterData = { "orgLocation.id" : entityId } - let subentitiesCode = await sunbirdService.schoolData( filterData, pageSize, pageNo, searchText ); + let fields = ["externalId"] + let subentitiesCode = await sunbirdService.schoolData( filterData, pageSize, pageNo, searchText, fields ); if( !subentitiesCode.success || !subentitiesCode.data || @@ -575,6 +512,7 @@ module.exports = class EntitiesHelper { count : subentitiesCode.data.response.count }) } + let schoolDetails = subentitiesCode.data.response.content; //get code from all data let schoolCodes = []; @@ -596,9 +534,9 @@ module.exports = class EntitiesHelper { count : 0 }) } - subentitiesData = entitiesData.data.response; + return resolve({ - data : subentitiesData, + data : entitiesData.data.response, count : subentitiesCode.data.response.count }) @@ -639,98 +577,6 @@ module.exports = class EntitiesHelper { }) } - - - // let formatedEntities = []; - - // subentitiesData.map( entityData => { - // let data = {}; - // data._id = entityData.id; - // data.entityType = entityData.type; - // data.name = entityData.name; - // data.externalId = entityData.code; - // data.label = entityData.name; - // data.value = entityData.id - // formatedEntities.push(data) - // } ); - - // subentitiesData = []; - // subentitiesData = formatedEntities; - - - - // let subEntitiesMatchingType = []; - // let parentId = []; - // parentId.push(entityId); - // let subEntities = await subEntitiesWithMatchingType( parentId,entityTraversalType,subEntitiesMatchingType ) - - // if( !subEntities.length > 0 ) { - // return resolve(subEntities) - // } - - // if( searchText !== "" ){ - // let matchEntities = []; - // subEntities.map( entityData => { - // if( entityData.name.match(new RegExp(searchText, 'i')) || entityData.code.match(new RegExp("^" + searchText, 'm')) ) { - // matchEntities.push(entityData) - // } - // }); - // subEntities = []; - // subEntities = matchEntities; - // } - - // let formatedEntities = []; - - // subEntities.map( entityData => { - // let data = {}; - // data._id = entityData.id; - // data.entityType = entityData.type; - // data.name = entityData.name; - // data.externalId = entityData.code; - // data.label = entityData.name; - // data.value = entityData.id - // formatedEntities.push(data) - // } ); - - // subEntities = []; - // subEntities = formatedEntities; - - // return resolve(subEntities); - - - - // let entityTraversal = `groups.${entityTraversalType}`; - - // let entitiesDocument = - // await this.entityDocuments( - // { - // _id: entityId, - // "groups" : { $exists : true }, - // [entityTraversal] : { $exists: true } - // }, - // [ entityTraversal ] - // ); - - // if( !entitiesDocument[0] ) { - // return resolve([]); - // } - - // let result = []; - - // if( entitiesDocument[0].groups[entityTraversalType].length > 0 ) { - - // let entityTraversalData = await this.search( - // searchText, - // pageSize, - // pageNo, - // entitiesDocument[0].groups[entityTraversalType] - // ); - - // result = entityTraversalData[0]; - - // } - - // return resolve(result); } catch(error) { return reject(error); From 22df75e2b59ad64a9be4ebe696bd598df4b331f2 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Wed, 29 Jun 2022 14:06:02 +0530 Subject: [PATCH 135/331] readme --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 21b699dc..8e2db83d 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ # ml-core-service Centralised Service to support other Services. It is used by ml-survey and ml-project + + From 9bb3a0957f2ce096c71cac7d76ec0c2de598cc51 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 22 Jul 2022 18:43:37 +0530 Subject: [PATCH 136/331] resolves for comments --- controllers/v1/entities.js | 59 ++++---- envVariables.js | 4 - generics/constants/common.js | 1 - generics/constants/endpoints.js | 6 +- generics/services/form.js | 4 +- generics/services/sunbird.js | 247 -------------------------------- generics/services/users.js | 227 ++++++++++++++++++++++++++++- module/entities/helper.js | 148 ++++--------------- module/programs/helper.js | 19 +-- module/solutions/helper.js | 33 ++--- module/users/helper.js | 37 +++-- 11 files changed, 327 insertions(+), 458 deletions(-) delete mode 100644 generics/services/sunbird.js diff --git a/controllers/v1/entities.js b/controllers/v1/entities.js index 624edc4f..1b0c4360 100644 --- a/controllers/v1/entities.js +++ b/controllers/v1/entities.js @@ -152,7 +152,6 @@ module.exports = class Entities extends Abstract { */ subEntityList(req) { - return new Promise(async (resolve, reject) => { if( !(req.params._id || req.body.entities) ) { @@ -162,39 +161,37 @@ module.exports = class Entities extends Abstract { }) } - try { - - let entityDocuments = await entitiesHelper.subEntityList( - req.body.entities ? req.body.entities : "", - req.params._id ? req.params._id : "", - req.query.type ? req.query.type : "", - req.searchText, - req.pageSize, - req.pageNo - ); - - if(entityDocuments.result && entityDocuments.result.data && Array.isArray(entityDocuments.result.data) && entityDocuments.result.data.length > 0) { - for (let pointerToEntitiesArray = 0; pointerToEntitiesArray < entityDocuments.result.data.length; pointerToEntitiesArray++) { - if(entityDocuments.result.data[pointerToEntitiesArray].entityType == "school") { - entityDocuments.result.data[pointerToEntitiesArray].label += " - " + entityDocuments.result.data[pointerToEntitiesArray].externalId; - } + try { + + let entityDocuments = await entitiesHelper.subEntityList( + req.body.entities ? req.body.entities : "", + req.params._id ? req.params._id : "", + req.query.type ? req.query.type : "", + req.searchText, + req.pageSize, + req.pageNo + ); + + if(entityDocuments.result && entityDocuments.result.data && Array.isArray(entityDocuments.result.data) && entityDocuments.result.data.length > 0) { + for (let pointerToEntitiesArray = 0; pointerToEntitiesArray < entityDocuments.result.data.length; pointerToEntitiesArray++) { + if(entityDocuments.result.data[pointerToEntitiesArray].entityType == "school") { + entityDocuments.result.data[pointerToEntitiesArray].label += " - " + entityDocuments.result.data[pointerToEntitiesArray].externalId; } } - - return resolve(entityDocuments); - - } catch (error) { - - return reject({ - status: error.status || httpStatusCode.internal_server_error.status, - message: error.message || httpStatusCode.internal_server_error.message, - errorObject: error - }) - } - - - }) + + return resolve(entityDocuments); + + } catch (error) { + + return reject({ + status: error.status || httpStatusCode.internal_server_error.status, + message: error.message || httpStatusCode.internal_server_error.message, + errorObject: error + }) + + } + }) } /** diff --git a/envVariables.js b/envVariables.js index 4b842053..ee9f0312 100644 --- a/envVariables.js +++ b/envVariables.js @@ -129,10 +129,6 @@ let enviromentVariables = { "message" : "App Portal base url", "optional" : true, "default": "https://dev.sunbirded.org" - }, - "SUNBIRD_SERVICE_URL" : { - "message" : "Required sunbird service url", - "optional" : false } } diff --git a/generics/constants/common.js b/generics/constants/common.js index 45c9da77..caf7cd12 100644 --- a/generics/constants/common.js +++ b/generics/constants/common.js @@ -68,7 +68,6 @@ module.exports = { "DEFAULT_SUBMISSION_REQUIRED" : 1, "SCHOOL" : "school", "SUBENTITY" :"subEntity_", - "SUNBIRD_SERVER_TIMEOUT" : 5000, "CACHE_TIME_PERIOD" : 43200, "FORM_API_TYPE" : "profileConfig" diff --git a/generics/constants/endpoints.js b/generics/constants/endpoints.js index 00a48946..a1d899ff 100644 --- a/generics/constants/endpoints.js +++ b/generics/constants/endpoints.js @@ -31,7 +31,7 @@ module.exports = { LIST_PROJECT : "/v1/userProjects/list", GET_QUESTIONS : "/v1/solutions/questions", GET_OBSERVATION : "/v1/observations/details", - GET_LOCATION_DATA : "/api/data/v1/location/search", - GET_FORM_DATA : "/api/data/v1/form/read", - GET_SCHOOL_DATA : "/api/org/v1/search" + GET_LOCATION_DATA : "/v1/location/search", + GET_FORM_DATA : "/v1/form/read", + GET_SCHOOL_DATA : "/v1/org/search" } \ No newline at end of file diff --git a/generics/services/form.js b/generics/services/form.js index 0a1dc765..8c8ef6b8 100644 --- a/generics/services/form.js +++ b/generics/services/form.js @@ -6,7 +6,7 @@ */ //dependencies -const sunbirdService = require(ROOT_PATH + '/generics/services/sunbird'); +const userService = require(ROOT_PATH + "/generics/services/users"); let cache = require(ROOT_PATH+"/generics/helpers/cache"); /** @@ -23,7 +23,7 @@ const formData = function ( stateLocationCode, entityKey ) { return new Promise(async (resolve, reject) => { try { - let subEntitiesDetails = await sunbirdService.formRead( stateLocationCode ); + let subEntitiesDetails = await userService.formRead( stateLocationCode ); if( !subEntitiesDetails.success) { return resolve({ message : constants.apiResponses.ENTITY_NOT_FOUND, diff --git a/generics/services/sunbird.js b/generics/services/sunbird.js deleted file mode 100644 index da3ddb4b..00000000 --- a/generics/services/sunbird.js +++ /dev/null @@ -1,247 +0,0 @@ -/** - * name : sunbird.js - * author : Vishnudas - * Date : 22-Feb-2022 - * Description : All Sunbird learner related api call. - */ - -//dependencies - - -const request = require('request'); -const sunbirdBaseUrl = process.env.SUNBIRD_SERVICE_URL; -const serverTimeout = process.env.SUNBIRD_SERVER_TIMEOUT ? parseInt(process.env.SUNBIRD_SERVER_TIMEOUT) : 500; -const dataLimit = process.env.SUNBIRD_RESPONSE_DATA_LIMIT ? parseInt(process.env.SUNBIRD_RESPONSE_DATA_LIMIT) : 10000; -/** - * - * @function - * @name learnerLocationSearch - * @param {String} bearerToken - autherization token. - * @param {object} filterData - bodydata . - * @returns {Promise} returns a promise. -*/ - -const learnerLocationSearch = function ( filterData, pageSize = "", pageNo = "", searchKey = "" ) { - return new Promise(async (resolve, reject) => { - try { - - let bodyData = {}; - bodyData["request"] = {}; - bodyData["request"]["filters"] = filterData; - - if ( pageSize !== "" ) { - bodyData["request"]["limit"] = pageSize; - } else { - bodyData["request"]["limit"] = dataLimit; - } - - if ( pageNo !== "" ) { - let offsetValue = pageSize * ( pageNo - 1 ); - bodyData["request"]["offset"] = offsetValue; - } - - if ( searchKey !== "" ) { - bodyData["request"]["query"] = searchKey - } - - - const url = - sunbirdBaseUrl + constants.endpoints.GET_LOCATION_DATA; - const options = { - headers : { - "Authorization" : process.env.SUNBIRD_SERVICE_AUTHERIZATION, - "content-type": "application/json" - }, - json : bodyData - }; - - request.post(url,options,sunbirdCallback); - - let result = { - success : true - }; - - function sunbirdCallback(err, data) { - - - if (err) { - result.success = false; - } else { - - let response = data.body; - if( response.responseCode === constants.common.OK) { - result["data"] = response.result; - } else { - result.success = false; - } - } - return resolve(result); - } - - setTimeout(function () { - return reject (result = { - success : false - }); - }, serverTimeout); - - - } catch (error) { - return reject(error); - } - }) -} - -/** - * - * @function - * @name formRead - * @param {String} bearerToken - autherization token. - * @param {object} bodyData - subType data. - * @returns {Promise} returns a promise. -*/ -const formRead = function ( subTypeData ) { - return new Promise(async (resolve, reject) => { - try { - - let bodyData = { - request : { - type: constants.common.FORM_API_TYPE, - subType: subTypeData, - action: constants.common.GET_METHOD - } - } - - const url = - sunbirdBaseUrl + constants.endpoints.GET_FORM_DATA; - const options = { - headers : { - "Authorization" : process.env.SUNBIRD_SERVICE_AUTHERIZATION, - "content-type": "application/json" - }, - json : bodyData - }; - - request.post(url,options,sunbirdCallback); - let result = { - success : true - }; - function sunbirdCallback(err, data) { - - - if (err) { - result.success = false; - } else { - - let response = data.body; - - if( response.responseCode === constants.common.OK) { - result["data"] = response.result; - result.success = true; - } else { - result.success = false; - } - } - return resolve(result); - } - setTimeout(function () { - return reject (result = { - success : false - }); - }, serverTimeout); - - } catch (error) { - return reject(error); - } - }) -} - -/** - * - * @function - * @name schoolData - * @param {String} bearerToken - autherization token. - * @param {object} bodyData - location id - * @param {array} fields - set of data keys need to be fetched. - * @param {String} searchKey - search key for fuzzy search. - * @returns {Promise} returns a promise. -*/ -const schoolData = function ( filterData, pageSize = "", pageNo = "", searchKey = "", fields) { - return new Promise(async (resolve, reject) => { - try { - - let bodyData = {}; - bodyData["request"] = {}; - bodyData["request"]["filters"] = filterData; - - if ( pageSize !== "" ) { - bodyData["request"]["limit"] = pageSize; - } - - if ( pageNo !== "" ) { - let offsetValue = pageSize * ( pageNo - 1 ); - bodyData["request"]["offset"] = offsetValue; - } - - if ( searchKey !== "" ) { - bodyData["request"]["fuzzy"] = { - "orgName" : searchKey - } - } - - //for getting specified key data only. - if ( fields.length > 0 ) { - bodyData["request"]["fields"] = fields; - } - - - - const url = - sunbirdBaseUrl + constants.endpoints.GET_SCHOOL_DATA; - const options = { - headers : { - "Authorization" : process.env.SUNBIRD_SERVICE_AUTHERIZATION, - "content-type": "application/json" - }, - json : bodyData - }; - - request.post(url,options,sunbirdCallback); - let result = { - success : true - }; - - function sunbirdCallback(err, data) { - - - - if (err) { - result.success = false; - } else { - - let response = data.body; - - if( response.responseCode === constants.common.OK) { - result["data"] = response.result; - } else { - result.success = false; - } - } - return resolve(result); - } - setTimeout(function () { - return reject (result = { - success : false - }); - }, serverTimeout); - - } catch (error) { - return reject(error); - } - }) -} - -module.exports = { - learnerLocationSearch : learnerLocationSearch, - formRead : formRead, - schoolData :schoolData -}; \ No newline at end of file diff --git a/generics/services/users.js b/generics/services/users.js index 9ba0ef1d..eff59ea1 100644 --- a/generics/services/users.js +++ b/generics/services/users.js @@ -8,6 +8,8 @@ //dependencies const request = require('request'); const userServiceUrl = process.env.USER_SERVICE_URL; +const serverTimeout = process.env.SUNBIRD_SERVER_TIMEOUT ? parseInt(process.env.SUNBIRD_SERVER_TIMEOUT) : 500; +const dataLimit = process.env.SUNBIRD_RESPONSE_DATA_LIMIT ? parseInt(process.env.SUNBIRD_RESPONSE_DATA_LIMIT) : 10000; const profile = function ( token,userId = "" ) { return new Promise(async (resolve, reject) => { @@ -57,6 +59,229 @@ const profile = function ( token,userId = "" ) { }) } +/** + * + * @function + * @name learnerLocationSearch + * @param {String} bearerToken - autherization token. + * @param {object} filterData - bodydata . + * @returns {Promise} returns a promise. +*/ + +const learnerLocationSearch = function ( filterData, pageSize = "", pageNo = "", searchKey = "" ) { + return new Promise(async (resolve, reject) => { + try { + + let bodyData = {}; + bodyData["request"] = {}; + bodyData["request"]["filters"] = filterData; + + if ( pageSize !== "" ) { + bodyData["request"]["limit"] = pageSize; + } else { + bodyData["request"]["limit"] = dataLimit; + } + + if ( pageNo !== "" ) { + let offsetValue = pageSize * ( pageNo - 1 ); + bodyData["request"]["offset"] = offsetValue; + } + + if ( searchKey !== "" ) { + bodyData["request"]["query"] = searchKey + } + + + const url = + userServiceUrl + constants.endpoints.GET_LOCATION_DATA; + const options = { + headers : { + "content-type": "application/json" + }, + json : bodyData + }; + + request.post(url,options,sunbirdCallback); + + let result = { + success : true + }; + + function sunbirdCallback(err, data) { + + + if (err) { + result.success = false; + } else { + + let response = data.body; + if( response.responseCode === constants.common.OK) { + result["data"] = response.result; + } else { + result.success = false; + } + } + return resolve(result); + } + + setTimeout(function () { + return resolve (result = { + success : false + }); + }, serverTimeout); + + + } catch (error) { + return reject(error); + } + }) + } + + /** + * + * @function + * @name formRead + * @param {String} bearerToken - autherization token. + * @param {object} bodyData - subType data. + * @returns {Promise} returns a promise. + */ + const formRead = function ( subTypeData ) { + return new Promise(async (resolve, reject) => { + try { + + let bodyData = { + request : { + type: constants.common.FORM_API_TYPE, + subType: subTypeData, + action: constants.common.GET_METHOD + } + } + + const url = + userServiceUrl + constants.endpoints.GET_FORM_DATA; + const options = { + headers : { + "content-type": "application/json" + }, + json : bodyData + }; + + request.post(url,options,sunbirdCallback); + let result = { + success : true + }; + function sunbirdCallback(err, data) { + + if (err) { + result.success = false; + } else { + + let response = data.body; + + if( response.responseCode === constants.common.OK) { + result["data"] = response.result; + result.success = true; + } else { + result.success = false; + } + } + return resolve(result); + } + setTimeout(function () { + return resolve (result = { + success : false + }); + }, serverTimeout); + + } catch (error) { + return reject(error); + } + }) + } + + /** + * + * @function + * @name schoolData + * @param {String} bearerToken - autherization token. + * @param {object} bodyData - location id + * @param {array} fields - set of data keys need to be fetched. + * @param {String} searchKey - search key for fuzzy search. + * @returns {Promise} returns a promise. + */ + const schoolData = function ( filterData, pageSize = "", pageNo = "", searchKey = "", fields) { + return new Promise(async (resolve, reject) => { + try { + + let bodyData = {}; + bodyData["request"] = {}; + bodyData["request"]["filters"] = filterData; + + if ( pageSize !== "" ) { + bodyData["request"]["limit"] = pageSize; + } + + if ( pageNo !== "" ) { + let offsetValue = pageSize * ( pageNo - 1 ); + bodyData["request"]["offset"] = offsetValue; + } + + if ( searchKey !== "" ) { + bodyData["request"]["fuzzy"] = { + "orgName" : searchKey + } + } + + //for getting specified key data only. + if ( fields.length > 0 ) { + bodyData["request"]["fields"] = fields; + } + + const url = + userServiceUrl + constants.endpoints.GET_SCHOOL_DATA; + const options = { + headers : { + "content-type": "application/json" + }, + json : bodyData + }; + + request.post(url,options,sunbirdCallback); + let result = { + success : true + }; + + function sunbirdCallback(err, data) { + + if (err) { + result.success = false; + } else { + + let response = data.body; + + if( response.responseCode === constants.common.OK) { + result["data"] = response.result; + } else { + result.success = false; + } + } + return resolve(result); + } + setTimeout(function () { + return resolve (result = { + success : false + }); + }, serverTimeout); + + } catch (error) { + return reject(error); + } + }) + } + module.exports = { - profile : profile + profile : profile, + learnerLocationSearch : learnerLocationSearch, + formRead : formRead, + schoolData :schoolData } diff --git a/module/entities/helper.js b/module/entities/helper.js index e059eab1..c0a960b9 100644 --- a/module/entities/helper.js +++ b/module/entities/helper.js @@ -3,7 +3,7 @@ const entityTypesHelper = require(MODULES_BASE_PATH + "/entityTypes/helper"); const userRolesHelper = require(MODULES_BASE_PATH + "/user-roles/helper"); // const elasticSearch = require(GENERIC_HELPERS_PATH + "/elastic-search"); -const sunbirdService = require(ROOT_PATH + '/generics/services/sunbird'); +const userService = require(ROOT_PATH + "/generics/services/users"); let cache = require(ROOT_PATH+"/generics/helpers/cache"); const formService = require(ROOT_PATH + '/generics/services/form'); module.exports = class EntitiesHelper { @@ -250,113 +250,26 @@ module.exports = class EntitiesHelper { "parentId" : entityId }; - let entitiesData = await sunbirdService.learnerLocationSearch( + let entitiesData = await userService.learnerLocationSearch( bodyData, pageSize, pageNo, searchText ); - if( !entitiesData.success || !entitiesData.data || !entitiesData.data.response.length > 0 ) { + if( !entitiesData.success || !entitiesData.data || !entitiesData.data.response || !entitiesData.data.response.length > 0 ) { return resolve({ data : entitiesData.data.response, count : entitiesData.data.count }); } - let immediateLocation = entitiesData.data.response; - return resolve({ data : immediateLocation, count : entitiesData.data.count }); - - // if( searchText !== "" ){ - // let matchEntities = []; - // immediateLocation.map( entityData => { - // if( entityData.name.match(new RegExp(searchText, 'i')) || entityData.code.match(new RegExp("^" + searchText, 'm')) ) { - // matchEntities.push(entityData) - // } - // }); - // immediateLocation = []; - // immediateLocation = matchEntities; - // } - - // let formatedEntities = []; - - // immediateLocation.map( entityData => { - // let data = {}; - // data._id = entityData.id; - // data.entityType = entityData.type; - // data.name = entityData.name; - // data.externalId = entityData.code; - // data.label = entityData.name; - // data.value = entityData.id - // formatedEntities.push(data) - // } ); - - // immediateLocation = []; - // immediateLocation = formatedEntities; - - - - - - // let projection = [ - // constants.schema.ENTITYTYPE, - // constants.schema.GROUPS - // ]; - - // let entitiesDocument = await this.entityDocuments({ - // _id: entityId - // }, projection); - - // let immediateEntities = []; - - // if (entitiesDocument[0] && - // entitiesDocument[0].groups && - // Object.keys(entitiesDocument[0].groups).length > 0 - // ) { - - // let getImmediateEntityTypes = - // await entityTypesHelper.entityTypesDocument({ - // name : entitiesDocument[0].entityType - // },["immediateChildrenEntityType"] - // ); - - // let immediateEntitiesIds; - - // Object.keys(entitiesDocument[0].groups).forEach(entityGroup => { - // if ( - // getImmediateEntityTypes[0].immediateChildrenEntityType && - // getImmediateEntityTypes[0].immediateChildrenEntityType.length > 0 && - // getImmediateEntityTypes[0].immediateChildrenEntityType.includes(entityGroup) - // ) { - // immediateEntitiesIds = - // entitiesDocument[0].groups[entityGroup]; - // } - // }) - // console.log("Immediate entities before : ",immediateEntitiesIds) - // if ( - // Array.isArray(immediateEntitiesIds) && - // immediateEntitiesIds.length > 0 - // ) { - - // let searchImmediateData = await this.search( - // searchText, - // pageSize, - // pageNo, - // immediateEntitiesIds - // ); - - // immediateEntities = searchImmediateData[0]; - // } - // } - // console.log("immediateEntities : ",immediateEntities) - // return resolve(immediateEntities); - } catch(error) { return reject(error); } @@ -382,7 +295,7 @@ module.exports = class EntitiesHelper { try { let result = {}; - let subentitiesResult = {}; + let subEntitiesResult = {}; let uniqueEntities = []; let obj = { entityId : entityId, @@ -393,21 +306,21 @@ module.exports = class EntitiesHelper { } if ( entityId !== "" ) { - subentitiesResult = await this.subEntities( + subEntitiesResult = await this.subEntities( obj ); } else { obj["entityId"] = entities; - subentitiesResult = await this.subEntities( + subEntitiesResult = await this.subEntities( obj ); } - if ( subentitiesResult && subentitiesResult.data && subentitiesResult.data.length > 0 ) { + if ( subEntitiesResult && subEntitiesResult.data && subEntitiesResult.data.length > 0 ) { let formatedEntities = []; - uniqueEntities = subentitiesResult.data + uniqueEntities = subEntitiesResult.data uniqueEntities.map( entityData => { let data = {}; data._id = entityData.id; @@ -423,7 +336,7 @@ module.exports = class EntitiesHelper { } result.data = uniqueEntities; - result.count = subentitiesResult.count; + result.count = subEntitiesResult.count; resolve({ message: constants.apiResponses.ENTITIES_FETCHED, @@ -500,7 +413,7 @@ module.exports = class EntitiesHelper { "orgLocation.id" : entityId } let fields = ["externalId"] - let subentitiesCode = await sunbirdService.schoolData( filterData, pageSize, pageNo, searchText, fields ); + let subentitiesCode = await userService.schoolData( filterData, pageSize, pageNo, searchText, fields ); if( !subentitiesCode.success || !subentitiesCode.data || @@ -526,9 +439,9 @@ module.exports = class EntitiesHelper { }; - let entitiesData = await sunbirdService.learnerLocationSearch( bodyData ); + let entitiesData = await userService.learnerLocationSearch( bodyData ); - if( !entitiesData.success || !entitiesData.data || !entitiesData.data.response.length > 0 ) { + if( !entitiesData.success || !entitiesData.data || !entitiesData.data.response || !entitiesData.data.response.length > 0 ) { return resolve({ data : [], count : 0 @@ -823,9 +736,9 @@ module.exports = class EntitiesHelper { "id" : stateLocationId }; - let entitiesData = await sunbirdService.learnerLocationSearch( bodyData ); + let entitiesData = await userService.learnerLocationSearch( bodyData ); - if( !entitiesData.success || !entitiesData.data || !entitiesData.data.response.length > 0 ) { + if( !entitiesData.success || !entitiesData.data || !entitiesData.data.response || !entitiesData.data.response.length > 0 ) { return resolve({ message : constants.apiResponses.ENTITY_NOT_FOUND, result : [] @@ -963,36 +876,35 @@ module.exports = class EntitiesHelper { } -// /** -// * get subEntities of matching type by recursion. -// * @method -// * @name subEntitiesWithMatchingType -// * @returns {Array} - Sub entities matching the type . -// */ +/** + * get subEntities of matching type by recursion. + * @method + * @name subEntitiesWithMatchingType + * @returns {Array} - Sub entities matching the type . +*/ -async function subEntitiesWithMatchingType( parentIds,entityType,matchingData ){ +async function subEntitiesWithMatchingType( parentIds,entityType, matchingData ) { - if( !parentIds.length > 0 ){ + if( !parentIds.length > 0 ) { return matchingData; - } + }; - let bodyData={ + let bodyData = { "parentId" : parentIds }; - let entityDetails = await sunbirdService.learnerLocationSearch(bodyData); + let entityDetails = await userService.learnerLocationSearch(bodyData); - if( ( !entityDetails.success || !entityDetails.data || !entityDetails.data.response.length > 0 ) && !matchingData.length > 0 ) { + if( ( !entityDetails.success || !entityDetails.data || !entityDetails.data.response || !entityDetails.data.response.length > 0 ) && !matchingData.length > 0 ) { return matchingData; } let entityData = entityDetails.data.response; - let mismatchEntities = []; entityData.map(entity => { - if( entity.type == entityType ) { + if ( entity.type == entityType ) { matchingData.push(entity) } else { @@ -1001,7 +913,6 @@ async function subEntitiesWithMatchingType( parentIds,entityType,matchingData ){ }); if( mismatchEntities.length > 0 ){ - await subEntitiesWithMatchingType(mismatchEntities,entityType,matchingData) } let uniqueEntities = []; @@ -1009,7 +920,4 @@ async function subEntitiesWithMatchingType( parentIds,entityType,matchingData ){ if (uniqueEntities.includes(data) === false) uniqueEntities.push(data); }); return uniqueEntities; - - - - } \ No newline at end of file +} \ No newline at end of file diff --git a/module/programs/helper.js b/module/programs/helper.js index 72715676..6edafa44 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -10,7 +10,7 @@ const entityTypesHelper = require(MODULES_BASE_PATH + "/entityTypes/helper"); const entitiesHelper = require(MODULES_BASE_PATH + "/entities/helper"); const userRolesHelper = require(MODULES_BASE_PATH + "/user-roles/helper"); -const sunbirdService = require(ROOT_PATH + '/generics/services/sunbird'); +const userService = require(ROOT_PATH + "/generics/services/users"); /** * ProgramsHelper @@ -211,9 +211,9 @@ module.exports = class ProgramsHelper { let bodyData = { "type" : scopeData.entityType } - let entityTypeData = await sunbirdService.learnerLocationSearch( bodyData ); + let entityTypeData = await userService.learnerLocationSearch( bodyData ); - if( !entityTypeData.success || !entityTypeData.data || !entityTypeData.data.response.length > 0 ) { + if( !entityTypeData.success || !entityTypeData.data || !entityTypeData.data.response || !entityTypeData.data.response.length > 0 ) { return resolve({ status : httpStatusCode.bad_request.status, message : constants.apiResponses.ENTITY_TYPES_NOT_FOUND @@ -241,8 +241,8 @@ module.exports = class ProgramsHelper { } - let entityData = await sunbirdService.learnerLocationSearch( bodyData ); - if( !entityData.success || !entityData.data || !entityData.data.response.length > 0 ) { + let entityData = await userService.learnerLocationSearch( bodyData ); + if( !entityData.success || !entityData.data || !entityData.data.response || !entityData.data.response.length > 0 ) { return resolve({ status : httpStatusCode.bad_request.status, message : constants.apiResponses.ENTITIES_NOT_FOUND @@ -724,7 +724,6 @@ module.exports = class ProgramsHelper { }; } - let locationIds = []; let bodyData={}; @@ -737,29 +736,25 @@ module.exports = class ProgramsHelper { "id" : locationIds } - let entitiesData = await sunbirdService.learnerLocationSearch( bodyData ); - + let entitiesData = await userService.learnerLocationSearch( bodyData ); - if( !entitiesData.success || !entitiesData.data || !entitiesData.data.count > 0 ) { + if( !entitiesData.success || !entitiesData.data || !entitiesData.data.response || !entitiesData.data.response.length > 0 ) { throw { message : constants.apiResponses.ENTITIES_NOT_FOUND }; } - let entityIds = []; entitiesData.data.response.forEach(entityResult => { entityIds.push(entityResult.id); }); - let updateProgram = await database.models.programs.findOneAndUpdate({ _id : programId },{ $addToSet : { "scope.entities" : { $each : entityIds } } },{ new : true }).lean(); - if( !updateProgram || !updateProgram._id ) { throw { message : constants.apiResponses.PROGRAM_NOT_UPDATED diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 43c32fb4..9323ca65 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -4,9 +4,6 @@ * created-date : 03-sep-2020 * Description : Solution related helper functionality. */ - - - // Dependencies const programsHelper = require(MODULES_BASE_PATH + "/programs/helper"); @@ -16,7 +13,7 @@ const userRolesHelper = require(MODULES_BASE_PATH + "/user-roles/helper"); const surveyService = require(ROOT_PATH + '/generics/services/survey'); const improvementProjectService = require(ROOT_PATH + '/generics/services/improvement-project'); const appsPortalBaseUrl = process.env.APP_PORTAL_BASE_URL + "/" ; -const sunbirdService = require(ROOT_PATH + '/generics/services/sunbird'); +const userService = require(ROOT_PATH + "/generics/services/users"); /** * SolutionsHelper @@ -138,8 +135,8 @@ module.exports = class SolutionsHelper { }; - let entitiesDetails = await sunbirdService.learnerLocationSearch( bodyData ); - if( !entitiesDetails.success || !entitiesDetails.data || !entitiesDetails.data.response.length > 0 ) { + let entitiesDetails = await userService.learnerLocationSearch( bodyData ); + if( !entitiesDetails.success || !entitiesDetails.data || !entitiesDetails.data.response || !entitiesDetails.data.response.length > 0 ) { throw { message : constants.apiResponses.ENTITIES_NOT_FOUND } @@ -263,8 +260,8 @@ module.exports = class SolutionsHelper { "id" : entityLocationIds }; - let entityDetails = await sunbirdService.learnerLocationSearch(bodyData); - if( !entityDetails.success || !entityDetails.data || !entityDetails.data.response.length > 0 ) { + let entityDetails = await userService.learnerLocationSearch(bodyData); + if( !entityDetails.success || !entityDetails.data || !entityDetails.data.response || !entityDetails.data.response.length > 0 ) { return resolve({ status : httpStatusCode.bad_request.status, message : constants.apiResponses.ENTITIES_NOT_FOUND @@ -1009,9 +1006,9 @@ module.exports = class SolutionsHelper { }; - let entitiesDetails = await sunbirdService.learnerLocationSearch( bodyData ); + let entitiesDetails = await userService.learnerLocationSearch( bodyData ); - if( !entitiesDetails.success || !entitiesDetails.data || !entitiesDetails.data.response.length > 0 ) { + if( !entitiesDetails.success || !entitiesDetails.data || !entitiesDetails.data.response || !entitiesDetails.data.response.length > 0 ) { return resolve({ status : httpStatusCode.bad_request.status, message : constants.apiResponses.ENTITIES_NOT_FOUND @@ -1984,12 +1981,12 @@ function _generateLink(appsPortalBaseUrl, prefix, solutionLink, solutionType) { } -// /** -// * get entitiesData of matching type by recursion. -// * @method -// * @name entitiesInParent -// * @returns {Array} - Entities matching the type under the parent. -// */ +/** + * get entitiesData of matching type by recursion. + * @method + * @name entitiesInParent + * @returns {Array} - Entities matching the type under the parent. +*/ async function entitiesInParent( solutionEntities,currentEntityType,matchingData ){ @@ -2000,9 +1997,9 @@ async function entitiesInParent( solutionEntities,currentEntityType,matchingData "parentId" : solutionEntities }; - let entityDetails = await sunbirdService.learnerLocationSearch(bodyData); + let entityDetails = await userService.learnerLocationSearch(bodyData); - if( ( !entityDetails.success || !entityDetails.data || !entityDetails.data.response.length > 0) && !matchingData.length > 0 ) { + if( ( !entityDetails.success || !entityDetails.data || !entityDetails.data.response || !entityDetails.data.response.length > 0) && !matchingData.length > 0 ) { return ({ status : httpStatusCode.bad_request.status, message : constants.apiResponses.ENTITIES_NOT_FOUND diff --git a/module/users/helper.js b/module/users/helper.js index dc43c976..ed75d4e0 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -12,7 +12,6 @@ const userRolesHelper = require(MODULES_BASE_PATH + "/user-roles/helper"); const entitiesHelper = require(MODULES_BASE_PATH + "/entities/helper"); const improvementProjectService = require(ROOT_PATH + "/generics/services/improvement-project"); const userService = require(ROOT_PATH + "/generics/services/users"); -const sunbirdService = require(ROOT_PATH + '/generics/services/sunbird'); let cache = require(ROOT_PATH+"/generics/helpers/cache"); const formService = require(ROOT_PATH + '/generics/services/form'); @@ -161,25 +160,25 @@ module.exports = class UsersHelper { let locationIds = []; let orgExternalId = []; let entitiesData = []; - let bodyData={}; + let bodyData = {}; - data.entities.forEach(entity=>{ - if (gen.utils.checkValidUUID(entity)) { + data.entities.forEach( entity => { + if ( gen.utils.checkValidUUID(entity) ) { locationIds.push(entity); } else { orgExternalId.push(entity) } }); - if ( locationIds.length > 0 ){ + if ( locationIds.length > 0 ) { bodyData = { "id" : locationIds } - let entityData = await sunbirdService.learnerLocationSearch( bodyData ); + let entityData = await userService.learnerLocationSearch( bodyData ); - if ( !entityData.success || !entityData.data || !entityData.data.count > 0 ) { + if ( !entityData.success || !entityData.data || !entityData.data.response || !entityData.data.response.length > 0 ) { return resolve({ status: httpStatusCode["bad_request"].status, message: constants.apiResponses.ENTITY_NOT_FOUND, @@ -199,9 +198,9 @@ module.exports = class UsersHelper { let filterData = { "externalId" : orgExternalId } - let schoolDetails = await sunbirdService.schoolData( filterData ); + let schoolDetails = await userService.schoolData( filterData ); let schoolDocuments = schoolDetails.data.response.content; - if( !schoolDetails.success || !schoolDocuments.length > 0 ) { + if ( !schoolDetails.success || !schoolDocuments.length > 0 ) { return resolve({ status: httpStatusCode["bad_request"].status, message: constants.apiResponses.ENTITY_NOT_FOUND, @@ -209,7 +208,7 @@ module.exports = class UsersHelper { }); } let schoolData = schoolDetails.data.response.content; - schoolData.forEach(entity =>{ + schoolData.forEach( entity => { entitiesData.push(entity.identifier) }); @@ -643,9 +642,9 @@ module.exports = class UsersHelper { }; } - let entityData = await sunbirdService.learnerLocationSearch( bodyData ); + let entityData = await userService.learnerLocationSearch( bodyData ); - if ( !entityData.success || !entityData.data || !entityData.data.response.length > 0) { + if ( !entityData.success || !entityData.data || !entityData.data.response || !entityData.data.response.length > 0) { throw { message: constants.apiResponses.ENTITIES_NOT_EXIST_IN_LOCATION, }; @@ -754,8 +753,8 @@ module.exports = class UsersHelper { "parentId" : requestedData[targetedEntityType] } } - let entitiesData = await sunbirdService.learnerLocationSearch( filterData ); - if( !entitiesData.success ||!entityData.data || !entityData.data.response.length > 0 ){ + let entitiesData = await userService.learnerLocationSearch( filterData ); + if( !entitiesData.success ||!entityData.data || !entityData.data.response || !entityData.data.response.length > 0 ){ targetedEntityType = constants.common.STATE_ENTITY_TYPE; } } @@ -769,8 +768,8 @@ module.exports = class UsersHelper { "code" : requestedData[targetedEntityType] }; } - let entitiesDocument = await sunbirdService.learnerLocationSearch( filterData ); - if ( !entitiesDocument.success || !entitiesDocument.data || !entitiesDocument.data.count > 0) { + let entitiesDocument = await userService.learnerLocationSearch( filterData ); + if ( !entitiesDocument.success || !entitiesDocument.data || !entitiesDocument.data.response || !entitiesDocument.data.response.length > 0) { throw { message: constants.apiResponses.ENTITY_NOT_FOUND }; @@ -807,7 +806,7 @@ module.exports = class UsersHelper { * @returns {Object} - Entity. */ - static getHighestTargetedEntity( roleWiseTargetedEntities,requestedData ) { + static getHighestTargetedEntity( roleWiseTargetedEntities, requestedData ) { return new Promise(async (resolve, reject) => { try { let entityKey = constants.common.SUBENTITY + requestedData.state; @@ -817,9 +816,9 @@ module.exports = class UsersHelper { "id" : requestedData.state }; - let entitiesData = await sunbirdService.learnerLocationSearch( filterData ); + let entitiesData = await userService.learnerLocationSearch( filterData ); - if( !entitiesData.success || !entitiesData.data || !entitiesData.data.response.length > 0 ) { + if( !entitiesData.success || !entitiesData.data || !entitiesData.data.response || !entitiesData.data.response.length > 0 ) { return resolve({ message : constants.apiResponses.ENTITY_NOT_FOUND, result : [] From d6d453925d58d8294080a8201db639f0ae4c8c47 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 22 Jul 2022 18:46:33 +0530 Subject: [PATCH 137/331] formatted --- module/entities/helper.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/module/entities/helper.js b/module/entities/helper.js index c0a960b9..d0380b2e 100644 --- a/module/entities/helper.js +++ b/module/entities/helper.js @@ -913,7 +913,7 @@ async function subEntitiesWithMatchingType( parentIds,entityType, matchingData ) }); if( mismatchEntities.length > 0 ){ - await subEntitiesWithMatchingType(mismatchEntities,entityType,matchingData) + await subEntitiesWithMatchingType(mismatchEntities, entityType, matchingData); } let uniqueEntities = []; matchingData.map( data => { From 901ed7c815adddc38ace5f7c664a3a392c478c80 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Tue, 26 Jul 2022 16:40:44 +0530 Subject: [PATCH 138/331] chage for school code --- module/programs/helper.js | 103 ++++++++++++++++++++++++-------------- 1 file changed, 66 insertions(+), 37 deletions(-) diff --git a/module/programs/helper.js b/module/programs/helper.js index 6edafa44..7dd3269f 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -227,34 +227,51 @@ module.exports = class ProgramsHelper { if( scopeData.entities && scopeData.entities.length > 0 ) { //call learners api for search - let locationIds = []; + let orgExternalId = []; + let entityIds = []; let bodyData={}; - + scopeData.entities.forEach(entity=>{ if (gen.utils.checkValidUUID(entity)) { locationIds.push(entity); + } else { + orgExternalId.push(entity); } }); - bodyData = { - "id" : locationIds + + if ( locationIds.length > 0 ) { + bodyData = { + "id" : locationIds + } + let entityData = await userService.learnerLocationSearch( bodyData ); + if ( entityData.success && entityData.data && entityData.data.response && entityData.data.response.length > 0 ) { + entityData.data.response.forEach( entity => { + entityIds.push(entity.id) + }); + } } + if ( orgExternalId.length > 0 ) { + let filterData = { + "externalId" : orgExternalId + } + let schoolDetails = await userService.schoolData( filterData ); + + if ( schoolDetails.success && schoolDetails.data && schoolDetails.data.response && schoolDetails.data.response.content && schoolDetails.data.response.content.length > 0 ) { + let schoolData = schoolDetails.data.response.content; + schoolData.forEach( entity => { + entityIds.push(entity.externalId) + }); + } + } - let entityData = await userService.learnerLocationSearch( bodyData ); - if( !entityData.success || !entityData.data || !entityData.data.response || !entityData.data.response.length > 0 ) { - return resolve({ - status : httpStatusCode.bad_request.status, - message : constants.apiResponses.ENTITIES_NOT_FOUND - }); + if( !entityIds.length > 0 ) { + throw { + message : constants.apiResponses.ENTITIES_NOT_FOUND + }; } - - let entities = entityData.data.response; - - scope["entities"] = entities.map(entity => { - return entity.id; - }); - + scope["entities"] = entityIds; } if( scopeData.roles ) { @@ -710,7 +727,6 @@ module.exports = class ProgramsHelper { static addEntitiesInScope( programId,entities ) { return new Promise(async (resolve, reject) => { try { - let programData = await this.programDocuments({ _id : programId, @@ -725,30 +741,50 @@ module.exports = class ProgramsHelper { } let locationIds = []; + let orgExternalId = []; + let entityIds = []; let bodyData={}; entities.forEach(entity=>{ if (gen.utils.checkValidUUID(entity)) { locationIds.push(entity); + } else { + orgExternalId.push(entity); } }); - bodyData = { - "id" : locationIds + + if ( locationIds.length > 0 ) { + bodyData = { + "id" : locationIds + } + let entityData = await userService.learnerLocationSearch( bodyData ); + if ( entityData.success && entityData.data && entityData.data.response && entityData.data.response.length > 0 ) { + entityData.data.response.forEach( entity => { + entityIds.push(entity.id) + }); + } + } + + if ( orgExternalId.length > 0 ) { + let filterData = { + "externalId" : orgExternalId + } + let schoolDetails = await userService.schoolData( filterData ); + + if ( schoolDetails.success && schoolDetails.data && schoolDetails.data.response && schoolDetails.data.response.content && schoolDetails.data.response.content.length > 0 ) { + let schoolData = schoolDetails.data.response.content; + schoolData.forEach( entity => { + entityIds.push(entity.externalId) + }); + } } - let entitiesData = await userService.learnerLocationSearch( bodyData ); - - if( !entitiesData.success || !entitiesData.data || !entitiesData.data.response || !entitiesData.data.response.length > 0 ) { + if( !entityIds.length > 0 ) { throw { message : constants.apiResponses.ENTITIES_NOT_FOUND }; } - let entityIds = []; - entitiesData.data.response.forEach(entityResult => { - entityIds.push(entityResult.id); - }); - let updateProgram = await database.models.programs.findOneAndUpdate({ _id : programId },{ @@ -767,6 +803,7 @@ module.exports = class ProgramsHelper { }); } catch(error) { + return resolve({ success : false, status : error.status ? @@ -876,19 +913,11 @@ module.exports = class ProgramsHelper { message : constants.apiResponses.ENTITIES_NOT_FOUND }; } - - let entityIds = []; - entities.forEach(entity => { - if (gen.utils.checkValidUUID(entity)) { - entityIds.push(entity); - } - - }); let updateProgram = await database.models.programs.findOneAndUpdate({ _id : programId },{ - $pull : { "scope.entities" : { $in : entityIds} } + $pull : { "scope.entities" : { $in : entities} } },{ new : true }).lean(); if( !updateProgram || !updateProgram._id ) { From 178399a6c206e226250208107e1ba10bbef27cd0 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Wed, 3 Aug 2022 10:13:47 +0530 Subject: [PATCH 139/331] solution create school code check --- module/solutions/helper.js | 55 ++++++++++++++++++++++++++++---------- 1 file changed, 41 insertions(+), 14 deletions(-) diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 9323ca65..3489f46d 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -130,24 +130,51 @@ module.exports = class SolutionsHelper { } if( solutionData.entities && solutionData.entities.length > 0 ) { - let bodyData={ - "id" : solutionData.entities - }; - + let locationIds = []; + let orgExternalId = []; + let entityIds = []; - let entitiesDetails = await userService.learnerLocationSearch( bodyData ); - if( !entitiesDetails.success || !entitiesDetails.data || !entitiesDetails.data.response || !entitiesDetails.data.response.length > 0 ) { - throw { - message : constants.apiResponses.ENTITIES_NOT_FOUND + solutionData.entities.forEach(entity=>{ + if (gen.utils.checkValidUUID(entity)) { + locationIds.push(entity); + } else { + orgExternalId.push(entity); + } + }); + console.log("id arrays : ",locationIds, orgExternalId) + if ( locationIds.length > 0 ) { + let bodyData = { + "id" : locationIds + } + let entityData = await userService.learnerLocationSearch( bodyData ); + if ( entityData.success && entityData.data && entityData.data.response && entityData.data.response.length > 0 ) { + entityData.data.response.forEach( entity => { + entityIds.push(entity.id) + }); + } + } + + if ( orgExternalId.length > 0 ) { + let filterData = { + "externalId" : orgExternalId + } + let schoolDetails = await userService.schoolData( filterData ); + + if ( schoolDetails.success && schoolDetails.data && schoolDetails.data.response && schoolDetails.data.response.content && schoolDetails.data.response.content.length > 0 ) { + let schoolData = schoolDetails.data.response.content; + schoolData.forEach( entity => { + entityIds.push(entity.externalId) + }); } } + console.log("entityIds : ",entityIds) + if( !entityIds.length > 0 ) { + throw { + message : constants.apiResponses.ENTITIES_NOT_FOUND + }; + } - let entitiesData = entitiesDetails.data.response; - - entitiesData = entitiesData.map( entity => { - return entity.id; - }) - solutionData.entities = entitiesData; + solutionData.entities = entityIds; } From 900d9e66cb9eb6228f90f18314cc3d05ef6350dd Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Wed, 3 Aug 2022 12:23:11 +0530 Subject: [PATCH 140/331] solutions/create --- module/solutions/helper.js | 113 +++++++++++++++++++++---------------- 1 file changed, 64 insertions(+), 49 deletions(-) diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 3489f46d..b2863661 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -141,7 +141,7 @@ module.exports = class SolutionsHelper { orgExternalId.push(entity); } }); - console.log("id arrays : ",locationIds, orgExternalId) + if ( locationIds.length > 0 ) { let bodyData = { "id" : locationIds @@ -167,7 +167,7 @@ module.exports = class SolutionsHelper { }); } } - console.log("entityIds : ",entityIds) + if( !entityIds.length > 0 ) { throw { message : constants.apiResponses.ENTITIES_NOT_FOUND @@ -214,7 +214,6 @@ module.exports = class SolutionsHelper { solutionCreation._id, solutionData.scope ? solutionData.scope : {} ); - } return resolve({ @@ -247,7 +246,6 @@ module.exports = class SolutionsHelper { return new Promise(async (resolve, reject) => { try { - let programData = await programsHelper.programDocuments({ _id : programId },["_id","scope"]); @@ -266,62 +264,81 @@ module.exports = class SolutionsHelper { message : constants.apiResponses.SOLUTION_NOT_FOUND }); } + if( programData[0].scope ) { let currentSolutionScope = JSON.parse(JSON.stringify(programData[0].scope)); if( Object.keys(scopeData).length > 0 ) { - //if scope data passed with request body if( scopeData.entityType ) { - currentSolutionScope.entityType = scopeData.entityType; + let bodyData = { "type" : scopeData.entityType } + let entityTypeData = await userService.learnerLocationSearch( bodyData, 1 ); + if ( entityTypeData.success && entityTypeData.data && entityTypeData.data.response && entityTypeData.data.response.length > 0 ) { + currentSolutionScope.entityType = entityTypeData.data.response[0].type + } } - + if( scopeData.entities && scopeData.entities.length > 0 ) { - let entityLocationIds = []; - scopeData.entities.forEach(entity => { + //call learners api for search + let locationIds = []; + let orgExternalId = []; + let entityIds = []; + let bodyData={}; + + scopeData.entities.forEach(entity=>{ if (gen.utils.checkValidUUID(entity)) { - entityLocationIds.push(entity); + locationIds.push(entity); + } else { + orgExternalId.push(entity); } }); - let bodyData = { - "id" : entityLocationIds - }; - - let entityDetails = await userService.learnerLocationSearch(bodyData); - if( !entityDetails.success || !entityDetails.data || !entityDetails.data.response || !entityDetails.data.response.length > 0 ) { - return resolve({ - status : httpStatusCode.bad_request.status, - message : constants.apiResponses.ENTITIES_NOT_FOUND - }); + + if ( locationIds.length > 0 ) { + bodyData = { + "id" : locationIds + } + let entityData = await userService.learnerLocationSearch( bodyData ); + if ( entityData.success && entityData.data && entityData.data.response && entityData.data.response.length > 0 ) { + entityData.data.response.forEach( entity => { + if( entity.type == currentSolutionScope.entityType ) { + entityIds.push(entity.id) + } + }); + } } - - let entityData = entityDetails.data.response; - let entities = []; - entityData.map(entity => { + + if ( orgExternalId.length > 0 && currentSolutionScope.entityType == constants.common.SCHOOL ) { + let filterData = { + "externalId" : orgExternalId + } + let schoolDetails = await userService.schoolData( filterData ); - if( entity.type == currentSolutionScope.entityType ) { - entities.push(entity.id) + if ( schoolDetails.success && schoolDetails.data && schoolDetails.data.response && schoolDetails.data.response.content && schoolDetails.data.response.content.length > 0 ) { + let schoolData = schoolDetails.data.response.content; + schoolData.forEach( entity => { + entityIds.push(entity.externalId) + }); } - }) - - if( !entities.length > 0 ) { + } + + if( !entityIds.length > 0 ) { return resolve({ status : httpStatusCode.bad_request.status, message : constants.apiResponses.ENTITIES_NOT_FOUND }); } - let entityIds = []; - + let entitiesData = []; + if( currentSolutionScope.entityType !== programData[0].scope.entityType ) { + let matchData = []; let childEntities = await entitiesInParent(currentSolutionScope.entities,currentSolutionScope.entityType,matchData); - - if( childEntities.length > 0) { - for( let entitiesIndex = 0; entitiesIndex < entities.length; entitiesIndex++ ) { + if( childEntities.length > 0 && entityIds.length > 0 ) { + for( let entitiesIndex = 0; entitiesIndex < entityIds.length; entitiesIndex++ ) { for( let childListIndex = 0; childListIndex < childEntities.length; childListIndex++) { - if( childEntities[childListIndex] == entities[entitiesIndex]){ - entityIds.push(entities[entitiesIndex]); + if( childEntities[childListIndex] == entityIds[entitiesIndex]){ + entitiesData.push(entityIds[entitiesIndex]); entitiesIndex++; } } @@ -329,23 +346,21 @@ module.exports = class SolutionsHelper { } } else { - entityIds = entities.map(entity => { - return entity._id; - }); - } - - if( !entityIds.length > 0 ) { + entitiesData = entityIds + } - return resolve({ - status : httpStatusCode.bad_request.status, - message : constants.apiResponses.SCOPE_ENTITY_INVALID - }); + if( !entitiesData.length > 0 ) { + + return resolve({ + status : httpStatusCode.bad_request.status, + message : constants.apiResponses.SCOPE_ENTITY_INVALID + }); - } + } - currentSolutionScope.entities = entityIds; + currentSolutionScope.entities = entitiesData; } - + if( scopeData.roles ) { if( Array.isArray(scopeData.roles) && scopeData.roles.length > 0 ) { From 635bf5870f9e05506956dfcd8a651ef2bf4ea52b Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Wed, 3 Aug 2022 16:39:09 +0530 Subject: [PATCH 141/331] programs,solutions and users school code check --- module/programs/helper.js | 2 +- module/solutions/helper.js | 61 +++++++++++++++++++++----------------- module/users/helper.js | 2 +- 3 files changed, 36 insertions(+), 29 deletions(-) diff --git a/module/programs/helper.js b/module/programs/helper.js index 7dd3269f..c6f6adfa 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -239,7 +239,7 @@ module.exports = class ProgramsHelper { orgExternalId.push(entity); } }); - + //locationIds contain id of location data. if ( locationIds.length > 0 ) { bodyData = { "id" : locationIds diff --git a/module/solutions/helper.js b/module/solutions/helper.js index b2863661..c797694f 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -1043,29 +1043,45 @@ module.exports = class SolutionsHelper { } } } - let bodyData={ - "id" : entities - }; + let locationIds = []; + let orgExternalId = []; + let entityIds = []; + let bodyData={}; + entities.forEach(entity=>{ + if (gen.utils.checkValidUUID(entity)) { + locationIds.push(entity); + } else { + orgExternalId.push(entity); + } + }); - let entitiesDetails = await userService.learnerLocationSearch( bodyData ); - - if( !entitiesDetails.success || !entitiesDetails.data || !entitiesDetails.data.response || !entitiesDetails.data.response.length > 0 ) { - return resolve({ - status : httpStatusCode.bad_request.status, - message : constants.apiResponses.ENTITIES_NOT_FOUND - }); + if ( locationIds.length > 0 ) { + bodyData = { + "id" : locationIds + } + let entityData = await userService.learnerLocationSearch( bodyData ); + if ( entityData.success && entityData.data && entityData.data.response && entityData.data.response.length > 0 ) { + entityData.data.response.forEach( entity => { + entityIds.push(entity.id) + }); + } } - let entitiesData = entitiesDetails.data.response; - let entityIds = []; - - entitiesData.map(entity => { - if( entity.type == solutionData[0].scope.entityType ) { - entityIds.push(entity.id) + if ( orgExternalId.length > 0 ) { + let filterData = { + "externalId" : orgExternalId } - }); + let schoolDetails = await userService.schoolData( filterData ); + if ( schoolDetails.success && schoolDetails.data && schoolDetails.data.response && schoolDetails.data.response.content && schoolDetails.data.response.content.length > 0 ) { + let schoolData = schoolDetails.data.response.content; + schoolData.forEach( entity => { + entityIds.push(entity.externalId) + }); + } + } + if( !entityIds.length > 0 ) { throw { message : constants.apiResponses.ENTITIES_NOT_FOUND @@ -1212,22 +1228,13 @@ module.exports = class SolutionsHelper { }; } - let entityIds = []; - entities.forEach(entity => { - if (gen.utils.checkValidUUID(entity)) { - entityIds.push(entity); - } - - }); - - let updateSolution = await database.models.solutions .findOneAndUpdate( { _id: solutionId, }, { - $pull: { "scope.entities": { $in: entityIds } }, + $pull: { "scope.entities": { $in: entities } }, }, { new: true } ) diff --git a/module/users/helper.js b/module/users/helper.js index ed75d4e0..c66c6231 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -209,7 +209,7 @@ module.exports = class UsersHelper { } let schoolData = schoolDetails.data.response.content; schoolData.forEach( entity => { - entitiesData.push(entity.identifier) + entitiesData.push(entity.externalId) }); solutionDataToBeUpdated["entityType"] = constants.common.SCHOOL; From d00af3bfe6cd6ddc31c35d3e56d6ce0fd6d6b88f Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Wed, 3 Aug 2022 16:46:55 +0530 Subject: [PATCH 142/331] change in users service --- generics/services/users.js | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/generics/services/users.js b/generics/services/users.js index eff59ea1..82476bc2 100644 --- a/generics/services/users.js +++ b/generics/services/users.js @@ -91,12 +91,11 @@ const learnerLocationSearch = function ( filterData, pageSize = "", pageNo = "", bodyData["request"]["query"] = searchKey } - const url = userServiceUrl + constants.endpoints.GET_LOCATION_DATA; const options = { headers : { - "content-type": "application/json" + "content-type": "application/json" }, json : bodyData }; @@ -209,7 +208,7 @@ const learnerLocationSearch = function ( filterData, pageSize = "", pageNo = "", * @param {String} searchKey - search key for fuzzy search. * @returns {Promise} returns a promise. */ - const schoolData = function ( filterData, pageSize = "", pageNo = "", searchKey = "", fields) { + const schoolData = function ( filterData, pageSize = "", pageNo = "", searchKey = "", fields = [] ) { return new Promise(async (resolve, reject) => { try { From af5acb05238176e3333301c85197b349317c1312 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 8 Aug 2022 14:48:06 +0530 Subject: [PATCH 143/331] form baseurl added --- generics/constants/endpoints.js | 2 +- generics/services/users.js | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/generics/constants/endpoints.js b/generics/constants/endpoints.js index a1d899ff..2deb5488 100644 --- a/generics/constants/endpoints.js +++ b/generics/constants/endpoints.js @@ -32,6 +32,6 @@ module.exports = { GET_QUESTIONS : "/v1/solutions/questions", GET_OBSERVATION : "/v1/observations/details", GET_LOCATION_DATA : "/v1/location/search", - GET_FORM_DATA : "/v1/form/read", + GET_FORM_DATA : "/plugin/v1/form/read", GET_SCHOOL_DATA : "/v1/org/search" } \ No newline at end of file diff --git a/generics/services/users.js b/generics/services/users.js index 82476bc2..5f6679b2 100644 --- a/generics/services/users.js +++ b/generics/services/users.js @@ -8,6 +8,7 @@ //dependencies const request = require('request'); const userServiceUrl = process.env.USER_SERVICE_URL; +const formServiceUrl = process.env.FORM_SERVICE_URL; const serverTimeout = process.env.SUNBIRD_SERVER_TIMEOUT ? parseInt(process.env.SUNBIRD_SERVER_TIMEOUT) : 500; const dataLimit = process.env.SUNBIRD_RESPONSE_DATA_LIMIT ? parseInt(process.env.SUNBIRD_RESPONSE_DATA_LIMIT) : 10000; @@ -157,7 +158,7 @@ const learnerLocationSearch = function ( filterData, pageSize = "", pageNo = "", } const url = - userServiceUrl + constants.endpoints.GET_FORM_DATA; + formServiceUrl + constants.endpoints.GET_FORM_DATA; const options = { headers : { "content-type": "application/json" From 6d35abc52a2744baa8c1f9c7ccc3ac426290c666 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 15 Aug 2022 23:22:40 +0530 Subject: [PATCH 144/331] review changes --- .env.sample | 9 +++- config/globals.js | 3 ++ controllers/v1/users.js | 2 +- envVariables.js | 15 ++++++ generics/constants/common.js | 6 +-- generics/helpers/cache.js | 14 +++-- generics/services/form.js | 83 ++++++++++++++++++++++++++---- generics/services/users.js | 99 +++++++----------------------------- module/entities/helper.js | 77 +++++++++++++++------------- module/programs/helper.js | 6 +-- module/solutions/helper.js | 94 +++++++++++----------------------- module/users/helper.js | 54 +++++++++++--------- 12 files changed, 236 insertions(+), 226 deletions(-) diff --git a/.env.sample b/.env.sample index 81301951..df583c04 100644 --- a/.env.sample +++ b/.env.sample @@ -38,4 +38,11 @@ ML_PROJECT_SERVICE_URL = "http://ml-project-service:3000" USER_SERVICE_URL = "http://user-service:3000" // Base url of the sunbird enviornment CSV_REPORTS_PATH = "public/report" // Report path -APP_PORTAL_BASE_URL = "https://dev.sunbirded.org" \ No newline at end of file +APP_PORTAL_BASE_URL = "https://dev.sunbirded.org" + +#CACHE TIME TO LIVE //Cache data time to live +CACHE_TTL = 43200 + +#USER service +USER_SERVICE_TIMEOUT = 5000 +USER_RESPONSE_DATA_LIMIT = 10000 \ No newline at end of file diff --git a/config/globals.js b/config/globals.js index 458f3998..c47cb1ce 100644 --- a/config/globals.js +++ b/config/globals.js @@ -99,4 +99,7 @@ module.exports = function () { } }); + //define cache as global variable + global.cache = require(ROOT_PATH+"/generics/helpers/cache"); + }; diff --git a/controllers/v1/users.js b/controllers/v1/users.js index c7ae76f3..37c841b0 100644 --- a/controllers/v1/users.js +++ b/controllers/v1/users.js @@ -554,7 +554,7 @@ module.exports = class Users extends Abstract { } // multiple targeted entity else if ( roleWiseTargetedEntities && roleWiseTargetedEntities.length > 1 ) { - + // request body contain role and entitytype and id let targetedEntity = await usersHelper.getHighestTargetedEntity( roleWiseTargetedEntities, req.body ); diff --git a/envVariables.js b/envVariables.js index ee9f0312..63ad30b7 100644 --- a/envVariables.js +++ b/envVariables.js @@ -129,6 +129,21 @@ let enviromentVariables = { "message" : "App Portal base url", "optional" : true, "default": "https://dev.sunbirded.org" + }, + "USER_SERVICE_TIMEOUT" : { + "message" : "User Service Timeout", + "optional" : true, + "default": 5000 + }, + "CACHE_TTL" : { + "message" : "Cache Time To Live", + "optional" : true, + "default": 43200 + }, + "USER_RESPONSE_DATA_LIMIT" : { + "message" : "User Response Data Limit", + "optional" : true, + "default": 10000 } } diff --git a/generics/constants/common.js b/generics/constants/common.js index caf7cd12..e227cbd8 100644 --- a/generics/constants/common.js +++ b/generics/constants/common.js @@ -67,8 +67,8 @@ module.exports = { "DISCOVERED_BY_ME" : "discoveredByMe", "DEFAULT_SUBMISSION_REQUIRED" : 1, "SCHOOL" : "school", - "SUBENTITY" :"subEntity_", - "CACHE_TIME_PERIOD" : 43200, - "FORM_API_TYPE" : "profileConfig" + "SUBENTITY" :"subEntityTypesOf_", + "CACHE_TTL" : 43200, + "PROFILE_CONFIG_FORM_KEY" : "profileConfig" }; diff --git a/generics/helpers/cache.js b/generics/helpers/cache.js index 603d1a29..2936d9ce 100644 --- a/generics/helpers/cache.js +++ b/generics/helpers/cache.js @@ -21,9 +21,15 @@ function getValue(key){ if (cache.has(key)) { data = cache.get(key); + return ({ + success: true, + result: data + }) + } else { + return ({ + success: false + }) } - - return data; } @@ -38,7 +44,7 @@ function getValue(key){ function setValue(key, value, timeout){ let data = cache.set( key, value, timeout ); - return data; + return true; } /** @@ -52,7 +58,7 @@ function setValue(key, value, timeout){ function removeKey(key){ let data = cache.del(key); - return; + return true; } module.exports = { diff --git a/generics/services/form.js b/generics/services/form.js index 8c8ef6b8..f888796a 100644 --- a/generics/services/form.js +++ b/generics/services/form.js @@ -6,15 +6,16 @@ */ //dependencies -const userService = require(ROOT_PATH + "/generics/services/users"); -let cache = require(ROOT_PATH+"/generics/helpers/cache"); +const request = require('request'); +const formServiceUrl = process.env.FORM_SERVICE_URL; +const cacheTimeToLive = parseInt(process.env.CACHE_TTL); +const serverTimeout = parseInt(process.env.USER_SERVICE_TIMEOUT); /** - * * @function * @name formData * @param {String} stateLocationCode - state location code. - * @param {object} entityKey - key to store data in cache + * @param {object} entityKey - key to store data in cache. * @returns {Promise} returns a promise. */ @@ -22,9 +23,9 @@ let cache = require(ROOT_PATH+"/generics/helpers/cache"); const formData = function ( stateLocationCode, entityKey ) { return new Promise(async (resolve, reject) => { try { - - let subEntitiesDetails = await userService.formRead( stateLocationCode ); - if( !subEntitiesDetails.success) { + //Get Sub Entity Types present in a particular state + let subEntitiesDetails = await formRead( stateLocationCode ); + if( !subEntitiesDetails.success ) { return resolve({ message : constants.apiResponses.ENTITY_NOT_FOUND, result : [] @@ -32,12 +33,12 @@ const formData = function ( stateLocationCode, entityKey ) { } let subEntityData = subEntitiesDetails.data.form.data.fields[1].children.teacher; - + //Entity type is stored in a key called code let subEntities = subEntityData.map( subEntity => { return subEntity.code; }) - - let setCache = cache.setValue(entityKey, subEntities, constants.common.CACHE_TIME_PERIOD); + //set cache data for given state + let setCache = cache.setValue(entityKey, subEntities, cacheTimeToLive); return resolve(subEntities); } catch (error) { @@ -45,6 +46,68 @@ const formData = function ( stateLocationCode, entityKey ) { } }) } + +/** + * + * @function + * @name formRead + * @param {object} subTypeData - State location code. + * @returns {Promise} returns a promise. +*/ +async function formRead ( subTypeData ) { + return new Promise(async (resolve, reject) => { + try { + + let bodyData = { + request : { + type: constants.common.PROFILE_CONFIG_FORM_KEY, + subType: subTypeData, + action: constants.common.GET_METHOD + } + } + + const url = + formServiceUrl + constants.endpoints.GET_FORM_DATA; + const options = { + headers : { + "content-type": "application/json" + }, + json : bodyData + }; + + request.post(url, options, requestCallBack); + let result = { + success : true + }; + function requestCallBack(err, data) { + + if (err) { + result.success = false; + } else { + + let response = data.body; + + if( response.responseCode === constants.common.OK) { + result["data"] = response.result; + result.success = true; + } else { + result.success = false; + } + } + return resolve(result); + } + setTimeout(function () { + return resolve (result = { + success : false + }); + }, serverTimeout); + + } catch (error) { + return reject(error); + } + }) +} + module.exports = { formData : formData } \ No newline at end of file diff --git a/generics/services/users.js b/generics/services/users.js index 5f6679b2..64853638 100644 --- a/generics/services/users.js +++ b/generics/services/users.js @@ -8,9 +8,8 @@ //dependencies const request = require('request'); const userServiceUrl = process.env.USER_SERVICE_URL; -const formServiceUrl = process.env.FORM_SERVICE_URL; -const serverTimeout = process.env.SUNBIRD_SERVER_TIMEOUT ? parseInt(process.env.SUNBIRD_SERVER_TIMEOUT) : 500; -const dataLimit = process.env.SUNBIRD_RESPONSE_DATA_LIMIT ? parseInt(process.env.SUNBIRD_RESPONSE_DATA_LIMIT) : 10000; +const serverTimeout = parseInt(process.env.USER_SERVICE_TIMEOUT); +const dataLimit = parseInt(process.env.USER_RESPONSE_DATA_LIMIT); const profile = function ( token,userId = "" ) { return new Promise(async (resolve, reject) => { @@ -63,16 +62,14 @@ const profile = function ( token,userId = "" ) { /** * * @function - * @name learnerLocationSearch - * @param {String} bearerToken - autherization token. + * @name locationSearch * @param {object} filterData - bodydata . * @returns {Promise} returns a promise. */ -const learnerLocationSearch = function ( filterData, pageSize = "", pageNo = "", searchKey = "" ) { +const locationSearch = function ( filterData, pageSize = "", pageNo = "", searchKey = "" ) { return new Promise(async (resolve, reject) => { try { - let bodyData = {}; bodyData["request"] = {}; bodyData["request"]["filters"] = filterData; @@ -97,26 +94,27 @@ const learnerLocationSearch = function ( filterData, pageSize = "", pageNo = "", const options = { headers : { "content-type": "application/json" - }, + }, json : bodyData }; - - request.post(url,options,sunbirdCallback); + request.post(url,options,requestCallback); let result = { success : true }; - function sunbirdCallback(err, data) { - - + function requestCallback(err, data) { if (err) { result.success = false; } else { - let response = data.body; - if( response.responseCode === constants.common.OK) { - result["data"] = response.result; + if( response.responseCode === constants.common.OK && + response.result && + response.result.response && + response.result.response.length > 0 + ) { + result["data"] = response.result.response; + result["count"] = response.result.count; } else { result.success = false; } @@ -137,67 +135,7 @@ const learnerLocationSearch = function ( filterData, pageSize = "", pageNo = "", }) } - /** - * - * @function - * @name formRead - * @param {String} bearerToken - autherization token. - * @param {object} bodyData - subType data. - * @returns {Promise} returns a promise. - */ - const formRead = function ( subTypeData ) { - return new Promise(async (resolve, reject) => { - try { - - let bodyData = { - request : { - type: constants.common.FORM_API_TYPE, - subType: subTypeData, - action: constants.common.GET_METHOD - } - } - - const url = - formServiceUrl + constants.endpoints.GET_FORM_DATA; - const options = { - headers : { - "content-type": "application/json" - }, - json : bodyData - }; - - request.post(url,options,sunbirdCallback); - let result = { - success : true - }; - function sunbirdCallback(err, data) { - - if (err) { - result.success = false; - } else { - - let response = data.body; - - if( response.responseCode === constants.common.OK) { - result["data"] = response.result; - result.success = true; - } else { - result.success = false; - } - } - return resolve(result); - } - setTimeout(function () { - return resolve (result = { - success : false - }); - }, serverTimeout); - } catch (error) { - return reject(error); - } - }) - } /** * @@ -242,16 +180,16 @@ const learnerLocationSearch = function ( filterData, pageSize = "", pageNo = "", const options = { headers : { "content-type": "application/json" - }, + }, json : bodyData }; - request.post(url,options,sunbirdCallback); + request.post(url,options,requestCallback); let result = { success : true }; - function sunbirdCallback(err, data) { + function requestCallback(err, data) { if (err) { result.success = false; @@ -281,7 +219,6 @@ const learnerLocationSearch = function ( filterData, pageSize = "", pageNo = "", module.exports = { profile : profile, - learnerLocationSearch : learnerLocationSearch, - formRead : formRead, + locationSearch : locationSearch, schoolData :schoolData } diff --git a/module/entities/helper.js b/module/entities/helper.js index d0380b2e..b44a870b 100644 --- a/module/entities/helper.js +++ b/module/entities/helper.js @@ -246,28 +246,29 @@ module.exports = class EntitiesHelper { return new Promise(async (resolve, reject) => { try { - let bodyData={ + //List of all immediateEntities based on entityId. + let bodyData = { "parentId" : entityId }; - let entitiesData = await userService.learnerLocationSearch( + let entitiesData = await userService.locationSearch( bodyData, pageSize, pageNo, searchText ); - if( !entitiesData.success || !entitiesData.data || !entitiesData.data.response || !entitiesData.data.response.length > 0 ) { + if( !entitiesData.success ) { return resolve({ - data : entitiesData.data.response, - count : entitiesData.data.count + data : entitiesData.data, + count : entitiesData.count }); } - let immediateLocation = entitiesData.data.response; + let immediateLocation = entitiesData.data; return resolve({ data : immediateLocation, - count : entitiesData.data.count + count : entitiesData.count }); } catch(error) { @@ -391,11 +392,11 @@ module.exports = class EntitiesHelper { } /** - * Get immediate entities. + * Get entities by traversal. * @method - * @name listByEntityType + * @name entityTraversal * @param {Object} entityId - * @returns {Array} - List of all immediateEntities based on entityId. + * @returns {Array} - List of all Entities based on entityId using traversal. */ static entityTraversal( @@ -407,7 +408,7 @@ module.exports = class EntitiesHelper { ) { return new Promise(async (resolve, reject) => { try { - + //list entities of type {entityTraversalType} which comes under the specified entity{entityId} if( entityTraversalType == constants.common.SCHOOL) { let filterData = { "orgLocation.id" : entityId @@ -434,14 +435,14 @@ module.exports = class EntitiesHelper { }); - let bodyData={ + let bodyData = { "code" : schoolCodes }; - let entitiesData = await userService.learnerLocationSearch( bodyData ); + let entitiesData = await userService.locationSearch( bodyData ); - if( !entitiesData.success || !entitiesData.data || !entitiesData.data.response || !entitiesData.data.response.length > 0 ) { + if( !entitiesData.success ) { return resolve({ data : [], count : 0 @@ -449,15 +450,16 @@ module.exports = class EntitiesHelper { } return resolve({ - data : entitiesData.data.response, + data : entitiesData.data, count : subentitiesCode.data.response.count }) } else { - let subEntitiesMatchingType = []; + /* if {entityId} is of a state and {entityTraversalType} is block , getSubEntitiesOfGivenType will return all entities of type block in that state*/ + let subEntitiesArray = []; - let subEntities = await subEntitiesWithMatchingType( entityId,entityTraversalType,subEntitiesMatchingType ) + let subEntities = await getSubEntitiesOfGivenType( entityId, entityTraversalType, subEntitiesArray ) if( !subEntities.length > 0 ) { return resolve({ @@ -465,7 +467,7 @@ module.exports = class EntitiesHelper { count : 0 }) } - + //searching here because search with traversal will affect result. let subentitiesData = subEntities let count = subentitiesData.length; if( searchText !== "" ){ @@ -713,9 +715,10 @@ module.exports = class EntitiesHelper { * @returns {Array} List of sub entity type. */ - static subEntityListBasedOnRoleAndLocation( stateLocationId,role ) { + static subEntityListBasedOnRoleAndLocation( stateLocationId, role ) { return new Promise(async (resolve, reject) => { try { + //key will be subEntityTypesOf_{stateLocationId} let entityKey = constants.common.SUBENTITY + stateLocationId; let rolesDocument = await userRolesHelper.roleDocuments({ @@ -728,31 +731,35 @@ module.exports = class EntitiesHelper { message: constants.apiResponses.USER_ROLES_NOT_FOUND } } + //check if data already available in cache + let subEntities = []; + let cacheData = await cache.getValue(entityKey); - let subEntities = await cache.getValue(entityKey); - - if( !subEntities.length > 0 ) { + if( !cacheData.success ) { let bodyData={ "id" : stateLocationId }; - let entitiesData = await userService.learnerLocationSearch( bodyData ); - - if( !entitiesData.success || !entitiesData.data || !entitiesData.data.response || !entitiesData.data.response.length > 0 ) { + let entitiesData = await userService.locationSearch( bodyData ); + + if( !entitiesData.success ) { return resolve({ message : constants.apiResponses.ENTITY_NOT_FOUND, result : [] }) } - let stateLocationCode = entitiesData.data.response[0].code; - subEntities = await formService.formData( stateLocationCode,entityKey ); + let stateLocationCode = entitiesData.data[0].code; + subEntities = await formService.formData( stateLocationCode, entityKey ); + if( !subEntities.length > 0 ) { return resolve({ message : constants.apiResponses.ENTITY_NOT_FOUND, result : [] }) } + } else { + subEntities = cacheData.result; } @@ -879,11 +886,13 @@ module.exports = class EntitiesHelper { /** * get subEntities of matching type by recursion. * @method - * @name subEntitiesWithMatchingType + * @name getSubEntitiesOfGivenType + * @param parentIds {Array} - Array of entity Ids- for which we are finding sub entities of given entityType + * @param entityType {string} - EntityType. * @returns {Array} - Sub entities matching the type . */ -async function subEntitiesWithMatchingType( parentIds,entityType, matchingData ) { +async function getSubEntitiesOfGivenType( parentIds, entityType, matchingData ) { if( !parentIds.length > 0 ) { return matchingData; @@ -892,14 +901,14 @@ async function subEntitiesWithMatchingType( parentIds,entityType, matchingData ) let bodyData = { "parentId" : parentIds }; - - let entityDetails = await userService.learnerLocationSearch(bodyData); + //get all immediate subEntities of type {entityType} + let entityDetails = await userService.locationSearch(bodyData); - if( ( !entityDetails.success || !entityDetails.data || !entityDetails.data.response || !entityDetails.data.response.length > 0 ) && !matchingData.length > 0 ) { + if( ( !entityDetails.success ) && !matchingData.length > 0 ) { return matchingData; } - let entityData = entityDetails.data.response; + let entityData = entityDetails.data; let mismatchEntities = []; entityData.map(entity => { @@ -913,7 +922,7 @@ async function subEntitiesWithMatchingType( parentIds,entityType, matchingData ) }); if( mismatchEntities.length > 0 ){ - await subEntitiesWithMatchingType(mismatchEntities, entityType, matchingData); + await getSubEntitiesOfGivenType(mismatchEntities, entityType, matchingData); } let uniqueEntities = []; matchingData.map( data => { diff --git a/module/programs/helper.js b/module/programs/helper.js index c6f6adfa..dc8d0aa0 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -211,7 +211,7 @@ module.exports = class ProgramsHelper { let bodyData = { "type" : scopeData.entityType } - let entityTypeData = await userService.learnerLocationSearch( bodyData ); + let entityTypeData = await userService.locationSearch( bodyData ); if( !entityTypeData.success || !entityTypeData.data || !entityTypeData.data.response || !entityTypeData.data.response.length > 0 ) { return resolve({ @@ -244,7 +244,7 @@ module.exports = class ProgramsHelper { bodyData = { "id" : locationIds } - let entityData = await userService.learnerLocationSearch( bodyData ); + let entityData = await userService.locationSearch( bodyData ); if ( entityData.success && entityData.data && entityData.data.response && entityData.data.response.length > 0 ) { entityData.data.response.forEach( entity => { entityIds.push(entity.id) @@ -757,7 +757,7 @@ module.exports = class ProgramsHelper { bodyData = { "id" : locationIds } - let entityData = await userService.learnerLocationSearch( bodyData ); + let entityData = await userService.locationSearch( bodyData ); if ( entityData.success && entityData.data && entityData.data.response && entityData.data.response.length > 0 ) { entityData.data.response.forEach( entity => { entityIds.push(entity.id) diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 36817045..53ceb6bf 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -146,9 +146,9 @@ module.exports = class SolutionsHelper { let bodyData = { "id" : locationIds } - let entityData = await userService.learnerLocationSearch( bodyData ); - if ( entityData.success && entityData.data && entityData.data.response && entityData.data.response.length > 0 ) { - entityData.data.response.forEach( entity => { + let entityData = await userService.locationSearch( bodyData ); + if ( entityData.success ) { + entityData.data.forEach( entity => { entityIds.push(entity.id) }); } @@ -272,9 +272,9 @@ module.exports = class SolutionsHelper { if( Object.keys(scopeData).length > 0 ) { if( scopeData.entityType ) { let bodyData = { "type" : scopeData.entityType } - let entityTypeData = await userService.learnerLocationSearch( bodyData, 1 ); - if ( entityTypeData.success && entityTypeData.data && entityTypeData.data.response && entityTypeData.data.response.length > 0 ) { - currentSolutionScope.entityType = entityTypeData.data.response[0].type + let entityTypeData = await userService.locationSearch( bodyData, 1 ); + if ( entityTypeData.success ) { + currentSolutionScope.entityType = entityTypeData.data[0].type } } @@ -297,9 +297,9 @@ module.exports = class SolutionsHelper { bodyData = { "id" : locationIds } - let entityData = await userService.learnerLocationSearch( bodyData ); - if ( entityData.success && entityData.data && entityData.data.response && entityData.data.response.length > 0 ) { - entityData.data.response.forEach( entity => { + let entityData = await userService.locationSearch( bodyData ); + if ( entityData.success ) { + entityData.data.forEach( entity => { if( entity.type == currentSolutionScope.entityType ) { entityIds.push(entity.id) } @@ -333,10 +333,16 @@ module.exports = class SolutionsHelper { if( currentSolutionScope.entityType !== programData[0].scope.entityType ) { let matchData = []; - let childEntities = await entitiesInParent(currentSolutionScope.entities,currentSolutionScope.entityType,matchData); - if( childEntities.length > 0 && entityIds.length > 0 ) { + let childEntities = []; + let childEntitiesDetails = await entitiesHelper.getSubEntitiesOfGivenType(currentSolutionScope.entities, currentSolutionScope.entityType, matchData); + + childEntitiesDetails.forEach( entity => { + childEntities.push(entity.id) + }); + + if( childEntities.length > 0 ) { for( let entitiesIndex = 0; entitiesIndex < entityIds.length; entitiesIndex++ ) { - for( let childListIndex = 0; childListIndex < childEntities.length; childListIndex++) { + for( let childListIndex = 0; childListIndex < childEntities.length; childListIndex++ ) { if( childEntities[childListIndex] == entityIds[entitiesIndex]){ entitiesData.push(entityIds[entitiesIndex]); entitiesIndex++; @@ -1019,9 +1025,14 @@ module.exports = class SolutionsHelper { if( solutionData[0].scope.entityType !== programData[0].scope.entityType ) { let matchData = []; + let childEntities = []; let checkEntityInParent = []; - let childEntities = await entitiesInParent(programData[0].scope.entities,solutionData[0].scope.entityType,matchData); - + let childEntitiesDetails = await entitiesHelper.getSubEntitiesOfGivenType(programData[0].scope.entities, solutionData[0].scope.entityType, matchData); + + childEntitiesDetails.forEach( entity => { + childEntities.push(entity.id); + }); + if( !childEntities.length > 0 ) { throw { message : constants.apiResponses.ENTITY_NOT_EXISTS_IN_PARENT @@ -1060,9 +1071,9 @@ module.exports = class SolutionsHelper { bodyData = { "id" : locationIds } - let entityData = await userService.learnerLocationSearch( bodyData ); - if ( entityData.success && entityData.data && entityData.data.response && entityData.data.response.length > 0 ) { - entityData.data.response.forEach( entity => { + let entityData = await userService.locationSearch( bodyData ); + if ( entityData.success ) { + entityData.data.forEach( entity => { entityIds.push(entity.id) }); } @@ -2110,51 +2121,4 @@ function _generateLink(appsPortalBaseUrl, prefix, solutionLink, solutionType) { return link; -} - -/** - * get entitiesData of matching type by recursion. - * @method - * @name entitiesInParent - * @returns {Array} - Entities matching the type under the parent. -*/ - -async function entitiesInParent( solutionEntities,currentEntityType,matchingData ){ - - if( !solutionEntities.length > 0 ){ - return matchingData; - } - let bodyData={ - "parentId" : solutionEntities - }; - - let entityDetails = await userService.learnerLocationSearch(bodyData); - - if( ( !entityDetails.success || !entityDetails.data || !entityDetails.data.response || !entityDetails.data.response.length > 0) && !matchingData.length > 0 ) { - return ({ - status : httpStatusCode.bad_request.status, - message : constants.apiResponses.ENTITIES_NOT_FOUND - }); - } - - let entityData = entityDetails.data.response; - - let mismatchEntities = []; - entityData.map(entity => { - if( entity.type == currentEntityType ) { - matchingData.push(entity.id) - } else { - mismatchEntities.push(entity.id) - } - }); - - if( mismatchEntities.length > 0 ){ - await entitiesInParent(mismatchEntities,currentEntityType,matchingData) - } - let uniqueEntities = []; - matchingData.map( data => { - if (uniqueEntities.includes(data) === false) uniqueEntities.push(data); - }); - return uniqueEntities; - - } +} \ No newline at end of file diff --git a/module/users/helper.js b/module/users/helper.js index 890f5054..411cc9d1 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -176,9 +176,9 @@ module.exports = class UsersHelper { bodyData = { "id" : locationIds } - let entityData = await userService.learnerLocationSearch( bodyData ); + let entityData = await userService.locationSearch( bodyData ); - if ( !entityData.success || !entityData.data || !entityData.data.response || !entityData.data.response.length > 0 ) { + if ( !entityData.success ) { return resolve({ status: httpStatusCode["bad_request"].status, message: constants.apiResponses.ENTITY_NOT_FOUND, @@ -186,11 +186,11 @@ module.exports = class UsersHelper { }); } - entityData.data.response.forEach( entity => { + entityData.data.forEach( entity => { entitiesData.push(entity.id) }); - solutionDataToBeUpdated["entityType"] = entityData.data.response[0].type; + solutionDataToBeUpdated["entityType"] = entityData.data[0].type; } @@ -372,9 +372,10 @@ module.exports = class UsersHelper { }) } - let subEntities = await cache.getValue(entityKey); + let subEntities = []; + let cacheData= await cache.getValue(entityKey); - if( !subEntities.length > 0 ) { + if( !cacheData.success ) { subEntities = await formService.formData( stateCode,entityKey ); if( !subEntities.length > 0 ) { return resolve({ @@ -382,6 +383,8 @@ module.exports = class UsersHelper { result : [] }) } + } else { + subEntities = cacheData.result; } @@ -660,9 +663,9 @@ module.exports = class UsersHelper { }; } - let entityData = await userService.learnerLocationSearch( bodyData ); + let entityData = await userService.locationSearch( bodyData ); - if ( !entityData.success || !entityData.data || !entityData.data.response || !entityData.data.response.length > 0) { + if ( !entityData.success ) { throw { message: constants.apiResponses.ENTITIES_NOT_EXIST_IN_LOCATION, }; @@ -683,7 +686,7 @@ module.exports = class UsersHelper { entityTypes = [constants.common.STATE_ENTITY_TYPE]; } else { let entitiesMappingForm = await this.entitiesMappingForm( - entityData.data.response[0].code, + entityData.data[0].code, rolesDocument[0]._id, entityKey ); @@ -771,8 +774,8 @@ module.exports = class UsersHelper { "parentId" : requestedData[targetedEntityType] } } - let entitiesData = await userService.learnerLocationSearch( filterData ); - if( !entitiesData.success ||!entityData.data || !entityData.data.response || !entityData.data.response.length > 0 ){ + let entitiesData = await userService.locationSearch( filterData ); + if( !entitiesData.success ){ targetedEntityType = constants.common.STATE_ENTITY_TYPE; } } @@ -781,19 +784,19 @@ module.exports = class UsersHelper { filterData = { "id" : requestedData[targetedEntityType] }; - } else { + } else { filterData = { "code" : requestedData[targetedEntityType] }; } - let entitiesDocument = await userService.learnerLocationSearch( filterData ); - if ( !entitiesDocument.success || !entitiesDocument.data || !entitiesDocument.data.response || !entitiesDocument.data.response.length > 0) { + let entitiesDocument = await userService.locationSearch( filterData ); + if ( !entitiesDocument.success ) { throw { message: constants.apiResponses.ENTITY_NOT_FOUND }; } - let entityData = entitiesDocument.data.response; + let entityData = entitiesDocument.data; let entityDataFormated = { "_id" : entityData[0].id, "entityType" : entityData[0].type, @@ -828,30 +831,33 @@ module.exports = class UsersHelper { return new Promise(async (resolve, reject) => { try { let entityKey = constants.common.SUBENTITY + requestedData.state; - let subEntities = await cache.getValue(entityKey); - if( !subEntities.length > 0 ) { + let subEntityTypes = []; + let cacheData = await cache.getValue(entityKey); + if( !cacheData.success > 0 ) { let filterData = { "id" : requestedData.state }; - let entitiesData = await userService.learnerLocationSearch( filterData ); + let entitiesData = await userService.locationSearch( filterData ); - if( !entitiesData.success || !entitiesData.data || !entitiesData.data.response || !entitiesData.data.response.length > 0 ) { + if( !entitiesData.success ) { return resolve({ message : constants.apiResponses.ENTITY_NOT_FOUND, result : [] }) } - let stateLocationCode = entitiesData.data.response[0].code; - subEntities = await formService.formData( stateLocationCode,entityKey ); - if( !subEntities.length > 0 ) { + let stateLocationCode = entitiesData.data[0].code; + subEntityTypes = await formService.formData( stateLocationCode,entityKey ); + if( !subEntityTypes.length > 0 ) { return resolve({ message : constants.apiResponses.ENTITY_NOT_FOUND, result : [] }) } - } - let targetedIndex = subEntities.length; + } else { + subEntityTypes = cacheData.result; + } + let targetedIndex = subEntityTypes.length; let roleWiseTarget; for( let roleWiseEntityIndex = 0; roleWiseEntityIndex < roleWiseTargetedEntities.length; roleWiseEntityIndex++ ) { for( let subEntitiesIndex = 0; subEntitiesIndex < subEntities.length; subEntitiesIndex++ ) { From cee79deaa6339fa4c9b8d520b70906799a5c643d Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 19 Aug 2022 11:45:47 +0530 Subject: [PATCH 145/331] review changes --- .env.sample | 10 ++++------ controllers/v1/users.js | 2 +- envVariables.js | 12 +++--------- generics/helpers/cache.js | 13 ++++--------- generics/services/users.js | 5 +---- module/entities/helper.js | 2 +- module/users/helper.js | 4 ++-- 7 files changed, 16 insertions(+), 32 deletions(-) diff --git a/.env.sample b/.env.sample index df583c04..98baa927 100644 --- a/.env.sample +++ b/.env.sample @@ -35,14 +35,12 @@ ML_SURVEY_SERVICE_URL = "http://ml-survey-service:3000" # ML Project Service Service ML_PROJECT_SERVICE_URL = "http://ml-project-service:3000" // ML Project service url +#USER service USER_SERVICE_URL = "http://user-service:3000" // Base url of the sunbird enviornment +USER_SERVICE_TIMEOUT = 5000 + CSV_REPORTS_PATH = "public/report" // Report path APP_PORTAL_BASE_URL = "https://dev.sunbirded.org" -#CACHE TIME TO LIVE //Cache data time to live -CACHE_TTL = 43200 - -#USER service -USER_SERVICE_TIMEOUT = 5000 -USER_RESPONSE_DATA_LIMIT = 10000 \ No newline at end of file +FORM_SERVICE_URL = "http://player:3000" diff --git a/controllers/v1/users.js b/controllers/v1/users.js index 37c841b0..2bae7fc5 100644 --- a/controllers/v1/users.js +++ b/controllers/v1/users.js @@ -554,7 +554,7 @@ module.exports = class Users extends Abstract { } // multiple targeted entity else if ( roleWiseTargetedEntities && roleWiseTargetedEntities.length > 1 ) { - // request body contain role and entitytype and id + // request body contain role and entity information let targetedEntity = await usersHelper.getHighestTargetedEntity( roleWiseTargetedEntities, req.body ); diff --git a/envVariables.js b/envVariables.js index 63ad30b7..3f6c59d4 100644 --- a/envVariables.js +++ b/envVariables.js @@ -135,15 +135,9 @@ let enviromentVariables = { "optional" : true, "default": 5000 }, - "CACHE_TTL" : { - "message" : "Cache Time To Live", - "optional" : true, - "default": 43200 - }, - "USER_RESPONSE_DATA_LIMIT" : { - "message" : "User Response Data Limit", - "optional" : true, - "default": 10000 + "FORM_SERVICE_URL" : { + "message" : "form service base url", + "optional" : false } } diff --git a/generics/helpers/cache.js b/generics/helpers/cache.js index 2936d9ce..7c6e10f4 100644 --- a/generics/helpers/cache.js +++ b/generics/helpers/cache.js @@ -21,14 +21,9 @@ function getValue(key){ if (cache.has(key)) { data = cache.get(key); - return ({ - success: true, - result: data - }) + return data; } else { - return ({ - success: false - }) + return false; } } @@ -39,7 +34,7 @@ function getValue(key){ * @name set * @params key - name of the cache key. * @params value - cache data to set. - * @returns {Array} - cache updated data. + * @returns {Boolean} - true */ function setValue(key, value, timeout){ @@ -52,7 +47,7 @@ function setValue(key, value, timeout){ * @method * @name remove * @params key - cache key need to be removed. - * @returns + * @returns {Boolean} - true */ function removeKey(key){ diff --git a/generics/services/users.js b/generics/services/users.js index 64853638..eccf6432 100644 --- a/generics/services/users.js +++ b/generics/services/users.js @@ -9,7 +9,6 @@ const request = require('request'); const userServiceUrl = process.env.USER_SERVICE_URL; const serverTimeout = parseInt(process.env.USER_SERVICE_TIMEOUT); -const dataLimit = parseInt(process.env.USER_RESPONSE_DATA_LIMIT); const profile = function ( token,userId = "" ) { return new Promise(async (resolve, reject) => { @@ -76,9 +75,7 @@ const locationSearch = function ( filterData, pageSize = "", pageNo = "", search if ( pageSize !== "" ) { bodyData["request"]["limit"] = pageSize; - } else { - bodyData["request"]["limit"] = dataLimit; - } + } if ( pageNo !== "" ) { let offsetValue = pageSize * ( pageNo - 1 ); diff --git a/module/entities/helper.js b/module/entities/helper.js index b44a870b..45c359e9 100644 --- a/module/entities/helper.js +++ b/module/entities/helper.js @@ -735,7 +735,7 @@ module.exports = class EntitiesHelper { let subEntities = []; let cacheData = await cache.getValue(entityKey); - if( !cacheData.success ) { + if( !cacheData ) { let bodyData={ "id" : stateLocationId }; diff --git a/module/users/helper.js b/module/users/helper.js index 411cc9d1..e11573b5 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -375,7 +375,7 @@ module.exports = class UsersHelper { let subEntities = []; let cacheData= await cache.getValue(entityKey); - if( !cacheData.success ) { + if( !cacheData ) { subEntities = await formService.formData( stateCode,entityKey ); if( !subEntities.length > 0 ) { return resolve({ @@ -833,7 +833,7 @@ module.exports = class UsersHelper { let entityKey = constants.common.SUBENTITY + requestedData.state; let subEntityTypes = []; let cacheData = await cache.getValue(entityKey); - if( !cacheData.success > 0 ) { + if( !cacheData ) { let filterData = { "id" : requestedData.state }; From 8171414c595a7dbe204f8f8e165aa25b8870c2f7 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 19 Aug 2022 12:09:58 +0530 Subject: [PATCH 146/331] review changes --- .env.sample | 1 - envVariables.js | 5 ----- generics/constants/common.js | 5 +++-- generics/services/users.js | 4 ++-- 4 files changed, 5 insertions(+), 10 deletions(-) diff --git a/.env.sample b/.env.sample index 98baa927..9e4f6bea 100644 --- a/.env.sample +++ b/.env.sample @@ -37,7 +37,6 @@ ML_PROJECT_SERVICE_URL = "http://ml-project-service:3000" #USER service USER_SERVICE_URL = "http://user-service:3000" // Base url of the sunbird enviornment -USER_SERVICE_TIMEOUT = 5000 CSV_REPORTS_PATH = "public/report" // Report path diff --git a/envVariables.js b/envVariables.js index 3f6c59d4..d3b36b0e 100644 --- a/envVariables.js +++ b/envVariables.js @@ -130,11 +130,6 @@ let enviromentVariables = { "optional" : true, "default": "https://dev.sunbirded.org" }, - "USER_SERVICE_TIMEOUT" : { - "message" : "User Service Timeout", - "optional" : true, - "default": 5000 - }, "FORM_SERVICE_URL" : { "message" : "form service base url", "optional" : false diff --git a/generics/constants/common.js b/generics/constants/common.js index e227cbd8..c66a84ac 100644 --- a/generics/constants/common.js +++ b/generics/constants/common.js @@ -68,7 +68,8 @@ module.exports = { "DEFAULT_SUBMISSION_REQUIRED" : 1, "SCHOOL" : "school", "SUBENTITY" :"subEntityTypesOf_", - "CACHE_TTL" : 43200, - "PROFILE_CONFIG_FORM_KEY" : "profileConfig" + "CACHE_TTL" : 43200, + "PROFILE_CONFIG_FORM_KEY" : "profileConfig", + "SERVER_TIME_OUT" : 5000 }; diff --git a/generics/services/users.js b/generics/services/users.js index eccf6432..6cf115cc 100644 --- a/generics/services/users.js +++ b/generics/services/users.js @@ -6,9 +6,9 @@ */ //dependencies +const { constants } = require('fs'); const request = require('request'); const userServiceUrl = process.env.USER_SERVICE_URL; -const serverTimeout = parseInt(process.env.USER_SERVICE_TIMEOUT); const profile = function ( token,userId = "" ) { return new Promise(async (resolve, reject) => { @@ -123,7 +123,7 @@ const locationSearch = function ( filterData, pageSize = "", pageNo = "", search return resolve (result = { success : false }); - }, serverTimeout); + }, constants.common.SERVER_TIME_OUT); } catch (error) { From 8831162240e5b439c215cebd170fcb523e986caf Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Sun, 21 Aug 2022 13:57:28 +0530 Subject: [PATCH 147/331] Hierarchy based access to the observation based on form's entity type --- module/users/helper.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/module/users/helper.js b/module/users/helper.js index 021724de..e9d2586c 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -743,6 +743,8 @@ module.exports = class UsersHelper { Object.keys(entities[0].groups).length > 0 ) { targetedEntityType = constants.common.STATE_ENTITY_TYPE; + } else if ( targetedEntityType === constants.common.SCHOOL ) { + targetedEntityType = constants.common.STATE_ENTITY_TYPE; } } From 435aed8b5ce8d90bf11aef85f43b6206c6766d71 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 22 Aug 2022 14:53:13 +0530 Subject: [PATCH 148/331] review changes and logic changes --- .env.sample | 2 +- controllers/v1/entities.js | 2 +- envVariables.js | 2 +- generics/services/form.js | 18 ++++--- generics/services/users.js | 17 ++++--- module/entities/helper.js | 96 ++++++++++++++++++-------------------- module/programs/helper.js | 18 +++---- module/users/helper.js | 18 +++---- 8 files changed, 86 insertions(+), 87 deletions(-) diff --git a/.env.sample b/.env.sample index 9e4f6bea..ff6a934c 100644 --- a/.env.sample +++ b/.env.sample @@ -42,4 +42,4 @@ CSV_REPORTS_PATH = "public/report" APP_PORTAL_BASE_URL = "https://dev.sunbirded.org" -FORM_SERVICE_URL = "http://player:3000" +FORM_SERVICE_URL = "http://player:3000" // Base url for form search diff --git a/controllers/v1/entities.js b/controllers/v1/entities.js index 1b0c4360..35ce6360 100644 --- a/controllers/v1/entities.js +++ b/controllers/v1/entities.js @@ -359,7 +359,7 @@ module.exports = class Entities extends Abstract { req.params._id, eachRole ); - + if(entityTypeMappingData.result && entityTypeMappingData.result.length > currentMaximumCountOfRequiredEntities) { currentMaximumCountOfRequiredEntities = entityTypeMappingData.result.length; subEntityTypeListData = entityTypeMappingData; diff --git a/envVariables.js b/envVariables.js index d3b36b0e..bff824ce 100644 --- a/envVariables.js +++ b/envVariables.js @@ -131,7 +131,7 @@ let enviromentVariables = { "default": "https://dev.sunbirded.org" }, "FORM_SERVICE_URL" : { - "message" : "form service base url", + "message" : "Form service base url", "optional" : false } } diff --git a/generics/services/form.js b/generics/services/form.js index f888796a..90eac246 100644 --- a/generics/services/form.js +++ b/generics/services/form.js @@ -8,14 +8,12 @@ //dependencies const request = require('request'); const formServiceUrl = process.env.FORM_SERVICE_URL; -const cacheTimeToLive = parseInt(process.env.CACHE_TTL); -const serverTimeout = parseInt(process.env.USER_SERVICE_TIMEOUT); /** * @function * @name formData - * @param {String} stateLocationCode - state location code. - * @param {object} entityKey - key to store data in cache. + * @param {String} stateLocationCode - state location code. eg: 28 + * @param {object} entityKey - key to store data in cache. eg: subEntityTypesOf_bc75cc99-9205-463e-a722-5326857838f8 * @returns {Promise} returns a promise. */ @@ -38,7 +36,7 @@ const formData = function ( stateLocationCode, entityKey ) { return subEntity.code; }) //set cache data for given state - let setCache = cache.setValue(entityKey, subEntities, cacheTimeToLive); + let setCache = cache.setValue(entityKey, subEntities, constants.common.CACHE_TTL); return resolve(subEntities); } catch (error) { @@ -51,17 +49,17 @@ const formData = function ( stateLocationCode, entityKey ) { * * @function * @name formRead - * @param {object} subTypeData - State location code. + * @param {String} stateLocationCode - State location code. * @returns {Promise} returns a promise. */ -async function formRead ( subTypeData ) { +async function formRead ( stateLocationCode ) { return new Promise(async (resolve, reject) => { try { let bodyData = { request : { type: constants.common.PROFILE_CONFIG_FORM_KEY, - subType: subTypeData, + subType: stateLocationCode, action: constants.common.GET_METHOD } } @@ -70,7 +68,7 @@ async function formRead ( subTypeData ) { formServiceUrl + constants.endpoints.GET_FORM_DATA; const options = { headers : { - "content-type": "application/json" + "content-type": "application/json", }, json : bodyData }; @@ -100,7 +98,7 @@ async function formRead ( subTypeData ) { return resolve (result = { success : false }); - }, serverTimeout); + }, constants.common.SERVER_TIME_OUT); } catch (error) { return reject(error); diff --git a/generics/services/users.js b/generics/services/users.js index 6cf115cc..5158ad7b 100644 --- a/generics/services/users.js +++ b/generics/services/users.js @@ -6,7 +6,6 @@ */ //dependencies -const { constants } = require('fs'); const request = require('request'); const userServiceUrl = process.env.USER_SERVICE_URL; @@ -62,7 +61,10 @@ const profile = function ( token,userId = "" ) { * * @function * @name locationSearch - * @param {object} filterData - bodydata . + * @param {object} filterData - contain filter object. + * @param {String} pageSize - requested page size. + * @param {String} pageNo - requested page number. + * @param {String} searchKey - search string. * @returns {Promise} returns a promise. */ @@ -90,7 +92,7 @@ const locationSearch = function ( filterData, pageSize = "", pageNo = "", search userServiceUrl + constants.endpoints.GET_LOCATION_DATA; const options = { headers : { - "content-type": "application/json" + "content-type": "application/json", }, json : bodyData }; @@ -138,9 +140,10 @@ const locationSearch = function ( filterData, pageSize = "", pageNo = "", search * * @function * @name schoolData - * @param {String} bearerToken - autherization token. - * @param {object} bodyData - location id - * @param {array} fields - set of data keys need to be fetched. + * @param {object} filterData - contain filter object. + * @param {String} pageSize - requested page size. + * @param {String} pageNo - requested page number. + * @param {String} searchKey - search string. * @param {String} searchKey - search key for fuzzy search. * @returns {Promise} returns a promise. */ @@ -176,7 +179,7 @@ const locationSearch = function ( filterData, pageSize = "", pageNo = "", search userServiceUrl + constants.endpoints.GET_SCHOOL_DATA; const options = { headers : { - "content-type": "application/json" + "content-type": "application/json", }, json : bodyData }; diff --git a/module/entities/helper.js b/module/entities/helper.js index 45c359e9..2fd26591 100644 --- a/module/entities/helper.js +++ b/module/entities/helper.js @@ -4,7 +4,6 @@ const entityTypesHelper = require(MODULES_BASE_PATH + "/entityTypes/helper"); const userRolesHelper = require(MODULES_BASE_PATH + "/user-roles/helper"); // const elasticSearch = require(GENERIC_HELPERS_PATH + "/elastic-search"); const userService = require(ROOT_PATH + "/generics/services/users"); -let cache = require(ROOT_PATH+"/generics/helpers/cache"); const formService = require(ROOT_PATH + '/generics/services/form'); module.exports = class EntitiesHelper { @@ -242,7 +241,7 @@ module.exports = class EntitiesHelper { * @returns {Array} - List of all immediateEntities based on entityId. */ - static immediateEntities(entityId, searchText = "",pageSize="",pageNo="") { + static immediateEntities(entityId, searchText = "", pageSize = "", pageNo = "") { return new Promise(async (resolve, reject) => { try { @@ -250,18 +249,18 @@ module.exports = class EntitiesHelper { let bodyData = { "parentId" : entityId }; - + // When filter passed as parentId all immediate child or sub entities data is returned. let entitiesData = await userService.locationSearch( bodyData, pageSize, pageNo, searchText ); - + // No data found or API call failure if( !entitiesData.success ) { return resolve({ - data : entitiesData.data, - count : entitiesData.count + data : [], + count : 0 }); } let immediateLocation = entitiesData.data; @@ -278,7 +277,7 @@ module.exports = class EntitiesHelper { } /** - * Get immediate entities for requested Array. + * Get sub entities for requested Array. * @method * @name subList * @param {params} entities - array of entitity ids @@ -290,14 +289,14 @@ module.exports = class EntitiesHelper { * @returns {Array} - List of all sub list entities. */ - static subEntityList( entities,entityId,type,search,limit,pageNo ) { + static subEntityList( entities, entityId, type, search, limit, pageNo ) { return new Promise(async (resolve, reject) => { try { let result = {}; let subEntitiesResult = {}; - let uniqueEntities = []; + let listOfSubEntities = []; let obj = { entityId : entityId, type : type, @@ -321,22 +320,23 @@ module.exports = class EntitiesHelper { if ( subEntitiesResult && subEntitiesResult.data && subEntitiesResult.data.length > 0 ) { let formatedEntities = []; - uniqueEntities = subEntitiesResult.data - uniqueEntities.map( entityData => { - let data = {}; - data._id = entityData.id; - data.entityType = entityData.type; - data.name = entityData.name; - data.externalId = entityData.code; - data.label = entityData.name; - data.value = entityData.id + listOfSubEntities = subEntitiesResult.data + listOfSubEntities.map( entityData => { + let data = { + _id: entityData.id, + entityType: entityData.type, + name: entityData.name, + externalId: entityData.code, + label: entityData.name, + value: entityData.id + }; formatedEntities.push(data) } ); - uniqueEntities = []; - uniqueEntities = formatedEntities; + listOfSubEntities = []; + listOfSubEntities = formatedEntities; } - result.data = uniqueEntities; + result.data = listOfSubEntities; result.count = subEntitiesResult.count; resolve({ @@ -366,7 +366,7 @@ module.exports = class EntitiesHelper { let entitiesDocument; if( entitiesData.type !== "" ) { - + // If requested for a specific entity tye use entityTraversal entitiesDocument = await this.entityTraversal( entitiesData.entityId, entitiesData.type, @@ -375,6 +375,7 @@ module.exports = class EntitiesHelper { entitiesData.pageNo ); } else { + // Get immediate entities entitiesDocument = await this.immediateEntities( entitiesData.entityId, entitiesData.search, @@ -414,6 +415,7 @@ module.exports = class EntitiesHelper { "orgLocation.id" : entityId } let fields = ["externalId"] + // Get school location code using org search. let subentitiesCode = await userService.schoolData( filterData, pageSize, pageNo, searchText, fields ); if( !subentitiesCode.success || @@ -430,6 +432,7 @@ module.exports = class EntitiesHelper { let schoolDetails = subentitiesCode.data.response.content; //get code from all data let schoolCodes = []; + //some default field is also coming. So filtering externalId from result schoolDetails.map(schoolData=> { schoolCodes.push(schoolData.externalId); }); @@ -439,7 +442,7 @@ module.exports = class EntitiesHelper { "code" : schoolCodes }; - + // Get school data using location code fetched using org api call let entitiesData = await userService.locationSearch( bodyData ); if( !entitiesData.success ) { @@ -736,10 +739,11 @@ module.exports = class EntitiesHelper { let cacheData = await cache.getValue(entityKey); if( !cacheData ) { + let bodyData={ "id" : stateLocationId }; - + // Calling location search to fetch state code let entitiesData = await userService.locationSearch( bodyData ); if( !entitiesData.success ) { @@ -748,10 +752,9 @@ module.exports = class EntitiesHelper { result : [] }) } - + // form search using state location code let stateLocationCode = entitiesData.data[0].code; subEntities = await formService.formData( stateLocationCode, entityKey ); - if( !subEntities.length > 0 ) { return resolve({ message : constants.apiResponses.ENTITY_NOT_FOUND, @@ -759,36 +762,29 @@ module.exports = class EntitiesHelper { }) } } else { - subEntities = cacheData.result; + subEntities = cacheData; } - - let result = []; + let result = subEntities; + let targetedEntityType = ""; - if( rolesDocument[0].entityTypes[0].entityType === constants.common.STATE_ENTITY_TYPE ) { - result = subEntities; - result.unshift(constants.common.STATE_ENTITY_TYPE); - } else { - - let targetedEntityType = ""; + rolesDocument[0].entityTypes.forEach(singleEntityType => { + if( subEntities.includes(singleEntityType.entityType) ) { + targetedEntityType = singleEntityType.entityType; + } + }); - rolesDocument[0].entityTypes.forEach(singleEntityType => { - if( subEntities.includes(singleEntityType.entityType) ) { - targetedEntityType = singleEntityType.entityType; - } - }); - - let findTargetedEntityIndex = - subEntities.findIndex(element => element === targetedEntityType); - if( findTargetedEntityIndex < 0 ) { - throw { - message : constants.apiResponses.SUB_ENTITY_NOT_FOUND, - result : [] - } + let findTargetedEntityIndex = + subEntities.findIndex(element => element === targetedEntityType); + if( findTargetedEntityIndex < 0 ) { + throw { + message : constants.apiResponses.SUB_ENTITY_NOT_FOUND, + result : [] } - - result = subEntities.slice(findTargetedEntityIndex); } + + result = subEntities.slice(findTargetedEntityIndex); + return resolve({ success: true, diff --git a/module/programs/helper.js b/module/programs/helper.js index dc8d0aa0..7d93716d 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -207,20 +207,20 @@ module.exports = class ProgramsHelper { let scope = {}; if( scopeData.entityType ) { - + // Get entity details of type {scopeData.entityType} let bodyData = { "type" : scopeData.entityType } let entityTypeData = await userService.locationSearch( bodyData ); - if( !entityTypeData.success || !entityTypeData.data || !entityTypeData.data.response || !entityTypeData.data.response.length > 0 ) { + if( !entityTypeData.success ) { return resolve({ status : httpStatusCode.bad_request.status, message : constants.apiResponses.ENTITY_TYPES_NOT_FOUND }); } - scope["entityType"] = entityTypeData.data.response[0].type; + scope["entityType"] = entityTypeData.data[0].type; } @@ -245,13 +245,13 @@ module.exports = class ProgramsHelper { "id" : locationIds } let entityData = await userService.locationSearch( bodyData ); - if ( entityData.success && entityData.data && entityData.data.response && entityData.data.response.length > 0 ) { - entityData.data.response.forEach( entity => { + if ( entityData.success ) { + entityData.data.forEach( entity => { entityIds.push(entity.id) }); } } - + // if ( orgExternalId.length > 0 ) { let filterData = { "externalId" : orgExternalId @@ -724,7 +724,7 @@ module.exports = class ProgramsHelper { * @returns {JSON} - Added entities data. */ - static addEntitiesInScope( programId,entities ) { + static addEntitiesInScope( programId, entities ) { return new Promise(async (resolve, reject) => { try { let programData = @@ -758,8 +758,8 @@ module.exports = class ProgramsHelper { "id" : locationIds } let entityData = await userService.locationSearch( bodyData ); - if ( entityData.success && entityData.data && entityData.data.response && entityData.data.response.length > 0 ) { - entityData.data.response.forEach( entity => { + if ( entityData.success ) { + entityData.data.forEach( entity => { entityIds.push(entity.id) }); } diff --git a/module/users/helper.js b/module/users/helper.js index e11573b5..12a75a49 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -12,7 +12,6 @@ const userRolesHelper = require(MODULES_BASE_PATH + "/user-roles/helper"); const entitiesHelper = require(MODULES_BASE_PATH + "/entities/helper"); const improvementProjectService = require(ROOT_PATH + "/generics/services/improvement-project"); const userService = require(ROOT_PATH + "/generics/services/users"); -let cache = require(ROOT_PATH+"/generics/helpers/cache"); const formService = require(ROOT_PATH + '/generics/services/form'); @@ -384,7 +383,7 @@ module.exports = class UsersHelper { }) } } else { - subEntities = cacheData.result; + subEntities = cacheData; } @@ -768,16 +767,19 @@ module.exports = class UsersHelper { } let filterData ={}; if (solutionData[0].entityType === targetedEntityType) { - + // if solution entity type and user tageted entity type are same if (gen.utils.checkValidUUID(requestedData[targetedEntityType])) { filterData = { "parentId" : requestedData[targetedEntityType] } - } - let entitiesData = await userService.locationSearch( filterData ); - if( !entitiesData.success ){ + let entitiesData = await userService.locationSearch( filterData ); + if( entitiesData.success ){ + targetedEntityType = constants.common.STATE_ENTITY_TYPE; + } + } else if ( targetedEntityType === constants.common.SCHOOL ) { targetedEntityType = constants.common.STATE_ENTITY_TYPE; - } + } + } if (gen.utils.checkValidUUID(requestedData[targetedEntityType])) { @@ -855,7 +857,7 @@ module.exports = class UsersHelper { }) } } else { - subEntityTypes = cacheData.result; + subEntityTypes = cacheData; } let targetedIndex = subEntityTypes.length; let roleWiseTarget; From 8eada1154a3e353f5ab23674fde0aa681cf18d71 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 22 Aug 2022 14:58:45 +0530 Subject: [PATCH 149/331] default url added --- envVariables.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/envVariables.js b/envVariables.js index bff824ce..89fd9a12 100644 --- a/envVariables.js +++ b/envVariables.js @@ -132,7 +132,8 @@ let enviromentVariables = { }, "FORM_SERVICE_URL" : { "message" : "Form service base url", - "optional" : false + "optional" : false, + "default": "http://player:3000" } } From ef7f3c421cfe374ff1d8973e19380dcf332cd3c6 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 22 Aug 2022 15:07:13 +0530 Subject: [PATCH 150/331] comments added --- module/entities/helper.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/module/entities/helper.js b/module/entities/helper.js index 2fd26591..909fc9f7 100644 --- a/module/entities/helper.js +++ b/module/entities/helper.js @@ -304,12 +304,13 @@ module.exports = class EntitiesHelper { limit :limit, pageNo : pageNo } - + //entity id passed as query parameter if ( entityId !== "" ) { subEntitiesResult = await this.subEntities( obj ); } else { + // entityId is an Array of entities passed in request body obj["entityId"] = entities; subEntitiesResult = await this.subEntities( obj @@ -317,7 +318,7 @@ module.exports = class EntitiesHelper { } - + //formating sub entities data. if ( subEntitiesResult && subEntitiesResult.data && subEntitiesResult.data.length > 0 ) { let formatedEntities = []; listOfSubEntities = subEntitiesResult.data From 7a2cb86bed18cd965a9bb4838999b537b9ef0018 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 22 Aug 2022 15:38:28 +0530 Subject: [PATCH 151/331] change in function signature --- generics/services/users.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/generics/services/users.js b/generics/services/users.js index 5158ad7b..9e5c2e15 100644 --- a/generics/services/users.js +++ b/generics/services/users.js @@ -142,9 +142,10 @@ const locationSearch = function ( filterData, pageSize = "", pageNo = "", search * @name schoolData * @param {object} filterData - contain filter object. * @param {String} pageSize - requested page size. - * @param {String} pageNo - requested page number. - * @param {String} searchKey - search string. + * @param {String} pageNo - requested page number. + * @param {String} searchKey - search string. * @param {String} searchKey - search key for fuzzy search. + * @param {String} fields - required field filter. * @returns {Promise} returns a promise. */ const schoolData = function ( filterData, pageSize = "", pageNo = "", searchKey = "", fields = [] ) { From 51972de65ad4bb5454f0a65c43228bc6fe2017e7 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Tue, 23 Aug 2022 16:01:42 +0530 Subject: [PATCH 152/331] formData name change --- generics/services/form.js | 6 +++--- module/entities/helper.js | 30 +++++++++++++++--------------- module/users/helper.js | 4 ++-- 3 files changed, 20 insertions(+), 20 deletions(-) diff --git a/generics/services/form.js b/generics/services/form.js index 90eac246..324e16be 100644 --- a/generics/services/form.js +++ b/generics/services/form.js @@ -11,14 +11,14 @@ const formServiceUrl = process.env.FORM_SERVICE_URL; /** * @function - * @name formData + * @name configForStateLocation * @param {String} stateLocationCode - state location code. eg: 28 * @param {object} entityKey - key to store data in cache. eg: subEntityTypesOf_bc75cc99-9205-463e-a722-5326857838f8 * @returns {Promise} returns a promise. */ -const formData = function ( stateLocationCode, entityKey ) { +const configForStateLocation = function ( stateLocationCode, entityKey ) { return new Promise(async (resolve, reject) => { try { //Get Sub Entity Types present in a particular state @@ -107,5 +107,5 @@ async function formRead ( stateLocationCode ) { } module.exports = { - formData : formData + configForStateLocation : configForStateLocation } \ No newline at end of file diff --git a/module/entities/helper.js b/module/entities/helper.js index 909fc9f7..5b739a32 100644 --- a/module/entities/helper.js +++ b/module/entities/helper.js @@ -755,7 +755,7 @@ module.exports = class EntitiesHelper { } // form search using state location code let stateLocationCode = entitiesData.data[0].code; - subEntities = await formService.formData( stateLocationCode, entityKey ); + subEntities = await formService.configForStateLocation( stateLocationCode, entityKey ); if( !subEntities.length > 0 ) { return resolve({ message : constants.apiResponses.ENTITY_NOT_FOUND, @@ -889,40 +889,40 @@ module.exports = class EntitiesHelper { * @returns {Array} - Sub entities matching the type . */ -async function getSubEntitiesOfGivenType( parentIds, entityType, matchingData ) { +async function getSubEntitiesOfGivenType( entityIds, entityType, result ) { - if( !parentIds.length > 0 ) { - return matchingData; + if( !entityIds.length > 0 ) { + return result; }; let bodyData = { - "parentId" : parentIds + "parentId" : entityIds }; //get all immediate subEntities of type {entityType} - let entityDetails = await userService.locationSearch(bodyData); + let childEntities = await userService.locationSearch(bodyData); - if( ( !entityDetails.success ) && !matchingData.length > 0 ) { - return matchingData; + if( ( !childEntities.success ) && !result.length > 0 ) { + return result; } - let entityData = entityDetails.data; + let entityData = childEntities.data; - let mismatchEntities = []; + let parentEntities = []; entityData.map(entity => { if ( entity.type == entityType ) { - matchingData.push(entity) + result.push(entity) } else { - mismatchEntities.push(entity.id) + parentEntities.push(entity.id) } }); - if( mismatchEntities.length > 0 ){ - await getSubEntitiesOfGivenType(mismatchEntities, entityType, matchingData); + if( parentEntities.length > 0 ){ + await getSubEntitiesOfGivenType(parentEntities, entityType, result); } let uniqueEntities = []; - matchingData.map( data => { + result.map( data => { if (uniqueEntities.includes(data) === false) uniqueEntities.push(data); }); return uniqueEntities; diff --git a/module/users/helper.js b/module/users/helper.js index 12a75a49..790b8496 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -375,7 +375,7 @@ module.exports = class UsersHelper { let cacheData= await cache.getValue(entityKey); if( !cacheData ) { - subEntities = await formService.formData( stateCode,entityKey ); + subEntities = await formService.configForStateLocation( stateCode,entityKey ); if( !subEntities.length > 0 ) { return resolve({ message : constants.apiResponses.ENTITY_NOT_FOUND, @@ -849,7 +849,7 @@ module.exports = class UsersHelper { }) } let stateLocationCode = entitiesData.data[0].code; - subEntityTypes = await formService.formData( stateLocationCode,entityKey ); + subEntityTypes = await formService.configForStateLocation( stateLocationCode,entityKey ); if( !subEntityTypes.length > 0 ) { return resolve({ message : constants.apiResponses.ENTITY_NOT_FOUND, From 2b68ae8227f824cd24ab8d04f7b4048fa2432708 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Tue, 23 Aug 2022 17:00:42 +0530 Subject: [PATCH 153/331] getSubEntitiesOfGivenType change --- module/entities/helper.js | 24 +++++++----------------- 1 file changed, 7 insertions(+), 17 deletions(-) diff --git a/module/entities/helper.js b/module/entities/helper.js index 5b739a32..7f0d2a42 100644 --- a/module/entities/helper.js +++ b/module/entities/helper.js @@ -905,25 +905,15 @@ async function getSubEntitiesOfGivenType( entityIds, entityType, result ) { return result; } - let entityData = childEntities.data; - let parentEntities = []; - entityData.map(entity => { - - if ( entity.type == entityType ) { - result.push(entity) - - } else { - parentEntities.push(entity.id) - } - }); - + if( childEntities.data[0].type == entityType ) { + result = childEntities.data; + } else { + parentEntities = childEntities.data; + } + if( parentEntities.length > 0 ){ await getSubEntitiesOfGivenType(parentEntities, entityType, result); } - let uniqueEntities = []; - result.map( data => { - if (uniqueEntities.includes(data) === false) uniqueEntities.push(data); - }); - return uniqueEntities; + return result; } \ No newline at end of file From 19d3d8633b332f131c35ac6d964c14548bd4c8f6 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Wed, 24 Aug 2022 18:27:42 +0530 Subject: [PATCH 154/331] review changes aug24 --- envVariables.js | 2 +- generics/helpers/utils.js | 26 ++++++++++++- generics/services/users.js | 18 +++++---- module/entities/helper.js | 14 +++---- module/programs/helper.js | 49 ++++++++---------------- module/solutions/helper.js | 77 +++++++++++++------------------------- module/users/helper.js | 32 ++++++---------- 7 files changed, 94 insertions(+), 124 deletions(-) diff --git a/envVariables.js b/envVariables.js index 89fd9a12..06e845c8 100644 --- a/envVariables.js +++ b/envVariables.js @@ -132,7 +132,7 @@ let enviromentVariables = { }, "FORM_SERVICE_URL" : { "message" : "Form service base url", - "optional" : false, + "optional" : true, "default": "http://player:3000" } } diff --git a/generics/helpers/utils.js b/generics/helpers/utils.js index 53d27c1d..52b8b06b 100644 --- a/generics/helpers/utils.js +++ b/generics/helpers/utils.js @@ -235,6 +235,29 @@ function md5Hash(value) { return md5(value); } +/** + * filter out location id and code + * @function + * @name filterLocationIdandCode + * @returns {Object} - Object contain locationid and location code array. +*/ + +function filterLocationIdandCode(dataArray) { + let locationIds = []; + let locationCodes = []; + dataArray.forEach(element=>{ + if (this.checkValidUUID(element)) { + locationIds.push(element); + } else { + locationCodes.push(element); + } + }); + return ({ + ids : locationIds, + codes : locationCodes + }); +} + module.exports = { camelCaseToTitleCase : camelCaseToTitleCase, lowerCase : lowerCase, @@ -249,5 +272,6 @@ module.exports = { valueParser : valueParser, checkValidUUID : checkValidUUID, convertStringToBoolean : convertStringToBoolean, - md5Hash : md5Hash + md5Hash : md5Hash, + filterLocationIdandCode : filterLocationIdandCode }; diff --git a/generics/services/users.js b/generics/services/users.js index 9e5c2e15..c00614f5 100644 --- a/generics/services/users.js +++ b/generics/services/users.js @@ -139,7 +139,7 @@ const locationSearch = function ( filterData, pageSize = "", pageNo = "", search /** * * @function - * @name schoolData + * @name orgSchoolSearch * @param {object} filterData - contain filter object. * @param {String} pageSize - requested page size. * @param {String} pageNo - requested page number. @@ -148,7 +148,7 @@ const locationSearch = function ( filterData, pageSize = "", pageNo = "", search * @param {String} fields - required field filter. * @returns {Promise} returns a promise. */ - const schoolData = function ( filterData, pageSize = "", pageNo = "", searchKey = "", fields = [] ) { + const orgSchoolSearch = function ( filterData, pageSize = "", pageNo = "", searchKey = "", fields = [] ) { return new Promise(async (resolve, reject) => { try { @@ -195,11 +195,15 @@ const locationSearch = function ( filterData, pageSize = "", pageNo = "", search if (err) { result.success = false; } else { - let response = data.body; - - if( response.responseCode === constants.common.OK) { - result["data"] = response.result; + if( response.responseCode === constants.common.OK && + response.result && + response.result.response && + response.result.response.content && + response.result.response.content.length > 0 + ){ + result["data"] = response.result.response.content; + result["count"] = response.result.response.count; } else { result.success = false; } @@ -221,5 +225,5 @@ const locationSearch = function ( filterData, pageSize = "", pageNo = "", search module.exports = { profile : profile, locationSearch : locationSearch, - schoolData :schoolData + orgSchoolSearch :orgSchoolSearch } diff --git a/module/entities/helper.js b/module/entities/helper.js index 7f0d2a42..981c96f8 100644 --- a/module/entities/helper.js +++ b/module/entities/helper.js @@ -417,20 +417,16 @@ module.exports = class EntitiesHelper { } let fields = ["externalId"] // Get school location code using org search. - let subentitiesCode = await userService.schoolData( filterData, pageSize, pageNo, searchText, fields ); + let subentitiesCode = await userService.orgSchoolSearch( filterData, pageSize, pageNo, searchText, fields ); - if( !subentitiesCode.success || - !subentitiesCode.data || - !subentitiesCode.data.response || - !subentitiesCode.data.response.content || - !subentitiesCode.data.response.content.length > 0 ) { + if( !subentitiesCode.success ) { return resolve({ data : [], - count : subentitiesCode.data.response.count + count : subentitiesCode.count }) } - let schoolDetails = subentitiesCode.data.response.content; + let schoolDetails = subentitiesCode.data; //get code from all data let schoolCodes = []; //some default field is also coming. So filtering externalId from result @@ -455,7 +451,7 @@ module.exports = class EntitiesHelper { return resolve({ data : entitiesData.data, - count : subentitiesCode.data.response.count + count : subentitiesCode.count }) diff --git a/module/programs/helper.js b/module/programs/helper.js index 7d93716d..a0800f28 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -227,22 +227,14 @@ module.exports = class ProgramsHelper { if( scopeData.entities && scopeData.entities.length > 0 ) { //call learners api for search - let locationIds = []; - let orgExternalId = []; let entityIds = []; let bodyData={}; + let locationData = gen.utils.filterLocationIdandCode(scopeData.entities) - scopeData.entities.forEach(entity=>{ - if (gen.utils.checkValidUUID(entity)) { - locationIds.push(entity); - } else { - orgExternalId.push(entity); - } - }); //locationIds contain id of location data. - if ( locationIds.length > 0 ) { + if ( locationData.ids.length > 0 ) { bodyData = { - "id" : locationIds + "id" : locationData.ids } let entityData = await userService.locationSearch( bodyData ); if ( entityData.success ) { @@ -252,14 +244,14 @@ module.exports = class ProgramsHelper { } } // - if ( orgExternalId.length > 0 ) { + if ( locationData.codes.length > 0 ) { let filterData = { - "externalId" : orgExternalId + "externalId" : locationData.codes } - let schoolDetails = await userService.schoolData( filterData ); + let schoolDetails = await userService.orgSchoolSearch( filterData ); - if ( schoolDetails.success && schoolDetails.data && schoolDetails.data.response && schoolDetails.data.response.content && schoolDetails.data.response.content.length > 0 ) { - let schoolData = schoolDetails.data.response.content; + if ( schoolDetails.success ) { + let schoolData = schoolDetails.data; schoolData.forEach( entity => { entityIds.push(entity.externalId) }); @@ -740,22 +732,13 @@ module.exports = class ProgramsHelper { }; } - let locationIds = []; - let orgExternalId = []; let entityIds = []; let bodyData={}; + let locationData = gen.utils.filterLocationIdandCode(entities) - entities.forEach(entity=>{ - if (gen.utils.checkValidUUID(entity)) { - locationIds.push(entity); - } else { - orgExternalId.push(entity); - } - }); - - if ( locationIds.length > 0 ) { + if ( locationData.ids.length > 0 ) { bodyData = { - "id" : locationIds + "id" : locationData.ids } let entityData = await userService.locationSearch( bodyData ); if ( entityData.success ) { @@ -765,14 +748,14 @@ module.exports = class ProgramsHelper { } } - if ( orgExternalId.length > 0 ) { + if ( locationData.codes.length > 0 ) { let filterData = { - "externalId" : orgExternalId + "externalId" : locationData.codes } - let schoolDetails = await userService.schoolData( filterData ); + let schoolDetails = await userService.orgSchoolSearch( filterData ); - if ( schoolDetails.success && schoolDetails.data && schoolDetails.data.response && schoolDetails.data.response.content && schoolDetails.data.response.content.length > 0 ) { - let schoolData = schoolDetails.data.response.content; + if ( schoolDetails.success ) { + let schoolData = schoolDetails.data; schoolData.forEach( entity => { entityIds.push(entity.externalId) }); diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 53ceb6bf..d0e0f60a 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -130,21 +130,12 @@ module.exports = class SolutionsHelper { } if( solutionData.entities && solutionData.entities.length > 0 ) { - let locationIds = []; - let orgExternalId = []; let entityIds = []; - - solutionData.entities.forEach(entity=>{ - if (gen.utils.checkValidUUID(entity)) { - locationIds.push(entity); - } else { - orgExternalId.push(entity); - } - }); - - if ( locationIds.length > 0 ) { + let locationData = gen.utils.filterLocationIdandCode(solutionData.entities) + + if ( locationData.ids.length > 0 ) { let bodyData = { - "id" : locationIds + "id" : locationData.ids } let entityData = await userService.locationSearch( bodyData ); if ( entityData.success ) { @@ -154,14 +145,14 @@ module.exports = class SolutionsHelper { } } - if ( orgExternalId.length > 0 ) { + if ( locationData.codes.length > 0 ) { let filterData = { - "externalId" : orgExternalId + "externalId" : locationData.codes } - let schoolDetails = await userService.schoolData( filterData ); + let schoolDetails = await userService.orgSchoolSearch( filterData ); - if ( schoolDetails.success && schoolDetails.data && schoolDetails.data.response && schoolDetails.data.response.content && schoolDetails.data.response.content.length > 0 ) { - let schoolData = schoolDetails.data.response.content; + if ( schoolDetails.success ) { + let schoolData = schoolDetails.data; schoolData.forEach( entity => { entityIds.push(entity.externalId) }); @@ -280,22 +271,13 @@ module.exports = class SolutionsHelper { if( scopeData.entities && scopeData.entities.length > 0 ) { //call learners api for search - let locationIds = []; - let orgExternalId = []; let entityIds = []; let bodyData={}; + let locationData = gen.utils.filterLocationIdandCode(sscopeData.entities) - scopeData.entities.forEach(entity=>{ - if (gen.utils.checkValidUUID(entity)) { - locationIds.push(entity); - } else { - orgExternalId.push(entity); - } - }); - - if ( locationIds.length > 0 ) { + if ( locationData.ids.length > 0 ) { bodyData = { - "id" : locationIds + "id" : locationData.ids } let entityData = await userService.locationSearch( bodyData ); if ( entityData.success ) { @@ -307,14 +289,14 @@ module.exports = class SolutionsHelper { } } - if ( orgExternalId.length > 0 && currentSolutionScope.entityType == constants.common.SCHOOL ) { + if ( locationData.codes.length > 0 && currentSolutionScope.entityType == constants.common.SCHOOL ) { let filterData = { - "externalId" : orgExternalId + "externalId" : locationData.codes } - let schoolDetails = await userService.schoolData( filterData ); + let schoolDetails = await userService.orgSchoolSearch( filterData ); - if ( schoolDetails.success && schoolDetails.data && schoolDetails.data.response && schoolDetails.data.response.content && schoolDetails.data.response.content.length > 0 ) { - let schoolData = schoolDetails.data.response.content; + if ( schoolDetails.success ) { + let schoolData = schoolDetails.data; schoolData.forEach( entity => { entityIds.push(entity.externalId) }); @@ -1054,22 +1036,13 @@ module.exports = class SolutionsHelper { } } } - let locationIds = []; - let orgExternalId = []; let entityIds = []; let bodyData={}; + let locationData = gen.utils.filterLocationIdandCode(entities) - entities.forEach(entity=>{ - if (gen.utils.checkValidUUID(entity)) { - locationIds.push(entity); - } else { - orgExternalId.push(entity); - } - }); - - if ( locationIds.length > 0 ) { + if ( locationData.ids.length > 0 ) { bodyData = { - "id" : locationIds + "id" : locationData.ids } let entityData = await userService.locationSearch( bodyData ); if ( entityData.success ) { @@ -1079,14 +1052,14 @@ module.exports = class SolutionsHelper { } } - if ( orgExternalId.length > 0 ) { + if ( locationData.codes.length > 0 ) { let filterData = { - "externalId" : orgExternalId + "externalId" : locationData.codes } - let schoolDetails = await userService.schoolData( filterData ); + let schoolDetails = await userService.orgSchoolSearch( filterData ); - if ( schoolDetails.success && schoolDetails.data && schoolDetails.data.response && schoolDetails.data.response.content && schoolDetails.data.response.content.length > 0 ) { - let schoolData = schoolDetails.data.response.content; + if ( schoolDetails.success ) { + let schoolData = schoolDetails.data; schoolData.forEach( entity => { entityIds.push(entity.externalId) }); diff --git a/module/users/helper.js b/module/users/helper.js index 790b8496..e43c4506 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -154,26 +154,16 @@ module.exports = class UsersHelper { data.entities && data.entities.length > 0 ) { - - - let locationIds = []; - let orgExternalId = []; + let entitiesData = []; let bodyData = {}; - - data.entities.forEach( entity => { - if ( gen.utils.checkValidUUID(entity) ) { - locationIds.push(entity); - } else { - orgExternalId.push(entity) - } - }); - - if ( locationIds.length > 0 ) { + let locationData = gen.utils.filterLocationIdandCode(data.entities) + + if ( locationData.ids.length > 0 ) { bodyData = { - "id" : locationIds + "id" : locationData.ids } let entityData = await userService.locationSearch( bodyData ); @@ -193,12 +183,12 @@ module.exports = class UsersHelper { } - if ( orgExternalId.length > 0 ) { + if ( locationData.codes.length > 0 ) { let filterData = { - "externalId" : orgExternalId + "externalId" : locationData.codes } - let schoolDetails = await userService.schoolData( filterData ); - let schoolDocuments = schoolDetails.data.response.content; + let schoolDetails = await userService.orgSchoolSearch( filterData ); + let schoolDocuments = schoolDetails.data; if ( !schoolDetails.success || !schoolDocuments.length > 0 ) { return resolve({ status: httpStatusCode["bad_request"].status, @@ -206,8 +196,8 @@ module.exports = class UsersHelper { result: {} }); } - let schoolData = schoolDetails.data.response.content; - schoolData.forEach( entity => { + + schoolDocuments.forEach( entity => { entitiesData.push(entity.externalId) }); From 77d7ebb7e9d91fceaeea74956b580c5ca6ead3c4 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 25 Aug 2022 10:40:16 +0530 Subject: [PATCH 155/331] review change --- generics/services/users.js | 45 +++++++++++++++++++++++++++++++++++--- 1 file changed, 42 insertions(+), 3 deletions(-) diff --git a/generics/services/users.js b/generics/services/users.js index c00614f5..cd0124ca 100644 --- a/generics/services/users.js +++ b/generics/services/users.js @@ -65,10 +65,13 @@ const profile = function ( token,userId = "" ) { * @param {String} pageSize - requested page size. * @param {String} pageNo - requested page number. * @param {String} searchKey - search string. + * @param {Boolean} formatResult - format result + * @param {Boolean} returnObject - return object or array. + * @param {Boolean} resultForSearchEntities - format result for searchEntities api call. * @returns {Promise} returns a promise. */ -const locationSearch = function ( filterData, pageSize = "", pageNo = "", searchKey = "" ) { +const locationSearch = function ( filterData, pageSize = "", pageNo = "", searchKey = "" , formatResult = false, returnObject = false, resultForSearchEntities = false ) { return new Promise(async (resolve, reject) => { try { let bodyData = {}; @@ -107,13 +110,49 @@ const locationSearch = function ( filterData, pageSize = "", pageNo = "", search result.success = false; } else { let response = data.body; + if( response.responseCode === constants.common.OK && response.result && response.result.response && response.result.response.length > 0 ) { - result["data"] = response.result.response; - result["count"] = response.result.count; + // format result if true + if ( formatResult ) { + let entityDocument = []; + response.result.response.map(entityData => { + let data = {}; + data._id = entityData.id; + data.entityType = entityData.type; + data.metaInformation = {}; + data.metaInformation.name = entityData.name; + data.metaInformation.externalId = entityData.code; + data.registryDetails = {}; + data.registryDetails.locationId = entityData.id; + data.registryDetails.code = entityData.code; + entityDocument.push(data); + }); + if ( returnObject ) { + result["data"] = entityDocument[0]; + result["count"] = response.result.count; + } else { + result["data"] = entityDocument; + result["count"] = response.result.count; + } + } else if ( resultForSearchEntities ) { + let entityDocument = []; + response.result.response.map(entityData => { + let data = {}; + data._id = entityData.id; + data.name = entityData.name; + data.externalId = entityData.code; + entityDocument.push(data); + }); + result["data"] = entityDocument; + result["count"] = response.result.count; + }else { + result["data"] = response.result.response; + result["count"] = response.result.count; + } } else { result.success = false; } From e66d7033f11c5737d61d993a43efb597e92adaf3 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 25 Aug 2022 11:07:07 +0530 Subject: [PATCH 156/331] users.js change --- generics/services/users.js | 41 ++++++++++++++++++++++++++++++++++++- module/entities/helper.js | 42 ++------------------------------------ module/solutions/helper.js | 4 ++-- 3 files changed, 44 insertions(+), 43 deletions(-) diff --git a/generics/services/users.js b/generics/services/users.js index cd0124ca..d54517b0 100644 --- a/generics/services/users.js +++ b/generics/services/users.js @@ -260,9 +260,48 @@ const locationSearch = function ( filterData, pageSize = "", pageNo = "", search } }) } + +/** + * get subEntities of matching type by recursion. + * @method + * @name getSubEntitiesBasedOnEntityType + * @param parentIds {Array} - Array of entity Ids- for which we are finding sub entities of given entityType + * @param entityType {string} - EntityType. + * @returns {Array} - Sub entities matching the type . +*/ + +async function getSubEntitiesBasedOnEntityType( entityIds, entityType, result ) { + + if( !entityIds.length > 0 ) { + return result; + }; + + let bodyData = { + "parentId" : entityIds + }; + //get all immediate subEntities of type {entityType} + let childEntities = await locationSearch(bodyData); + + if( ( !childEntities.success ) && !result.length > 0 ) { + return result; + } + + let parentEntities = []; + if( childEntities.data[0].type == entityType ) { + result = childEntities.data; + } else { + parentEntities = childEntities.data; + } + + if( parentEntities.length > 0 ){ + await getSubEntitiesBasedOnEntityType(parentEntities, entityType, result); + } + return result; +} module.exports = { profile : profile, locationSearch : locationSearch, - orgSchoolSearch :orgSchoolSearch + orgSchoolSearch :orgSchoolSearch, + getSubEntitiesBasedOnEntityType : getSubEntitiesBasedOnEntityType } diff --git a/module/entities/helper.js b/module/entities/helper.js index 981c96f8..400f10b0 100644 --- a/module/entities/helper.js +++ b/module/entities/helper.js @@ -456,10 +456,10 @@ module.exports = class EntitiesHelper { } else { - /* if {entityId} is of a state and {entityTraversalType} is block , getSubEntitiesOfGivenType will return all entities of type block in that state*/ + /* if {entityId} is of a state and {entityTraversalType} is block , getSubEntitiesBasedOnEntityType will return all entities of type block in that state*/ let subEntitiesArray = []; - let subEntities = await getSubEntitiesOfGivenType( entityId, entityTraversalType, subEntitiesArray ) + let subEntities = await userService.getSubEntitiesBasedOnEntityType( entityId, entityTraversalType, subEntitiesArray ) if( !subEntities.length > 0 ) { return resolve({ @@ -875,41 +875,3 @@ module.exports = class EntitiesHelper { } } - -/** - * get subEntities of matching type by recursion. - * @method - * @name getSubEntitiesOfGivenType - * @param parentIds {Array} - Array of entity Ids- for which we are finding sub entities of given entityType - * @param entityType {string} - EntityType. - * @returns {Array} - Sub entities matching the type . -*/ - -async function getSubEntitiesOfGivenType( entityIds, entityType, result ) { - - if( !entityIds.length > 0 ) { - return result; - }; - - let bodyData = { - "parentId" : entityIds - }; - //get all immediate subEntities of type {entityType} - let childEntities = await userService.locationSearch(bodyData); - - if( ( !childEntities.success ) && !result.length > 0 ) { - return result; - } - - let parentEntities = []; - if( childEntities.data[0].type == entityType ) { - result = childEntities.data; - } else { - parentEntities = childEntities.data; - } - - if( parentEntities.length > 0 ){ - await getSubEntitiesOfGivenType(parentEntities, entityType, result); - } - return result; -} \ No newline at end of file diff --git a/module/solutions/helper.js b/module/solutions/helper.js index d0e0f60a..72d53b60 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -316,7 +316,7 @@ module.exports = class SolutionsHelper { let matchData = []; let childEntities = []; - let childEntitiesDetails = await entitiesHelper.getSubEntitiesOfGivenType(currentSolutionScope.entities, currentSolutionScope.entityType, matchData); + let childEntitiesDetails = await userService.getSubEntitiesBasedOnEntityType(currentSolutionScope.entities, currentSolutionScope.entityType, matchData); childEntitiesDetails.forEach( entity => { childEntities.push(entity.id) @@ -1009,7 +1009,7 @@ module.exports = class SolutionsHelper { let matchData = []; let childEntities = []; let checkEntityInParent = []; - let childEntitiesDetails = await entitiesHelper.getSubEntitiesOfGivenType(programData[0].scope.entities, solutionData[0].scope.entityType, matchData); + let childEntitiesDetails = await userService.getSubEntitiesBasedOnEntityType(programData[0].scope.entities, solutionData[0].scope.entityType, matchData); childEntitiesDetails.forEach( entity => { childEntities.push(entity.id); From 181d7dfe633f34105a3b9e83a99c27ae245ad7f7 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 25 Aug 2022 11:52:43 +0530 Subject: [PATCH 157/331] removed serch code --- module/entities/helper.js | 33 +++++++++++++-------------------- 1 file changed, 13 insertions(+), 20 deletions(-) diff --git a/module/entities/helper.js b/module/entities/helper.js index 400f10b0..95ccee2f 100644 --- a/module/entities/helper.js +++ b/module/entities/helper.js @@ -467,28 +467,21 @@ module.exports = class EntitiesHelper { count : 0 }) } - //searching here because search with traversal will affect result. - let subentitiesData = subEntities - let count = subentitiesData.length; - if( searchText !== "" ){ - let matchEntities = []; - subentitiesData.map( entityData => { - if( entityData.name.match(new RegExp(searchText, 'i')) || entityData.code.match(new RegExp("^" + searchText, 'm')) ) { - matchEntities.push(entityData) - } - }); - subentitiesData = []; - subentitiesData = matchEntities; - } - - if (subentitiesData.length > 0) { - let startIndex = pageSize * (pageNo - 1); - let endIndex = startIndex + pageSize; - subentitiesData = subentitiesData.slice(startIndex, endIndex); + // call locationSearch with search and pagination + let subEntityIds = subEntities.map(function (entity) { return entity.id; }); + let filter = { + "id" : subEntityIds } + let subentitiesData = await userService.locationSearch( + filter, + pageSize, + pageNo, + searchText + ); + return resolve({ - data : subentitiesData, - count : count + data : subentitiesData.data, + count : subentitiesData.count }) } From 5e2f6d8cea1f53f5903c37f28ff199b3d67ccc33 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 25 Aug 2022 17:41:12 +0530 Subject: [PATCH 158/331] user aggrigation change --- generics/services/users.js | 43 +++++++++++++++++++------------------- 1 file changed, 21 insertions(+), 22 deletions(-) diff --git a/generics/services/users.js b/generics/services/users.js index d54517b0..fface554 100644 --- a/generics/services/users.js +++ b/generics/services/users.js @@ -74,29 +74,29 @@ const profile = function ( token,userId = "" ) { const locationSearch = function ( filterData, pageSize = "", pageNo = "", searchKey = "" , formatResult = false, returnObject = false, resultForSearchEntities = false ) { return new Promise(async (resolve, reject) => { try { - let bodyData = {}; - bodyData["request"] = {}; - bodyData["request"]["filters"] = filterData; - - if ( pageSize !== "" ) { - bodyData["request"]["limit"] = pageSize; - } - - if ( pageNo !== "" ) { - let offsetValue = pageSize * ( pageNo - 1 ); - bodyData["request"]["offset"] = offsetValue; - } - - if ( searchKey !== "" ) { - bodyData["request"]["query"] = searchKey - } - + let bodyData = {}; + bodyData["request"] = {}; + bodyData["request"]["filters"] = filterData; + + if ( pageSize !== "" ) { + bodyData["request"]["limit"] = pageSize; + } + + if ( pageNo !== "" ) { + let offsetValue = pageSize * ( pageNo - 1 ); + bodyData["request"]["offset"] = offsetValue; + } + + if ( searchKey !== "" ) { + bodyData["request"]["query"] = searchKey + } + const url = userServiceUrl + constants.endpoints.GET_LOCATION_DATA; const options = { headers : { - "content-type": "application/json", - }, + "content-type": "application/json" + }, json : bodyData }; request.post(url,options,requestCallback); @@ -219,7 +219,7 @@ const locationSearch = function ( filterData, pageSize = "", pageNo = "", search userServiceUrl + constants.endpoints.GET_SCHOOL_DATA; const options = { headers : { - "content-type": "application/json", + "content-type": "application/json" }, json : bodyData }; @@ -285,12 +285,11 @@ async function getSubEntitiesBasedOnEntityType( entityIds, entityType, result ) if( ( !childEntities.success ) && !result.length > 0 ) { return result; } - let parentEntities = []; if( childEntities.data[0].type == entityType ) { result = childEntities.data; } else { - parentEntities = childEntities.data; + parentEntities = childEntities.map(function (entity) { return entity.id; }); } if( parentEntities.length > 0 ){ From 75bcffd6fbcf68903448aa9467443a6696ca4d75 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 25 Aug 2022 18:44:58 +0530 Subject: [PATCH 159/331] review change program helper --- module/programs/helper.js | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/module/programs/helper.js b/module/programs/helper.js index a0800f28..3f823ea2 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -724,7 +724,7 @@ module.exports = class ProgramsHelper { _id : programId, scope : { $exists : true }, isAPrivateProgram : false - },["_id"]); + },["_id","scope.entityType"]); if( !programData.length > 0 ) { throw { @@ -738,7 +738,8 @@ module.exports = class ProgramsHelper { if ( locationData.ids.length > 0 ) { bodyData = { - "id" : locationData.ids + "id" : locationData.ids, + "type": programData[0].scope.entityType } let entityData = await userService.locationSearch( bodyData ); if ( entityData.success ) { @@ -750,7 +751,8 @@ module.exports = class ProgramsHelper { if ( locationData.codes.length > 0 ) { let filterData = { - "externalId" : locationData.codes + "externalId" : locationData.codes, + "type": programData[0].scope.entityType } let schoolDetails = await userService.orgSchoolSearch( filterData ); From f31af94e7bfd90b89552fa61f3f404cdb48bd1a7 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 25 Aug 2022 18:52:33 +0530 Subject: [PATCH 160/331] variable name change --- module/solutions/helper.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 72d53b60..a986e24c 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -263,7 +263,7 @@ module.exports = class SolutionsHelper { if( Object.keys(scopeData).length > 0 ) { if( scopeData.entityType ) { let bodyData = { "type" : scopeData.entityType } - let entityTypeData = await userService.locationSearch( bodyData, 1 ); + let entityTypeData = await userService.locationSearch( bodyData); if ( entityTypeData.success ) { currentSolutionScope.entityType = entityTypeData.data[0].type } @@ -273,7 +273,7 @@ module.exports = class SolutionsHelper { //call learners api for search let entityIds = []; let bodyData={}; - let locationData = gen.utils.filterLocationIdandCode(sscopeData.entities) + let locationData = gen.utils.filterLocationIdandCode(scopeData.entities) if ( locationData.ids.length > 0 ) { bodyData = { From 9e83b5348c71aea22710ad2d4a1bd6a380bc9fb1 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 26 Aug 2022 12:16:10 +0530 Subject: [PATCH 161/331] solution/create api --- models/solutions.js | 1 - module/solutions/helper.js | 58 +++++++++++--------------------------- 2 files changed, 17 insertions(+), 42 deletions(-) diff --git a/models/solutions.js b/models/solutions.js index 6ba182a1..5affdfb6 100644 --- a/models/solutions.js +++ b/models/solutions.js @@ -68,7 +68,6 @@ module.exports = { referenceFrom : String, scope : { entityType : String, - entityTypeId : "ObjectId", entities : { type : Array, index : true diff --git a/module/solutions/helper.js b/module/solutions/helper.js index a986e24c..32f80229 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -166,7 +166,6 @@ module.exports = class SolutionsHelper { } solutionData.entities = entityIds; - } if( solutionData.minNoOfSubmissionsRequired && @@ -197,7 +196,7 @@ module.exports = class SolutionsHelper { }, { $addToSet: { components : solutionCreation._id } }); - + if( !solutionData.excludeScope && programData[0].scope ) { let solutionScope = await this.setScope( @@ -255,7 +254,6 @@ module.exports = class SolutionsHelper { message : constants.apiResponses.SOLUTION_NOT_FOUND }); } - if( programData[0].scope ) { let currentSolutionScope = JSON.parse(JSON.stringify(programData[0].scope)); @@ -277,28 +275,27 @@ module.exports = class SolutionsHelper { if ( locationData.ids.length > 0 ) { bodyData = { - "id" : locationData.ids + "id" : locationData.ids, + "type" : currentSolutionScope.entityType } let entityData = await userService.locationSearch( bodyData ); if ( entityData.success ) { entityData.data.forEach( entity => { - if( entity.type == currentSolutionScope.entityType ) { - entityIds.push(entity.id) - } + entityIds.push(entity.id) }); } } - if ( locationData.codes.length > 0 && currentSolutionScope.entityType == constants.common.SCHOOL ) { + if ( locationData.codes.length > 0 ) { let filterData = { - "externalId" : locationData.codes + "code" : locationData.codes, + "type" : currentSolutionScope.entityType } - let schoolDetails = await userService.orgSchoolSearch( filterData ); + let entityDetails = await userService.locationSearch( filterData ); - if ( schoolDetails.success ) { - let schoolData = schoolDetails.data; - schoolData.forEach( entity => { - entityIds.push(entity.externalId) + if ( entityDetails.success ) { + entityDetails.data.forEach( entity => { + entityIds.push(entity.id) }); } } @@ -309,30 +306,15 @@ module.exports = class SolutionsHelper { message : constants.apiResponses.ENTITIES_NOT_FOUND }); } - + let entitiesData = []; - + if( currentSolutionScope.entityType !== programData[0].scope.entityType ) { - - let matchData = []; - let childEntities = []; - let childEntitiesDetails = await userService.getSubEntitiesBasedOnEntityType(currentSolutionScope.entities, currentSolutionScope.entityType, matchData); - - childEntitiesDetails.forEach( entity => { - childEntities.push(entity.id) - }); - + let result = []; + let childEntities = await userService.getSubEntitiesBasedOnEntityType(currentSolutionScope.entities, currentSolutionScope.entityType, result); if( childEntities.length > 0 ) { - for( let entitiesIndex = 0; entitiesIndex < entityIds.length; entitiesIndex++ ) { - for( let childListIndex = 0; childListIndex < childEntities.length; childListIndex++ ) { - if( childEntities[childListIndex] == entityIds[entitiesIndex]){ - entitiesData.push(entityIds[entitiesIndex]); - entitiesIndex++; - } - } - } + entitiesData = entityIds.filter(element => childEntities.includes(element)); } - } else { entitiesData = entityIds } @@ -1007,14 +989,9 @@ module.exports = class SolutionsHelper { if( solutionData[0].scope.entityType !== programData[0].scope.entityType ) { let matchData = []; - let childEntities = []; let checkEntityInParent = []; - let childEntitiesDetails = await userService.getSubEntitiesBasedOnEntityType(programData[0].scope.entities, solutionData[0].scope.entityType, matchData); + let childEntities = await userService.getSubEntitiesBasedOnEntityType(programData[0].scope.entities, solutionData[0].scope.entityType, matchData); - childEntitiesDetails.forEach( entity => { - childEntities.push(entity.id); - }); - if( !childEntities.length > 0 ) { throw { message : constants.apiResponses.ENTITY_NOT_EXISTS_IN_PARENT @@ -1318,7 +1295,6 @@ module.exports = class SolutionsHelper { let totalCount = 0; let mergedData = []; let solutionIds = []; - if( assignedSolutions.success && assignedSolutions.data ) { // Remove observation solutions which for project tasks. From b09917c1a8a1105828ddf823c4135940ce0176fa Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 26 Aug 2022 13:52:59 +0530 Subject: [PATCH 162/331] subEntities api --- module/entities/helper.js | 114 +++++++++++++++++++------------------- 1 file changed, 56 insertions(+), 58 deletions(-) diff --git a/module/entities/helper.js b/module/entities/helper.js index 95ccee2f..2be4fd78 100644 --- a/module/entities/helper.js +++ b/module/entities/helper.js @@ -21,66 +21,65 @@ module.exports = class EntitiesHelper { * @returns {Array} - returns an array of entities data. */ - static entityDocuments( - findQuery = "all", - fields = "all", - skipFields = "none", - limitingValue = "", - skippingValue = "", - sortedData = "" - ) { - return new Promise(async (resolve, reject) => { - try { - - let queryObject = {}; - - if (findQuery != "all") { - queryObject = findQuery; - if( queryObject._id && typeof queryObject._id != "object" && !gen.utils.isValidMongoId(queryObject._id.toString()) ) { - queryObject["registryDetails.locationId"] = queryObject._id; - delete queryObject._id + static entityDocuments( + findQuery = "all", + fields = "all", + skipFields = "none", + limitingValue = "", + skippingValue = "", + sortedData = "" + ) { + return new Promise(async (resolve, reject) => { + try { + + let queryObject = {}; + + if (findQuery != "all") { + queryObject = findQuery; + if( queryObject._id && typeof queryObject._id != "object" && !gen.utils.isValidMongoId(queryObject._id.toString()) ) { + queryObject["registryDetails.locationId"] = queryObject._id; + delete queryObject._id + } } - } - - let projectionObject = {}; - - if (fields != "all") { - fields.forEach(element => { - projectionObject[element] = 1; - }); - } - - if (skipFields != "none") { - skipFields.forEach(element => { - projectionObject[element] = 0; - }); - } - - let entitiesDocuments; - - if( sortedData !== "" ) { + let projectionObject = {}; - entitiesDocuments = await database.models.entities - .find(queryObject, projectionObject) - .sort(sortedData) - .limit(limitingValue) - .skip(skippingValue) - .lean(); - } else { + if (fields != "all") { + + fields.forEach(element => { + projectionObject[element] = 1; + }); + } + + if (skipFields != "none") { + skipFields.forEach(element => { + projectionObject[element] = 0; + }); + } + + let entitiesDocuments; - entitiesDocuments = await database.models.entities - .find(queryObject, projectionObject) - .limit(limitingValue) - .skip(skippingValue) - .lean(); + if( sortedData !== "" ) { + + entitiesDocuments = await database.models.entities + .find(queryObject, projectionObject) + .sort(sortedData) + .limit(limitingValue) + .skip(skippingValue) + .lean(); + } else { + + entitiesDocuments = await database.models.entities + .find(queryObject, projectionObject) + .limit(limitingValue) + .skip(skippingValue) + .lean(); + } + return resolve(entitiesDocuments); + } catch (error) { + return reject(error); } - - return resolve(entitiesDocuments); - } catch (error) { - return reject(error); - } - }); + }); } /** @@ -460,7 +459,7 @@ module.exports = class EntitiesHelper { let subEntitiesArray = []; let subEntities = await userService.getSubEntitiesBasedOnEntityType( entityId, entityTraversalType, subEntitiesArray ) - + if( !subEntities.length > 0 ) { return resolve({ data : subEntities, @@ -468,9 +467,8 @@ module.exports = class EntitiesHelper { }) } // call locationSearch with search and pagination - let subEntityIds = subEntities.map(function (entity) { return entity.id; }); let filter = { - "id" : subEntityIds + "id" : subEntities } let subentitiesData = await userService.locationSearch( filter, From be1eadb4943a5626e8c4d00dc07e782da4f0e61a Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 26 Aug 2022 18:37:14 +0530 Subject: [PATCH 163/331] test and review changes --- generics/services/users.js | 45 +++++++++++++++++++++----------------- models/programs.js | 1 - models/solutions.js | 1 - module/programs/helper.js | 27 ++++++++++++----------- module/solutions/helper.js | 27 +++++++++-------------- module/users/helper.js | 12 +++++----- 6 files changed, 55 insertions(+), 58 deletions(-) diff --git a/generics/services/users.js b/generics/services/users.js index fface554..9dee42f0 100644 --- a/generics/services/users.js +++ b/generics/services/users.js @@ -91,11 +91,12 @@ const locationSearch = function ( filterData, pageSize = "", pageNo = "", search bodyData["request"]["query"] = searchKey } + const url = userServiceUrl + constants.endpoints.GET_LOCATION_DATA; const options = { headers : { - "content-type": "application/json" + "content-type": "application/json", }, json : bodyData }; @@ -219,8 +220,8 @@ const locationSearch = function ( filterData, pageSize = "", pageNo = "", search userServiceUrl + constants.endpoints.GET_SCHOOL_DATA; const options = { headers : { - "content-type": "application/json" - }, + "content-type": "application/json", + }, json : bodyData }; @@ -253,7 +254,7 @@ const locationSearch = function ( filterData, pageSize = "", pageNo = "", search return resolve (result = { success : false }); - }, serverTimeout); + }, constants.common.SERVER_TIME_OUT); } catch (error) { return reject(error); @@ -270,32 +271,36 @@ const locationSearch = function ( filterData, pageSize = "", pageNo = "", search * @returns {Array} - Sub entities matching the type . */ -async function getSubEntitiesBasedOnEntityType( entityIds, entityType, result ) { - - if( !entityIds.length > 0 ) { - return result; - }; +async function getSubEntitiesBasedOnEntityType( parentIds, entityType, result ) { - let bodyData = { - "parentId" : entityIds + if( !parentIds.length > 0 ){ + return result; + } + let bodyData={ + "parentId" : parentIds }; - //get all immediate subEntities of type {entityType} - let childEntities = await locationSearch(bodyData); - if( ( !childEntities.success ) && !result.length > 0 ) { - return result; + let entityDetails = await locationSearch(bodyData); + if( !entityDetails.success ) { + return (result); } + + let entityData = entityDetails.data; let parentEntities = []; - if( childEntities.data[0].type == entityType ) { - result = childEntities.data; + entityData.map(entity => { + if( entity.type == entityType ) { + result.push(entity.id) } else { - parentEntities = childEntities.map(function (entity) { return entity.id; }); + parentEntities.push(entity.id) } + }); if( parentEntities.length > 0 ){ - await getSubEntitiesBasedOnEntityType(parentEntities, entityType, result); + await getSubEntitiesBasedOnEntityType(parentEntities,entityType,result) } - return result; + + let uniqueEntities = _.uniq(result); + return uniqueEntities; } module.exports = { diff --git a/models/programs.js b/models/programs.js index 02bcdea9..3372a08a 100644 --- a/models/programs.js +++ b/models/programs.js @@ -24,7 +24,6 @@ module.exports = { }, scope : { entityType : String, - entityTypeId : "ObjectId", entities : { type : Array, index : true diff --git a/models/solutions.js b/models/solutions.js index 5affdfb6..f4e1b3bd 100644 --- a/models/solutions.js +++ b/models/solutions.js @@ -16,7 +16,6 @@ module.exports = { themes: Array, flattenedThemes : Array, questionSequenceByEcm: Object, - entityTypeId: "ObjectId", entityType: String, type: String, subType: String, diff --git a/module/programs/helper.js b/module/programs/helper.js index 3f823ea2..1cc32bf3 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -234,7 +234,8 @@ module.exports = class ProgramsHelper { //locationIds contain id of location data. if ( locationData.ids.length > 0 ) { bodyData = { - "id" : locationData.ids + "id" : locationData.ids, + "type" : scopeData.entityType } let entityData = await userService.locationSearch( bodyData ); if ( entityData.success ) { @@ -243,17 +244,18 @@ module.exports = class ProgramsHelper { }); } } - // + if ( locationData.codes.length > 0 ) { let filterData = { - "externalId" : locationData.codes + "code" : locationData.codes, + "type" : scopeData.entityType } - let schoolDetails = await userService.orgSchoolSearch( filterData ); + let entityDetails = await userService.locationSearch( filterData ); - if ( schoolDetails.success ) { - let schoolData = schoolDetails.data; - schoolData.forEach( entity => { - entityIds.push(entity.externalId) + if ( entityDetails.success ) { + let entitiesData = entityDetails.data; + entitiesData.forEach( entity => { + entityIds.push(entity.id) }); } } @@ -751,14 +753,13 @@ module.exports = class ProgramsHelper { if ( locationData.codes.length > 0 ) { let filterData = { - "externalId" : locationData.codes, + "code" : locationData.codes, "type": programData[0].scope.entityType } - let schoolDetails = await userService.orgSchoolSearch( filterData ); + let entityDetails = await userService.locationSearch( filterData ); - if ( schoolDetails.success ) { - let schoolData = schoolDetails.data; - schoolData.forEach( entity => { + if ( entityDetails.success ) { + entityDetails.data.forEach( entity => { entityIds.push(entity.externalId) }); } diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 32f80229..1c02743a 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -986,6 +986,7 @@ module.exports = class SolutionsHelper { message : constants.apiResponses.PROGRAM_NOT_FOUND }); } + if( solutionData[0].scope.entityType !== programData[0].scope.entityType ) { let matchData = []; @@ -997,16 +998,7 @@ module.exports = class SolutionsHelper { message : constants.apiResponses.ENTITY_NOT_EXISTS_IN_PARENT } } - - for( let entitiesIndex = 0; entitiesIndex < entities.length; entitiesIndex++ ) { - for( let childListIndex = 0; childListIndex < childEntities.length; childListIndex++) { - if( childEntities[childListIndex] == entities[entitiesIndex]){ - checkEntityInParent.push(entities[entitiesIndex]); - entitiesIndex++; - } - } - } - + checkEntityInParent = entities.filter(element => childEntities.includes(element)); if( !checkEntityInParent.length > 0 ) { throw { message : constants.apiResponses.ENTITY_NOT_EXISTS_IN_PARENT @@ -1019,7 +1011,8 @@ module.exports = class SolutionsHelper { if ( locationData.ids.length > 0 ) { bodyData = { - "id" : locationData.ids + "id" : locationData.ids, + "type" : solutionData[0].scope.entityType } let entityData = await userService.locationSearch( bodyData ); if ( entityData.success ) { @@ -1031,14 +1024,14 @@ module.exports = class SolutionsHelper { if ( locationData.codes.length > 0 ) { let filterData = { - "externalId" : locationData.codes + "code" : locationData.codes, + "type" : solutionData[0].scope.entityType } - let schoolDetails = await userService.orgSchoolSearch( filterData ); + let entityDetails = await userService.locationSearch( filterData ); - if ( schoolDetails.success ) { - let schoolData = schoolDetails.data; - schoolData.forEach( entity => { - entityIds.push(entity.externalId) + if ( entityDetails.success ) { + entityDetails.data.forEach( entity => { + entityIds.push(entity.id) }); } } diff --git a/module/users/helper.js b/module/users/helper.js index e43c4506..f5826ae2 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -185,11 +185,11 @@ module.exports = class UsersHelper { if ( locationData.codes.length > 0 ) { let filterData = { - "externalId" : locationData.codes + "code" : locationData.codes } - let schoolDetails = await userService.orgSchoolSearch( filterData ); - let schoolDocuments = schoolDetails.data; - if ( !schoolDetails.success || !schoolDocuments.length > 0 ) { + let entityDetails = await userService.locationSearch( filterData ); + let entityDocuments = entityDetails.data; + if ( !entityDetails.success || !entityDocuments.length > 0 ) { return resolve({ status: httpStatusCode["bad_request"].status, message: constants.apiResponses.ENTITY_NOT_FOUND, @@ -197,8 +197,8 @@ module.exports = class UsersHelper { }); } - schoolDocuments.forEach( entity => { - entitiesData.push(entity.externalId) + entityDocuments.forEach( entity => { + entitiesData.push(entity.id) }); solutionDataToBeUpdated["entityType"] = constants.common.SCHOOL; From ffc0209d4e22cd61dda6eb6b06cb78b074db4dd8 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Tue, 30 Aug 2022 12:43:05 +0530 Subject: [PATCH 164/331] added entityType --- module/solutions/helper.js | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 09234d47..d9b9fbed 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -263,7 +263,7 @@ module.exports = class SolutionsHelper { } if( programData[0].scope ) { - + let currentSolutionScope = JSON.parse(JSON.stringify(programData[0].scope)); if( Object.keys(scopeData).length > 0 ) { @@ -290,7 +290,7 @@ module.exports = class SolutionsHelper { entityTypeId : currentSolutionScope.entityTypeId },["_id"] ); - + if( !entities.length > 0 ) { return resolve({ status : httpStatusCode.bad_request.status, @@ -301,6 +301,7 @@ module.exports = class SolutionsHelper { let entityIds = []; if( currentSolutionScope.entityType !== programData[0].scope.entityType ) { + for( let entity = 0; entity < entities.length; entity ++ ) { let entityQuery = { @@ -310,7 +311,7 @@ module.exports = class SolutionsHelper { let entityInParent = await entitiesHelper.entityDocuments(entityQuery); - + if( entityInParent.length > 0 ) { entityIds.push(ObjectId(entities[entity]._id)); } @@ -709,7 +710,8 @@ module.exports = class SolutionsHelper { "creator", "endDate", "link", - "referenceFrom" + "referenceFrom", + "entityType" ] ); From 94fab83cbe856db55ae287ef9f5cacb2569ee35a Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Thu, 1 Sep 2022 14:04:24 +0530 Subject: [PATCH 165/331] commented scope entity type check --- module/solutions/helper.js | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 1c02743a..c261c007 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -309,15 +309,15 @@ module.exports = class SolutionsHelper { let entitiesData = []; - if( currentSolutionScope.entityType !== programData[0].scope.entityType ) { - let result = []; - let childEntities = await userService.getSubEntitiesBasedOnEntityType(currentSolutionScope.entities, currentSolutionScope.entityType, result); - if( childEntities.length > 0 ) { - entitiesData = entityIds.filter(element => childEntities.includes(element)); - } - } else { + // if( currentSolutionScope.entityType !== programData[0].scope.entityType ) { + // let result = []; + // let childEntities = await userService.getSubEntitiesBasedOnEntityType(currentSolutionScope.entities, currentSolutionScope.entityType, result); + // if( childEntities.length > 0 ) { + // entitiesData = entityIds.filter(element => childEntities.includes(element)); + // } + // } else { entitiesData = entityIds - } + // } if( !entitiesData.length > 0 ) { From 858254692e88295923770f47432d7d650f5f440d Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Fri, 2 Sep 2022 15:25:07 +0530 Subject: [PATCH 166/331] added getParentEntities --- generics/services/users.js | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/generics/services/users.js b/generics/services/users.js index 9dee42f0..db36d4fb 100644 --- a/generics/services/users.js +++ b/generics/services/users.js @@ -302,10 +302,47 @@ async function getSubEntitiesBasedOnEntityType( parentIds, entityType, result ) let uniqueEntities = _.uniq(result); return uniqueEntities; } + +/** + * get Parent Entities of an entity. + * @method + * @name getParentEntities + * @param {String} entityId - entity id + * @returns {Array} - parent entities. +*/ + +async function getParentEntities( entityId, iteration = 0, parentEntities ) { + + if ( iteration == 0 ) { + parentEntities = []; + } + + let filterQuery = { + "id" : entityId + }; + + let entityDetails = await locationSearch(filterQuery); + if ( !entityDetails.success ) { + return parentEntities; + } else { + + let entityData = entityDetails.data[0]; + if ( iteration > 0 ) parentEntities.push(entityData); + if ( entityData.parentId ) { + iteration = iteration + 1; + entityId = entityData.parentId; + await getParentEntities(entityId, iteration, parentEntities); + } + } + + return parentEntities; + +} module.exports = { profile : profile, locationSearch : locationSearch, orgSchoolSearch :orgSchoolSearch, getSubEntitiesBasedOnEntityType : getSubEntitiesBasedOnEntityType + getParentEntities : getParentEntities } From 99441f244367e8adbffc9d319af02d4ba73ed16d Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Fri, 2 Sep 2022 16:58:52 +0530 Subject: [PATCH 167/331] url issue --- generics/services/improvement-project.js | 9 ++++++++- generics/services/users.js | 2 +- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/generics/services/improvement-project.js b/generics/services/improvement-project.js index 6393c7f6..018eaea8 100644 --- a/generics/services/improvement-project.js +++ b/generics/services/improvement-project.js @@ -7,6 +7,7 @@ //dependencies const request = require('request'); +const patternForDetectLang = /^[A-Za-z0-9]*$/; /** * List of user assigned projects. @@ -28,7 +29,13 @@ var assignedProjects = function ( token,search = "",filter = "" ) { if( filter !== "" ) { url = url + "&filter=" + filter; } - + + //finding the type of language + if (!patternForDetectLang.test(search)) { + console.log("encodeed") + url = encodeURI(url); + } + return new Promise(async (resolve, reject) => { try { diff --git a/generics/services/users.js b/generics/services/users.js index db36d4fb..482d1e58 100644 --- a/generics/services/users.js +++ b/generics/services/users.js @@ -343,6 +343,6 @@ module.exports = { profile : profile, locationSearch : locationSearch, orgSchoolSearch :orgSchoolSearch, - getSubEntitiesBasedOnEntityType : getSubEntitiesBasedOnEntityType + getSubEntitiesBasedOnEntityType : getSubEntitiesBasedOnEntityType, getParentEntities : getParentEntities } From 549c7b53e2313cc5d21081aeec52a2df5dbabade Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Fri, 2 Sep 2022 17:08:36 +0530 Subject: [PATCH 168/331] url issue --- generics/services/improvement-project.js | 1 - 1 file changed, 1 deletion(-) diff --git a/generics/services/improvement-project.js b/generics/services/improvement-project.js index 018eaea8..cbfa5ff8 100644 --- a/generics/services/improvement-project.js +++ b/generics/services/improvement-project.js @@ -32,7 +32,6 @@ var assignedProjects = function ( token,search = "",filter = "" ) { //finding the type of language if (!patternForDetectLang.test(search)) { - console.log("encodeed") url = encodeURI(url); } From d00deee7b5cf8c872242a70528d8f9fb2a597b76 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Fri, 2 Sep 2022 17:55:13 +0530 Subject: [PATCH 169/331] es script to convert objectid to locationId --- README.md | 7 + migrations/entityToLocationId.js | 296 +++++++++++++++++++++++++++++++ 2 files changed, 303 insertions(+) create mode 100644 migrations/entityToLocationId.js diff --git a/README.md b/README.md index 8e2db83d..f1058819 100644 --- a/README.md +++ b/README.md @@ -2,4 +2,11 @@ Centralised Service to support other Services. It is used by ml-survey and ml-project +### Migrations for entity generalization +Steps to run the migration files +- Navigate to migrations folder +- The first script which convert mongoId to locationId. To run the script use the below command, + > run entityToLocationId.js +- Run the final script which add entity hierarchy to the existing observationSubmissions & project collections. + > run addHierarchy.js diff --git a/migrations/entityToLocationId.js b/migrations/entityToLocationId.js new file mode 100644 index 00000000..c0888541 --- /dev/null +++ b/migrations/entityToLocationId.js @@ -0,0 +1,296 @@ +/** + * name : entityToLocationId.js + * author : Priyanka Pradeep + * created-date : 02-Sep-2022 + * Description : Migration script for convert entity to locationId. + */ + +const path = require("path"); +let rootPath = path.join(__dirname, '..') +require('dotenv').config({ path: rootPath+'/.env' }) +let _ = require("lodash"); +let mongoUrl = process.env.MONGODB_URL; +let dbName = mongoUrl.split("/").pop(); +let url = mongoUrl.split(dbName)[0]; +var MongoClient = require('mongodb').MongoClient; +var ObjectId = require('mongodb').ObjectID; + +(async () => { + + let connection = await MongoClient.connect(url, { useNewUrlParser: true }); + let db = connection.db(dbName); + console.log(dbName,"dbName") + try { + + let collections = { + "observationSubmissions" : { + "query" : { + }, + "projection": { + entityId:1,_id:0 + } + }, + "projects" : { + "query" : { + entityId:{$exists:true} + }, + "projection": { + entityId:1,_id:0 + } + } + } + + let entityIds = []; + //loop project & obeservationSubmission collections and get entityId + for ( let eachModel in collections ) { + //fetch each current collection and get entityId + let collectionDocs = await db.collection(eachModel).find(collections[eachModel].query).project(collections[eachModel].projection).toArray(); + collectionDocs.forEach( eachDoc => { + entityIds.push(eachDoc.entityId.toString()); + }) + + //eliminate duplication of ids + entityIds = _.uniq(entityIds); + } + + let chunkOfEntityIds = _.chunk(entityIds, 5); + //loop entity + for ( let chunkPointer = 0; chunkPointer < chunkOfEntityIds.length; chunkPointer++ ) { + + let entityIds = chunkOfEntityIds[chunkPointer]; + //convert to obejctId + let entityIdToObjectId = await convertToObjectId(entityIds); + //fetch entity documents + let entityDocuments = await db.collection('entities').find({_id:{ $in : entityIdToObjectId}}).project({ + "registryDetails.locationId":1, + "registryDetails.code":1, + }).toArray(); + + //loop the entity documents + for ( let entityPointer = 0; entityPointer < entityDocuments.length; entityPointer++ ) { + + let currentEntity = entityDocuments[entityPointer]; + //loop all the collections + for ( let currentModel in collections ) { + + let findQuery = { + "entityId": currentEntity._id + } + + let updateObject = { + "$set" : {} + }; + + //update query for project + if ( currentModel == "projects") { + updateObject["$set"]["entityId"] = currentEntity.registryDetails.locationId; + updateObject["$set"]["entityInformation._id"] = currentEntity.registryDetails.locationId; + updateObject["$set"]["entityInformation.externalId"] = currentEntity.registryDetails.code; + + } else if ( currentModel == "observationSubmissions" ) { + updateObject["$set"]["entityId"] = currentEntity.registryDetails.locationId; + updateObject["$set"]["entityExternalId"] = currentEntity.registryDetails.code; + updateObject["$set"]["entityInformation.externalId"] = currentEntity.registryDetails.code; + } + + //update the projects & observationSubmission collection + if ( updateObject && Object.keys(updateObject["$set"]).length > 0 ) { + let updateCollection = await db.collection(currentModel).updateMany(findQuery,updateObject); + } + } + } + } + + console.log("observations & projects collections updated") + + //update programs, solutions & observation collections + let otherCollections = { + "programs" : { + "query" : { + 'scope.entities':{$exists:true, $ne : []} + }, + "projection": { + 'scope.entities':1,_id:1 + } + }, + "observations" : { + "query" : { + entities:{$exists:true, $ne: []} + }, + "projection": { + entities:1,_id:1 + } + }, + "solutions.1" : { + "query" : { + 'scope.entities':{$exists:true, $ne : []} + }, + "projection": { + 'scope.entities':1,_id:1 + }, + "field": "scope.entities" + }, + "solutions.2" : { + "query" : { + 'entities':{$exists:true, $ne : []} + }, + "projection": { + entities:1,_id:1 + }, + "field": "entities" + } + + } + + //loop observation, solutions and programs collections + for ( let eachCollection in otherCollections ) { + + let getName = eachCollection.split("."); + let collectionName = getName[0]; + let otherCollectionDocs = await db.collection(collectionName).find(otherCollections[eachCollection].query).project(otherCollections[eachCollection].projection).toArray(); + let chunkOfOtherCollection = _.chunk(otherCollectionDocs, 10); + + for (let pointerToOtherCollection = 0; pointerToOtherCollection < chunkOfOtherCollection.length; pointerToOtherCollection++ ) { + let eachChunkCollections = chunkOfOtherCollection[pointerToOtherCollection]; + //loop each collection + for ( let pointerToChunk = 0; pointerToChunk < eachChunkCollections.length; pointerToChunk++ ) { + + let eachDocument = eachChunkCollections[pointerToChunk]; + let query = { + _id: eachDocument._id + } + + let updateQuery = { + "$set" : {} + } + + let eachEntityIds = []; + if ( eachCollection == "observations") { + eachEntityIds = eachDocument.entities; + } else if ( eachCollection == "programs" ) { + eachEntityIds = eachDocument.scope.entities; + } else if ( eachCollection == "solutions.1" && otherCollections[eachCollection].field == "scope.entities") { + eachEntityIds = eachDocument.scope.entities; + } else if ( eachCollection == "solutions.2" && otherCollections[eachCollection].field == "entities") { + eachEntityIds = eachDocument.entities; + } + + let entityIdToObjectId = await convertToObjectId(eachEntityIds); + //fetch entity + let entityDocs = await db.collection('entities').find({_id:{ $in : entityIdToObjectId}, registryDetails:{$exists:true}}).project({ + "registryDetails.locationId":1, + "registryDetails.code":1, + }).toArray(); + + let newEntityIds = []; + if ( entityDocs && entityDocs.length > 0 ) { + entityDocs.forEach( entity => { + newEntityIds.push(entity.registryDetails.locationId); + }) + } + + if ( eachCollection == "observations" ) { + updateQuery["$set"] = { + "entities" : newEntityIds + } + } else if ( eachCollection == "programs") { + updateQuery["$set"] = { + "scope.entities" : newEntityIds + } + } else if ( eachCollection == "solutions.1" && otherCollections[eachCollection].field == "scope.entities") { + updateQuery["$set"] = { + "scope.entities" : newEntityIds + } + } else if ( eachCollection == "solutions.2" && otherCollections[eachCollection].field == "entities") { + updateQuery["$set"] = { + "entities" : newEntityIds + } + } + + //update collection + if ( updateQuery && Object.keys(updateQuery["$set"]).length > 0 ) { + let updateCollections = await db.collection(collectionName).updateMany(query,updateQuery); + } + } + } + + console.log(eachCollection,"updated") + } + + //update observationInformation in project task + let projectDocument = await db.collection('projects').find({ + "tasks.type" : "observation", + "tasks.observationInformation":{$exists:true} + }).project({_id:1}).toArray(); + + let chunkOfProjectDocument = _.chunk(projectDocument, 10); + let projectIds; + + for (let pointerToProject = 0; pointerToProject < chunkOfProjectDocument.length; pointerToProject++) { + + projectIds = await chunkOfProjectDocument[pointerToProject].map( + projectDoc => { + return projectDoc._id; + } + ); + + let projectDocuments = await db.collection('projects').find({ + _id: { $in : projectIds } + }).project({ + "_id": 1, + "tasks._id" : 1, + "tasks.observationInformation" : 1 + }).toArray(); + + await Promise.all( + projectDocuments.map(async eachProject => { + + let tasks = eachProject.tasks; + for ( let taskCounter = 0; taskCounter < tasks.length; taskCounter++) { + let currentTask = tasks[taskCounter]; + if ( currentTask.observationInformation ) { + + let observationInformation = currentTask.observationInformation; + + let taskUpdateObject = { + "$set" : {} + }; + + if ( observationInformation.entityId ) { + + let entityDocuments = await db.collection('entities').find({_id: ObjectId(observationInformation.entityId) }).project({ + "registryDetails.locationId":1 + }).toArray(); + + if ( entityDocuments.length > 0 ) { + observationInformation.entityId = entityDocuments[0].registryDetails.locationId; + } + } + + taskUpdateObject["$set"]["tasks.$.observationInformation"] = observationInformation; + + if ( taskUpdateObject["$set"] && Object.keys(taskUpdateObject["$set"]).length > 0 ) { + + let updateTaskData = await db.collection('projects').findOneAndUpdate({ + "_id": eachProject._id, + "tasks._id": currentTask._id + }, taskUpdateObject); + } + } + } + })) + + } + console.log("project task updated") + console.log("completed") + + function convertToObjectId(ids){ + return ids.map(id => ObjectId(id)); + } + + connection.close(); + } + catch (error) { + console.log(error) + } +})().catch(err => console.error(err)); From a9aa1e2a15ddf1cb1ba1100397f2459204dc8b34 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 2 Sep 2022 18:13:07 +0530 Subject: [PATCH 170/331] heirarchy script added --- migrations/addHeirarchy.js | 175 +++++++++++++++++++++++++++++++++++++ 1 file changed, 175 insertions(+) create mode 100644 migrations/addHeirarchy.js diff --git a/migrations/addHeirarchy.js b/migrations/addHeirarchy.js new file mode 100644 index 00000000..31703057 --- /dev/null +++ b/migrations/addHeirarchy.js @@ -0,0 +1,175 @@ +let _ = require("lodash"); +const request = require('request'); +const path = require("path"); +let rootPath = path.join(__dirname, '..') +let endPoints = require(rootPath+'/generics/constants/endpoints') +require('dotenv').config({ path: rootPath+'/.env' }) +let MongoClient = require("mongodb").MongoClient; +let endPoint = endPoints.GET_LOCATION_DATA; +let userServiceUrl = process.env.USER_SERVICE_URL; +let mongoUrl = process.env.MONGODB_URL; +let dbName = mongoUrl.split("/").pop(); +let url = mongoUrl.split(dbName)[0]; + + + + +(async () => { + + let connection = await MongoClient.connect(url, { useNewUrlParser: true }); + let db = connection.db(dbName); + try { + + let collections = { + "observationSubmissions" : { + "query" : { + }, + "projection": { + entityId:1,_id:0 + } + }, + "projects" : { + "query" : { + entityId:{$exists:true} + }, + "projection": { + entityId:1,_id:0 + } + } + } + + let entityIds = []; + //loop project & obeservationSubmission collections and get entityId + for ( let eachModel in collections ) { + //fetch each current collection and get entityId + let collectionDocs = await db.collection(eachModel).find(collections[eachModel].query).project(collections[eachModel].projection).toArray(); + collectionDocs.forEach( eachDoc => { + entityIds.push(eachDoc.entityId.toString()); + }) + + //eliminate duplication of ids + entityIds = _.uniq(entityIds); + } + + let chunkOfEntityIds = _.chunk(entityIds, 5); + //loop entity + for ( let chunkPointer = 0; chunkPointer < chunkOfEntityIds.length; chunkPointer++ ) { + //chunk of entity ids + let entityIds = chunkOfEntityIds[chunkPointer]; + + for ( let entityIdpointer = 0 ; entityIdpointer < entityIds.length; entityIdpointer++ ) { + let parentData = await getParentEntities(entityIds[entityIdpointer]); + + for ( let currentModel in collections ) { + + let findQuery = { + "entityId": entityIds[entityIdpointer] + } + + let updateObject = { + "$set" : {} + }; + + //update query for project and observationSubmission + updateObject["$set"]["entityInformation.hierarchy"] = parentData; + //update the projects & observationSubmission collection + if ( updateObject && Object.keys(updateObject["$set"]).length > 0 ) { + let updateCollection = await db.collection(currentModel).updateMany(findQuery,updateObject); + } + } + + } + + } + console.log("observationsSubmissions & projects collections updated") + + + // call location search api + function locationSearch ( filterData ) { + return new Promise(async (resolve, reject) => { + try { + + let bodyData={}; + bodyData["request"] = {}; + bodyData["request"]["filters"] = filterData; + const url = + userServiceUrl + endPoint; + const options = { + headers : { + "content-type": "application/json" + }, + json : bodyData + }; + + request.post(url,options,requestCallback); + let result = { + success : true + }; + + function requestCallback(err, data) { + if (err) { + result.success = false; + } else { + let response = data.body; + + if( response.responseCode === "OK" && + response.result && + response.result.response && + response.result.response.length > 0 + ) { + result["data"] = response.result.response; + result["count"] = response.result.count; + } else { + result.success = false; + } + } + return resolve(result); + } + + setTimeout(function () { + return resolve (result = { + success : false + }); + }, 5000); + + } catch (error) { + return reject(error); + } + }) + } + + //get parent data of a given entity + async function getParentEntities( entityId, iteration = 0, parentEntities ) { + + if ( iteration == 0 ) { + parentEntities = []; + } + + let filterQuery = { + "id" : entityId + }; + + let entityDetails = await locationSearch(filterQuery); + if ( !entityDetails.success ) { + return parentEntities; + } else { + + let entityData = entityDetails.data[0]; + if ( iteration > 0 ) parentEntities.push(entityData); + if ( entityData.parentId ) { + iteration = iteration + 1; + entityId = entityData.parentId; + await getParentEntities(entityId, iteration, parentEntities); + } + } + + return parentEntities; + + } + + connection.close(); + } + catch (error) { + console.log(error) + } +})().catch(err => console.error(err)); From 7f82ce64832a3c25b2e9dae09b276becf54b6563 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 2 Sep 2022 18:29:59 +0530 Subject: [PATCH 171/331] script folder change --- README.md | 4 +- migrations/entity-5.0/addHeirarchy.js | 175 ++++++++++++ migrations/entity-5.0/entityToLocationId.js | 296 ++++++++++++++++++++ 3 files changed, 473 insertions(+), 2 deletions(-) create mode 100644 migrations/entity-5.0/addHeirarchy.js create mode 100644 migrations/entity-5.0/entityToLocationId.js diff --git a/README.md b/README.md index f1058819..6a3d033b 100644 --- a/README.md +++ b/README.md @@ -4,9 +4,9 @@ It is used by ml-survey and ml-project ### Migrations for entity generalization Steps to run the migration files -- Navigate to migrations folder +- Navigate to migrations/entity-5.0/ folder - The first script which convert mongoId to locationId. To run the script use the below command, > run entityToLocationId.js - Run the final script which add entity hierarchy to the existing observationSubmissions & project collections. - > run addHierarchy.js + > run addHierarchy.js diff --git a/migrations/entity-5.0/addHeirarchy.js b/migrations/entity-5.0/addHeirarchy.js new file mode 100644 index 00000000..31703057 --- /dev/null +++ b/migrations/entity-5.0/addHeirarchy.js @@ -0,0 +1,175 @@ +let _ = require("lodash"); +const request = require('request'); +const path = require("path"); +let rootPath = path.join(__dirname, '..') +let endPoints = require(rootPath+'/generics/constants/endpoints') +require('dotenv').config({ path: rootPath+'/.env' }) +let MongoClient = require("mongodb").MongoClient; +let endPoint = endPoints.GET_LOCATION_DATA; +let userServiceUrl = process.env.USER_SERVICE_URL; +let mongoUrl = process.env.MONGODB_URL; +let dbName = mongoUrl.split("/").pop(); +let url = mongoUrl.split(dbName)[0]; + + + + +(async () => { + + let connection = await MongoClient.connect(url, { useNewUrlParser: true }); + let db = connection.db(dbName); + try { + + let collections = { + "observationSubmissions" : { + "query" : { + }, + "projection": { + entityId:1,_id:0 + } + }, + "projects" : { + "query" : { + entityId:{$exists:true} + }, + "projection": { + entityId:1,_id:0 + } + } + } + + let entityIds = []; + //loop project & obeservationSubmission collections and get entityId + for ( let eachModel in collections ) { + //fetch each current collection and get entityId + let collectionDocs = await db.collection(eachModel).find(collections[eachModel].query).project(collections[eachModel].projection).toArray(); + collectionDocs.forEach( eachDoc => { + entityIds.push(eachDoc.entityId.toString()); + }) + + //eliminate duplication of ids + entityIds = _.uniq(entityIds); + } + + let chunkOfEntityIds = _.chunk(entityIds, 5); + //loop entity + for ( let chunkPointer = 0; chunkPointer < chunkOfEntityIds.length; chunkPointer++ ) { + //chunk of entity ids + let entityIds = chunkOfEntityIds[chunkPointer]; + + for ( let entityIdpointer = 0 ; entityIdpointer < entityIds.length; entityIdpointer++ ) { + let parentData = await getParentEntities(entityIds[entityIdpointer]); + + for ( let currentModel in collections ) { + + let findQuery = { + "entityId": entityIds[entityIdpointer] + } + + let updateObject = { + "$set" : {} + }; + + //update query for project and observationSubmission + updateObject["$set"]["entityInformation.hierarchy"] = parentData; + //update the projects & observationSubmission collection + if ( updateObject && Object.keys(updateObject["$set"]).length > 0 ) { + let updateCollection = await db.collection(currentModel).updateMany(findQuery,updateObject); + } + } + + } + + } + console.log("observationsSubmissions & projects collections updated") + + + // call location search api + function locationSearch ( filterData ) { + return new Promise(async (resolve, reject) => { + try { + + let bodyData={}; + bodyData["request"] = {}; + bodyData["request"]["filters"] = filterData; + const url = + userServiceUrl + endPoint; + const options = { + headers : { + "content-type": "application/json" + }, + json : bodyData + }; + + request.post(url,options,requestCallback); + let result = { + success : true + }; + + function requestCallback(err, data) { + if (err) { + result.success = false; + } else { + let response = data.body; + + if( response.responseCode === "OK" && + response.result && + response.result.response && + response.result.response.length > 0 + ) { + result["data"] = response.result.response; + result["count"] = response.result.count; + } else { + result.success = false; + } + } + return resolve(result); + } + + setTimeout(function () { + return resolve (result = { + success : false + }); + }, 5000); + + } catch (error) { + return reject(error); + } + }) + } + + //get parent data of a given entity + async function getParentEntities( entityId, iteration = 0, parentEntities ) { + + if ( iteration == 0 ) { + parentEntities = []; + } + + let filterQuery = { + "id" : entityId + }; + + let entityDetails = await locationSearch(filterQuery); + if ( !entityDetails.success ) { + return parentEntities; + } else { + + let entityData = entityDetails.data[0]; + if ( iteration > 0 ) parentEntities.push(entityData); + if ( entityData.parentId ) { + iteration = iteration + 1; + entityId = entityData.parentId; + await getParentEntities(entityId, iteration, parentEntities); + } + } + + return parentEntities; + + } + + connection.close(); + } + catch (error) { + console.log(error) + } +})().catch(err => console.error(err)); diff --git a/migrations/entity-5.0/entityToLocationId.js b/migrations/entity-5.0/entityToLocationId.js new file mode 100644 index 00000000..c0888541 --- /dev/null +++ b/migrations/entity-5.0/entityToLocationId.js @@ -0,0 +1,296 @@ +/** + * name : entityToLocationId.js + * author : Priyanka Pradeep + * created-date : 02-Sep-2022 + * Description : Migration script for convert entity to locationId. + */ + +const path = require("path"); +let rootPath = path.join(__dirname, '..') +require('dotenv').config({ path: rootPath+'/.env' }) +let _ = require("lodash"); +let mongoUrl = process.env.MONGODB_URL; +let dbName = mongoUrl.split("/").pop(); +let url = mongoUrl.split(dbName)[0]; +var MongoClient = require('mongodb').MongoClient; +var ObjectId = require('mongodb').ObjectID; + +(async () => { + + let connection = await MongoClient.connect(url, { useNewUrlParser: true }); + let db = connection.db(dbName); + console.log(dbName,"dbName") + try { + + let collections = { + "observationSubmissions" : { + "query" : { + }, + "projection": { + entityId:1,_id:0 + } + }, + "projects" : { + "query" : { + entityId:{$exists:true} + }, + "projection": { + entityId:1,_id:0 + } + } + } + + let entityIds = []; + //loop project & obeservationSubmission collections and get entityId + for ( let eachModel in collections ) { + //fetch each current collection and get entityId + let collectionDocs = await db.collection(eachModel).find(collections[eachModel].query).project(collections[eachModel].projection).toArray(); + collectionDocs.forEach( eachDoc => { + entityIds.push(eachDoc.entityId.toString()); + }) + + //eliminate duplication of ids + entityIds = _.uniq(entityIds); + } + + let chunkOfEntityIds = _.chunk(entityIds, 5); + //loop entity + for ( let chunkPointer = 0; chunkPointer < chunkOfEntityIds.length; chunkPointer++ ) { + + let entityIds = chunkOfEntityIds[chunkPointer]; + //convert to obejctId + let entityIdToObjectId = await convertToObjectId(entityIds); + //fetch entity documents + let entityDocuments = await db.collection('entities').find({_id:{ $in : entityIdToObjectId}}).project({ + "registryDetails.locationId":1, + "registryDetails.code":1, + }).toArray(); + + //loop the entity documents + for ( let entityPointer = 0; entityPointer < entityDocuments.length; entityPointer++ ) { + + let currentEntity = entityDocuments[entityPointer]; + //loop all the collections + for ( let currentModel in collections ) { + + let findQuery = { + "entityId": currentEntity._id + } + + let updateObject = { + "$set" : {} + }; + + //update query for project + if ( currentModel == "projects") { + updateObject["$set"]["entityId"] = currentEntity.registryDetails.locationId; + updateObject["$set"]["entityInformation._id"] = currentEntity.registryDetails.locationId; + updateObject["$set"]["entityInformation.externalId"] = currentEntity.registryDetails.code; + + } else if ( currentModel == "observationSubmissions" ) { + updateObject["$set"]["entityId"] = currentEntity.registryDetails.locationId; + updateObject["$set"]["entityExternalId"] = currentEntity.registryDetails.code; + updateObject["$set"]["entityInformation.externalId"] = currentEntity.registryDetails.code; + } + + //update the projects & observationSubmission collection + if ( updateObject && Object.keys(updateObject["$set"]).length > 0 ) { + let updateCollection = await db.collection(currentModel).updateMany(findQuery,updateObject); + } + } + } + } + + console.log("observations & projects collections updated") + + //update programs, solutions & observation collections + let otherCollections = { + "programs" : { + "query" : { + 'scope.entities':{$exists:true, $ne : []} + }, + "projection": { + 'scope.entities':1,_id:1 + } + }, + "observations" : { + "query" : { + entities:{$exists:true, $ne: []} + }, + "projection": { + entities:1,_id:1 + } + }, + "solutions.1" : { + "query" : { + 'scope.entities':{$exists:true, $ne : []} + }, + "projection": { + 'scope.entities':1,_id:1 + }, + "field": "scope.entities" + }, + "solutions.2" : { + "query" : { + 'entities':{$exists:true, $ne : []} + }, + "projection": { + entities:1,_id:1 + }, + "field": "entities" + } + + } + + //loop observation, solutions and programs collections + for ( let eachCollection in otherCollections ) { + + let getName = eachCollection.split("."); + let collectionName = getName[0]; + let otherCollectionDocs = await db.collection(collectionName).find(otherCollections[eachCollection].query).project(otherCollections[eachCollection].projection).toArray(); + let chunkOfOtherCollection = _.chunk(otherCollectionDocs, 10); + + for (let pointerToOtherCollection = 0; pointerToOtherCollection < chunkOfOtherCollection.length; pointerToOtherCollection++ ) { + let eachChunkCollections = chunkOfOtherCollection[pointerToOtherCollection]; + //loop each collection + for ( let pointerToChunk = 0; pointerToChunk < eachChunkCollections.length; pointerToChunk++ ) { + + let eachDocument = eachChunkCollections[pointerToChunk]; + let query = { + _id: eachDocument._id + } + + let updateQuery = { + "$set" : {} + } + + let eachEntityIds = []; + if ( eachCollection == "observations") { + eachEntityIds = eachDocument.entities; + } else if ( eachCollection == "programs" ) { + eachEntityIds = eachDocument.scope.entities; + } else if ( eachCollection == "solutions.1" && otherCollections[eachCollection].field == "scope.entities") { + eachEntityIds = eachDocument.scope.entities; + } else if ( eachCollection == "solutions.2" && otherCollections[eachCollection].field == "entities") { + eachEntityIds = eachDocument.entities; + } + + let entityIdToObjectId = await convertToObjectId(eachEntityIds); + //fetch entity + let entityDocs = await db.collection('entities').find({_id:{ $in : entityIdToObjectId}, registryDetails:{$exists:true}}).project({ + "registryDetails.locationId":1, + "registryDetails.code":1, + }).toArray(); + + let newEntityIds = []; + if ( entityDocs && entityDocs.length > 0 ) { + entityDocs.forEach( entity => { + newEntityIds.push(entity.registryDetails.locationId); + }) + } + + if ( eachCollection == "observations" ) { + updateQuery["$set"] = { + "entities" : newEntityIds + } + } else if ( eachCollection == "programs") { + updateQuery["$set"] = { + "scope.entities" : newEntityIds + } + } else if ( eachCollection == "solutions.1" && otherCollections[eachCollection].field == "scope.entities") { + updateQuery["$set"] = { + "scope.entities" : newEntityIds + } + } else if ( eachCollection == "solutions.2" && otherCollections[eachCollection].field == "entities") { + updateQuery["$set"] = { + "entities" : newEntityIds + } + } + + //update collection + if ( updateQuery && Object.keys(updateQuery["$set"]).length > 0 ) { + let updateCollections = await db.collection(collectionName).updateMany(query,updateQuery); + } + } + } + + console.log(eachCollection,"updated") + } + + //update observationInformation in project task + let projectDocument = await db.collection('projects').find({ + "tasks.type" : "observation", + "tasks.observationInformation":{$exists:true} + }).project({_id:1}).toArray(); + + let chunkOfProjectDocument = _.chunk(projectDocument, 10); + let projectIds; + + for (let pointerToProject = 0; pointerToProject < chunkOfProjectDocument.length; pointerToProject++) { + + projectIds = await chunkOfProjectDocument[pointerToProject].map( + projectDoc => { + return projectDoc._id; + } + ); + + let projectDocuments = await db.collection('projects').find({ + _id: { $in : projectIds } + }).project({ + "_id": 1, + "tasks._id" : 1, + "tasks.observationInformation" : 1 + }).toArray(); + + await Promise.all( + projectDocuments.map(async eachProject => { + + let tasks = eachProject.tasks; + for ( let taskCounter = 0; taskCounter < tasks.length; taskCounter++) { + let currentTask = tasks[taskCounter]; + if ( currentTask.observationInformation ) { + + let observationInformation = currentTask.observationInformation; + + let taskUpdateObject = { + "$set" : {} + }; + + if ( observationInformation.entityId ) { + + let entityDocuments = await db.collection('entities').find({_id: ObjectId(observationInformation.entityId) }).project({ + "registryDetails.locationId":1 + }).toArray(); + + if ( entityDocuments.length > 0 ) { + observationInformation.entityId = entityDocuments[0].registryDetails.locationId; + } + } + + taskUpdateObject["$set"]["tasks.$.observationInformation"] = observationInformation; + + if ( taskUpdateObject["$set"] && Object.keys(taskUpdateObject["$set"]).length > 0 ) { + + let updateTaskData = await db.collection('projects').findOneAndUpdate({ + "_id": eachProject._id, + "tasks._id": currentTask._id + }, taskUpdateObject); + } + } + } + })) + + } + console.log("project task updated") + console.log("completed") + + function convertToObjectId(ids){ + return ids.map(id => ObjectId(id)); + } + + connection.close(); + } + catch (error) { + console.log(error) + } +})().catch(err => console.error(err)); From b9c727004367a98de42bcfa9baf320574b9cfef4 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 2 Sep 2022 18:33:06 +0530 Subject: [PATCH 172/331] remove file --- migrations/addHeirarchy.js | 175 ------------------ migrations/entityToLocationId.js | 296 ------------------------------- 2 files changed, 471 deletions(-) delete mode 100644 migrations/addHeirarchy.js delete mode 100644 migrations/entityToLocationId.js diff --git a/migrations/addHeirarchy.js b/migrations/addHeirarchy.js deleted file mode 100644 index 31703057..00000000 --- a/migrations/addHeirarchy.js +++ /dev/null @@ -1,175 +0,0 @@ -let _ = require("lodash"); -const request = require('request'); -const path = require("path"); -let rootPath = path.join(__dirname, '..') -let endPoints = require(rootPath+'/generics/constants/endpoints') -require('dotenv').config({ path: rootPath+'/.env' }) -let MongoClient = require("mongodb").MongoClient; -let endPoint = endPoints.GET_LOCATION_DATA; -let userServiceUrl = process.env.USER_SERVICE_URL; -let mongoUrl = process.env.MONGODB_URL; -let dbName = mongoUrl.split("/").pop(); -let url = mongoUrl.split(dbName)[0]; - - - - -(async () => { - - let connection = await MongoClient.connect(url, { useNewUrlParser: true }); - let db = connection.db(dbName); - try { - - let collections = { - "observationSubmissions" : { - "query" : { - }, - "projection": { - entityId:1,_id:0 - } - }, - "projects" : { - "query" : { - entityId:{$exists:true} - }, - "projection": { - entityId:1,_id:0 - } - } - } - - let entityIds = []; - //loop project & obeservationSubmission collections and get entityId - for ( let eachModel in collections ) { - //fetch each current collection and get entityId - let collectionDocs = await db.collection(eachModel).find(collections[eachModel].query).project(collections[eachModel].projection).toArray(); - collectionDocs.forEach( eachDoc => { - entityIds.push(eachDoc.entityId.toString()); - }) - - //eliminate duplication of ids - entityIds = _.uniq(entityIds); - } - - let chunkOfEntityIds = _.chunk(entityIds, 5); - //loop entity - for ( let chunkPointer = 0; chunkPointer < chunkOfEntityIds.length; chunkPointer++ ) { - //chunk of entity ids - let entityIds = chunkOfEntityIds[chunkPointer]; - - for ( let entityIdpointer = 0 ; entityIdpointer < entityIds.length; entityIdpointer++ ) { - let parentData = await getParentEntities(entityIds[entityIdpointer]); - - for ( let currentModel in collections ) { - - let findQuery = { - "entityId": entityIds[entityIdpointer] - } - - let updateObject = { - "$set" : {} - }; - - //update query for project and observationSubmission - updateObject["$set"]["entityInformation.hierarchy"] = parentData; - //update the projects & observationSubmission collection - if ( updateObject && Object.keys(updateObject["$set"]).length > 0 ) { - let updateCollection = await db.collection(currentModel).updateMany(findQuery,updateObject); - } - } - - } - - } - console.log("observationsSubmissions & projects collections updated") - - - // call location search api - function locationSearch ( filterData ) { - return new Promise(async (resolve, reject) => { - try { - - let bodyData={}; - bodyData["request"] = {}; - bodyData["request"]["filters"] = filterData; - const url = - userServiceUrl + endPoint; - const options = { - headers : { - "content-type": "application/json" - }, - json : bodyData - }; - - request.post(url,options,requestCallback); - let result = { - success : true - }; - - function requestCallback(err, data) { - if (err) { - result.success = false; - } else { - let response = data.body; - - if( response.responseCode === "OK" && - response.result && - response.result.response && - response.result.response.length > 0 - ) { - result["data"] = response.result.response; - result["count"] = response.result.count; - } else { - result.success = false; - } - } - return resolve(result); - } - - setTimeout(function () { - return resolve (result = { - success : false - }); - }, 5000); - - } catch (error) { - return reject(error); - } - }) - } - - //get parent data of a given entity - async function getParentEntities( entityId, iteration = 0, parentEntities ) { - - if ( iteration == 0 ) { - parentEntities = []; - } - - let filterQuery = { - "id" : entityId - }; - - let entityDetails = await locationSearch(filterQuery); - if ( !entityDetails.success ) { - return parentEntities; - } else { - - let entityData = entityDetails.data[0]; - if ( iteration > 0 ) parentEntities.push(entityData); - if ( entityData.parentId ) { - iteration = iteration + 1; - entityId = entityData.parentId; - await getParentEntities(entityId, iteration, parentEntities); - } - } - - return parentEntities; - - } - - connection.close(); - } - catch (error) { - console.log(error) - } -})().catch(err => console.error(err)); diff --git a/migrations/entityToLocationId.js b/migrations/entityToLocationId.js deleted file mode 100644 index c0888541..00000000 --- a/migrations/entityToLocationId.js +++ /dev/null @@ -1,296 +0,0 @@ -/** - * name : entityToLocationId.js - * author : Priyanka Pradeep - * created-date : 02-Sep-2022 - * Description : Migration script for convert entity to locationId. - */ - -const path = require("path"); -let rootPath = path.join(__dirname, '..') -require('dotenv').config({ path: rootPath+'/.env' }) -let _ = require("lodash"); -let mongoUrl = process.env.MONGODB_URL; -let dbName = mongoUrl.split("/").pop(); -let url = mongoUrl.split(dbName)[0]; -var MongoClient = require('mongodb').MongoClient; -var ObjectId = require('mongodb').ObjectID; - -(async () => { - - let connection = await MongoClient.connect(url, { useNewUrlParser: true }); - let db = connection.db(dbName); - console.log(dbName,"dbName") - try { - - let collections = { - "observationSubmissions" : { - "query" : { - }, - "projection": { - entityId:1,_id:0 - } - }, - "projects" : { - "query" : { - entityId:{$exists:true} - }, - "projection": { - entityId:1,_id:0 - } - } - } - - let entityIds = []; - //loop project & obeservationSubmission collections and get entityId - for ( let eachModel in collections ) { - //fetch each current collection and get entityId - let collectionDocs = await db.collection(eachModel).find(collections[eachModel].query).project(collections[eachModel].projection).toArray(); - collectionDocs.forEach( eachDoc => { - entityIds.push(eachDoc.entityId.toString()); - }) - - //eliminate duplication of ids - entityIds = _.uniq(entityIds); - } - - let chunkOfEntityIds = _.chunk(entityIds, 5); - //loop entity - for ( let chunkPointer = 0; chunkPointer < chunkOfEntityIds.length; chunkPointer++ ) { - - let entityIds = chunkOfEntityIds[chunkPointer]; - //convert to obejctId - let entityIdToObjectId = await convertToObjectId(entityIds); - //fetch entity documents - let entityDocuments = await db.collection('entities').find({_id:{ $in : entityIdToObjectId}}).project({ - "registryDetails.locationId":1, - "registryDetails.code":1, - }).toArray(); - - //loop the entity documents - for ( let entityPointer = 0; entityPointer < entityDocuments.length; entityPointer++ ) { - - let currentEntity = entityDocuments[entityPointer]; - //loop all the collections - for ( let currentModel in collections ) { - - let findQuery = { - "entityId": currentEntity._id - } - - let updateObject = { - "$set" : {} - }; - - //update query for project - if ( currentModel == "projects") { - updateObject["$set"]["entityId"] = currentEntity.registryDetails.locationId; - updateObject["$set"]["entityInformation._id"] = currentEntity.registryDetails.locationId; - updateObject["$set"]["entityInformation.externalId"] = currentEntity.registryDetails.code; - - } else if ( currentModel == "observationSubmissions" ) { - updateObject["$set"]["entityId"] = currentEntity.registryDetails.locationId; - updateObject["$set"]["entityExternalId"] = currentEntity.registryDetails.code; - updateObject["$set"]["entityInformation.externalId"] = currentEntity.registryDetails.code; - } - - //update the projects & observationSubmission collection - if ( updateObject && Object.keys(updateObject["$set"]).length > 0 ) { - let updateCollection = await db.collection(currentModel).updateMany(findQuery,updateObject); - } - } - } - } - - console.log("observations & projects collections updated") - - //update programs, solutions & observation collections - let otherCollections = { - "programs" : { - "query" : { - 'scope.entities':{$exists:true, $ne : []} - }, - "projection": { - 'scope.entities':1,_id:1 - } - }, - "observations" : { - "query" : { - entities:{$exists:true, $ne: []} - }, - "projection": { - entities:1,_id:1 - } - }, - "solutions.1" : { - "query" : { - 'scope.entities':{$exists:true, $ne : []} - }, - "projection": { - 'scope.entities':1,_id:1 - }, - "field": "scope.entities" - }, - "solutions.2" : { - "query" : { - 'entities':{$exists:true, $ne : []} - }, - "projection": { - entities:1,_id:1 - }, - "field": "entities" - } - - } - - //loop observation, solutions and programs collections - for ( let eachCollection in otherCollections ) { - - let getName = eachCollection.split("."); - let collectionName = getName[0]; - let otherCollectionDocs = await db.collection(collectionName).find(otherCollections[eachCollection].query).project(otherCollections[eachCollection].projection).toArray(); - let chunkOfOtherCollection = _.chunk(otherCollectionDocs, 10); - - for (let pointerToOtherCollection = 0; pointerToOtherCollection < chunkOfOtherCollection.length; pointerToOtherCollection++ ) { - let eachChunkCollections = chunkOfOtherCollection[pointerToOtherCollection]; - //loop each collection - for ( let pointerToChunk = 0; pointerToChunk < eachChunkCollections.length; pointerToChunk++ ) { - - let eachDocument = eachChunkCollections[pointerToChunk]; - let query = { - _id: eachDocument._id - } - - let updateQuery = { - "$set" : {} - } - - let eachEntityIds = []; - if ( eachCollection == "observations") { - eachEntityIds = eachDocument.entities; - } else if ( eachCollection == "programs" ) { - eachEntityIds = eachDocument.scope.entities; - } else if ( eachCollection == "solutions.1" && otherCollections[eachCollection].field == "scope.entities") { - eachEntityIds = eachDocument.scope.entities; - } else if ( eachCollection == "solutions.2" && otherCollections[eachCollection].field == "entities") { - eachEntityIds = eachDocument.entities; - } - - let entityIdToObjectId = await convertToObjectId(eachEntityIds); - //fetch entity - let entityDocs = await db.collection('entities').find({_id:{ $in : entityIdToObjectId}, registryDetails:{$exists:true}}).project({ - "registryDetails.locationId":1, - "registryDetails.code":1, - }).toArray(); - - let newEntityIds = []; - if ( entityDocs && entityDocs.length > 0 ) { - entityDocs.forEach( entity => { - newEntityIds.push(entity.registryDetails.locationId); - }) - } - - if ( eachCollection == "observations" ) { - updateQuery["$set"] = { - "entities" : newEntityIds - } - } else if ( eachCollection == "programs") { - updateQuery["$set"] = { - "scope.entities" : newEntityIds - } - } else if ( eachCollection == "solutions.1" && otherCollections[eachCollection].field == "scope.entities") { - updateQuery["$set"] = { - "scope.entities" : newEntityIds - } - } else if ( eachCollection == "solutions.2" && otherCollections[eachCollection].field == "entities") { - updateQuery["$set"] = { - "entities" : newEntityIds - } - } - - //update collection - if ( updateQuery && Object.keys(updateQuery["$set"]).length > 0 ) { - let updateCollections = await db.collection(collectionName).updateMany(query,updateQuery); - } - } - } - - console.log(eachCollection,"updated") - } - - //update observationInformation in project task - let projectDocument = await db.collection('projects').find({ - "tasks.type" : "observation", - "tasks.observationInformation":{$exists:true} - }).project({_id:1}).toArray(); - - let chunkOfProjectDocument = _.chunk(projectDocument, 10); - let projectIds; - - for (let pointerToProject = 0; pointerToProject < chunkOfProjectDocument.length; pointerToProject++) { - - projectIds = await chunkOfProjectDocument[pointerToProject].map( - projectDoc => { - return projectDoc._id; - } - ); - - let projectDocuments = await db.collection('projects').find({ - _id: { $in : projectIds } - }).project({ - "_id": 1, - "tasks._id" : 1, - "tasks.observationInformation" : 1 - }).toArray(); - - await Promise.all( - projectDocuments.map(async eachProject => { - - let tasks = eachProject.tasks; - for ( let taskCounter = 0; taskCounter < tasks.length; taskCounter++) { - let currentTask = tasks[taskCounter]; - if ( currentTask.observationInformation ) { - - let observationInformation = currentTask.observationInformation; - - let taskUpdateObject = { - "$set" : {} - }; - - if ( observationInformation.entityId ) { - - let entityDocuments = await db.collection('entities').find({_id: ObjectId(observationInformation.entityId) }).project({ - "registryDetails.locationId":1 - }).toArray(); - - if ( entityDocuments.length > 0 ) { - observationInformation.entityId = entityDocuments[0].registryDetails.locationId; - } - } - - taskUpdateObject["$set"]["tasks.$.observationInformation"] = observationInformation; - - if ( taskUpdateObject["$set"] && Object.keys(taskUpdateObject["$set"]).length > 0 ) { - - let updateTaskData = await db.collection('projects').findOneAndUpdate({ - "_id": eachProject._id, - "tasks._id": currentTask._id - }, taskUpdateObject); - } - } - } - })) - - } - console.log("project task updated") - console.log("completed") - - function convertToObjectId(ids){ - return ids.map(id => ObjectId(id)); - } - - connection.close(); - } - catch (error) { - console.log(error) - } -})().catch(err => console.error(err)); From ceb29cc51df0139afbd26e8ec150ae2d39501594 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Mon, 5 Sep 2022 09:57:23 +0530 Subject: [PATCH 173/331] search issue fixed for projects --- generics/services/improvement-project.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/generics/services/improvement-project.js b/generics/services/improvement-project.js index 6393c7f6..d975710d 100644 --- a/generics/services/improvement-project.js +++ b/generics/services/improvement-project.js @@ -7,6 +7,7 @@ //dependencies const request = require('request'); +const patternForDetectLang = /^[A-Za-z0-9]*$/; /** * List of user assigned projects. @@ -28,6 +29,11 @@ var assignedProjects = function ( token,search = "",filter = "" ) { if( filter !== "" ) { url = url + "&filter=" + filter; } + + //finding the type of language + if (!patternForDetectLang.test(search)) { + url = encodeURI(url); + } return new Promise(async (resolve, reject) => { try { From 09b382e5e8798c98f1d31d2af97f858096d2beb8 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 5 Sep 2022 10:16:00 +0530 Subject: [PATCH 174/331] script folder changes --- README.md | 7 ------- migrations/entity-generalisation-5.0/README.md | 7 +++++++ .../addEntityHierarchyInProjectsAndSubmissions.js} | 0 .../convertEntityIdToLocationId.js} | 0 4 files changed, 7 insertions(+), 7 deletions(-) create mode 100644 migrations/entity-generalisation-5.0/README.md rename migrations/{entity-5.0/addHeirarchy.js => entity-generalisation-5.0/addEntityHierarchyInProjectsAndSubmissions.js} (100%) rename migrations/{entity-5.0/entityToLocationId.js => entity-generalisation-5.0/convertEntityIdToLocationId.js} (100%) diff --git a/README.md b/README.md index 6a3d033b..8e2db83d 100644 --- a/README.md +++ b/README.md @@ -2,11 +2,4 @@ Centralised Service to support other Services. It is used by ml-survey and ml-project -### Migrations for entity generalization -Steps to run the migration files -- Navigate to migrations/entity-5.0/ folder -- The first script which convert mongoId to locationId. To run the script use the below command, - > run entityToLocationId.js -- Run the final script which add entity hierarchy to the existing observationSubmissions & project collections. - > run addHierarchy.js diff --git a/migrations/entity-generalisation-5.0/README.md b/migrations/entity-generalisation-5.0/README.md new file mode 100644 index 00000000..bba75cf5 --- /dev/null +++ b/migrations/entity-generalisation-5.0/README.md @@ -0,0 +1,7 @@ +### Migrations for entity generalization +Steps to run the migration files +- Navigate to migrations/entity-generalisation-5.0/ folder +- The first script which convert mongoId to locationId. To run the script use the below command, + > run convertEntityIdToLocationId.js +- Run the final script which add entity hierarchy to the existing observationSubmissions & project collections. + > run addEntityHierarchyInProjectsAndSubmissions.js \ No newline at end of file diff --git a/migrations/entity-5.0/addHeirarchy.js b/migrations/entity-generalisation-5.0/addEntityHierarchyInProjectsAndSubmissions.js similarity index 100% rename from migrations/entity-5.0/addHeirarchy.js rename to migrations/entity-generalisation-5.0/addEntityHierarchyInProjectsAndSubmissions.js diff --git a/migrations/entity-5.0/entityToLocationId.js b/migrations/entity-generalisation-5.0/convertEntityIdToLocationId.js similarity index 100% rename from migrations/entity-5.0/entityToLocationId.js rename to migrations/entity-generalisation-5.0/convertEntityIdToLocationId.js From ee53b74b8d65e2b467293af04df3257b07bf9884 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 5 Sep 2022 10:25:19 +0530 Subject: [PATCH 175/331] script readme change --- migrations/entity-generalisation-5.0/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/migrations/entity-generalisation-5.0/README.md b/migrations/entity-generalisation-5.0/README.md index bba75cf5..74a88505 100644 --- a/migrations/entity-generalisation-5.0/README.md +++ b/migrations/entity-generalisation-5.0/README.md @@ -1,7 +1,7 @@ -### Migrations for entity generalization +## Migrations for entity generalization Steps to run the migration files - Navigate to migrations/entity-generalisation-5.0/ folder - The first script which convert mongoId to locationId. To run the script use the below command, - > run convertEntityIdToLocationId.js + > node convertEntityIdToLocationId.js - Run the final script which add entity hierarchy to the existing observationSubmissions & project collections. - > run addEntityHierarchyInProjectsAndSubmissions.js \ No newline at end of file + > node addEntityHierarchyInProjectsAndSubmissions.js \ No newline at end of file From 047f9f54830ba96f73a3fe040ac44a47e9344d43 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Mon, 5 Sep 2022 11:09:21 +0530 Subject: [PATCH 176/331] migration fix --- .../addEntityHierarchyInProjectsAndSubmissions.js | 5 +---- .../entity-generalisation-5.0/convertEntityIdToLocationId.js | 2 +- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/migrations/entity-generalisation-5.0/addEntityHierarchyInProjectsAndSubmissions.js b/migrations/entity-generalisation-5.0/addEntityHierarchyInProjectsAndSubmissions.js index 31703057..cd6dd756 100644 --- a/migrations/entity-generalisation-5.0/addEntityHierarchyInProjectsAndSubmissions.js +++ b/migrations/entity-generalisation-5.0/addEntityHierarchyInProjectsAndSubmissions.js @@ -1,7 +1,7 @@ let _ = require("lodash"); const request = require('request'); const path = require("path"); -let rootPath = path.join(__dirname, '..') +let rootPath = path.join(__dirname, '../../') let endPoints = require(rootPath+'/generics/constants/endpoints') require('dotenv').config({ path: rootPath+'/.env' }) let MongoClient = require("mongodb").MongoClient; @@ -11,9 +11,6 @@ let mongoUrl = process.env.MONGODB_URL; let dbName = mongoUrl.split("/").pop(); let url = mongoUrl.split(dbName)[0]; - - - (async () => { let connection = await MongoClient.connect(url, { useNewUrlParser: true }); diff --git a/migrations/entity-generalisation-5.0/convertEntityIdToLocationId.js b/migrations/entity-generalisation-5.0/convertEntityIdToLocationId.js index c0888541..3773d265 100644 --- a/migrations/entity-generalisation-5.0/convertEntityIdToLocationId.js +++ b/migrations/entity-generalisation-5.0/convertEntityIdToLocationId.js @@ -6,7 +6,7 @@ */ const path = require("path"); -let rootPath = path.join(__dirname, '..') +let rootPath = path.join(__dirname, '../../') require('dotenv').config({ path: rootPath+'/.env' }) let _ = require("lodash"); let mongoUrl = process.env.MONGODB_URL; From 9427ba885956951951e29d1a7aec76dce228862d Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Tue, 6 Sep 2022 16:47:13 +0530 Subject: [PATCH 177/331] env variable change --- envVariables.js | 89 +++++++++++++++++++++++---------------- generics/services/form.js | 6 +-- 2 files changed, 55 insertions(+), 40 deletions(-) diff --git a/envVariables.js b/envVariables.js index 06e845c8..1d659041 100644 --- a/envVariables.js +++ b/envVariables.js @@ -142,52 +142,67 @@ let success = true; module.exports = function() { Object.keys(enviromentVariables).forEach(eachEnvironmentVariable=>{ - let tableObj = { [eachEnvironmentVariable] : "PASSED" }; + let tableObj = { + [eachEnvironmentVariable] : "PASSED" + }; + + let keyCheckPass = true; + - if( - enviromentVariables[eachEnvironmentVariable].requiredIf - && process.env[enviromentVariables[eachEnvironmentVariable].requiredIf.key] - && process.env[enviromentVariables[eachEnvironmentVariable].requiredIf.key] === enviromentVariables[eachEnvironmentVariable].requiredIf.value - ) { - enviromentVariables[eachEnvironmentVariable].optional = false; + if(enviromentVariables[eachEnvironmentVariable].optional === true + && enviromentVariables[eachEnvironmentVariable].requiredIf + && enviromentVariables[eachEnvironmentVariable].requiredIf.key + && enviromentVariables[eachEnvironmentVariable].requiredIf.key != "" + && enviromentVariables[eachEnvironmentVariable].requiredIf.operator + && validRequiredIfOperators.includes(enviromentVariables[eachEnvironmentVariable].requiredIf.operator) + && enviromentVariables[eachEnvironmentVariable].requiredIf.value + && enviromentVariables[eachEnvironmentVariable].requiredIf.value != "") { + switch (enviromentVariables[eachEnvironmentVariable].requiredIf.operator) { + case "EQUALS": + if(process.env[enviromentVariables[eachEnvironmentVariable].requiredIf.key] === enviromentVariables[eachEnvironmentVariable].requiredIf.value) { + enviromentVariables[eachEnvironmentVariable].optional = false; + } + break; + case "NOT_EQUALS": + if(process.env[enviromentVariables[eachEnvironmentVariable].requiredIf.key] != enviromentVariables[eachEnvironmentVariable].requiredIf.value) { + enviromentVariables[eachEnvironmentVariable].optional = false; + } + break; + default: + break; + } } - - if( - !process.env[eachEnvironmentVariable] && - !(enviromentVariables[eachEnvironmentVariable].optional) - ) { - success = false; - - if( - enviromentVariables[eachEnvironmentVariable].default && - enviromentVariables[eachEnvironmentVariable].default != "" - ) { - process.env[eachEnvironmentVariable] = - enviromentVariables[eachEnvironmentVariable].default; + if(enviromentVariables[eachEnvironmentVariable].optional === false) { + if(!(process.env[eachEnvironmentVariable]) + || process.env[eachEnvironmentVariable] == "") { + success = false; + keyCheckPass = false; + } else if (enviromentVariables[eachEnvironmentVariable].possibleValues + && Array.isArray(enviromentVariables[eachEnvironmentVariable].possibleValues) + && enviromentVariables[eachEnvironmentVariable].possibleValues.length > 0) { + if(!enviromentVariables[eachEnvironmentVariable].possibleValues.includes(process.env[eachEnvironmentVariable])) { + success = false; + keyCheckPass = false; + enviromentVariables[eachEnvironmentVariable].message += ` Valid values - ${enviromentVariables[eachEnvironmentVariable].possibleValues.join(", ")}` + } } + } + + if((!(process.env[eachEnvironmentVariable]) + || process.env[eachEnvironmentVariable] == "") + && enviromentVariables[eachEnvironmentVariable].default + && enviromentVariables[eachEnvironmentVariable].default != "") { + process.env[eachEnvironmentVariable] = enviromentVariables[eachEnvironmentVariable].default; + } - if( - enviromentVariables[eachEnvironmentVariable] && - enviromentVariables[eachEnvironmentVariable].message !== "" - ) { + if(!keyCheckPass) { + if(enviromentVariables[eachEnvironmentVariable].message !== "") { tableObj[eachEnvironmentVariable] = enviromentVariables[eachEnvironmentVariable].message; } else { - tableObj[eachEnvironmentVariable] = "required"; - } - - } else { - - tableObj[eachEnvironmentVariable] = "Passed"; - - if( - enviromentVariables[eachEnvironmentVariable].possibleValues && - !enviromentVariables[eachEnvironmentVariable].possibleValues.includes(process.env[eachEnvironmentVariable]) - ) { - tableObj[eachEnvironmentVariable] = ` Valid values - ${enviromentVariables[eachEnvironmentVariable].possibleValues.join(", ")}`; + tableObj[eachEnvironmentVariable] = `FAILED - ${eachEnvironmentVariable} is required`; } - } tableData.push(tableObj); diff --git a/generics/services/form.js b/generics/services/form.js index 324e16be..0f423c9b 100644 --- a/generics/services/form.js +++ b/generics/services/form.js @@ -7,7 +7,6 @@ //dependencies const request = require('request'); -const formServiceUrl = process.env.FORM_SERVICE_URL; /** * @function @@ -63,9 +62,10 @@ async function formRead ( stateLocationCode ) { action: constants.common.GET_METHOD } } - + const url = - formServiceUrl + constants.endpoints.GET_FORM_DATA; + process.env.FORM_SERVICE_URL + constants.endpoints.GET_FORM_DATA; + const options = { headers : { "content-type": "application/json", From 73b1e66fdd7946df3d70b380e77668b07f968046 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 9 Sep 2022 09:54:31 +0530 Subject: [PATCH 178/331] QA_issue_5 & 6 - targetedEntity --- controllers/v1/users.js | 4 +--- module/users/helper.js | 18 +++++++----------- 2 files changed, 8 insertions(+), 14 deletions(-) diff --git a/controllers/v1/users.js b/controllers/v1/users.js index fb66ec1f..813416ff 100644 --- a/controllers/v1/users.js +++ b/controllers/v1/users.js @@ -539,7 +539,6 @@ module.exports = class Users extends Abstract { roleWiseTargetedEntities.push(detailEntity.data); } } - //no targeted entity if ( roleWiseTargetedEntities.length == 0 ) { throw { @@ -566,8 +565,7 @@ module.exports = class Users extends Abstract { message: constants.apiResponses.ENTITIES_NOT_ALLOWED_IN_ROLE }; } - - targetedEntities.result = targetedEntity.data[0]; + targetedEntities.result = targetedEntity.data; } } diff --git a/module/users/helper.js b/module/users/helper.js index a5ba81b8..a358d2e5 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -375,8 +375,6 @@ module.exports = class UsersHelper { } else { subEntities = cacheData; } - - let roleEntityType = ""; rolesData[0].entityTypes.forEach(roleData => { @@ -735,10 +733,10 @@ module.exports = class UsersHelper { message: constants.apiResponses.USER_ROLES_NOT_FOUND }; } - + let requestedEntityTypes = Object.keys(_.omit(requestedData, ['role'])); let targetedEntityType = ""; - + rolesDocument[0].entityTypes.forEach((singleEntityType) => { if (requestedEntityTypes.includes(singleEntityType.entityType)) { targetedEntityType = singleEntityType.entityType; @@ -764,10 +762,7 @@ module.exports = class UsersHelper { } } else if ( targetedEntityType === constants.common.SCHOOL ) { targetedEntityType = constants.common.STATE_ENTITY_TYPE; - } else if ( targetedEntityType === constants.common.SCHOOL ) { - targetedEntityType = constants.common.STATE_ENTITY_TYPE; - } - + } } if (gen.utils.checkValidUUID(requestedData[targetedEntityType])) { @@ -823,6 +818,7 @@ module.exports = class UsersHelper { let entityKey = constants.common.SUBENTITY + requestedData.state; let subEntityTypes = []; let cacheData = await cache.getValue(entityKey); + if( !cacheData ) { let filterData = { "id" : requestedData.state @@ -847,11 +843,12 @@ module.exports = class UsersHelper { } else { subEntityTypes = cacheData; } + let targetedIndex = subEntityTypes.length; let roleWiseTarget; for( let roleWiseEntityIndex = 0; roleWiseEntityIndex < roleWiseTargetedEntities.length; roleWiseEntityIndex++ ) { - for( let subEntitiesIndex = 0; subEntitiesIndex < subEntities.length; subEntitiesIndex++ ) { - if( roleWiseTargetedEntities[roleWiseEntityIndex].entityType == subEntities[subEntitiesIndex] ) { + for( let subEntitiesIndex = 0; subEntitiesIndex < subEntityTypes.length; subEntitiesIndex++ ) { + if( roleWiseTargetedEntities[roleWiseEntityIndex].entityType == subEntityTypes[subEntitiesIndex] ) { if( subEntitiesIndex < targetedIndex) { targetedIndex = subEntitiesIndex; roleWiseTarget = roleWiseEntityIndex; @@ -859,7 +856,6 @@ module.exports = class UsersHelper { } } } - let targetedEntity = roleWiseTargetedEntities[roleWiseTarget]; return resolve({ message: constants.apiResponses.SOLUTION_TARGETED_ENTITY, From 6c04b58b6efb95069d4822c9ab6174093c632114 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Mon, 26 Sep 2022 09:09:49 +0530 Subject: [PATCH 179/331] program details --- controllers/v1/programs.js | 50 ++++++++++++++++++++++++++++++++++++++ module/programs/helper.js | 41 +++++++++++++++++++++++++++++++ module/solutions/helper.js | 2 +- 3 files changed, 92 insertions(+), 1 deletion(-) diff --git a/controllers/v1/programs.js b/controllers/v1/programs.js index ed739041..9992ab31 100644 --- a/controllers/v1/programs.js +++ b/controllers/v1/programs.js @@ -442,4 +442,54 @@ module.exports = class Programs extends Abstract { }); } + /** + * @api {get} /assessment/api/v1/programs/details/:programId Program Details + * @apiVersion 1.0.0 + * @apiName Program Details + * @apiGroup Programs + * @apiHeader {String} X-authenticated-user-token Authenticity token + * @apiSampleRequest /assessment/api/v1/programs/details/5ffbf8909259097d48017bbf + * @apiUse successBody + * @apiUse errorBody + * @apiParamExample {json} Response: + * { + "message": "Program details fetched successfully", + "status": 200, + "result": { + + } + } + */ + + /** + * Details of the program + * @method + * @name details + * @param {Object} req - requested data. + * @param {String} req.params._id - program id. + * @returns {Array} Program scope roles. + */ + + async details(req) { + return new Promise(async (resolve, reject) => { + try { + + let programData = await programsHelper.details( + req.params._id + ); + + programData["result"] = programData.data; + + return resolve(programData); + + } catch (error) { + return reject({ + status: error.status || httpStatusCode.internal_server_error.status, + message: error.message || httpStatusCode.internal_server_error.message, + errorObject: error + }); + } + }); + } + } \ No newline at end of file diff --git a/module/programs/helper.js b/module/programs/helper.js index 0c0d63f0..7698b109 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -933,6 +933,47 @@ module.exports = class ProgramsHelper { }) } }) + } + + /** + * Program details. + * @method + * @name details + * @param {String} programId - Program Id. + * @returns {Object} - Details of the program. + */ + + static details(programId) { + return new Promise(async (resolve, reject) => { + try { + + let programData = await this.programDocuments({ + _id: programId + }); + + if ( !programData.length > 0 ) { + return resolve({ + status: httpStatusCode.bad_request.status, + message: constants.apiResponses.PROGRAM_NOT_FOUND + }); + } + + return resolve({ + message: constants.apiResponses.PROGRAMS_FETCHED, + success: true, + data: programData[0] + }); + + } catch (error) { + return resolve({ + success: false, + status: error.status + ? error.status + : httpStatusCode['internal_server_error'].status, + message: error.message + }); + } + }); } }; diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 96a4b4cf..aa105885 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -1222,7 +1222,7 @@ module.exports = class SolutionsHelper { * Solution details. * @method * @name details - * @param {String} solutionId - Program Id. + * @param {String} solutionId - Solution Id. * @returns {Object} - Details of the solution. */ From 4e8b4d8011da40012723ccdf4d63481687a795a4 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Mon, 26 Sep 2022 18:09:51 +0530 Subject: [PATCH 180/331] admin controller --- config/db/mongodb.js | 7 +- controllers/v1/admin.js | 245 ++++++++++++++++++++++++++++ generics/constants/api-responses.js | 7 +- generics/constants/common.js | 5 +- 4 files changed, 260 insertions(+), 4 deletions(-) create mode 100644 controllers/v1/admin.js diff --git a/config/db/mongodb.js b/config/db/mongodb.js index 83095aa8..abace431 100644 --- a/config/db/mongodb.js +++ b/config/db/mongodb.js @@ -70,11 +70,16 @@ var databaseConfiguration = function () { return model; }; + var getCollection = function (modelName) { + return db.collection(modelName); + } + return { database: db, createModel: createModel, ObjectId: objectId, - models: db.models + models: db.models, + getCollection : getCollection }; }; diff --git a/controllers/v1/admin.js b/controllers/v1/admin.js new file mode 100644 index 00000000..66601dce --- /dev/null +++ b/controllers/v1/admin.js @@ -0,0 +1,245 @@ +/** + * name : admin.js + * author : Priyanka Pradeep + * created-date : 23-09-2022 + * Description : Admin Related information. + */ + + // Dependencies + const adminHelper = require(MODULES_BASE_PATH + "/admin/helper"); + + /** + * Admin + * @class + */ + module.exports = class Admin { + + static get name() { + return "admin"; + } + + /** + * @api {post} /kendra/api/v1/admin/dbFind/:collectionName + * List of data based on collection + * @apiVersion 1.0.0 + * @apiGroup Admin + * @apiSampleRequest /kendra/api/v1/admin/dbFind/projects + * @param {json} Request-Body: + * { + * "query" : { + "userId": "18155ae6-493d-4369-9668-165eb6dcaa2a", + "_id": "601921116ffa9c5e9d0b53e5" + }, + "projection" : ["title"], + "limit": 100, + "skip": 2 + } + * @apiParamExample {json} Response: + * { + "message": "Data Fetched Or Updated Successfully", + "status": 200, + "result": [ + { + "_id": "601921e86ffa9c5e9d0b53e7", + "title": "Please edit this project for submitting your Prerak Head Teacher of the Block-19-20 project" + }, + { + "_id": "60193ce26ffa9c5e9d0b53fe", + "title": "Please edit this project for submitting your Prerak Head Teacher of the Block-19-20 project" + } + ] + * } + * @apiUse successBody + * @apiUse errorBody + */ + + /** + * List of data based on collection + * @method + * @name dbFind + * @param {String} _id - MongoDB Collection Name + * @param {Object} req - Req Body + * @returns {JSON} list of data. + */ + + async dbFind(req) { + return new Promise(async (resolve, reject) => { + try { + + let result = await adminHelper.dbFind( + req.params._id, + req.body + ); + + return resolve(result); + + } catch (error) { + return reject({ + status: error.status || httpStatusCode.internal_server_error.status, + message: error.message || httpStatusCode.internal_server_error.message, + errorObject: error + }) + } + }) + } + + /** + * @api {post} /kendra/api/v1/admin/dbDelete/:collectionName + * Delete the data from collection + * @apiVersion 1.0.0 + * @apiGroup Admin + * @apiSampleRequest /kendra/api/v1/admin/dbDelete/projects + * @param {json} Request-Body: + * { + * "query" : { + * "_id": { $in : ["601921e86ffa9c5e9d0b53e7","60193ce26ffa9c5e9d0b53fe"]}, + } + * @apiParamExample {json} Response: + * { + "message": "Data deleted successfully", + "status": 200 + * } + * @apiUse successBody + * @apiUse errorBody + */ + + /** + * Delete the data from collection + * @method + * @name dbDelete + * @param {String} _id - MongoDB Collection Name + * @param {Object} req - Req Body + * @returns {JSON} list of data. + */ + + async dbDelete(req) { + return new Promise(async (resolve, reject) => { + try { + + let result = await adminHelper.dbDelete( + req.params._id, + req.body + ); + + return resolve(result); + + } catch (error) { + return reject({ + status: error.status || httpStatusCode.internal_server_error.status, + message: error.message || httpStatusCode.internal_server_error.message, + errorObject: error + }) + } + }) + } + + /** + * @api {post} /kendra/api/v1/admin/dbUpdate/:collectionName + * Update the data in collection + * @apiVersion 1.0.0 + * @apiGroup Admin + * @apiSampleRequest /kendra/api/v1/admin/dbUpdate/projects + * @param {json} Request-Body: + * { + * "query" : { + * "_id": { $in : ["601921e86ffa9c5e9d0b53e7","60193ce26ffa9c5e9d0b53fe"]}, + } + * @apiParamExample {json} Response: + * { + "message": "Data Updated successfully", + "status": 200 + * } + * @apiUse successBody + * @apiUse errorBody + */ + + /** + * Update the data in collection + * @method + * @name dbUpdate + * @param {String} _id - MongoDB Collection Name + * @param {Object} req - Req Body + * @returns {JSON} list of data. + */ + + async dbUpdate(req) { + return new Promise(async (resolve, reject) => { + try { + + let result = await adminHelper.dbUpdate( + req.params._id, + req.body + ); + + return resolve(result); + + } catch (error) { + return reject({ + status: error.status || httpStatusCode.internal_server_error.status, + message: error.message || httpStatusCode.internal_server_error.message, + errorObject: error + }) + } + }) + } + + /** + * @api {post} /kendra/api/v1/admin/dbCreate/:collectionName + * Create the new record + * @apiVersion 1.0.0 + * @apiGroup Admin + * @apiSampleRequest /kendra/api/v1/admin/dbCreate/apps + * @param {json} Request-Body: + * { + "name": "samiksha", + "displayName": "Samiksha", + "description": "Get the app to discover more", + "logo": "https://storage.googleapis.com/download/storage/v1/b/sl-dev-storage/o/static%2Fapps%2Fsamiksha.png?alt=media", + "playstoreLink": "https://play.google.com/store/apps/details?id=org.shikshalokam.samiksha", + "appStoreLink": "https://apps.apple.com/in/app/shikshalokam-samiksha/id1442066610" + } + * @apiParamExample {json} Response: + * { + "message": "Data Created successfully", + "status": 200, + "result" : { + "_id": "601921e86ffa9c5e9d0b53e7" + } + } + * } + * @apiUse successBody + * @apiUse errorBody + */ + + /** + * Create the new record + * @method + * @name dbCreate + * @param {String} _id - MongoDB Collection Name + * @param {Object} req - Req Body + * @returns {JSON} list of data. + */ + + async dbCreate(req) { + return new Promise(async (resolve, reject) => { + try { + + let result = await adminHelper.dbCreate( + req.params._id, + req.body + ); + + return resolve(result); + + } catch (error) { + return reject({ + status: error.status || httpStatusCode.internal_server_error.status, + message: error.message || httpStatusCode.internal_server_error.message, + errorObject: error + }) + } + }) + } + +}; + \ No newline at end of file diff --git a/generics/constants/api-responses.js b/generics/constants/api-responses.js index ba16ea5f..7f4fdd5a 100644 --- a/generics/constants/api-responses.js +++ b/generics/constants/api-responses.js @@ -181,6 +181,11 @@ module.exports = { "SOLUTION_TARGETED_ENTITY" : "Targeted Entity Types Fetched", "ENTITY_ID_OR_LOCATION_ID_NOT_FOUND" : "Entity id or location id not found", "NOT_AUTHORIZED_TO_ACCESS" :"You are not authorised to access this resource", - "NO_LOCATION_ID_FOUND_IN_DATA" : "Location Id not found in data" + "NO_LOCATION_ID_FOUND_IN_DATA" : "Location Id not found in data", + "QUERY_REQUIRED" : "required findQuery or updateQuery", + "DATA_FETCHED_SUCCESSFULLY" : "Data fetched successfully", + "DATA_DELETED_SUCCESSFULLY" : "Data deleted successfully", + "DATA_UPDATED_SUCCESSFULLY" : "Data updated successfully", + "FAILED_TO_CREATE_RECORD" : "Failed to create record in DB", }; diff --git a/generics/constants/common.js b/generics/constants/common.js index c66a84ac..c54a4b1c 100644 --- a/generics/constants/common.js +++ b/generics/constants/common.js @@ -70,6 +70,7 @@ module.exports = { "SUBENTITY" :"subEntityTypesOf_", "CACHE_TTL" : 43200, "PROFILE_CONFIG_FORM_KEY" : "profileConfig", - "SERVER_TIME_OUT" : 5000 - + "SERVER_TIME_OUT" : 5000, + "FIND" : "find", + "UPDATE" : "update" }; From 9a76eb887f3607b16011f56783c02ea9212b42ac Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Tue, 27 Sep 2022 14:47:51 +0530 Subject: [PATCH 181/331] admin apis --- controllers/v1/admin.js | 11 +- generics/helpers/utils.js | 7 +- module/admin/helper.js | 275 +++++++++++++++++++++++++++++++++++ module/admin/validator/v1.js | 34 +++++ 4 files changed, 324 insertions(+), 3 deletions(-) create mode 100644 module/admin/helper.js create mode 100644 module/admin/validator/v1.js diff --git a/controllers/v1/admin.js b/controllers/v1/admin.js index 66601dce..1a7bd3bb 100644 --- a/controllers/v1/admin.js +++ b/controllers/v1/admin.js @@ -93,6 +93,8 @@ * { * "query" : { * "_id": { $in : ["601921e86ffa9c5e9d0b53e7","60193ce26ffa9c5e9d0b53fe"]}, + }, + "mongoIdKeys" : ["_id"] } * @apiParamExample {json} Response: * { @@ -141,8 +143,13 @@ * @apiSampleRequest /kendra/api/v1/admin/dbUpdate/projects * @param {json} Request-Body: * { - * "query" : { - * "_id": { $in : ["601921e86ffa9c5e9d0b53e7","60193ce26ffa9c5e9d0b53fe"]}, + "findQuery": { + "_id": { "$in" : ["601921e86ffa9c5e9d0b53e7"] } + }, + "mongoIdKeys" : ["_id"], + "updateQuery" : { + "$set" : { "status": "started"} + } } * @apiParamExample {json} Response: * { diff --git a/generics/helpers/utils.js b/generics/helpers/utils.js index 52b8b06b..cd742ae6 100644 --- a/generics/helpers/utils.js +++ b/generics/helpers/utils.js @@ -258,6 +258,10 @@ function filterLocationIdandCode(dataArray) { }); } +function arrayIdsTobjectIds(ids) { + return ids.map(id => ObjectId(id)); +} + module.exports = { camelCaseToTitleCase : camelCaseToTitleCase, lowerCase : lowerCase, @@ -273,5 +277,6 @@ module.exports = { checkValidUUID : checkValidUUID, convertStringToBoolean : convertStringToBoolean, md5Hash : md5Hash, - filterLocationIdandCode : filterLocationIdandCode + filterLocationIdandCode : filterLocationIdandCode, + arrayIdsTobjectIds : arrayIdsTobjectIds }; diff --git a/module/admin/helper.js b/module/admin/helper.js new file mode 100644 index 00000000..46ec1b6a --- /dev/null +++ b/module/admin/helper.js @@ -0,0 +1,275 @@ +/** + * name : admin/helper.js + * author : Priyanka Pradeep + * created-date : 23-09-2022 + * Description : All admin related helper functions. + */ + +//Dependencies + +/** + * adminHelper + * @class +*/ + +module.exports = class adminHelper { + + /** + * List of data based on collection. + * @method + * @name list + * @param {Object} filterQueryObject - filter query data. + * @param {Object} [projection = {}] - projected data. + * @returns {Promise} returns a promise. + */ + + static list( + collection, + query = "all", + fields = "all", + skipFields = "none", + limitingValue = 100, + skippingValue = 0, + sortedData = "" + ) { + return new Promise(async (resolve, reject) => { + try { + + let queryObject = {}; + + if (query != "all") { + queryObject = query; + } + + let projectionObject = {}; + + if (fields != "all") { + + fields.forEach(element => { + projectionObject[element] = 1; + }); + } + + if (skipFields != "none") { + skipFields.forEach(element => { + projectionObject[element] = 0; + }); + } + + let mongoDBDocuments; + + if( sortedData !== "" ) { + + mongoDBDocuments = await database.getCollection(collection) + .find(queryObject) + .project(projectionObject) + .sort(sortedData) + .limit(limitingValue) + .toArray(); + + } else { + + mongoDBDocuments = await database.getCollection(collection) + .find(queryObject) + .project(projectionObject) + .skip(skippingValue) + .limit(limitingValue) + .toArray(); + } + + return resolve({ + success: true, + message: constants.apiResponses.DATA_FETCHED_SUCCESSFULLY, + data: mongoDBDocuments + }); + + } catch (error) { + return resolve({ + success: false, + message: error.message, + data: false + }); + } + }) + + + } + + + /** + * List of data based on collection + * @method + * @name dbFind + * @param {Object} reqBody - request body + * @returns {Object} - collection details. + */ + + static dbFind( collection, reqBody ) { + return new Promise(async (resolve, reject) => { + try { + + if ( reqBody.mongoIdKeys ) { + reqBody.query = await this.convertStringToObjectIdInQuery(reqBody.query, reqBody.mongoIdKeys); + } + + let mongoDBDocuments = await this.list( + collection, + reqBody.query, + reqBody.projection ? reqBody.projection : [], + "none", + reqBody.limit ? reqBody.limit : 100, + reqBody.skip ? reqBody.skip : 0 + + ); + + return resolve({ + message : constants.apiResponses.DATA_FETCHED_SUCCESSFULLY, + success : true, + result: mongoDBDocuments.data ? mongoDBDocuments.data : [] + }); + + } catch (error) { + return resolve({ + success: false, + message: error.message, + data: false + }); + } + }) + } + + /** + * Delete the data from collection + * @method + * @name dbDelete + * @param {Object} reqBody - request body + * @returns {Object} - collection details. + */ + + static dbDelete( collection, reqBody ) { + return new Promise(async (resolve, reject) => { + try { + + if ( reqBody.mongoIdKeys ) { + reqBody.query = await this.convertStringToObjectIdInQuery(reqBody.query, reqBody.mongoIdKeys); + } + + let deleteData = await database.getCollection(collection).deleteMany(reqBody.query); + + return resolve({ + message : constants.apiResponses.DATA_DELETED_SUCCESSFULLY, + success : true + }); + + } catch (error) { + return resolve({ + success: false, + message: error.message, + data: false + }); + } + }) + } + + /** + * Update the data in any model + * @method + * @name dbUpdate + * @param {Object} reqBody - request body + * @returns {Object} - collection details. + */ + + static dbUpdate( collection, reqBody ) { + return new Promise(async (resolve, reject) => { + try { + + if ( reqBody.mongoIdKeys ) { + reqBody.query = await this.convertStringToObjectIdInQuery(reqBody.findQuery, reqBody.mongoIdKeys); + } + + let updateData = await database.getCollection(collection).updateMany(reqBody.findQuery, reqBody.updateQuery); + + return resolve({ + message : constants.apiResponses.DATA_UPDATED_SUCCESSFULLY, + success : true + }); + + } catch (error) { + return resolve({ + success: false, + message: error.message, + data: false + }); + } + }) + } + + /** + * Create a new mongodb record + * @method + * @name dbCreate + * @param {Object} reqBody - request body + * @returns {Object} - collection details. + */ + + static dbCreate( collection, reqBody ) { + return new Promise(async (resolve, reject) => { + try { + + let insertData = await database.getCollection(collection).create(reqBody); + + if( !insertData._id ) { + throw { + message : constants.apiResponses.FAILED_TO_CREATE_RECORD + } + } + + return resolve({ + message : constants.apiResponses.DATA_UPDATED_SUCCESSFULLY, + success : true, + result : { + _id : insertData._id + } + }); + + } catch (error) { + return resolve({ + success: false, + message: error.message, + data: false + }); + } + }) + } + + /** + * Convert String to ObjectIds inside Query. + * @method + * @name convertStringToObjectIdInQuery + * @returns {Array} Query. + */ + + static convertStringToObjectIdInQuery(query, mongoIdKeys) { + + for ( let pointerToArray = 0; pointerToArray < mongoIdKeys.length; pointerToArray++ ) { + let eachKey = mongoIdKeys[pointerToArray]; + let currentQuery = query[eachKey]; + + if ( typeof(currentQuery) === "string") { + query[eachKey] = gen.utils.convertStringToObjectId(currentQuery); + } else if ( typeof(currentQuery) === "object") { + + let nestedKey = Object.keys(query[eachKey]); + if ( nestedKey ) { + let convertedIds = []; + nestedKey = nestedKey[0]; + query[eachKey][nestedKey] = gen.utils.arrayIdsTobjectIds(currentQuery[nestedKey]); + } + } + } + + return query; + } + +} + diff --git a/module/admin/validator/v1.js b/module/admin/validator/v1.js new file mode 100644 index 00000000..c19311b0 --- /dev/null +++ b/module/admin/validator/v1.js @@ -0,0 +1,34 @@ +/** + * name : v1.js + * author : Priyanka Pradeep + * created-date : 25-Sep-2022 + * Description : Admin validation. + */ + +module.exports = (req) => { + + let adminValidator = { + + dbFind : function () { + req.checkParams("_id").exists().withMessage("required mongodb collection name"); + req.checkBody("query").exists().withMessage("required mongoDB find query"); + }, + dbDelete : function () { + req.checkParams("_id").exists().withMessage("required mongodb collection name"); + req.checkBody("query").exists().withMessage("required mongoDB find query"); + }, + dbUpdate : function () { + req.checkParams("_id").exists().withMessage("required mongodb collection name"); + req.checkBody("findQuery").exists().withMessage("required mongoDB find query"); + req.checkBody("updateQuery").exists().withMessage("required mongoDB update query"); + }, + dbCreate : function () { + req.checkParams("_id").exists().withMessage("required mongodb collection name"); + }, + } + + if (adminValidator[req.params.method]) { + adminValidator[req.params.method](); + } + +}; \ No newline at end of file From cbda4823b93b92413c5f997399cdfa2c5153a463 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Tue, 27 Sep 2022 14:52:13 +0530 Subject: [PATCH 182/331] removed unwanted code --- generics/constants/api-responses.js | 2 +- generics/constants/common.js | 4 +--- module/admin/helper.js | 2 +- 3 files changed, 3 insertions(+), 5 deletions(-) diff --git a/generics/constants/api-responses.js b/generics/constants/api-responses.js index 7f4fdd5a..d3fe6e50 100644 --- a/generics/constants/api-responses.js +++ b/generics/constants/api-responses.js @@ -182,10 +182,10 @@ module.exports = { "ENTITY_ID_OR_LOCATION_ID_NOT_FOUND" : "Entity id or location id not found", "NOT_AUTHORIZED_TO_ACCESS" :"You are not authorised to access this resource", "NO_LOCATION_ID_FOUND_IN_DATA" : "Location Id not found in data", - "QUERY_REQUIRED" : "required findQuery or updateQuery", "DATA_FETCHED_SUCCESSFULLY" : "Data fetched successfully", "DATA_DELETED_SUCCESSFULLY" : "Data deleted successfully", "DATA_UPDATED_SUCCESSFULLY" : "Data updated successfully", + "DATA_CREATED_SUCCESSFULLY" : "Data created successfully", "FAILED_TO_CREATE_RECORD" : "Failed to create record in DB", }; diff --git a/generics/constants/common.js b/generics/constants/common.js index c54a4b1c..30e42fe7 100644 --- a/generics/constants/common.js +++ b/generics/constants/common.js @@ -70,7 +70,5 @@ module.exports = { "SUBENTITY" :"subEntityTypesOf_", "CACHE_TTL" : 43200, "PROFILE_CONFIG_FORM_KEY" : "profileConfig", - "SERVER_TIME_OUT" : 5000, - "FIND" : "find", - "UPDATE" : "update" + "SERVER_TIME_OUT" : 5000 }; diff --git a/module/admin/helper.js b/module/admin/helper.js index 46ec1b6a..809c117f 100644 --- a/module/admin/helper.js +++ b/module/admin/helper.js @@ -225,7 +225,7 @@ module.exports = class adminHelper { } return resolve({ - message : constants.apiResponses.DATA_UPDATED_SUCCESSFULLY, + message : constants.apiResponses.DATA_CREATED_SUCCESSFULLY, success : true, result : { _id : insertData._id From 25ad4c45f4e1315e33b011f28eb712eb4ce172c9 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Tue, 27 Sep 2022 14:57:11 +0530 Subject: [PATCH 183/331] authenticator file changes --- generics/middleware/authenticator.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/generics/middleware/authenticator.js b/generics/middleware/authenticator.js index b664f2ed..a3e8f87b 100644 --- a/generics/middleware/authenticator.js +++ b/generics/middleware/authenticator.js @@ -102,7 +102,12 @@ module.exports = async function (req, res, next) { "/solutions/addRolesInScope", "/solutions/addEntitiesInScope", "solutions/removeRolesInScope", - "/solutions/removeEntitiesInScope" + "/solutions/removeEntitiesInScope", + "/programs/details", + "/admin/dbUpdate", + "/admin/dbFind", + "/admin/dbDelete", + "/admin/dbCreate" ]; for(let path = 0; path < mandatoryInternalAccessApiPaths.length ; path++ ) { From 15a4fd858a6b69172bd43567defb9bc0ccac09ba Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Wed, 28 Sep 2022 17:23:52 +0530 Subject: [PATCH 184/331] commented dbDelete and dbUpdate --- module/admin/helper.js | 126 ++++++++++++++++++++--------------------- 1 file changed, 63 insertions(+), 63 deletions(-) diff --git a/module/admin/helper.js b/module/admin/helper.js index 809c117f..2c249c48 100644 --- a/module/admin/helper.js +++ b/module/admin/helper.js @@ -138,71 +138,71 @@ module.exports = class adminHelper { }) } - /** - * Delete the data from collection - * @method - * @name dbDelete - * @param {Object} reqBody - request body - * @returns {Object} - collection details. - */ - - static dbDelete( collection, reqBody ) { - return new Promise(async (resolve, reject) => { - try { - - if ( reqBody.mongoIdKeys ) { - reqBody.query = await this.convertStringToObjectIdInQuery(reqBody.query, reqBody.mongoIdKeys); - } + // /** + // * Delete the data from collection + // * @method + // * @name dbDelete + // * @param {Object} reqBody - request body + // * @returns {Object} - collection details. + // */ + + // static dbDelete( collection, reqBody ) { + // return new Promise(async (resolve, reject) => { + // try { + + // if ( reqBody.mongoIdKeys ) { + // reqBody.query = await this.convertStringToObjectIdInQuery(reqBody.query, reqBody.mongoIdKeys); + // } - let deleteData = await database.getCollection(collection).deleteMany(reqBody.query); - - return resolve({ - message : constants.apiResponses.DATA_DELETED_SUCCESSFULLY, - success : true - }); - - } catch (error) { - return resolve({ - success: false, - message: error.message, - data: false - }); - } - }) - } - - /** - * Update the data in any model - * @method - * @name dbUpdate - * @param {Object} reqBody - request body - * @returns {Object} - collection details. - */ - - static dbUpdate( collection, reqBody ) { - return new Promise(async (resolve, reject) => { - try { - - if ( reqBody.mongoIdKeys ) { - reqBody.query = await this.convertStringToObjectIdInQuery(reqBody.findQuery, reqBody.mongoIdKeys); - } - - let updateData = await database.getCollection(collection).updateMany(reqBody.findQuery, reqBody.updateQuery); + // let deleteData = await database.getCollection(collection).deleteMany(reqBody.query); + + // return resolve({ + // message : constants.apiResponses.DATA_DELETED_SUCCESSFULLY, + // success : true + // }); + + // } catch (error) { + // return resolve({ + // success: false, + // message: error.message, + // data: false + // }); + // } + // }) + // } + + // /** + // * Update the data in any model + // * @method + // * @name dbUpdate + // * @param {Object} reqBody - request body + // * @returns {Object} - collection details. + // */ + + // static dbUpdate( collection, reqBody ) { + // return new Promise(async (resolve, reject) => { + // try { + + // if ( reqBody.mongoIdKeys ) { + // reqBody.query = await this.convertStringToObjectIdInQuery(reqBody.findQuery, reqBody.mongoIdKeys); + // } + + // let updateData = await database.getCollection(collection).updateMany(reqBody.findQuery, reqBody.updateQuery); - return resolve({ - message : constants.apiResponses.DATA_UPDATED_SUCCESSFULLY, - success : true - }); - - } catch (error) { - return resolve({ - success: false, - message: error.message, - data: false - }); - } - }) - } + // return resolve({ + // message : constants.apiResponses.DATA_UPDATED_SUCCESSFULLY, + // success : true + // }); + + // } catch (error) { + // return resolve({ + // success: false, + // message: error.message, + // data: false + // }); + // } + // }) + // } /** * Create a new mongodb record From b6dbe2d8b7f11c7936b5b5bc7956306a33659365 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Wed, 28 Sep 2022 17:26:49 +0530 Subject: [PATCH 185/331] commented dbDelete and dbUpdate --- controllers/v1/admin.js | 208 ++++++++++++++++++++-------------------- 1 file changed, 104 insertions(+), 104 deletions(-) diff --git a/controllers/v1/admin.js b/controllers/v1/admin.js index 1a7bd3bb..10ea5bc9 100644 --- a/controllers/v1/admin.js +++ b/controllers/v1/admin.js @@ -83,112 +83,112 @@ }) } - /** - * @api {post} /kendra/api/v1/admin/dbDelete/:collectionName - * Delete the data from collection - * @apiVersion 1.0.0 - * @apiGroup Admin - * @apiSampleRequest /kendra/api/v1/admin/dbDelete/projects - * @param {json} Request-Body: - * { - * "query" : { - * "_id": { $in : ["601921e86ffa9c5e9d0b53e7","60193ce26ffa9c5e9d0b53fe"]}, - }, - "mongoIdKeys" : ["_id"] - } - * @apiParamExample {json} Response: - * { - "message": "Data deleted successfully", - "status": 200 - * } - * @apiUse successBody - * @apiUse errorBody - */ - - /** - * Delete the data from collection - * @method - * @name dbDelete - * @param {String} _id - MongoDB Collection Name - * @param {Object} req - Req Body - * @returns {JSON} list of data. - */ - - async dbDelete(req) { - return new Promise(async (resolve, reject) => { - try { - - let result = await adminHelper.dbDelete( - req.params._id, - req.body - ); - - return resolve(result); + // /** + // * @api {post} /kendra/api/v1/admin/dbDelete/:collectionName + // * Delete the data from collection + // * @apiVersion 1.0.0 + // * @apiGroup Admin + // * @apiSampleRequest /kendra/api/v1/admin/dbDelete/projects + // * @param {json} Request-Body: + // * { + // * "query" : { + // * "_id": { $in : ["601921e86ffa9c5e9d0b53e7","60193ce26ffa9c5e9d0b53fe"]}, + // }, + // "mongoIdKeys" : ["_id"] + // } + // * @apiParamExample {json} Response: + // * { + // "message": "Data deleted successfully", + // "status": 200 + // * } + // * @apiUse successBody + // * @apiUse errorBody + // */ + + // /** + // * Delete the data from collection + // * @method + // * @name dbDelete + // * @param {String} _id - MongoDB Collection Name + // * @param {Object} req - Req Body + // * @returns {JSON} list of data. + // */ + + // async dbDelete(req) { + // return new Promise(async (resolve, reject) => { + // try { + + // let result = await adminHelper.dbDelete( + // req.params._id, + // req.body + // ); + + // return resolve(result); - } catch (error) { - return reject({ - status: error.status || httpStatusCode.internal_server_error.status, - message: error.message || httpStatusCode.internal_server_error.message, - errorObject: error - }) - } - }) - } - - /** - * @api {post} /kendra/api/v1/admin/dbUpdate/:collectionName - * Update the data in collection - * @apiVersion 1.0.0 - * @apiGroup Admin - * @apiSampleRequest /kendra/api/v1/admin/dbUpdate/projects - * @param {json} Request-Body: - * { - "findQuery": { - "_id": { "$in" : ["601921e86ffa9c5e9d0b53e7"] } - }, - "mongoIdKeys" : ["_id"], - "updateQuery" : { - "$set" : { "status": "started"} - } - } - * @apiParamExample {json} Response: - * { - "message": "Data Updated successfully", - "status": 200 - * } - * @apiUse successBody - * @apiUse errorBody - */ - - /** - * Update the data in collection - * @method - * @name dbUpdate - * @param {String} _id - MongoDB Collection Name - * @param {Object} req - Req Body - * @returns {JSON} list of data. - */ - - async dbUpdate(req) { - return new Promise(async (resolve, reject) => { - try { - - let result = await adminHelper.dbUpdate( - req.params._id, - req.body - ); - - return resolve(result); + // } catch (error) { + // return reject({ + // status: error.status || httpStatusCode.internal_server_error.status, + // message: error.message || httpStatusCode.internal_server_error.message, + // errorObject: error + // }) + // } + // }) + // } + + // * + // * @api {post} /kendra/api/v1/admin/dbUpdate/:collectionName + // * Update the data in collection + // * @apiVersion 1.0.0 + // * @apiGroup Admin + // * @apiSampleRequest /kendra/api/v1/admin/dbUpdate/projects + // * @param {json} Request-Body: + // * { + // "findQuery": { + // "_id": { "$in" : ["601921e86ffa9c5e9d0b53e7"] } + // }, + // "mongoIdKeys" : ["_id"], + // "updateQuery" : { + // "$set" : { "status": "started"} + // } + // } + // * @apiParamExample {json} Response: + // * { + // "message": "Data Updated successfully", + // "status": 200 + // * } + // * @apiUse successBody + // * @apiUse errorBody + + + // /** + // * Update the data in collection + // * @method + // * @name dbUpdate + // * @param {String} _id - MongoDB Collection Name + // * @param {Object} req - Req Body + // * @returns {JSON} list of data. + // */ + + // async dbUpdate(req) { + // return new Promise(async (resolve, reject) => { + // try { + + // let result = await adminHelper.dbUpdate( + // req.params._id, + // req.body + // ); + + // return resolve(result); - } catch (error) { - return reject({ - status: error.status || httpStatusCode.internal_server_error.status, - message: error.message || httpStatusCode.internal_server_error.message, - errorObject: error - }) - } - }) - } + // } catch (error) { + // return reject({ + // status: error.status || httpStatusCode.internal_server_error.status, + // message: error.message || httpStatusCode.internal_server_error.message, + // errorObject: error + // }) + // } + // }) + // } /** * @api {post} /kendra/api/v1/admin/dbCreate/:collectionName From eea556bfeb31db265ca253b0f46a84c528ba7bb3 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 29 Sep 2022 19:15:04 +0530 Subject: [PATCH 186/331] certificate template apis added --- .env.sample | 3 + controllers/v1/certificateTemplates.js | 114 ++++++++++++++++++++ envVariables.js | 6 +- generics/constants/api-responses.js | 2 + models/certificateTemplates.js | 14 +++ module/certificateTemplates/helper.js | 93 ++++++++++++++++ module/certificateTemplates/validator/v1.js | 28 +++++ 7 files changed, 259 insertions(+), 1 deletion(-) create mode 100644 controllers/v1/certificateTemplates.js create mode 100644 models/certificateTemplates.js create mode 100644 module/certificateTemplates/helper.js create mode 100644 module/certificateTemplates/validator/v1.js diff --git a/.env.sample b/.env.sample index ff6a934c..10978e4c 100644 --- a/.env.sample +++ b/.env.sample @@ -43,3 +43,6 @@ CSV_REPORTS_PATH = "public/report" APP_PORTAL_BASE_URL = "https://dev.sunbirded.org" FORM_SERVICE_URL = "http://player:3000" // Base url for form search + +#CERTIFICATE_ISSUER_KID +CERTIFICATE_ISSUER_KID = "1-de2ed8d1-e8d8-40a9-b1ba-7694a16a4c8d" // This issuer Kid is used in sunbird RC end \ No newline at end of file diff --git a/controllers/v1/certificateTemplates.js b/controllers/v1/certificateTemplates.js new file mode 100644 index 00000000..bd46f120 --- /dev/null +++ b/controllers/v1/certificateTemplates.js @@ -0,0 +1,114 @@ +/** + * name : certificateTemplates.js + * author : Vishnu + * created-date : 29-Sep-2022 + * Description : Certificate template related information. +*/ + +// Dependencies +const certificateTemplateHelper = require(MODULES_BASE_PATH + "/certificateTemplates/helper"); + +module.exports = class CertificateTemplates extends Abstract { + // Adding model schema + constructor() { + super(schemas["certificateTemplates"]); + } + + /** + * @api {post} /kendra/api/v1/certificateTemplates/create + * @apiVersion 1.0.0 + * @apiName Create solution + * @apiGroup CreateTemplates + * @apiParamExample {json} Request-Body: + * <---- Add request body here-----> + * @apiHeader {String} internal-access-token - internal access token + * @apiHeader {String} X-authenticated-user-token - Authenticity token + * @apiSampleRequest /kendra/api/v1/certificateTemplates/create + * @apiUse successBody + * @apiUse errorBody + * @apiParamExample {json} Response: + * { + "status": 200, + "message": "Template added successfully", + "result": { + id": "6011136a2d25b926974d9ec9" + } + } + */ + + /** + * Create certificate template. + * @method + * @name create + * @param {Object} req - requested data. + * @returns {JSON} Created certificate template data. + */ + + async create(req) { + return new Promise(async (resolve, reject) => { + try { + let certificateTemplateData = await certificateTemplateHelper.create( req.body ); + certificateTemplateData["result"] = certificateTemplateData.data; + return resolve(certificateTemplateData); + + } catch (error) { + return reject({ + status: error.status || httpStatusCode.internal_server_error.status, + message: error.message || httpStatusCode.internal_server_error.message, + errorObject: error + }); + } + }); + } + + /** + * @api {patch} /kendra/api/v1/certificateTemplates/update/:certificate templateId + * @apiVersion 1.0.0 + * @apiName Update Certificate Template + * @apiGroup CreateTemplates + * @apiSampleRequest /kendra/api/v1/certificateTemplates/update/63358e94848b9be74d482b29 + * @apiHeader {String} internal-access-token internal access token + * @apiHeader {String} X-authenticated-user-token Authenticity token + * @apiUse successBody + * @apiUse errorBody + * @apiParamExample {json} Response: + * { + "status": 200, + "message": "Template updated successfully", + "result": { + id": "63358e94848b9be74d482b29" + } + } + */ + + /** + * Update certificate template. + * @method + * @name update + * @param {Object} req - requested data. + * @param {String} req.params._id - certificate template Id. + * @returns {JSON} Certificate updation status + */ + + async update(req) { + return new Promise(async (resolve, reject) => { + try { + + let certificateTemplateData = await certificateTemplateHelper.update( + req.params._id, + req.body, + ); + certificateTemplateData["result"] = certificateTemplateData.data; + return resolve(certificateTemplateData); + } + catch (error) { + reject({ + status: error.status || httpStatusCode.internal_server_error.status, + message: error.message || httpStatusCode.internal_server_error.message, + errorObject: error + }) + } + }) + } + +} \ No newline at end of file diff --git a/envVariables.js b/envVariables.js index 1d659041..3f8394e4 100644 --- a/envVariables.js +++ b/envVariables.js @@ -134,7 +134,11 @@ let enviromentVariables = { "message" : "Form service base url", "optional" : true, "default": "http://player:3000" - } + }, + "CERTIFICATE_ISSUER_KID": { + "message" : "Required certificate issuer kid", + "optional" : false + }, } let success = true; diff --git a/generics/constants/api-responses.js b/generics/constants/api-responses.js index d3fe6e50..b2db48b1 100644 --- a/generics/constants/api-responses.js +++ b/generics/constants/api-responses.js @@ -187,5 +187,7 @@ module.exports = { "DATA_UPDATED_SUCCESSFULLY" : "Data updated successfully", "DATA_CREATED_SUCCESSFULLY" : "Data created successfully", "FAILED_TO_CREATE_RECORD" : "Failed to create record in DB", + "CERTIFICATE_TEMPLATE_ADDED" : "Template added successfully", + "CERTIFICATE_TEMPLATE_UPDATED" : "Template updated successfully" }; diff --git a/models/certificateTemplates.js b/models/certificateTemplates.js new file mode 100644 index 00000000..68af69f6 --- /dev/null +++ b/models/certificateTemplates.js @@ -0,0 +1,14 @@ +module.exports = { + name: "certificateTemplates", + schema: { + templateUrl: { + type : String, + index : true + }, + issuer: Object, + status: String, + solutionId: String, + programId: String, + criteria: Object + } + }; \ No newline at end of file diff --git a/module/certificateTemplates/helper.js b/module/certificateTemplates/helper.js new file mode 100644 index 00000000..87ebfe00 --- /dev/null +++ b/module/certificateTemplates/helper.js @@ -0,0 +1,93 @@ +/** + * name : helper.js + * author : Vishnu + * created-date : 29-sep-2022 + * Description : Certificate Template related helper functionality. +*/ + +const { ObjectId } = require("mongodb"); + +/** + * CertificateTemplatesHelper + * @class +*/ +module.exports = class CertificateTemplatesHelper { + + /** + * Create certificate template. + * @method create + * @name create + * @param {Object} data - certificate template creation data. + * @returns {JSON} created certificate template details. + */ + + static create(data) { + return new Promise(async (resolve, reject) => { + try { + data.issuer.kid = process.env.CERTIFICATE_ISSUER_KID; + let certificateTemplateCreated = + await database.models.certificateTemplates.create( + data + ); + return resolve({ + message : constants.apiResponses.CERTIFICATE_TEMPLATE_ADDED, + data : { + id : certificateTemplateCreated._id + } + }); + + } catch (error) { + return reject(error); + } + }); + } + + /** + * Update certificate template. + * @method update + * @name update + * @param {String} templateId - certificate template Id. + * @param {Object} data - certificate template updation data. + * @returns {JSON} Updated certificate template details. + */ + + static update(templateId, data) { + return new Promise(async (resolve, reject) => { + try { + // Adding issuer kid from env + if ( data.issuer ) { + data.issuer.kid = process.env.CERTIFICATE_ISSUER_KID; + } + // If templateUrl value passed as empty string. + if ( !data.templateUrl ) { + delete data.templateUrl; + } + // If solutionId value passed as empty string. + if ( !data.solutionId ) { + delete data.solutionId; + } + // If programId value passed as empty string. + if ( !data.programId ) { + delete data.programId; + } + let updateObject = { + "$set" : data + }; + let certificateTemplateUpdated = + await database.models.certificateTemplates.findOneAndUpdate( + {_id: templateId}, + updateObject + ); + return resolve({ + message : constants.apiResponses.CERTIFICATE_TEMPLATE_UPDATED, + data : { + id : certificateTemplateUpdated._id + } + }); + + } catch (error) { + return reject(error); + } + }); + } +} diff --git a/module/certificateTemplates/validator/v1.js b/module/certificateTemplates/validator/v1.js new file mode 100644 index 00000000..0d18cb97 --- /dev/null +++ b/module/certificateTemplates/validator/v1.js @@ -0,0 +1,28 @@ +/** + * name : v1.js + * author : Vishnu + * created-date : 29-Sep-2022 + * Description : Certificate Template Validation. +*/ + +module.exports = (req) => { + + let certificateTemplatesValidator = { + + create : function () { + req.checkBody('templateUrl', 'templateUrl is required').exists({checkFalsy: true}).isLength({ min: 1 }); + req.checkBody('solutionId', 'solutionId is required').exists({checkFalsy: true}).isLength({ min: 1 }); + req.checkBody('programId', 'programId is required').exists({checkFalsy: true}).isLength({ min: 1 }); + req.checkBody("issuer").exists().withMessage("issuer is required"); + req.checkBody("criteria").exists().withMessage("criteria is required"); + }, + update : function () { + req.checkParams("_id").exists().withMessage("required certificate templateId"); + }, + } + + if (certificateTemplatesValidator[req.params.method]) { + certificateTemplatesValidator[req.params.method](); + } + +}; \ No newline at end of file From 4f88e28d1e90ca261a24b1dc11504d6443a437c0 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 3 Oct 2022 21:52:20 +0530 Subject: [PATCH 187/331] mapping certificate template to solution and project --- models/certificateTemplates.js | 4 ++-- models/solutions.js | 3 ++- module/users/helper.js | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/models/certificateTemplates.js b/models/certificateTemplates.js index 68af69f6..dc986286 100644 --- a/models/certificateTemplates.js +++ b/models/certificateTemplates.js @@ -7,8 +7,8 @@ module.exports = { }, issuer: Object, status: String, - solutionId: String, - programId: String, + solutionId: "ObjectId", + programId: "ObjectId", criteria: Object } }; \ No newline at end of file diff --git a/models/solutions.js b/models/solutions.js index fe7bf6c3..389027a7 100644 --- a/models/solutions.js +++ b/models/solutions.js @@ -99,6 +99,7 @@ module.exports = { type: Number, default: 1 }, - reportInformation : Object + reportInformation : Object, + certificateTemplateId : "ObjectId" } }; \ No newline at end of file diff --git a/module/users/helper.js b/module/users/helper.js index a358d2e5..b7d3c3b1 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -216,7 +216,7 @@ module.exports = class UsersHelper { { _id: data.solutionId, }, - ["name", "link", "type", "subType", "externalId", "description"] + ["name", "link", "type", "subType", "externalId", "description", "certificateTemplateId"] ); if ( !solutionData.length > 0 ) { From 67f1c27ca4cefd344ca3f2002670a607fb49b161 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 6 Oct 2022 11:49:38 +0530 Subject: [PATCH 188/331] certificate template api changes --- controllers/v1/certificateTemplates.js | 71 ++++----------------- models/certificateTemplates.js | 12 ++-- module/certificateTemplates/validator/v1.js | 20 +++--- 3 files changed, 31 insertions(+), 72 deletions(-) diff --git a/controllers/v1/certificateTemplates.js b/controllers/v1/certificateTemplates.js index bd46f120..4c2a7045 100644 --- a/controllers/v1/certificateTemplates.js +++ b/controllers/v1/certificateTemplates.js @@ -15,7 +15,7 @@ module.exports = class CertificateTemplates extends Abstract { } /** - * @api {post} /kendra/api/v1/certificateTemplates/create + * @api {post/patch} /kendra/api/v1/certificateTemplates/create * @apiVersion 1.0.0 * @apiName Create solution * @apiGroup CreateTemplates @@ -37,7 +37,7 @@ module.exports = class CertificateTemplates extends Abstract { */ /** - * Create certificate template. + * Create/update certificate template. * @method * @name create * @param {Object} req - requested data. @@ -47,10 +47,18 @@ module.exports = class CertificateTemplates extends Abstract { async create(req) { return new Promise(async (resolve, reject) => { try { - let certificateTemplateData = await certificateTemplateHelper.create( req.body ); - certificateTemplateData["result"] = certificateTemplateData.data; - return resolve(certificateTemplateData); - + if ( req.method === "POST" ) { + let certificateTemplateData = await certificateTemplateHelper.create( req.body ); + certificateTemplateData["result"] = certificateTemplateData.data; + return resolve(certificateTemplateData); + } else if ( req.method === "PATCH" ) { + let certificateTemplateData = await certificateTemplateHelper.update( + req.params._id, + req.body, + ); + certificateTemplateData["result"] = certificateTemplateData.data; + return resolve(certificateTemplateData); + } } catch (error) { return reject({ status: error.status || httpStatusCode.internal_server_error.status, @@ -60,55 +68,4 @@ module.exports = class CertificateTemplates extends Abstract { } }); } - - /** - * @api {patch} /kendra/api/v1/certificateTemplates/update/:certificate templateId - * @apiVersion 1.0.0 - * @apiName Update Certificate Template - * @apiGroup CreateTemplates - * @apiSampleRequest /kendra/api/v1/certificateTemplates/update/63358e94848b9be74d482b29 - * @apiHeader {String} internal-access-token internal access token - * @apiHeader {String} X-authenticated-user-token Authenticity token - * @apiUse successBody - * @apiUse errorBody - * @apiParamExample {json} Response: - * { - "status": 200, - "message": "Template updated successfully", - "result": { - id": "63358e94848b9be74d482b29" - } - } - */ - - /** - * Update certificate template. - * @method - * @name update - * @param {Object} req - requested data. - * @param {String} req.params._id - certificate template Id. - * @returns {JSON} Certificate updation status - */ - - async update(req) { - return new Promise(async (resolve, reject) => { - try { - - let certificateTemplateData = await certificateTemplateHelper.update( - req.params._id, - req.body, - ); - certificateTemplateData["result"] = certificateTemplateData.data; - return resolve(certificateTemplateData); - } - catch (error) { - reject({ - status: error.status || httpStatusCode.internal_server_error.status, - message: error.message || httpStatusCode.internal_server_error.message, - errorObject: error - }) - } - }) - } - } \ No newline at end of file diff --git a/models/certificateTemplates.js b/models/certificateTemplates.js index dc986286..8071a48f 100644 --- a/models/certificateTemplates.js +++ b/models/certificateTemplates.js @@ -1,14 +1,14 @@ module.exports = { name: "certificateTemplates", schema: { - templateUrl: { - type : String, - index : true - }, + templateUrl: String, issuer: Object, status: String, - solutionId: "ObjectId", + solutionId: { + type : "ObjectId", + index : true + }, programId: "ObjectId", criteria: Object } - }; \ No newline at end of file +}; \ No newline at end of file diff --git a/module/certificateTemplates/validator/v1.js b/module/certificateTemplates/validator/v1.js index 0d18cb97..0571088c 100644 --- a/module/certificateTemplates/validator/v1.js +++ b/module/certificateTemplates/validator/v1.js @@ -10,15 +10,17 @@ module.exports = (req) => { let certificateTemplatesValidator = { create : function () { - req.checkBody('templateUrl', 'templateUrl is required').exists({checkFalsy: true}).isLength({ min: 1 }); - req.checkBody('solutionId', 'solutionId is required').exists({checkFalsy: true}).isLength({ min: 1 }); - req.checkBody('programId', 'programId is required').exists({checkFalsy: true}).isLength({ min: 1 }); - req.checkBody("issuer").exists().withMessage("issuer is required"); - req.checkBody("criteria").exists().withMessage("criteria is required"); - }, - update : function () { - req.checkParams("_id").exists().withMessage("required certificate templateId"); - }, + if ( req.method === "POST" ) { + req.checkBody('templateUrl', 'templateUrl is required').exists({checkFalsy: true}).isLength({ min: 1 }); + req.checkBody('solutionId', 'solutionId is required').exists({checkFalsy: true}).isLength({ min: 1 }); + req.checkBody('programId', 'programId is required').exists({checkFalsy: true}).isLength({ min: 1 }); + req.checkBody("issuer").exists().withMessage("issuer is required"); + req.checkBody("criteria").exists().withMessage("criteria is required"); + } else if ( req.method === "PATCH" ) { + req.checkParams("_id").exists().withMessage("required certificate templateId"); + } + + } } if (certificateTemplatesValidator[req.params.method]) { From 10d140f247635e4dac268d285958ab0bdb448bb6 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 6 Oct 2022 20:10:07 +0530 Subject: [PATCH 189/331] certificate template upload api added --- controllers/v1/certificateTemplates.js | 132 +++++++++++++++++++- generics/constants/common.js | 3 +- models/certificateTemplates.js | 10 +- module/certificateTemplates/helper.js | 78 +++++++++++- module/certificateTemplates/validator/v1.js | 1 + module/cloud-services/files/helper.js | 4 +- 6 files changed, 219 insertions(+), 9 deletions(-) diff --git a/controllers/v1/certificateTemplates.js b/controllers/v1/certificateTemplates.js index 4c2a7045..692d7ad2 100644 --- a/controllers/v1/certificateTemplates.js +++ b/controllers/v1/certificateTemplates.js @@ -17,10 +17,76 @@ module.exports = class CertificateTemplates extends Abstract { /** * @api {post/patch} /kendra/api/v1/certificateTemplates/create * @apiVersion 1.0.0 - * @apiName Create solution + * @apiName Create certificate template * @apiGroup CreateTemplates * @apiParamExample {json} Request-Body: - * <---- Add request body here-----> + * { "templateUrl" :"certificate/template/ba9aa220-ff1b-4717-b6ea-ace55f04fc16/c9dbee8d-8c0b-4e0d-9d10-37d4a8f6afc6/wow.svg", + "criteria" : { + "validationText" : "Complete validation message", + "expression" : "C1&&C2&&C3", + "conditions" : { + "C1" : { + "validationText" : "Project Should be submitted within program Enddate", + "expression" : "C1&&C2", + "conditions" : { + "C1" : { + "scope" : "project", + "key" : "status", + "operator" : "==", + "value" : "submitted" + }, + "C2" : { + "scope" : "project", + "key" : "completedDate", + "operator" : "<", + "value" : "15-08-2022" + } + } + }, + "C2" : { + "validationText" : "Evidence project level validation", + "expression" : "C1", + "conditions" : { + "C1" : { + "scope" : "project", + "key" : "attachments", + "function" : "count", + "filter" : { + "key" : "type", + "value" : "all" + }, + "operator" : ">", + "value" : 1 + } + } + }, + "C3" : { + "validationText" : "Evidence task level validation", + "expression" : "C1&&C2&&C3", + "conditions" : { + "C1" : { + "scope" : "task", + "key" : "attachments", + "function" : "count", + "filter" : { + "key" : "type", + "value" : "all" + }, + "operator" : ">", + "value" : 1 + } + } + } + } + }, + "issuer": { + "name":"Kerala" + }, + "status" : "active", + "solutionId" : "5ff9dc1b9259097d48017bbe", + "programId" : "605083ba09b7bd61555580fb" + + } * @apiHeader {String} internal-access-token - internal access token * @apiHeader {String} X-authenticated-user-token - Authenticity token * @apiSampleRequest /kendra/api/v1/certificateTemplates/create @@ -68,4 +134,66 @@ module.exports = class CertificateTemplates extends Abstract { } }); } + + /** + * @api {post} /kendra/api/v1/certificateTemplates/uploadCertificateTemplate + * @apiVersion 1.0.0 + * @apiName upload certificate template + * @apiGroup uploadCertificateTemplate + * @apiHeader {String} internal-access-token - internal access token + * @apiHeader {String} X-authenticated-user-token - Authenticity token + * @apiSampleRequest /kendra/api/v1/certificateTemplates/uploadCertificateTemplate + * @apiUse successBody + * @apiUse errorBody + * @apiParamExample {json} Response: + * { + "message": "File uploaded successfully", + "status": 200, + "result": { + "success": true, + "data": { + "templateUrl": "certificate/template/ba9aa220-ff1b-4717-b6ea-ace55f04fc16/c9dbee8d-8c0b-4e0d-9d10-37d4a8f6afc6/template.svg" + } + } + } + */ + + /** + * uploadCertificateTemplate. + * @method + * @name uploadCertificateTemplate + * @param {Object} req - requested data. + * @returns {JSON} file uploaded details. + */ + + async uploadCertificateTemplate(req) { + return new Promise(async (resolve, reject) => { + try { + + if ( req.files && req.files.file ) { + let uploadedTemplateDetails = + await certificateTemplateHelper.uploadToCloud( + req.files, + req.userDetails ? req.userDetails.userId : "" + ); + return resolve({ + message: constants.apiResponses.FILE_UPLOADED, + result: uploadedTemplateDetails + }) + } else { + return reject({ + status: httpStatusCode["bad_request"].status, + message: httpStatusCode["bad_request"].message + + }); + } + } catch (error) { + return reject({ + status: error.status || httpStatusCode.internal_server_error.status, + message: error.message || httpStatusCode.internal_server_error.message, + errorObject: error + }); + } + }); + } } \ No newline at end of file diff --git a/generics/constants/common.js b/generics/constants/common.js index 30e42fe7..976fa10f 100644 --- a/generics/constants/common.js +++ b/generics/constants/common.js @@ -70,5 +70,6 @@ module.exports = { "SUBENTITY" :"subEntityTypesOf_", "CACHE_TTL" : 43200, "PROFILE_CONFIG_FORM_KEY" : "profileConfig", - "SERVER_TIME_OUT" : 5000 + "SERVER_TIME_OUT" : 5000, + "CERTIFICATE" : "certificate" }; diff --git a/models/certificateTemplates.js b/models/certificateTemplates.js index 8071a48f..e7b76cf1 100644 --- a/models/certificateTemplates.js +++ b/models/certificateTemplates.js @@ -3,12 +3,18 @@ module.exports = { schema: { templateUrl: String, issuer: Object, - status: String, + status: { + type : String, + required : true + }, solutionId: { type : "ObjectId", index : true }, programId: "ObjectId", - criteria: Object + criteria: { + type : Object, + required : true + } } }; \ No newline at end of file diff --git a/module/certificateTemplates/helper.js b/module/certificateTemplates/helper.js index 87ebfe00..e06cf1ed 100644 --- a/module/certificateTemplates/helper.js +++ b/module/certificateTemplates/helper.js @@ -4,6 +4,9 @@ * created-date : 29-sep-2022 * Description : Certificate Template related helper functionality. */ +// dependencies +const filesHelpers = require(ROOT_PATH+"/module/cloud-services/files/helper"); +const request = require("request"); const { ObjectId } = require("mongodb"); @@ -49,9 +52,9 @@ module.exports = class CertificateTemplatesHelper { * @param {String} templateId - certificate template Id. * @param {Object} data - certificate template updation data. * @returns {JSON} Updated certificate template details. - */ + */ - static update(templateId, data) { + static update(templateId, data) { return new Promise(async (resolve, reject) => { try { // Adding issuer kid from env @@ -88,6 +91,75 @@ module.exports = class CertificateTemplatesHelper { } catch (error) { return reject(error); } - }); + }); + } + + /** + * upload certificate template. + * @method uploadToCloud + * @name uploadToCloud + * @param {Object} fileData - file to upload. + * @param {String} userId - user Id. + * @returns {JSON} Uploaded certificate template details. + */ + + static uploadToCloud(fileData, userId = "") { + return new Promise(async (resolve, reject) => { + try { + const requestData = { + "template": { + "files": [fileData.file.name] + } + }; + let signedUrl = + await filesHelpers.preSignedUrls( + requestData, + constants.common.CERTIFICATE, + userId + ); + + // upload file using signed Url + if (signedUrl.data && + Object.keys(signedUrl.data).length > 0 && + signedUrl.data.template && + signedUrl.data.template.files.length > 0 && + signedUrl.data.template.files[0].url && + signedUrl.data.template.files[0].url !== "" + ) { + + let fileUploadUrl = signedUrl.data.template.files[0].url; + let file = fileData.file.data; + + try { + await request({ + url: fileUploadUrl, + method: 'put', + headers: { + "x-ms-blob-type" : "BlockBlob", + "Content-Type": "multipart/form-data" + }, + body: file + }) + + return resolve({ + success: true, + data: { + templateUrl: signedUrl.data.template.files[0].payload.sourcePath + } + }) + + } catch (error) { + return reject(error); + } + } + else { + return resolve({ + success: false + }) + } + } catch (error) { + return reject(error); + } + }); } } diff --git a/module/certificateTemplates/validator/v1.js b/module/certificateTemplates/validator/v1.js index 0571088c..7f442a5d 100644 --- a/module/certificateTemplates/validator/v1.js +++ b/module/certificateTemplates/validator/v1.js @@ -16,6 +16,7 @@ module.exports = (req) => { req.checkBody('programId', 'programId is required').exists({checkFalsy: true}).isLength({ min: 1 }); req.checkBody("issuer").exists().withMessage("issuer is required"); req.checkBody("criteria").exists().withMessage("criteria is required"); + req.checkBody("status").exists().withMessage("status is required"); } else if ( req.method === "PATCH" ) { req.checkParams("_id").exists().withMessage("required certificate templateId"); } diff --git a/module/cloud-services/files/helper.js b/module/cloud-services/files/helper.js index d0444ff2..3cc4dcd9 100644 --- a/module/cloud-services/files/helper.js +++ b/module/cloud-services/files/helper.js @@ -83,7 +83,9 @@ module.exports = class FilesHelper { if (referenceType == constants.common.DHITI) { folderPath = "reports/" - + } else if (referenceType == constants.common.CERTIFICATE) { + // Folder path specifically for project certificates + folderPath = "certificate/" + payloadIds[0] + "/" + userId + "/" + gen.utils.generateUniqueId() + "/"; } else { folderPath = "survey/" + payloadIds[0] + "/" + userId + "/" + gen.utils.generateUniqueId() + "/"; } From 4213b9aba673f3561d435a45fa7adccbc570ae68 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 7 Oct 2022 09:28:58 +0530 Subject: [PATCH 190/331] templateUrl property changed --- models/certificateTemplates.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/models/certificateTemplates.js b/models/certificateTemplates.js index e7b76cf1..12f9ab1f 100644 --- a/models/certificateTemplates.js +++ b/models/certificateTemplates.js @@ -1,7 +1,10 @@ module.exports = { name: "certificateTemplates", schema: { - templateUrl: String, + templateUrl: { + type : String, + required : true + }, issuer: Object, status: { type : String, From 4ef1f1251910d7ee5c927a6f124bfcbf007b6f47 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 7 Oct 2022 13:46:03 +0530 Subject: [PATCH 191/331] templateUrl auto update added to template upload api --- controllers/v1/certificateTemplates.js | 3 +- models/certificateTemplates.js | 5 +-- module/certificateTemplates/helper.js | 36 ++++++++++++++------- module/certificateTemplates/validator/v1.js | 4 ++- module/cloud-services/files/helper.js | 5 +-- 5 files changed, 34 insertions(+), 19 deletions(-) diff --git a/controllers/v1/certificateTemplates.js b/controllers/v1/certificateTemplates.js index 692d7ad2..3eafce37 100644 --- a/controllers/v1/certificateTemplates.js +++ b/controllers/v1/certificateTemplates.js @@ -173,7 +173,8 @@ module.exports = class CertificateTemplates extends Abstract { if ( req.files && req.files.file ) { let uploadedTemplateDetails = await certificateTemplateHelper.uploadToCloud( - req.files, + req.files, + req.params._id, req.userDetails ? req.userDetails.userId : "" ); return resolve({ diff --git a/models/certificateTemplates.js b/models/certificateTemplates.js index 12f9ab1f..e7b76cf1 100644 --- a/models/certificateTemplates.js +++ b/models/certificateTemplates.js @@ -1,10 +1,7 @@ module.exports = { name: "certificateTemplates", schema: { - templateUrl: { - type : String, - required : true - }, + templateUrl: String, issuer: Object, status: { type : String, diff --git a/module/certificateTemplates/helper.js b/module/certificateTemplates/helper.js index e06cf1ed..786cc9d2 100644 --- a/module/certificateTemplates/helper.js +++ b/module/certificateTemplates/helper.js @@ -99,35 +99,41 @@ module.exports = class CertificateTemplatesHelper { * @method uploadToCloud * @name uploadToCloud * @param {Object} fileData - file to upload. - * @param {String} userId - user Id. + * @param {String} templateId - templateId. + * @param {String} userId - user Id. * @returns {JSON} Uploaded certificate template details. */ - static uploadToCloud(fileData, userId = "") { + static uploadToCloud(fileData, templateId, userId = "") { return new Promise(async (resolve, reject) => { try { + const now = new Date(); + const date = now.getFullYear() + "-"+ now.getMonth() + "-" + now.getDate() + "-" + now.getTime(); + const fileName = userId + "_" + date + ".svg"; const requestData = { - "template": { - "files": [fileData.file.name] + "templates": { + "files": [fileName] } }; + let signedUrl = await filesHelpers.preSignedUrls( requestData, constants.common.CERTIFICATE, - userId + userId, + templateId ); // upload file using signed Url if (signedUrl.data && Object.keys(signedUrl.data).length > 0 && - signedUrl.data.template && - signedUrl.data.template.files.length > 0 && - signedUrl.data.template.files[0].url && - signedUrl.data.template.files[0].url !== "" + signedUrl.data.templates && + signedUrl.data.templates.files.length > 0 && + signedUrl.data.templates.files[0].url && + signedUrl.data.templates.files[0].url !== "" ) { - let fileUploadUrl = signedUrl.data.template.files[0].url; + let fileUploadUrl = signedUrl.data.templates.files[0].url; let file = fileData.file.data; try { @@ -140,11 +146,19 @@ module.exports = class CertificateTemplatesHelper { }, body: file }) + // Update certificate template url in certificateTemplates collection + let updateCertificateTemplate = await this.update( + templateId, + { + templateUrl : signedUrl.data.templates.files[0].payload.sourcePath + } + ); return resolve({ success: true, data: { - templateUrl: signedUrl.data.template.files[0].payload.sourcePath + templateId: updateCertificateTemplate.data.id, + templateUrl: signedUrl.data.templates.files[0].payload.sourcePath } }) diff --git a/module/certificateTemplates/validator/v1.js b/module/certificateTemplates/validator/v1.js index 7f442a5d..ebe80323 100644 --- a/module/certificateTemplates/validator/v1.js +++ b/module/certificateTemplates/validator/v1.js @@ -11,7 +11,6 @@ module.exports = (req) => { create : function () { if ( req.method === "POST" ) { - req.checkBody('templateUrl', 'templateUrl is required').exists({checkFalsy: true}).isLength({ min: 1 }); req.checkBody('solutionId', 'solutionId is required').exists({checkFalsy: true}).isLength({ min: 1 }); req.checkBody('programId', 'programId is required').exists({checkFalsy: true}).isLength({ min: 1 }); req.checkBody("issuer").exists().withMessage("issuer is required"); @@ -21,6 +20,9 @@ module.exports = (req) => { req.checkParams("_id").exists().withMessage("required certificate templateId"); } + }, + uploadCertificateTemplate : function () { + req.checkParams("_id").exists().withMessage("required certificate templateId"); } } diff --git a/module/cloud-services/files/helper.js b/module/cloud-services/files/helper.js index 3cc4dcd9..f248629a 100644 --- a/module/cloud-services/files/helper.js +++ b/module/cloud-services/files/helper.js @@ -24,10 +24,11 @@ module.exports = class FilesHelper { * @param {Array} payloadData - payload for files data. * @param {String} referenceType - reference type * @param {String} userId - Logged in user id. + * @param {String} templateId - certificateTemplateId. * @returns {Array} - consists of all signed urls files. */ - static preSignedUrls(payloadData, referenceType,userId) { + static preSignedUrls(payloadData, referenceType, userId, templateId = "") { return new Promise(async (resolve, reject) => { try { @@ -85,7 +86,7 @@ module.exports = class FilesHelper { folderPath = "reports/" } else if (referenceType == constants.common.CERTIFICATE) { // Folder path specifically for project certificates - folderPath = "certificate/" + payloadIds[0] + "/" + userId + "/" + gen.utils.generateUniqueId() + "/"; + folderPath = "certificate/" + payloadIds[0] + "/" + templateId + "/"; } else { folderPath = "survey/" + payloadIds[0] + "/" + userId + "/" + gen.utils.generateUniqueId() + "/"; } From bc0915a6d1636f38918629b646e2368576c6a52f Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 7 Oct 2022 13:59:05 +0530 Subject: [PATCH 192/331] upload folderpath changed --- module/cloud-services/files/helper.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/module/cloud-services/files/helper.js b/module/cloud-services/files/helper.js index f248629a..753398d5 100644 --- a/module/cloud-services/files/helper.js +++ b/module/cloud-services/files/helper.js @@ -86,7 +86,7 @@ module.exports = class FilesHelper { folderPath = "reports/" } else if (referenceType == constants.common.CERTIFICATE) { // Folder path specifically for project certificates - folderPath = "certificate/" + payloadIds[0] + "/" + templateId + "/"; + folderPath = "certificateTemplates/" + templateId + "/"; } else { folderPath = "survey/" + payloadIds[0] + "/" + userId + "/" + gen.utils.generateUniqueId() + "/"; } From fb1c44d8b833cb1e091f92e03e6eaed12813c80a Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 13 Oct 2022 15:11:38 +0530 Subject: [PATCH 193/331] sample request and response changes --- controllers/v1/certificateTemplates.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/controllers/v1/certificateTemplates.js b/controllers/v1/certificateTemplates.js index 3eafce37..9c2859fd 100644 --- a/controllers/v1/certificateTemplates.js +++ b/controllers/v1/certificateTemplates.js @@ -20,7 +20,7 @@ module.exports = class CertificateTemplates extends Abstract { * @apiName Create certificate template * @apiGroup CreateTemplates * @apiParamExample {json} Request-Body: - * { "templateUrl" :"certificate/template/ba9aa220-ff1b-4717-b6ea-ace55f04fc16/c9dbee8d-8c0b-4e0d-9d10-37d4a8f6afc6/wow.svg", + * { "templateUrl" :"certificateTemplates/6343bd978f9d8980b7841e85/ba9aa220-ff1b-4717-b6ea-ace55f04fc16_2022-9-10-1665383945769.svg?", "criteria" : { "validationText" : "Complete validation message", "expression" : "C1&&C2&&C3", @@ -152,7 +152,7 @@ module.exports = class CertificateTemplates extends Abstract { "result": { "success": true, "data": { - "templateUrl": "certificate/template/ba9aa220-ff1b-4717-b6ea-ace55f04fc16/c9dbee8d-8c0b-4e0d-9d10-37d4a8f6afc6/template.svg" + "templateUrl": "certificateTemplates/6343bd978f9d8980b7841e85/ba9aa220-ff1b-4717-b6ea-ace55f04fc16_2022-9-10-1665383945769.svg?" } } } From 8d8220e7596942be01f79715158dcc926d8b5c8f Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 13 Oct 2022 15:15:13 +0530 Subject: [PATCH 194/331] sample req changes --- controllers/v1/certificateTemplates.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/controllers/v1/certificateTemplates.js b/controllers/v1/certificateTemplates.js index 9c2859fd..c1caa8ba 100644 --- a/controllers/v1/certificateTemplates.js +++ b/controllers/v1/certificateTemplates.js @@ -20,7 +20,7 @@ module.exports = class CertificateTemplates extends Abstract { * @apiName Create certificate template * @apiGroup CreateTemplates * @apiParamExample {json} Request-Body: - * { "templateUrl" :"certificateTemplates/6343bd978f9d8980b7841e85/ba9aa220-ff1b-4717-b6ea-ace55f04fc16_2022-9-10-1665383945769.svg?", + * { "templateUrl" :"certificateTemplates/6343bd978f9d8980b7841e85/ba9aa220-ff1b-4717-b6ea-ace55f04fc16_2022-9-10-1665383945769.svg", "criteria" : { "validationText" : "Complete validation message", "expression" : "C1&&C2&&C3", @@ -152,7 +152,7 @@ module.exports = class CertificateTemplates extends Abstract { "result": { "success": true, "data": { - "templateUrl": "certificateTemplates/6343bd978f9d8980b7841e85/ba9aa220-ff1b-4717-b6ea-ace55f04fc16_2022-9-10-1665383945769.svg?" + "templateUrl": "certificateTemplates/6343bd978f9d8980b7841e85/ba9aa220-ff1b-4717-b6ea-ace55f04fc16_2022-9-10-1665383945769.svg" } } } From ab0091155a2eabe44a61a8a8a3aa2d6466bc8716 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 14 Oct 2022 11:06:58 +0530 Subject: [PATCH 195/331] document count added --- module/admin/helper.js | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/module/admin/helper.js b/module/admin/helper.js index 2c249c48..b2afe40d 100644 --- a/module/admin/helper.js +++ b/module/admin/helper.js @@ -76,11 +76,15 @@ module.exports = class adminHelper { .limit(limitingValue) .toArray(); } + // finding document count from db. We can't get it from result array length because a limiting value is passed + let docCount = await database.getCollection(collection) + .find(queryObject).count(); return resolve({ success: true, message: constants.apiResponses.DATA_FETCHED_SUCCESSFULLY, - data: mongoDBDocuments + data: mongoDBDocuments, + count: docCount }); } catch (error) { @@ -125,7 +129,8 @@ module.exports = class adminHelper { return resolve({ message : constants.apiResponses.DATA_FETCHED_SUCCESSFULLY, success : true, - result: mongoDBDocuments.data ? mongoDBDocuments.data : [] + result: mongoDBDocuments.data ? mongoDBDocuments.data : [], + count: mongoDBDocuments.count ? mongoDBDocuments.count : 0 }); } catch (error) { From f39c76bb8149d9549b64a8f71717bca3a570b519 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Mon, 24 Oct 2022 15:41:02 +0530 Subject: [PATCH 196/331] hotfix for search entity --- generics/helpers/utils.js | 14 +++++++++++++- generics/services/users.js | 15 +++++++++++---- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/generics/helpers/utils.js b/generics/helpers/utils.js index cd742ae6..fed2c4a7 100644 --- a/generics/helpers/utils.js +++ b/generics/helpers/utils.js @@ -262,6 +262,17 @@ function arrayIdsTobjectIds(ids) { return ids.map(id => ObjectId(id)); } +/** + * check whether string contains only number + * @function + * @name checkIfStringIsNumber + * @returns {Boolean} returns a Boolean value true/false +*/ + +function checkIfStringIsNumber(str) { + return /^[0-9]+$/.test(str); +} + module.exports = { camelCaseToTitleCase : camelCaseToTitleCase, lowerCase : lowerCase, @@ -278,5 +289,6 @@ module.exports = { convertStringToBoolean : convertStringToBoolean, md5Hash : md5Hash, filterLocationIdandCode : filterLocationIdandCode, - arrayIdsTobjectIds : arrayIdsTobjectIds + arrayIdsTobjectIds : arrayIdsTobjectIds, + checkIfStringIsNumber : checkIfStringIsNumber }; diff --git a/generics/services/users.js b/generics/services/users.js index 482d1e58..505a36aa 100644 --- a/generics/services/users.js +++ b/generics/services/users.js @@ -206,9 +206,16 @@ const locationSearch = function ( filterData, pageSize = "", pageNo = "", search } if ( searchKey !== "" ) { - bodyData["request"]["fuzzy"] = { - "orgName" : searchKey + if ( gen.utils.checkIfStringIsNumber(searchKey) ) { + bodyData["request"]["fuzzy"] = { + "externalId" : searchKey + } + } else { + bodyData["request"]["fuzzy"] = { + "orgName" : searchKey + } } + } //for getting specified key data only. @@ -220,7 +227,7 @@ const locationSearch = function ( filterData, pageSize = "", pageNo = "", search userServiceUrl + constants.endpoints.GET_SCHOOL_DATA; const options = { headers : { - "content-type": "application/json", + "content-type": "application/json" }, json : bodyData }; @@ -231,7 +238,7 @@ const locationSearch = function ( filterData, pageSize = "", pageNo = "", search }; function requestCallback(err, data) { - + if (err) { result.success = false; } else { From 4f805a58e2c9a6b2d6b6966f5c087376db8b5511 Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Thu, 27 Oct 2022 11:37:09 +0530 Subject: [PATCH 197/331] form config type change --- generics/constants/common.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/generics/constants/common.js b/generics/constants/common.js index 30e42fe7..7e8c91d7 100644 --- a/generics/constants/common.js +++ b/generics/constants/common.js @@ -69,6 +69,6 @@ module.exports = { "SCHOOL" : "school", "SUBENTITY" :"subEntityTypesOf_", "CACHE_TTL" : 43200, - "PROFILE_CONFIG_FORM_KEY" : "profileConfig", + "PROFILE_CONFIG_FORM_KEY" : "profileConfig_v2", "SERVER_TIME_OUT" : 5000 }; From 1c49ba697fe495997d7bfb5bc4ce5acd01c279ee Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 28 Oct 2022 21:34:23 +0530 Subject: [PATCH 198/331] review changes --- controllers/v1/certificateTemplates.js | 9 +++++---- models/certificateTemplates.js | 8 ++++++-- module/certificateTemplates/helper.js | 1 + 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/controllers/v1/certificateTemplates.js b/controllers/v1/certificateTemplates.js index c1caa8ba..df928b47 100644 --- a/controllers/v1/certificateTemplates.js +++ b/controllers/v1/certificateTemplates.js @@ -18,7 +18,7 @@ module.exports = class CertificateTemplates extends Abstract { * @api {post/patch} /kendra/api/v1/certificateTemplates/create * @apiVersion 1.0.0 * @apiName Create certificate template - * @apiGroup CreateTemplates + * @apiGroup CertificateTemplates * @apiParamExample {json} Request-Body: * { "templateUrl" :"certificateTemplates/6343bd978f9d8980b7841e85/ba9aa220-ff1b-4717-b6ea-ace55f04fc16_2022-9-10-1665383945769.svg", "criteria" : { @@ -87,6 +87,7 @@ module.exports = class CertificateTemplates extends Abstract { "programId" : "605083ba09b7bd61555580fb" } + * @apiHeader {String} internal-access-token - internal access token * @apiHeader {String} X-authenticated-user-token - Authenticity token * @apiSampleRequest /kendra/api/v1/certificateTemplates/create @@ -159,14 +160,14 @@ module.exports = class CertificateTemplates extends Abstract { */ /** - * uploadCertificateTemplate. + * uploadTemplate. * @method - * @name uploadCertificateTemplate + * @name uploadTemplate * @param {Object} req - requested data. * @returns {JSON} file uploaded details. */ - async uploadCertificateTemplate(req) { + async uploadTemplate(req) { return new Promise(async (resolve, reject) => { try { diff --git a/models/certificateTemplates.js b/models/certificateTemplates.js index e7b76cf1..81760163 100644 --- a/models/certificateTemplates.js +++ b/models/certificateTemplates.js @@ -2,14 +2,18 @@ module.exports = { name: "certificateTemplates", schema: { templateUrl: String, - issuer: Object, + issuer: { + type : Object, + required : true + }, status: { type : String, required : true }, solutionId: { type : "ObjectId", - index : true + index : true, + unique : true }, programId: "ObjectId", criteria: { diff --git a/module/certificateTemplates/helper.js b/module/certificateTemplates/helper.js index 786cc9d2..cfd8f095 100644 --- a/module/certificateTemplates/helper.js +++ b/module/certificateTemplates/helper.js @@ -150,6 +150,7 @@ module.exports = class CertificateTemplatesHelper { let updateCertificateTemplate = await this.update( templateId, { + // certificateTemplates/6343bd978f9d8980b7841e85/ba9aa220-ff1b-4717-b6ea-ace55f04fc16_2022-9-10-1665383945769.svg templateUrl : signedUrl.data.templates.files[0].payload.sourcePath } ); From 3fb9ec4e5b9f7846e6a588728c9f3c8b2bb663c6 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 28 Oct 2022 21:43:16 +0530 Subject: [PATCH 199/331] schema changes added, common.js conflict resolve --- generics/constants/common.js | 2 +- models/certificateTemplates.js | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/generics/constants/common.js b/generics/constants/common.js index 976fa10f..7bf0c8a2 100644 --- a/generics/constants/common.js +++ b/generics/constants/common.js @@ -69,7 +69,7 @@ module.exports = { "SCHOOL" : "school", "SUBENTITY" :"subEntityTypesOf_", "CACHE_TTL" : 43200, - "PROFILE_CONFIG_FORM_KEY" : "profileConfig", + "PROFILE_CONFIG_FORM_KEY" : "profileConfig_v2", "SERVER_TIME_OUT" : 5000, "CERTIFICATE" : "certificate" }; diff --git a/models/certificateTemplates.js b/models/certificateTemplates.js index 81760163..91a07cd4 100644 --- a/models/certificateTemplates.js +++ b/models/certificateTemplates.js @@ -8,7 +8,8 @@ module.exports = { }, status: { type : String, - required : true + required : true, + default : "ACTIVE" }, solutionId: { type : "ObjectId", From 8bdbbe9acb540b5aba79fb5a60836d48c986084e Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 31 Oct 2022 10:15:47 +0530 Subject: [PATCH 200/331] env changes --- .env.sample | 4 +++- envVariables.js | 12 ++++++++++-- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/.env.sample b/.env.sample index 10978e4c..a12679bd 100644 --- a/.env.sample +++ b/.env.sample @@ -45,4 +45,6 @@ APP_PORTAL_BASE_URL = "https://dev.sunbirded.org" FORM_SERVICE_URL = "http://player:3000" // Base url for form search #CERTIFICATE_ISSUER_KID -CERTIFICATE_ISSUER_KID = "1-de2ed8d1-e8d8-40a9-b1ba-7694a16a4c8d" // This issuer Kid is used in sunbird RC end \ No newline at end of file +CERTIFICATE_ISSUER_KID = "1-de2ed8d1-e8d8-40a9-b1ba-7694a16a4c8d" // This issuer Kid is used in sunbird RC end + +PROJECT_CERTIFICATE_ON_OFF = "ON/OFF" // Project certificate enable or disable flag \ No newline at end of file diff --git a/envVariables.js b/envVariables.js index 3f8394e4..bc510ffe 100644 --- a/envVariables.js +++ b/envVariables.js @@ -135,10 +135,18 @@ let enviromentVariables = { "optional" : true, "default": "http://player:3000" }, - "CERTIFICATE_ISSUER_KID": { - "message" : "Required certificate issuer kid", + "PROJECT_CERTIFICATE_ON_OFF" : { + "message" : "Enable/Disable project certification", "optional" : false }, + "CERTIFICATE_ISSUER_KID" : { + "message" : "Required certificate issuer kid", + "optional" : true, + "requiredIf" : { + "key": "PROJECT_CERTIFICATE_ON_OFF", + "value" : "ON" + } + } } let success = true; From 2c05f40a37ae4befbc54b572a1343929f78ebc3a Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 10 Nov 2022 18:17:38 +0530 Subject: [PATCH 201/331] oracle-cloud storage added --- envVariables.js | 59 ++++++++- generics/constants/common.js | 3 +- generics/services/oracle-cloud.js | 168 ++++++++++++++++++++++++++ module/cloud-services/files/helper.js | 7 +- module/files/helper.js | 12 +- 5 files changed, 244 insertions(+), 5 deletions(-) create mode 100644 generics/services/oracle-cloud.js diff --git a/envVariables.js b/envVariables.js index 1d659041..a9f2a329 100644 --- a/envVariables.js +++ b/envVariables.js @@ -29,6 +29,7 @@ let enviromentVariables = { "optional" : true, "requiredIf" : { "key": "CLOUD_STORAGE", + "operator": "EQUALS", "value" : "GC" } }, @@ -37,6 +38,7 @@ let enviromentVariables = { "optional" : true, "requiredIf" : { "key": "CLOUD_STORAGE", + "operator": "EQUALS", "value" : "GC" } }, @@ -45,6 +47,7 @@ let enviromentVariables = { "optional" : true, "requiredIf" : { "key": "CLOUD_STORAGE", + "operator": "EQUALS", "value" : "AZURE" } }, @@ -53,6 +56,7 @@ let enviromentVariables = { "optional" : true, "requiredIf" : { "key": "CLOUD_STORAGE", + "operator": "EQUALS", "value" : "AZURE" } }, @@ -61,6 +65,7 @@ let enviromentVariables = { "optional" : true, "requiredIf" : { "key": "CLOUD_STORAGE", + "operator": "EQUALS", "value" : "AZURE" } }, @@ -69,6 +74,7 @@ let enviromentVariables = { "optional" : true, "requiredIf" : { "key": "CLOUD_STORAGE", + "operator": "EQUALS", "value" : "AWS" } }, @@ -77,6 +83,7 @@ let enviromentVariables = { "optional" : true, "requiredIf" : { "key": "CLOUD_STORAGE", + "operator": "EQUALS", "value" : "AWS" } }, @@ -85,6 +92,7 @@ let enviromentVariables = { "optional" : true, "requiredIf" : { "key": "CLOUD_STORAGE", + "operator": "EQUALS", "value" : "AWS" } }, @@ -93,6 +101,7 @@ let enviromentVariables = { "optional" : true, "requiredIf" : { "key": "CLOUD_STORAGE", + "operator": "EQUALS", "value" : "AWS" } }, @@ -101,6 +110,7 @@ let enviromentVariables = { "optional" : true, "requiredIf" : { "key": "CLOUD_STORAGE", + "operator": "EQUALS", "value" : "AWS" } }, @@ -134,7 +144,52 @@ let enviromentVariables = { "message" : "Form service base url", "optional" : true, "default": "http://player:3000" - } + }, + "OCI_ACCESS_KEY_ID" : { + "message" : "Required oracle access key id", + "optional" : true, + "requiredIf" : { + "key": "CLOUD_STORAGE", + "operator": "EQUALS", + "value" : "OC" + } + }, + "OCI_SECRET_ACCESS_KEY" : { + "message" : "Required Oracle secret access key", + "optional" : true, + "requiredIf" : { + "key": "CLOUD_STORAGE", + "operator": "EQUALS", + "value" : "OC" + } + }, + "OCI_BUCKET_NAME" : { + "message" : "Required Oracle bucket name", + "optional" : true, + "requiredIf" : { + "key": "CLOUD_STORAGE", + "operator": "EQUALS", + "value" : "OC" + } + }, + "OCI_BUCKET_REGION" : { + "message" : "Required Oracle bucket region", + "optional" : true, + "requiredIf" : { + "key": "CLOUD_STORAGE", + "operator": "EQUALS", + "value" : "OC" + } + }, + "OCI_BUCKET_ENDPOINT" : { + "message" : "Required Oracle bucket endpoint", + "optional" : true, + "requiredIf" : { + "key": "CLOUD_STORAGE", + "operator": "EQUALS", + "value" : "OC" + } + }, } let success = true; @@ -147,7 +202,7 @@ module.exports = function() { }; let keyCheckPass = true; - + let validRequiredIfOperators = ["EQUALS","NOT_EQUALS"] if(enviromentVariables[eachEnvironmentVariable].optional === true && enviromentVariables[eachEnvironmentVariable].requiredIf diff --git a/generics/constants/common.js b/generics/constants/common.js index 7e8c91d7..0f6952b8 100644 --- a/generics/constants/common.js +++ b/generics/constants/common.js @@ -70,5 +70,6 @@ module.exports = { "SUBENTITY" :"subEntityTypesOf_", "CACHE_TTL" : 43200, "PROFILE_CONFIG_FORM_KEY" : "profileConfig_v2", - "SERVER_TIME_OUT" : 5000 + "SERVER_TIME_OUT" : 5000, + "ORACLE_CLOUD_SERVICE" : "OC" }; diff --git a/generics/services/oracle-cloud.js b/generics/services/oracle-cloud.js new file mode 100644 index 00000000..e5635d06 --- /dev/null +++ b/generics/services/oracle-cloud.js @@ -0,0 +1,168 @@ +/** + * name : oracle-cloud.js + * author : vishnu + * created-date : 10-Nov-2022 + * Description : All oracle-cloud related functionality + */ + +// Dependencies +const AWS = require('aws-sdk'); +const OCI_ACCESS_KEY_ID = +(process.env.OCI_ACCESS_KEY_ID && process.env.OCI_ACCESS_KEY_ID != "") ? +process.env.OCI_ACCESS_KEY_ID : ""; + +const OCI_SECRET_ACCESS_KEY = +(process.env.OCI_SECRET_ACCESS_KEY && process.env.OCI_SECRET_ACCESS_KEY != "") ? +process.env.OCI_SECRET_ACCESS_KEY : ""; + +AWS.config.update({ + accessKeyId : OCI_ACCESS_KEY_ID, + secretAccessKey : OCI_SECRET_ACCESS_KEY, + region : process.env.OCI_BUCKET_REGION, + endpoint : process.env.OCI_BUCKET_ENDPOINT, + s3ForcePathStyle : true, + signatureVersion : 'v4' +}); + +const s3 = new AWS.S3(); + +/** + * Upload file in oracle cloud. + * @function + * @name uploadFile + * @param file - file to upload. + * @param filePath - file path + * @returns {Object} - upload file information +*/ + +let uploadFile = function( file,filePath,bucketName ) { + + return new Promise( async(resolve,reject)=>{ + + let bucket = bucketName ? bucketName : process.env.DEFAULT_BUCKET_NAME; + const uploadParams = { + Bucket: bucket, + Key: filePath, + Body: file + }; + + s3.upload(uploadParams,function(err,data){ + if( err ) { + return reject({ + message : "Could not upload file in oracle" + }); + } else { + let result = { + name : data.key, + bucket : data.Bucket, + location : data.Location + }; + + return resolve(result); + } + }) + + }) +} + +/** + * Get downloadable url. + * @function + * @name getDownloadableUrl + * @param filePath - file path + * @returns {String} - Get downloadable url link +*/ + +let getDownloadableUrl = function( filePath,bucketName ) { + + return new Promise( async(resolve,reject)=>{ + + try { + if( filePath == "" ) { + throw new Error(httpStatusCode.bad_request.status); + } + + let noOfMinutes = constants.common.NO_OF_MINUTES; + let expiry = constants.common.NO_OF_EXPIRY_TIME * noOfMinutes; + let bucket = bucketName ? bucketName : process.env.DEFAULT_BUCKET_NAME; + + const downloadableUrl = s3.getSignedUrl('getObject', { + Bucket: bucket, + Key: filePath, + Expires: expiry + }); + return resolve(downloadableUrl); + } catch(error) { + return reject(error); + } + + }) +} + + /** + * Get oracle s3 cloud signed url. + * @method + * @name getS3SignedUrl + * @param {String} fileName - fileName. + * @param {String} bucketName - name of the bucket. + * @returns {Object} - signed url and s3 file name. + */ + +let signedUrl = ( fileName ,bucketName ) =>{ + return new Promise(async (resolve, reject) => { + try { + + if( fileName == "" ) { + throw new Error(httpStatusCode.bad_request.status); + } + + let noOfMinutes = constants.common.NO_OF_MINUTES; + let expiry = constants.common.NO_OF_EXPIRY_TIME * noOfMinutes; + + try { + + const url = await s3.getSignedUrl('putObject', { + Bucket : bucketName, + Key : fileName, + Expires : expiry + }); + + let result = { + success : true, + url : url + }; + + if(url && url != "") { + + result["name"] = fileName; + + } else { + + result["success"] = false; + + } + + return resolve(result); + + } catch (error) { + return resolve({ + success : false, + message : error.message, + response : error + }); + } + + + } catch (error) { + return reject(error); + } + }) +} + + +module.exports = { + s3: s3, + uploadFile : uploadFile, + getDownloadableUrl : getDownloadableUrl, + signedUrl : signedUrl +}; \ No newline at end of file diff --git a/module/cloud-services/files/helper.js b/module/cloud-services/files/helper.js index d0444ff2..39c0da96 100644 --- a/module/cloud-services/files/helper.js +++ b/module/cloud-services/files/helper.js @@ -40,6 +40,8 @@ module.exports = class FilesHelper { bucketName = process.env.AWS_BUCKET_NAME; } else if (cloudStorage === "GC" ) { bucketName = process.env.GCP_BUCKET_NAME; + } else if (cloudStorage === constants.common.ORACLE_CLOUD_SERVICE ) { + bucketName = process.env.OCI_BUCKET_NAME; } else { bucketName = process.env.AZURE_STORAGE_CONTAINER; } @@ -136,7 +138,10 @@ module.exports = class FilesHelper { bucketName = process.env.AWS_BUCKET_NAME; } else if (cloudStorage === "GC") { bucketName = process.env.GCP_BUCKET_NAME; - } else { + } else if (cloudStorage === constants.common.ORACLE_CLOUD_SERVICE) { + bucketName = process.env.OCI_BUCKET_NAME; + } + else { bucketName = process.env.AZURE_STORAGE_CONTAINER; } diff --git a/module/files/helper.js b/module/files/helper.js index 96d1d5db..42a1b3c7 100644 --- a/module/files/helper.js +++ b/module/files/helper.js @@ -14,6 +14,7 @@ const awsServices = require(ROOT_PATH + '/generics/services/aws'); const googleCloudServices = require(ROOT_PATH + '/generics/services/google-cloud'); const azureService = require(ROOT_PATH + '/generics/services/azure'); +const oracleSerices = require(ROOT_PATH + '/generics/services/oracle-cloud'); /** * FilesHelper @@ -81,6 +82,12 @@ module.exports = class FilesHelper { filePathForBucket, bucketName ) + } else if (cloudStorage === constants.common.ORACLE_CLOUD_SERVICE) { + result = await oracleSerices.uploadFile( + file, + filePathForBucket, + bucketName + ) } if (deleteFile) { _removeFiles(filePath); @@ -202,6 +209,8 @@ module.exports = class FilesHelper { signedUrlResponse = await awsServices.signedUrl(file, bucket) } else if (cloudStorage === constants.common.AZURE_SERVICE) { signedUrlResponse = await azureService.signedUrl(file, bucket) + } else if (cloudStorage === constants.common.ORACLE_CLOUD_SERVICE) { + signedUrlResponse = await oracleSerices.signedUrl(file, bucket) } if (signedUrlResponse.success) { @@ -396,8 +405,9 @@ function _getLinkFromCloudService(filePath, bucketName, cloudStorage) { ) } else if (cloudStorage === constants.common.AZURE_SERVICE) { result = await azureService.getDownloadableUrl(filePath, bucketName) + } else if (cloudStorage === constants.common.ORACLE_CLOUD_SERVICE) { + result = await oracleSerices.getDownloadableUrl(filePath, bucketName) } - return resolve(result) } catch (error) { return reject(error) From 784523ad650837be690e03f695fda6e963fc99b2 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 10 Nov 2022 18:21:05 +0530 Subject: [PATCH 202/331] downloadable url expiry removed --- generics/services/oracle-cloud.js | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/generics/services/oracle-cloud.js b/generics/services/oracle-cloud.js index e5635d06..7bbaee70 100644 --- a/generics/services/oracle-cloud.js +++ b/generics/services/oracle-cloud.js @@ -82,14 +82,11 @@ let getDownloadableUrl = function( filePath,bucketName ) { throw new Error(httpStatusCode.bad_request.status); } - let noOfMinutes = constants.common.NO_OF_MINUTES; - let expiry = constants.common.NO_OF_EXPIRY_TIME * noOfMinutes; let bucket = bucketName ? bucketName : process.env.DEFAULT_BUCKET_NAME; const downloadableUrl = s3.getSignedUrl('getObject', { Bucket: bucket, - Key: filePath, - Expires: expiry + Key: filePath }); return resolve(downloadableUrl); } catch(error) { From 7d11793345bfcc9b0147f4c48f3b3cce6429fe20 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 10 Nov 2022 21:37:27 +0530 Subject: [PATCH 203/331] query removed from downloadable URL --- generics/services/oracle-cloud.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/generics/services/oracle-cloud.js b/generics/services/oracle-cloud.js index 7bbaee70..ee14e916 100644 --- a/generics/services/oracle-cloud.js +++ b/generics/services/oracle-cloud.js @@ -88,7 +88,8 @@ let getDownloadableUrl = function( filePath,bucketName ) { Bucket: bucket, Key: filePath }); - return resolve(downloadableUrl); + let urlWithoutQueryParam = downloadableUrl.split('?') + return resolve(urlWithoutQueryParam[0]); } catch(error) { return reject(error); } From 078a9067202cbf5d4dc154560f51b65bb2f0b295 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 11 Nov 2022 12:55:53 +0530 Subject: [PATCH 204/331] Review: .env.sample added, variable change && aws logic added --- .env.sample | 7 +++++++ envVariables.js | 10 +++++----- generics/constants/common.js | 2 +- generics/services/oracle-cloud.js | 14 +++----------- 4 files changed, 16 insertions(+), 17 deletions(-) diff --git a/.env.sample b/.env.sample index ff6a934c..b08c09f7 100644 --- a/.env.sample +++ b/.env.sample @@ -43,3 +43,10 @@ CSV_REPORTS_PATH = "public/report" APP_PORTAL_BASE_URL = "https://dev.sunbirded.org" FORM_SERVICE_URL = "http://player:3000" // Base url for form search + +# Oracle Cloud Configuration +OCI_ACCESS_KEY_ID = '23b90..............d01d' // Oracle cloud storage access key Id +OCI_SECRET_ACCESS_KEY = '22levMw5Ci............SmNE=' // Oracle cloud storage secret access key +OCI_BUCKET_NAME = 'oracle cloud bucket name' // Oracle cloud bucket name +OCI_BUCKET_REGION = 'ap-hyderabad-1' // Oracle cloud bucket region +OCI_BUCKET_ENDPOINT = 'https://pmt5.compat.storage.ap-h1.oraclecloud.com' // Oracle cloud bucket endPoint \ No newline at end of file diff --git a/envVariables.js b/envVariables.js index a9f2a329..655142c6 100644 --- a/envVariables.js +++ b/envVariables.js @@ -151,7 +151,7 @@ let enviromentVariables = { "requiredIf" : { "key": "CLOUD_STORAGE", "operator": "EQUALS", - "value" : "OC" + "value" : "OCI" } }, "OCI_SECRET_ACCESS_KEY" : { @@ -160,7 +160,7 @@ let enviromentVariables = { "requiredIf" : { "key": "CLOUD_STORAGE", "operator": "EQUALS", - "value" : "OC" + "value" : "OCI" } }, "OCI_BUCKET_NAME" : { @@ -169,7 +169,7 @@ let enviromentVariables = { "requiredIf" : { "key": "CLOUD_STORAGE", "operator": "EQUALS", - "value" : "OC" + "value" : "OCI" } }, "OCI_BUCKET_REGION" : { @@ -178,7 +178,7 @@ let enviromentVariables = { "requiredIf" : { "key": "CLOUD_STORAGE", "operator": "EQUALS", - "value" : "OC" + "value" : "OCI" } }, "OCI_BUCKET_ENDPOINT" : { @@ -187,7 +187,7 @@ let enviromentVariables = { "requiredIf" : { "key": "CLOUD_STORAGE", "operator": "EQUALS", - "value" : "OC" + "value" : "OCI" } }, } diff --git a/generics/constants/common.js b/generics/constants/common.js index 0f6952b8..00e4d7a3 100644 --- a/generics/constants/common.js +++ b/generics/constants/common.js @@ -71,5 +71,5 @@ module.exports = { "CACHE_TTL" : 43200, "PROFILE_CONFIG_FORM_KEY" : "profileConfig_v2", "SERVER_TIME_OUT" : 5000, - "ORACLE_CLOUD_SERVICE" : "OC" + "ORACLE_CLOUD_SERVICE" : "OCI" }; diff --git a/generics/services/oracle-cloud.js b/generics/services/oracle-cloud.js index ee14e916..681b9566 100644 --- a/generics/services/oracle-cloud.js +++ b/generics/services/oracle-cloud.js @@ -78,18 +78,10 @@ let getDownloadableUrl = function( filePath,bucketName ) { return new Promise( async(resolve,reject)=>{ try { - if( filePath == "" ) { - throw new Error(httpStatusCode.bad_request.status); - } - let bucket = bucketName ? bucketName : process.env.DEFAULT_BUCKET_NAME; - - const downloadableUrl = s3.getSignedUrl('getObject', { - Bucket: bucket, - Key: filePath - }); - let urlWithoutQueryParam = downloadableUrl.split('?') - return resolve(urlWithoutQueryParam[0]); + let downloadableUrl = + `${process.env.OCI_BUCKET_ENDPOINT}/${bucket}/${filePath}`; + return resolve(downloadableUrl); } catch(error) { return reject(error); } From b13a212706d1133b4b883c65736e77b6ee3ef245 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 14 Nov 2022 13:32:13 +0530 Subject: [PATCH 205/331] operator key added --- envVariables.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/envVariables.js b/envVariables.js index bc510ffe..feacadaa 100644 --- a/envVariables.js +++ b/envVariables.js @@ -142,6 +142,7 @@ let enviromentVariables = { "CERTIFICATE_ISSUER_KID" : { "message" : "Required certificate issuer kid", "optional" : true, + "operator" : "EQUALS", "requiredIf" : { "key": "PROJECT_CERTIFICATE_ON_OFF", "value" : "ON" @@ -159,7 +160,7 @@ module.exports = function() { }; let keyCheckPass = true; - + let validRequiredIfOperators = ["EQUALS","NOT_EQUALS"] if(enviromentVariables[eachEnvironmentVariable].optional === true && enviromentVariables[eachEnvironmentVariable].requiredIf From 1485bee639feac1ccd531d1385300e8d1766117a Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Wed, 16 Nov 2022 14:29:09 +0530 Subject: [PATCH 206/331] certificate template model change --- models/certificateTemplates.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/models/certificateTemplates.js b/models/certificateTemplates.js index 91a07cd4..1883773d 100644 --- a/models/certificateTemplates.js +++ b/models/certificateTemplates.js @@ -16,7 +16,11 @@ module.exports = { index : true, unique : true }, - programId: "ObjectId", + programId: { + type : "ObjectId", + index : true, + required : true + }, criteria: { type : Object, required : true From fb3b5e64561a6ea937467d5637f748096c8e3bda Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Wed, 16 Nov 2022 14:32:09 +0530 Subject: [PATCH 207/331] review changes --- module/certificateTemplates/helper.js | 16 ++++++---------- module/cloud-services/files/helper.js | 2 +- 2 files changed, 7 insertions(+), 11 deletions(-) diff --git a/module/certificateTemplates/helper.js b/module/certificateTemplates/helper.js index cfd8f095..07cd166b 100644 --- a/module/certificateTemplates/helper.js +++ b/module/certificateTemplates/helper.js @@ -27,7 +27,7 @@ module.exports = class CertificateTemplatesHelper { static create(data) { return new Promise(async (resolve, reject) => { try { - data.issuer.kid = process.env.CERTIFICATE_ISSUER_KID; + //#remove data.issuer.kid = process.env.CERTIFICATE_ISSUER_KID; let certificateTemplateCreated = await database.models.certificateTemplates.create( data @@ -57,10 +57,6 @@ module.exports = class CertificateTemplatesHelper { static update(templateId, data) { return new Promise(async (resolve, reject) => { try { - // Adding issuer kid from env - if ( data.issuer ) { - data.issuer.kid = process.env.CERTIFICATE_ISSUER_KID; - } // If templateUrl value passed as empty string. if ( !data.templateUrl ) { delete data.templateUrl; @@ -108,7 +104,7 @@ module.exports = class CertificateTemplatesHelper { return new Promise(async (resolve, reject) => { try { const now = new Date(); - const date = now.getFullYear() + "-"+ now.getMonth() + "-" + now.getDate() + "-" + now.getTime(); + const date = now.getDate() + "-"+ now.getMonth() + "-" + now.getFullYear() + "-" + now.getTime(); const fileName = userId + "_" + date + ".svg"; const requestData = { "templates": { @@ -118,10 +114,10 @@ module.exports = class CertificateTemplatesHelper { let signedUrl = await filesHelpers.preSignedUrls( - requestData, - constants.common.CERTIFICATE, - userId, - templateId + requestData, // data to upload + constants.common.CERTIFICATE, // referenceType + "", + templateId // certificate template i ); // upload file using signed Url diff --git a/module/cloud-services/files/helper.js b/module/cloud-services/files/helper.js index 753398d5..9d051165 100644 --- a/module/cloud-services/files/helper.js +++ b/module/cloud-services/files/helper.js @@ -28,7 +28,7 @@ module.exports = class FilesHelper { * @returns {Array} - consists of all signed urls files. */ - static preSignedUrls(payloadData, referenceType, userId, templateId = "") { + static preSignedUrls(payloadData, referenceType, userId = "", templateId = "") { return new Promise(async (resolve, reject) => { try { From 3210bb8fec63e712c0a7ef362b8a0aa09b5cd862 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Wed, 16 Nov 2022 16:33:04 +0530 Subject: [PATCH 208/331] env changes --- .env.sample | 7 +------ envVariables.js | 13 ------------- module/certificateTemplates/helper.js | 1 - 3 files changed, 1 insertion(+), 20 deletions(-) diff --git a/.env.sample b/.env.sample index a12679bd..42dfefb0 100644 --- a/.env.sample +++ b/.env.sample @@ -42,9 +42,4 @@ CSV_REPORTS_PATH = "public/report" APP_PORTAL_BASE_URL = "https://dev.sunbirded.org" -FORM_SERVICE_URL = "http://player:3000" // Base url for form search - -#CERTIFICATE_ISSUER_KID -CERTIFICATE_ISSUER_KID = "1-de2ed8d1-e8d8-40a9-b1ba-7694a16a4c8d" // This issuer Kid is used in sunbird RC end - -PROJECT_CERTIFICATE_ON_OFF = "ON/OFF" // Project certificate enable or disable flag \ No newline at end of file +FORM_SERVICE_URL = "http://player:3000" // Base url for form search \ No newline at end of file diff --git a/envVariables.js b/envVariables.js index feacadaa..3a5eca6e 100644 --- a/envVariables.js +++ b/envVariables.js @@ -134,19 +134,6 @@ let enviromentVariables = { "message" : "Form service base url", "optional" : true, "default": "http://player:3000" - }, - "PROJECT_CERTIFICATE_ON_OFF" : { - "message" : "Enable/Disable project certification", - "optional" : false - }, - "CERTIFICATE_ISSUER_KID" : { - "message" : "Required certificate issuer kid", - "optional" : true, - "operator" : "EQUALS", - "requiredIf" : { - "key": "PROJECT_CERTIFICATE_ON_OFF", - "value" : "ON" - } } } diff --git a/module/certificateTemplates/helper.js b/module/certificateTemplates/helper.js index 07cd166b..c9226cde 100644 --- a/module/certificateTemplates/helper.js +++ b/module/certificateTemplates/helper.js @@ -27,7 +27,6 @@ module.exports = class CertificateTemplatesHelper { static create(data) { return new Promise(async (resolve, reject) => { try { - //#remove data.issuer.kid = process.env.CERTIFICATE_ISSUER_KID; let certificateTemplateCreated = await database.models.certificateTemplates.create( data From 4f5cfcff4c3416c1d8580f19961b50090c3be29c Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 18 Nov 2022 10:52:49 +0530 Subject: [PATCH 209/331] generics utils missing code added --- generics/helpers/utils.js | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/generics/helpers/utils.js b/generics/helpers/utils.js index cd742ae6..fed2c4a7 100644 --- a/generics/helpers/utils.js +++ b/generics/helpers/utils.js @@ -262,6 +262,17 @@ function arrayIdsTobjectIds(ids) { return ids.map(id => ObjectId(id)); } +/** + * check whether string contains only number + * @function + * @name checkIfStringIsNumber + * @returns {Boolean} returns a Boolean value true/false +*/ + +function checkIfStringIsNumber(str) { + return /^[0-9]+$/.test(str); +} + module.exports = { camelCaseToTitleCase : camelCaseToTitleCase, lowerCase : lowerCase, @@ -278,5 +289,6 @@ module.exports = { convertStringToBoolean : convertStringToBoolean, md5Hash : md5Hash, filterLocationIdandCode : filterLocationIdandCode, - arrayIdsTobjectIds : arrayIdsTobjectIds + arrayIdsTobjectIds : arrayIdsTobjectIds, + checkIfStringIsNumber : checkIfStringIsNumber }; From 8fea3b67f657b66baac708ad7503f0ccb003fb00 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 18 Nov 2022 10:59:56 +0530 Subject: [PATCH 210/331] users service missing code added --- generics/services/users.js | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/generics/services/users.js b/generics/services/users.js index 482d1e58..dad76493 100644 --- a/generics/services/users.js +++ b/generics/services/users.js @@ -206,9 +206,16 @@ const locationSearch = function ( filterData, pageSize = "", pageNo = "", search } if ( searchKey !== "" ) { - bodyData["request"]["fuzzy"] = { - "orgName" : searchKey + if ( gen.utils.checkIfStringIsNumber(searchKey) ) { + bodyData["request"]["fuzzy"] = { + "externalId" : searchKey + } + } else { + bodyData["request"]["fuzzy"] = { + "orgName" : searchKey + } } + } //for getting specified key data only. @@ -220,7 +227,7 @@ const locationSearch = function ( filterData, pageSize = "", pageNo = "", search userServiceUrl + constants.endpoints.GET_SCHOOL_DATA; const options = { headers : { - "content-type": "application/json", + "content-type": "application/json" }, json : bodyData }; From 485ae5e964cdfd4b04a42be414aa37906a4cae66 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 18 Nov 2022 11:11:14 +0530 Subject: [PATCH 211/331] code update adminApi --- module/admin/helper.js | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/module/admin/helper.js b/module/admin/helper.js index 2c249c48..b2afe40d 100644 --- a/module/admin/helper.js +++ b/module/admin/helper.js @@ -76,11 +76,15 @@ module.exports = class adminHelper { .limit(limitingValue) .toArray(); } + // finding document count from db. We can't get it from result array length because a limiting value is passed + let docCount = await database.getCollection(collection) + .find(queryObject).count(); return resolve({ success: true, message: constants.apiResponses.DATA_FETCHED_SUCCESSFULLY, - data: mongoDBDocuments + data: mongoDBDocuments, + count: docCount }); } catch (error) { @@ -125,7 +129,8 @@ module.exports = class adminHelper { return resolve({ message : constants.apiResponses.DATA_FETCHED_SUCCESSFULLY, success : true, - result: mongoDBDocuments.data ? mongoDBDocuments.data : [] + result: mongoDBDocuments.data ? mongoDBDocuments.data : [], + count: mongoDBDocuments.count ? mongoDBDocuments.count : 0 }); } catch (error) { From 77bea70ccded43d2bf4f474f188f3f5df2a2b01b Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Sun, 20 Nov 2022 11:48:16 +0530 Subject: [PATCH 212/331] templateUpload review changes --- module/certificateTemplates/helper.js | 5 ++--- module/cloud-services/files/helper.js | 4 ++-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/module/certificateTemplates/helper.js b/module/certificateTemplates/helper.js index c9226cde..6c968765 100644 --- a/module/certificateTemplates/helper.js +++ b/module/certificateTemplates/helper.js @@ -104,7 +104,7 @@ module.exports = class CertificateTemplatesHelper { try { const now = new Date(); const date = now.getDate() + "-"+ now.getMonth() + "-" + now.getFullYear() + "-" + now.getTime(); - const fileName = userId + "_" + date + ".svg"; + const fileName = templateId + '/' + userId + "_" + date + ".svg"; const requestData = { "templates": { "files": [fileName] @@ -115,8 +115,7 @@ module.exports = class CertificateTemplatesHelper { await filesHelpers.preSignedUrls( requestData, // data to upload constants.common.CERTIFICATE, // referenceType - "", - templateId // certificate template i + "" ); // upload file using signed Url diff --git a/module/cloud-services/files/helper.js b/module/cloud-services/files/helper.js index 8a436b3b..6b2fb387 100644 --- a/module/cloud-services/files/helper.js +++ b/module/cloud-services/files/helper.js @@ -28,7 +28,7 @@ module.exports = class FilesHelper { * @returns {Array} - consists of all signed urls files. */ - static preSignedUrls(payloadData, referenceType, userId = "", templateId = "") { + static preSignedUrls(payloadData, referenceType, userId = "") { return new Promise(async (resolve, reject) => { try { @@ -88,7 +88,7 @@ module.exports = class FilesHelper { folderPath = "reports/" } else if (referenceType == constants.common.CERTIFICATE) { // Folder path specifically for project certificates - folderPath = "certificateTemplates/" + templateId + "/"; + folderPath = "certificateTemplates/"; } else { folderPath = "survey/" + payloadIds[0] + "/" + userId + "/" + gen.utils.generateUniqueId() + "/"; } From d2e256ebfd69c3b1ef0ecff0600ea06249ac6296 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 21 Nov 2022 13:03:40 +0530 Subject: [PATCH 213/331] review changes --- generics/constants/api-responses.js | 4 +++- module/certificateTemplates/helper.js | 12 ++++++++---- module/certificateTemplates/validator/v1.js | 2 +- 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/generics/constants/api-responses.js b/generics/constants/api-responses.js index b2db48b1..c0fdc6a5 100644 --- a/generics/constants/api-responses.js +++ b/generics/constants/api-responses.js @@ -188,6 +188,8 @@ module.exports = { "DATA_CREATED_SUCCESSFULLY" : "Data created successfully", "FAILED_TO_CREATE_RECORD" : "Failed to create record in DB", "CERTIFICATE_TEMPLATE_ADDED" : "Template added successfully", - "CERTIFICATE_TEMPLATE_UPDATED" : "Template updated successfully" + "CERTIFICATE_TEMPLATE_UPDATED" : "Template updated successfully", + "CERTIFICATE_TEMPLATE_NOT_UPDATED" : "Template updation failed" + }; diff --git a/module/certificateTemplates/helper.js b/module/certificateTemplates/helper.js index 6c968765..1314da61 100644 --- a/module/certificateTemplates/helper.js +++ b/module/certificateTemplates/helper.js @@ -76,6 +76,11 @@ module.exports = class CertificateTemplatesHelper { {_id: templateId}, updateObject ); + if ( certificateTemplateUpdated == null ) { + throw{ + message: constants.apiResponses.CERTIFICATE_TEMPLATE_NOT_UPDATED + } + } return resolve({ message : constants.apiResponses.CERTIFICATE_TEMPLATE_UPDATED, data : { @@ -113,11 +118,10 @@ module.exports = class CertificateTemplatesHelper { let signedUrl = await filesHelpers.preSignedUrls( - requestData, // data to upload - constants.common.CERTIFICATE, // referenceType - "" + requestData, // data to upload + constants.common.CERTIFICATE, // referenceType ); - + // upload file using signed Url if (signedUrl.data && Object.keys(signedUrl.data).length > 0 && diff --git a/module/certificateTemplates/validator/v1.js b/module/certificateTemplates/validator/v1.js index ebe80323..588038cd 100644 --- a/module/certificateTemplates/validator/v1.js +++ b/module/certificateTemplates/validator/v1.js @@ -9,7 +9,7 @@ module.exports = (req) => { let certificateTemplatesValidator = { - create : function () { + createOrUpdate : function () { if ( req.method === "POST" ) { req.checkBody('solutionId', 'solutionId is required').exists({checkFalsy: true}).isLength({ min: 1 }); req.checkBody('programId', 'programId is required').exists({checkFalsy: true}).isLength({ min: 1 }); From 654f3bfaea9829b1a9afdeafaacecd6f0eb63402 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 21 Nov 2022 14:33:12 +0530 Subject: [PATCH 214/331] review changes --- module/certificateTemplates/helper.js | 60 ++++++++++++++------------- 1 file changed, 31 insertions(+), 29 deletions(-) diff --git a/module/certificateTemplates/helper.js b/module/certificateTemplates/helper.js index 1314da61..c1e830eb 100644 --- a/module/certificateTemplates/helper.js +++ b/module/certificateTemplates/helper.js @@ -56,37 +56,39 @@ module.exports = class CertificateTemplatesHelper { static update(templateId, data) { return new Promise(async (resolve, reject) => { try { - // If templateUrl value passed as empty string. - if ( !data.templateUrl ) { - delete data.templateUrl; - } - // If solutionId value passed as empty string. - if ( !data.solutionId ) { - delete data.solutionId; - } - // If programId value passed as empty string. - if ( !data.programId ) { - delete data.programId; + + // in case support team pass below values as empty string (not valid) we cant check it with validator. So adding it here + // If templateUrl value passed as empty string. + if ( !data.templateUrl ) { + delete data.templateUrl; + } + // If solutionId value passed as empty string. + if ( !data.solutionId ) { + delete data.solutionId; + } + // If programId value passed as empty string. + if ( !data.programId ) { + delete data.programId; + } + let updateObject = { + "$set" : data + }; + let certificateTemplateUpdated = + await database.models.certificateTemplates.findOneAndUpdate( + {_id: templateId}, + updateObject + ); + if ( certificateTemplateUpdated == null ) { + throw{ + message: constants.apiResponses.CERTIFICATE_TEMPLATE_NOT_UPDATED } - let updateObject = { - "$set" : data - }; - let certificateTemplateUpdated = - await database.models.certificateTemplates.findOneAndUpdate( - {_id: templateId}, - updateObject - ); - if ( certificateTemplateUpdated == null ) { - throw{ - message: constants.apiResponses.CERTIFICATE_TEMPLATE_NOT_UPDATED + } + return resolve({ + message : constants.apiResponses.CERTIFICATE_TEMPLATE_UPDATED, + data : { + id : certificateTemplateUpdated._id } - } - return resolve({ - message : constants.apiResponses.CERTIFICATE_TEMPLATE_UPDATED, - data : { - id : certificateTemplateUpdated._id - } - }); + }); } catch (error) { return reject(error); From cd7a6e3e91dff1f650e366391fbae0d4da59b453 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 21 Nov 2022 14:35:20 +0530 Subject: [PATCH 215/331] changes api-responses --- generics/constants/api-responses.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/generics/constants/api-responses.js b/generics/constants/api-responses.js index c0fdc6a5..e6b4bb0c 100644 --- a/generics/constants/api-responses.js +++ b/generics/constants/api-responses.js @@ -190,6 +190,4 @@ module.exports = { "CERTIFICATE_TEMPLATE_ADDED" : "Template added successfully", "CERTIFICATE_TEMPLATE_UPDATED" : "Template updated successfully", "CERTIFICATE_TEMPLATE_NOT_UPDATED" : "Template updation failed" - - }; From 905aa3f88be2f5d9bf86abb892a6ce92e3967f2d Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Tue, 22 Nov 2022 18:26:03 +0530 Subject: [PATCH 216/331] svg Edit api added --- controllers/v1/certificateTemplates.js | 48 +++++- generics/constants/api-responses.js | 3 +- module/certificateTemplates/helper.js | 160 +++++++++++++++++--- module/certificateTemplates/validator/v1.js | 3 + package.json | 1 + 5 files changed, 189 insertions(+), 26 deletions(-) diff --git a/controllers/v1/certificateTemplates.js b/controllers/v1/certificateTemplates.js index 67e91e75..8db7b181 100644 --- a/controllers/v1/certificateTemplates.js +++ b/controllers/v1/certificateTemplates.js @@ -136,7 +136,7 @@ module.exports = class CertificateTemplates extends Abstract { }); } - /** + /** * @api {post} /kendra/api/v1/certificateTemplates/uploadCertificateTemplate * @apiVersion 1.0.0 * @apiName upload certificate template @@ -176,7 +176,8 @@ module.exports = class CertificateTemplates extends Abstract { await certificateTemplateHelper.uploadToCloud( req.files, req.params._id, - req.userDetails ? req.userDetails.userId : "" + req.userDetails ? req.userDetails.userId : "", + req.query.updateTemplate ? req.query.updateTemplate : true ); return resolve({ message: constants.apiResponses.FILE_UPLOADED, @@ -198,4 +199,47 @@ module.exports = class CertificateTemplates extends Abstract { } }); } + /** + * @api {post} /kendra/api/v1/certificateTemplates/editSvg + * @apiVersion 1.0.0 + * @apiName edit certificate template svg + * @apiGroup editSvg + * @apiHeader {String} internal-access-token - internal access token + * @apiHeader {String} X-authenticated-user-token - Authenticity token + * @apiSampleRequest /kendra/api/v1/certificateTemplates/editSvg?baseTemplateFilePath=certificateTemplates/Base_template/ba9aa220-ff1b-4717-b6ea-ace55f04fc16_22-10-2022-1669118494135.svg + * @apiUse successBody + * @apiUse errorBody + * @apiParamExample {json} Response: + * { + "message": "Template edited successfully", + "status": 200, + "result": { + "url": "https://sunbirdstagingpublic.blob.core.windows.net/samiksha/certificateTemplates/BASE_TEMPLATE/_22-10-2022-1669120782574.svg?sv=2020-10-02&st=2022-11-22T12%3A39%3A42Z&se=2023-11-22T12%3A49%3A42Z&sr=b&sp=rw&sig=gLnKb1T32swAQQ%2Bgtaaa967d6c0GIL%2FGRcGCwjvpI30%3D" + } +} + */ + + /** + * generate cettificate templateSvg. + * @method + * @name editSvg + * @param {Object} req - requested data. + * @returns {JSON} -svg uploaded details. + */ + + async editSvg(req) { + return new Promise(async (resolve, reject) => { + try { + + let svgData = await certificateTemplateHelper.editSvg(req.files, req.body, req.query.baseTemplateFilePath); + return resolve(svgData); + } catch (error) { + return reject({ + status: error.status || httpStatusCode.internal_server_error.status, + message: error.message || httpStatusCode.internal_server_error.message, + errorObject: error + }); + } + }); + } } \ No newline at end of file diff --git a/generics/constants/api-responses.js b/generics/constants/api-responses.js index e6b4bb0c..ef66e329 100644 --- a/generics/constants/api-responses.js +++ b/generics/constants/api-responses.js @@ -189,5 +189,6 @@ module.exports = { "FAILED_TO_CREATE_RECORD" : "Failed to create record in DB", "CERTIFICATE_TEMPLATE_ADDED" : "Template added successfully", "CERTIFICATE_TEMPLATE_UPDATED" : "Template updated successfully", - "CERTIFICATE_TEMPLATE_NOT_UPDATED" : "Template updation failed" + "CERTIFICATE_TEMPLATE_NOT_UPDATED" : "Template updation failed", + "BASE_CERTIFICATE_TEMPLATE_NOT_FOUND" : "Base certificate template not found" }; diff --git a/module/certificateTemplates/helper.js b/module/certificateTemplates/helper.js index c1e830eb..38333a7b 100644 --- a/module/certificateTemplates/helper.js +++ b/module/certificateTemplates/helper.js @@ -5,10 +5,10 @@ * Description : Certificate Template related helper functionality. */ // dependencies -const filesHelpers = require(ROOT_PATH+"/module/cloud-services/files/helper"); const request = require("request"); - -const { ObjectId } = require("mongodb"); +let fs = require('fs'); +const cheerio = require('cheerio'); +const filesHelpers = require(ROOT_PATH+"/module/cloud-services/files/helper"); /** * CertificateTemplatesHelper @@ -98,7 +98,7 @@ module.exports = class CertificateTemplatesHelper { /** * upload certificate template. - * @method uploadToCloud + * @method * @name uploadToCloud * @param {Object} fileData - file to upload. * @param {String} templateId - templateId. @@ -106,7 +106,7 @@ module.exports = class CertificateTemplatesHelper { * @returns {JSON} Uploaded certificate template details. */ - static uploadToCloud(fileData, templateId, userId = "") { + static uploadToCloud(fileData, templateId, userId = "", updateTemplate) { return new Promise(async (resolve, reject) => { try { const now = new Date(); @@ -132,37 +132,44 @@ module.exports = class CertificateTemplatesHelper { signedUrl.data.templates.files[0].url && signedUrl.data.templates.files[0].url !== "" ) { - let fileUploadUrl = signedUrl.data.templates.files[0].url; let file = fileData.file.data; try { - await request({ - url: fileUploadUrl, - method: 'put', - headers: { - "x-ms-blob-type" : "BlockBlob", - "Content-Type": "multipart/form-data" - }, - body: file - }) + await request({ + url: fileUploadUrl, + method: 'put', + headers: { + "x-ms-blob-type" : "BlockBlob", + "Content-Type": "multipart/form-data" + }, + body: file + }) + let updateCertificateTemplate = {}; + if (updateTemplate === true) { // Update certificate template url in certificateTemplates collection - let updateCertificateTemplate = await this.update( + updateCertificateTemplate = await this.update( templateId, { // certificateTemplates/6343bd978f9d8980b7841e85/ba9aa220-ff1b-4717-b6ea-ace55f04fc16_2022-9-10-1665383945769.svg templateUrl : signedUrl.data.templates.files[0].payload.sourcePath } ); - return resolve({ - success: true, - data: { - templateId: updateCertificateTemplate.data.id, - templateUrl: signedUrl.data.templates.files[0].payload.sourcePath - } + success: true, + data: { + templateId: updateCertificateTemplate.data.id, + templateUrl: signedUrl.data.templates.files[0].payload.sourcePath + } }) - + } + return resolve({ + success: true, + data: { + templateUrl: signedUrl.data.templates.files[0].payload.sourcePath + } + }) + } catch (error) { return reject(error); } @@ -177,4 +184,111 @@ module.exports = class CertificateTemplatesHelper { } }); } + + /** + * create svg template by editing base template. + * @method + * @name editSvg + * @param {Object} files - file to replace. + * @param {Object} textData - texts to edit. + * @param {String} templateUrl - Base template filepath. + * @returns {JSON} Uploaded certificate template details. + */ + static editSvg( files, textData, templateUrl ) { + return new Promise(async (resolve, reject) => { + try { + // getDownloadable url of svg file that we are using as template + let baseTemplateDownloadableUrl = await filesHelpers.getDownloadableUrl([templateUrl]); + let baseTemplate = await getBaseTemplate( baseTemplateDownloadableUrl.result[0].url) + if ( !baseTemplate.success ) { + throw { + message: constants.apiResponses.BASE_CERTIFICATE_TEMPLATE_NOT_FOUND + } + } + // load Base template svg elements + const $ = cheerio.load(baseTemplate.result); + let htmltags = ["","","","","",""]; + let imageNames = ["stateLogo1","stateLogo2","signatureImg1","signatureImg2"]; + let textKeys = ["stateTitle","signatureTitle1a","signatureTitle2a"]; + + // edit image elements + for ( let imageNamesIndex = 0; imageNamesIndex < imageNames.length; imageNamesIndex++ ) { + + if ( files[imageNames[imageNamesIndex]] && files[imageNames[imageNamesIndex]]['data'] && files[imageNames[imageNamesIndex]]['data'] != "" ) { + let data = files[imageNames[imageNamesIndex]]['data']; + let imageData = 'data:image/png;base64,' + data.toString('base64'); + const element = $('#' + imageNames[imageNamesIndex]); + element.attr('href',imageData); + } + + } + + // edit text elements + for ( let textKeysIndex = 0; textKeysIndex < textKeys.length; textKeysIndex++ ) { + + if ( textData[textKeys[textKeysIndex]] ) { + let updateText = textData[textKeys[textKeysIndex]]; + const element = $('#' + textKeys[textKeysIndex]); + element.text(updateText); + } + } + let updatedSvg = $.html(); + + // remove html tags- svg file does not require these tags + for ( let index = 0; index < htmltags.length; index++ ) { + updatedSvg = updatedSvg.replace( htmltags[index], "" ); + } + + // file data to upload to cloud + let fileData = { + file : { + data: updatedSvg + } + }; + // upload new svg created from base template to cloud + const uploadTemplate = await this.uploadToCloud(fileData, "BASE_TEMPLATE", "", false ) + if ( !uploadTemplate.success ) { + throw { + message : constants.apiResponses.COULD_NOT_UPLOAD_CONTENT + } + } + + // getDownloadable url of uploaded template + let downloadableUrl = await filesHelpers.getDownloadableUrl([uploadTemplate.data.templateUrl]); + return resolve({ + message: "Template edited successfully", + result: { + url: downloadableUrl.result[0].url + } + }); + } catch (error) { + return reject(error); + } + }) + } + +} + +// Function to fetch data information from cloud using downloadable Url +const getBaseTemplate = function ( templateUrl ) { + return new Promise(async (resolve, reject) => { + try { + request.get(templateUrl, function (error, response, body) { + if (!error && response.statusCode == 200) { + + return resolve({ + success: true, + result: body + }); + } else { + throw { + success: false + } + } + }); + + } catch (error) { + return reject(error); + } + }) } diff --git a/module/certificateTemplates/validator/v1.js b/module/certificateTemplates/validator/v1.js index 588038cd..54b541ed 100644 --- a/module/certificateTemplates/validator/v1.js +++ b/module/certificateTemplates/validator/v1.js @@ -23,6 +23,9 @@ module.exports = (req) => { }, uploadCertificateTemplate : function () { req.checkParams("_id").exists().withMessage("required certificate templateId"); + }, + editSvg : function () { + req.checkQuery("baseTemplateFilePath").not().isEmpty().withMessage("Please provide base template filepath as baseTemplateFilePath. This cannot be empty") } } diff --git a/package.json b/package.json index 08459a30..32642b16 100644 --- a/package.json +++ b/package.json @@ -29,6 +29,7 @@ "cache-manager": "^2.9.0", "chai": "^4.2.0", "chai-http": "^4.3.0", + "cheerio": "^1.0.0-rc.12", "cli-table": "^0.3.1", "commander": "^2.20.0", "cors": "^2.8.4", From 156fa40315804abcdf775f737e614e0db7cc9b3f Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 24 Nov 2022 16:31:08 +0530 Subject: [PATCH 217/331] solution projection updated --- module/solutions/helper.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/module/solutions/helper.js b/module/solutions/helper.js index aa105885..11e51c58 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -817,7 +817,6 @@ module.exports = class SolutionsHelper { if( !queryData.success ) { return resolve(queryData); } - queryData.data["_id"] = solutionId; let targetedSolutionDetails = await this.solutionDocuments( @@ -836,7 +835,8 @@ module.exports = class SolutionsHelper { "entityTypeId", "language", "creator", - "link" + "link", + "certificateTemplateId" ] ); From de740466260bbcaf6f49f339d10a6299fd3df06a Mon Sep 17 00:00:00 2001 From: Priyanka Pradeep Date: Mon, 28 Nov 2022 16:10:15 +0530 Subject: [PATCH 218/331] solution list fix --- module/solutions/helper.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 11e51c58..648b1421 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -693,7 +693,8 @@ module.exports = class SolutionsHelper { "endDate", "link", "referenceFrom", - "entityType" + "entityType", + "certificateTemplateId" ] ); From edaf3b41222632aa7b7a2a1ca120d75e987deee9 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Tue, 13 Dec 2022 20:06:05 +0530 Subject: [PATCH 219/331] user-extension solution api : criteriaLevelReport and scoringSystem added to projection --- module/user-extension/helper.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/module/user-extension/helper.js b/module/user-extension/helper.js index 74d03dfa..a468e55a 100644 --- a/module/user-extension/helper.js +++ b/module/user-extension/helper.js @@ -667,7 +667,9 @@ module.exports = class UserExtensionHelper { "name", "type", "subType", - "isRubricDriven" + "isRubricDriven", + "scoringSystem", + "criteriaLevelReport" ]); return resolve({ From 8763643f3d78a516ff9afc55459bbf43b2ced222 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 29 Dec 2022 13:35:55 +0530 Subject: [PATCH 220/331] solutions model updated : rootOrganisations and createdFor added --- models/solutions.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/models/solutions.js b/models/solutions.js index 389027a7..fe162fa5 100644 --- a/models/solutions.js +++ b/models/solutions.js @@ -100,6 +100,8 @@ module.exports = { default: 1 }, reportInformation : Object, - certificateTemplateId : "ObjectId" + certificateTemplateId : "ObjectId", + rootOrganisations : Array, + createdFor : Array } }; \ No newline at end of file From 32c29bcc651f125cfc00027726fd58c6a8452ba7 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Tue, 10 Jan 2023 18:47:57 +0530 Subject: [PATCH 221/331] ED-599 PII data story- kafka added, join api added, solutions api updated, model aded --- config/index.js | 11 +++ config/kafka.js | 98 +++++++++++++++++++++ controllers/v1/programUsers.js | 22 +++++ controllers/v1/programs.js | 55 +++++++++++- controllers/v1/users.js | 3 +- envVariables.js | 8 ++ generics/constants/api-responses.js | 4 +- generics/constants/endpoints.js | 3 +- generics/kafka/producers.js | 85 +++++++++++++++++++ generics/services/users.js | 6 +- models/programUsers.js | 37 ++++++++ models/programs.js | 4 + module/programs/helper.js | 127 ++++++++++++++++++++++++++++ module/programs/validator/v1.js | 7 +- module/users/helper.js | 21 ++++- 15 files changed, 481 insertions(+), 10 deletions(-) create mode 100644 config/kafka.js create mode 100644 controllers/v1/programUsers.js create mode 100644 generics/kafka/producers.js create mode 100644 models/programUsers.js diff --git a/config/index.js b/config/index.js index 18fd6178..b77a7c37 100644 --- a/config/index.js +++ b/config/index.js @@ -27,6 +27,16 @@ let db_connect = function () { // global.elasticsearch = require("./db/elastic-search")(); // }; +/** + * Kafka connection. + * @function + * @name kafka_connect +*/ + +const kafka_connect = function() { + global.kafkaClient = require("./kafka")(); +}; + const configuration = { root: require("path").normalize(__dirname + "/.."), app: { @@ -35,6 +45,7 @@ const configuration = { }; db_connect(); +kafka_connect(); // elasticsearch_connect(); module.exports = configuration; diff --git a/config/kafka.js b/config/kafka.js new file mode 100644 index 00000000..732d0c73 --- /dev/null +++ b/config/kafka.js @@ -0,0 +1,98 @@ +/** + * name : kafka.js + * author : vishnu + * created-date : 10-Jan-2023 + * Description : Kafka Configurations related information. +*/ + + +//dependencies +const kafka = require('kafka-node'); +const PROGRAM_USERS_SUBMISSION_TOPIC = process.env.PROGRAM_USERS_SUBMISSION_TOPIC; + +/** + * Kafka configurations. + * @function + * @name connect +*/ + +const connect = function() { + + const Producer = kafka.Producer + KeyedMessage = kafka.KeyedMessage + + const client = new kafka.KafkaClient({ + kafkaHost : process.env.KAFKA_URL + }); + + client.on('error', function(error) { + console.log("kafka connection error!") + }); + + const producer = new Producer(client) + + producer.on('ready', function () { + console.log("Connected to Kafka"); + }); + + producer.on('error', function (err) { + console.log("kafka producer creation error!") + }) + + _sendToKafkaConsumers( + PROGRAM_USERS_SUBMISSION_TOPIC, + process.env.KAFKA_URL + ); + + return { + kafkaProducer: producer, + kafkaClient: client + }; + +}; + +/** + * Send data based on topic to kafka consumers + * @function + * @name _sendToKafkaConsumers + * @param {String} topic - name of kafka topic. + * @param {String} host - kafka host +*/ + +var _sendToKafkaConsumers = function (topic,host) { + + if (topic && topic != "") { + + let consumer = new kafka.ConsumerGroup( + { + kafkaHost : host, + groupId : process.env.KAFKA_GROUP_ID, + autoCommit : true + },topic + ); + + consumer.on('message', async function (message) { + + console.log("-------Kafka consumer log starts here------------------"); + console.log("Topic Name: ", topic); + console.log("Message: ", JSON.stringify(message)); + console.log("-------Kafka consumer log ends here------------------"); + + + if (message && message.topic === PROGRAM_USERS_SUBMISSION_TOPIC) { + submissionsConsumer.messageReceived(message); + } + }); + + consumer.on('error', async function (error) { + + if(error.topics && error.topics[0] === PROGRAM_USERS_SUBMISSION_TOPIC) { + submissionsConsumer.errorTriggered(error); + } + + }); + + } +}; + +module.exports = connect; diff --git a/controllers/v1/programUsers.js b/controllers/v1/programUsers.js new file mode 100644 index 00000000..6ed2242d --- /dev/null +++ b/controllers/v1/programUsers.js @@ -0,0 +1,22 @@ +/** + * name : programUsers.js + * author : Vishnu + * created-date : 9-Jan-2023 + * Description : PII data related controller. +*/ + +/** + * programUsers + * @class + */ +module.exports = class ProgramUsers extends Abstract { + constructor() { + super(schemas["programUsers"]); + } + + static get name() { + return "programUsers"; + } + +}; + diff --git a/controllers/v1/programs.js b/controllers/v1/programs.js index 9992ab31..6f2fd5ea 100644 --- a/controllers/v1/programs.js +++ b/controllers/v1/programs.js @@ -492,4 +492,57 @@ module.exports = class Programs extends Abstract { }); } -} \ No newline at end of file + /** + * @api {get} /assessment/api/v1/programs/join/:programId + * @apiVersion 1.0.0 + * @apiName Program Join + * @apiGroup Programs + * @apiHeader {String} X-authenticated-user-token Authenticity token + * @apiHeader {String} X-App-Ver Appversion + * @apiSampleRequest /assessment/api/v1/programs/join/5ffbf8909259097d48017bbf + * @apiUse successBody + * @apiUse errorBody + * @apiParamExample {json} Response: + * + */ + + /** + * join program + * @method + * @name join + * @param {Object} req - requested data. + * @param {String} req.params._id - program id. + * @returns {Object} Program join status. + */ + + async join(req) { + return new Promise(async (resolve, reject) => { + try { + + let programJoin = await programsHelper.join( + req.params._id, + req.body, + req.userDetails.userId, + req.userDetails.userToken, + req.headers["x-app-id"] ? + req.headers["x-app-id"] : + req.headers.appname ? req.headers.appname : "", + req.headers["x-app-ver"] ? + req.headers["x-app-ver"] : + req.headers.appversion ? req.headers.appversion : "" + ); + programJoin["result"] = programJoin.data; + return resolve(programJoin); + + } catch (error) { + return reject({ + status: error.status || httpStatusCode.internal_server_error.status, + message: error.message || httpStatusCode.internal_server_error.message, + errorObject: error + }); + } + }); + } + +} + diff --git a/controllers/v1/users.js b/controllers/v1/users.js index 813416ff..b99dc11c 100644 --- a/controllers/v1/users.js +++ b/controllers/v1/users.js @@ -277,7 +277,8 @@ module.exports = class Users extends Abstract { req.pageSize, req.pageNo, req.searchText, - req.userDetails.userToken + req.userDetails.userToken, + req.userDetails.userId ); targetedSolutions["result"] = targetedSolutions.data; diff --git a/envVariables.js b/envVariables.js index 655142c6..a5ea3486 100644 --- a/envVariables.js +++ b/envVariables.js @@ -190,6 +190,14 @@ let enviromentVariables = { "value" : "OCI" } }, + "KAFKA_COMMUNICATIONS_ON_OFF" : { + "message" : "Enable/Disable kafka communications", + "optional" : false + }, + "KAFKA_URL" : { + "message" : "Required", + "optional" : false + }, } let success = true; diff --git a/generics/constants/api-responses.js b/generics/constants/api-responses.js index ef66e329..52c580d5 100644 --- a/generics/constants/api-responses.js +++ b/generics/constants/api-responses.js @@ -190,5 +190,7 @@ module.exports = { "CERTIFICATE_TEMPLATE_ADDED" : "Template added successfully", "CERTIFICATE_TEMPLATE_UPDATED" : "Template updated successfully", "CERTIFICATE_TEMPLATE_NOT_UPDATED" : "Template updation failed", - "BASE_CERTIFICATE_TEMPLATE_NOT_FOUND" : "Base certificate template not found" + "BASE_CERTIFICATE_TEMPLATE_NOT_FOUND" : "Base certificate template not found", + "PROGRAM_JOIN_FAILED" : "Failed to join program", + "JOINED_PROGRAM" : "You have joined this program successfully" }; diff --git a/generics/constants/endpoints.js b/generics/constants/endpoints.js index 2deb5488..8e9ae543 100644 --- a/generics/constants/endpoints.js +++ b/generics/constants/endpoints.js @@ -33,5 +33,6 @@ module.exports = { GET_OBSERVATION : "/v1/observations/details", GET_LOCATION_DATA : "/v1/location/search", GET_FORM_DATA : "/plugin/v1/form/read", - GET_SCHOOL_DATA : "/v1/org/search" + GET_SCHOOL_DATA : "/v1/org/search", + USER_READ_V5 : "/v5/user/read" } \ No newline at end of file diff --git a/generics/kafka/producers.js b/generics/kafka/producers.js new file mode 100644 index 00000000..4b9646c1 --- /dev/null +++ b/generics/kafka/producers.js @@ -0,0 +1,85 @@ +/** + * name : producer.js + * author : Vishnu + * created-date : 10-Jan-2023 + * Description : Kafka Producer related information. +*/ + +// Dependencies +const kafkaCommunicationsOnOff = (!process.env.KAFKA_COMMUNICATIONS_ON_OFF || process.env.KAFKA_COMMUNICATIONS_ON_OFF != "OFF") ? "ON" : "OFF"; +const programUsersSubmissionTopic = (process.env.PROGRAM_USERS_SUBMISSION_TOPIC && process.env.PROGRAM_USERS_SUBMISSION_TOPIC != "OFF") ? process.env.PROGRAM_USERS_SUBMISSION_TOPIC : "sl-improvement-project-submission-dev"; + +/** + * Push program users to kafka. + * @function + * @name pushProgramUsersToKafka + * @param {Object} message - Message data. +*/ + +const pushProgramUsersToKafka = function (message) { + return new Promise(async (resolve, reject) => { + try { + + let kafkaPushStatus = await pushMessageToKafka([{ + topic: programUsersSubmissionTopic, + messages: JSON.stringify(message) + }]); + + return resolve(kafkaPushStatus); + + } catch (error) { + return reject(error); + } + }) +} + + + +/** + * Push message to kafka. + * @function + * @name pushMessageToKafka + * @param {Object} payload - Payload data. +*/ + +const pushMessageToKafka = function(payload) { + return new Promise((resolve, reject) => { + + if (kafkaCommunicationsOnOff != "ON") { + throw reject("Kafka configuration is not done"); + } + + console.log("-------Kafka producer log starts here------------------"); + console.log("Topic Name: ", payload[0].topic); + console.log("Message: ", JSON.stringify(payload)); + console.log("-------Kafka producer log ends here------------------"); + + + kafkaClient.kafkaProducer.send(payload, (err, data) => { + if (err) { + return reject("Kafka push to topic "+ payload[0].topic +" failed."); + } else { + return resolve(data); + } + }) + + }).then(result => { + + return { + status : "success", + message: "Kafka push to topic "+ payload[0].topic +" successful with number - "+result[payload[0].topic][0] + }; + + }).catch((err) => { + return { + status : "failed", + message: err + } + }) +} + + +module.exports = { + pushProgramUsersToKafka : pushProgramUsersToKafka +}; + diff --git a/generics/services/users.js b/generics/services/users.js index dad76493..c1ce2fbb 100644 --- a/generics/services/users.js +++ b/generics/services/users.js @@ -12,11 +12,11 @@ const userServiceUrl = process.env.USER_SERVICE_URL; const profile = function ( token,userId = "" ) { return new Promise(async (resolve, reject) => { try { - - let url = userServiceUrl + constants.endpoints.USER_READ; + + let url = userServiceUrl + constants.endpoints.USER_READ_V5; if( userId !== "" ) { - url = url + "/" + userId; + url = url + "/" + userId + "?" + "fields=organisations,roles,locations,declarations,externalIds" } const options = { diff --git a/models/programUsers.js b/models/programUsers.js new file mode 100644 index 00000000..29f1cb28 --- /dev/null +++ b/models/programUsers.js @@ -0,0 +1,37 @@ +module.exports = { + name: "programUsers", + schema: { + programId: { + type : "ObjectId", + required: true, + index: true + }, + consentForPIIDataSharing: { + agree: Boolean, + date: Date + }, + consentHistory: { + type: Array, + default: [] + }, + userId: { + type: String, + index: true + }, + noOfResourcesStarted: { + type:Number, + index: true + }, + userProfile: Object, + userRoleInformation: Object, + appInformation: Object + }, + compoundIndex: [ + { + "name" :{ userId: 1, programId: 1 }, + "indexType" : { unique: true } + } + ] +}; + + \ No newline at end of file diff --git a/models/programs.js b/models/programs.js index 233fd9d6..abedc577 100644 --- a/models/programs.js +++ b/models/programs.js @@ -47,6 +47,10 @@ module.exports = { default : false, type : Boolean, index : true + }, + requestForPIIConsent: { + type: Boolean, + default: false } } }; diff --git a/module/programs/helper.js b/module/programs/helper.js index 7698b109..1b7db92b 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -11,6 +11,7 @@ const entityTypesHelper = require(MODULES_BASE_PATH + "/entityTypes/helper"); const entitiesHelper = require(MODULES_BASE_PATH + "/entities/helper"); const userRolesHelper = require(MODULES_BASE_PATH + "/user-roles/helper"); const userService = require(ROOT_PATH + "/generics/services/users"); +const kafkaProducersHelper = require(ROOT_PATH + "/generics/kafka/producers"); /** * ProgramsHelper @@ -976,6 +977,132 @@ module.exports = class ProgramsHelper { }); } + /** + * Program join. + * @method + * @name join + * @param {String} programId - Program Id. + * @param {Object} data - body data. + * @param {String} userId - Logged in user id. + * @param {String} userToken - User token. + * @param {String} [appName = ""] - App Name. + * @param {String} [appVersion = ""] - App Version. + * @returns {Object} - Details of the program join. + */ + + static join( programId, data, userId, userToken, appName = "", appVersion = "" ) { + return new Promise(async (resolve, reject) => { + try { + //Using programId fetch program name. Also checking the program status in the query. + let programData = await this.programDocuments({ + _id: programId, + status: constants.common.ACTIVE + },["name"]); + + if ( !programData.length > 0 ) { + throw ({ + status: httpStatusCode.bad_request.status, + message: constants.apiResponses.PROGRAM_NOT_FOUND + }); + } + + let programUsersData = {}; + //Fetch user profile information by calling sunbird's user read api. + //!Important check specific fields of userProfile. + let userProfile = await userService.profile(userToken, userId); + if ( !userProfile.success || + !userProfile.data || + !userProfile.data.response + ) { + throw ({ + status: httpStatusCode.bad_request.status, + message: constants.apiResponses.PROGRAM_JOIN_FAILED + }); + } + programUsersData = { + programId: programId, + userRoleInformation: data.userRoleInformation, + userId: userId, + userProfile: userProfile.data.response + } + if( appName != "" ) { + programUsersData['appInformation.appName'] = appName; + } + if( appVersion != "" ) { + programUsersData['appInformation.appVersion'] = appVersion; + } + + //consentForPIIDataSharing is optional. + if( data.consentForPIIDataSharing == true || data.consentForPIIDataSharing == false ) { + programUsersData.consentForPIIDataSharing = { + agree: data.consentForPIIDataSharing, + date: new Date() + } + } + + //create or update query + const query = { + programId: programId, + userId: userId + }; + + //Check data already present in db. + const programUsers = await database.models.programUsers.find( + query, + ["consentForPIIDataSharing"] + ).lean(); + + // Data already present in programUsers collection, Require updation, else create new entry. + let joinProgram; + if( programUsers.length > 0 ) { + + let update = {}; + if( programUsers[0].consentForPIIDataSharing && (data.consentForPIIDataSharing == true || data.consentForPIIDataSharing == false )) { + update['$push'] = { consentHistory: programUsers[0].consentForPIIDataSharing } + } + update['$set'] = programUsersData; + joinProgram = await database.models.programUsers.findOneAndUpdate(query, update, {new:true}); + + } else { + + joinProgram = + await database.models.programUsers.create( + programUsersData + ); + + } + if (!joinProgram._id) { + throw { + message: constants.apiResponses.PROGRAM_JOIN_FAILED, + status: httpStatusCode.bad_request.status + } + } + joinProgram.programName = programData[0].name; + + // push programUsers details to kafka + await kafkaProducersHelper.pushProgramUsersToKafka(joinProgram); + + return resolve({ + message: constants.apiResponses.JOINED_PROGRAM, + success: true, + data: { + _id : joinProgram._id + } + }); + + } catch (error) { + console.log("error:",error) + return resolve({ + success: false, + status: error.status + ? error.status + : httpStatusCode['internal_server_error'].status, + message: error.message + }); + } + }); + } + }; const solutionsHelper = require(MODULES_BASE_PATH + "/solutions/helper"); \ No newline at end of file diff --git a/module/programs/validator/v1.js b/module/programs/validator/v1.js index 4cb484c3..a5da3c80 100644 --- a/module/programs/validator/v1.js +++ b/module/programs/validator/v1.js @@ -31,7 +31,12 @@ module.exports = (req) => { removeEntitiesInScope : function () { req.checkParams("_id").exists().withMessage("required program id"); req.checkBody("entities").exists().withMessage("required entities to be added"); - } + }, + join : function () { + req.checkParams("_id").exists().withMessage("required program id"); + req.checkParams("_id").isMongoId().withMessage("invalid Mongo Id"); + req.checkBody("userRoleInformation").exists().withMessage("required userRoleInformation to be added"); + }, } if (programsValidator[req.params.method]) { diff --git a/module/users/helper.js b/module/users/helper.js index b7d3c3b1..24c6fe68 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -436,10 +436,12 @@ module.exports = class UsersHelper { * @param {String} pageSize page size. * @param {String} pageNo page no. * @param {String} search search text. + * @param {String} token user token. + * @param {String} userId user userId. * @returns {Object} targeted user solutions. */ - static solutions(programId, requestedData, pageSize, pageNo, search, token) { + static solutions(programId, requestedData, pageSize, pageNo, search, token, userId) { return new Promise(async (resolve, reject) => { try { @@ -447,7 +449,7 @@ module.exports = class UsersHelper { { _id: programId }, - ["name"] + ["name","requestForPIIConsent"] ); if (!programData.length > 0) { @@ -539,10 +541,25 @@ module.exports = class UsersHelper { programName: programData[0].name, programId: programId, description: constants.common.TARGETED_SOLUTION_TEXT, + requestForPIIConsent: programData[0].requestForPIIConsent ? programData[0].requestForPIIConsent : false, data: mergedData, count: totalCount }; + //check programUsers collection for consentForPIIDataSharing + let programUsersData = await database.models.programUsers.find( + { + programId: programId, + userId: userId + }, + ["consentForPIIDataSharing"] + ).lean(); + + //if consentForPIIDataSharing is present append with response + if( programUsersData.length > 0 && programUsersData[0].consentForPIIDataSharing ) { + result.consentForPIIDataSharing = programUsersData[0].consentForPIIDataSharing; + } + return resolve({ message: constants.apiResponses.PROGRAM_SOLUTIONS_FETCHED, success: true, From e3df299eae0ad75021dad58f6b5ec243a1c52017 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 12 Jan 2023 08:22:04 +0530 Subject: [PATCH 222/331] admin api optimization --- controllers/v1/certificateBaseTemplates.js | 83 ++++++++++++++ controllers/v1/certificateTemplates.js | 14 +-- generics/constants/api-responses.js | 4 +- models/certificateBaseTemplates.js | 16 +++ models/certificateTemplates.js | 3 +- module/certificateBaseTemplates/helper.js | 103 ++++++++++++++++++ .../certificateBaseTemplates/validator/v1.js | 27 +++++ module/certificateTemplates/helper.js | 16 ++- module/certificateTemplates/validator/v1.js | 5 +- 9 files changed, 257 insertions(+), 14 deletions(-) create mode 100644 controllers/v1/certificateBaseTemplates.js create mode 100644 models/certificateBaseTemplates.js create mode 100644 module/certificateBaseTemplates/helper.js create mode 100644 module/certificateBaseTemplates/validator/v1.js diff --git a/controllers/v1/certificateBaseTemplates.js b/controllers/v1/certificateBaseTemplates.js new file mode 100644 index 00000000..170bce10 --- /dev/null +++ b/controllers/v1/certificateBaseTemplates.js @@ -0,0 +1,83 @@ +/** + * name : certificateBaseTemplates.js + * author : Vishnu + * created-date : 11-Jan-2023 + * Description : Certificate base template related information. +*/ + +// Dependencies +const certificateBaseTemplateHelper = require(MODULES_BASE_PATH + "/certificateBaseTemplates/helper"); + +module.exports = class CertificateBaseTemplates extends Abstract { + // Adding model schema + constructor() { + super(schemas["certificateBaseTemplates"]); + } + + /** + * @api {post/patch} /kendra/api/v1/certificateBaseTemplates/createOrUpdate + * @apiVersion 1.0.0 + * @apiName Create certificate template + * @apiGroup certificateBaseTemplates + * @apiParamExample {json} Request-Body: + * { + "code": "SingleLogoSingleSign" + } + + * @apiHeader {String} internal-access-token - internal access token + * @apiHeader {String} X-authenticated-user-token - Authenticity token + * @apiSampleRequest /kendra/api/v1/certificateBaseTemplates/createOrUpdate + * @apiUse successBody + * @apiUse errorBody + * @apiParamExample {json} Response: + * { + "status": 200, + "message": "Base template added successfully", + "result": { + id": "6011136a2d25b926974d9ec9" + } + } + */ + + /** + * Create/update certificate base template. + * @method + * @name createOrUpdate + * @param {Object} req - requested data. + * @returns {JSON} Created certificate base template data. + */ + + async createOrUpdate(req) { + return new Promise(async (resolve, reject) => { + try { + if ( req.method === "POST" ) { + if ( req.files && req.files.file ) { + let certificateBaseTemplateData = await certificateBaseTemplateHelper.create( req.body, req.files, req.userDetails.userId ); + certificateBaseTemplateData["result"] = certificateBaseTemplateData.data; + return resolve(certificateBaseTemplateData); + } else { + throw ({ + status: httpStatusCode["bad_request"].status, + message: httpStatusCode["bad_request"].message + }); + } + } else if ( req.method === "PATCH" ) { + let certificateBaseTemplateData = await certificateBaseTemplateHelper.update( + req.params._id, + req.body, + req.files, + req.userDetails.userId + ); + certificateBaseTemplateData["result"] = certificateBaseTemplateData.data; + return resolve(certificateBaseTemplateData); + } + } catch (error) { + return reject({ + status: error.status || httpStatusCode.internal_server_error.status, + message: error.message || httpStatusCode.internal_server_error.message, + errorObject: error + }); + } + }); + } +} \ No newline at end of file diff --git a/controllers/v1/certificateTemplates.js b/controllers/v1/certificateTemplates.js index 8db7b181..e0a74d27 100644 --- a/controllers/v1/certificateTemplates.js +++ b/controllers/v1/certificateTemplates.js @@ -200,13 +200,13 @@ module.exports = class CertificateTemplates extends Abstract { }); } /** - * @api {post} /kendra/api/v1/certificateTemplates/editSvg + * @api {post} /kendra/api/v1/certificateTemplates/createSvg * @apiVersion 1.0.0 - * @apiName edit certificate template svg - * @apiGroup editSvg + * @apiName createSvg certificate template svg + * @apiGroup createSvg * @apiHeader {String} internal-access-token - internal access token * @apiHeader {String} X-authenticated-user-token - Authenticity token - * @apiSampleRequest /kendra/api/v1/certificateTemplates/editSvg?baseTemplateFilePath=certificateTemplates/Base_template/ba9aa220-ff1b-4717-b6ea-ace55f04fc16_22-10-2022-1669118494135.svg + * @apiSampleRequest /kendra/api/v1/certificateTemplates/createSvg?baseTemplateId= * @apiUse successBody * @apiUse errorBody * @apiParamExample {json} Response: @@ -222,16 +222,16 @@ module.exports = class CertificateTemplates extends Abstract { /** * generate cettificate templateSvg. * @method - * @name editSvg + * @name createSvg * @param {Object} req - requested data. * @returns {JSON} -svg uploaded details. */ - async editSvg(req) { + async createSvg(req) { return new Promise(async (resolve, reject) => { try { - let svgData = await certificateTemplateHelper.editSvg(req.files, req.body, req.query.baseTemplateFilePath); + let svgData = await certificateTemplateHelper.createSvg(req.files, req.body, req.query.baseTemplateId); return resolve(svgData); } catch (error) { return reject({ diff --git a/generics/constants/api-responses.js b/generics/constants/api-responses.js index ef66e329..0fa43321 100644 --- a/generics/constants/api-responses.js +++ b/generics/constants/api-responses.js @@ -190,5 +190,7 @@ module.exports = { "CERTIFICATE_TEMPLATE_ADDED" : "Template added successfully", "CERTIFICATE_TEMPLATE_UPDATED" : "Template updated successfully", "CERTIFICATE_TEMPLATE_NOT_UPDATED" : "Template updation failed", - "BASE_CERTIFICATE_TEMPLATE_NOT_FOUND" : "Base certificate template not found" + "BASE_CERTIFICATE_TEMPLATE_NOT_FOUND" : "Base certificate template not found", + "CERTIFICATE_BASE_TEMPLATE_UPDATED" : "Base template updated successfully", + "CERTIFICATE_BASE_TEMPLATE_NOT_UPDATED" : "Base template updation failed", }; diff --git a/models/certificateBaseTemplates.js b/models/certificateBaseTemplates.js new file mode 100644 index 00000000..910ec841 --- /dev/null +++ b/models/certificateBaseTemplates.js @@ -0,0 +1,16 @@ +module.exports = { + name: "certificateBaseTemplates", + schema: { + code: { + type : String, + required : true, + index: true + }, + name: { + type : String + }, + url: { + type : String, + } + } +}; \ No newline at end of file diff --git a/models/certificateTemplates.js b/models/certificateTemplates.js index 1883773d..929b8542 100644 --- a/models/certificateTemplates.js +++ b/models/certificateTemplates.js @@ -24,6 +24,7 @@ module.exports = { criteria: { type : Object, required : true - } + }, + baseTemplateId : "ObjectId" } }; \ No newline at end of file diff --git a/module/certificateBaseTemplates/helper.js b/module/certificateBaseTemplates/helper.js new file mode 100644 index 00000000..28e912b4 --- /dev/null +++ b/module/certificateBaseTemplates/helper.js @@ -0,0 +1,103 @@ +/** + * name : helper.js + * author : Vishnu + * created-date : 11-Jan-2023 + * Description : Certificate Template related helper functionality. +*/ +// dependencies +const certificateTemplateHelper = require(MODULES_BASE_PATH + "/certificateTemplates/helper"); + +/** + * CertificateBaseTemplatesHelper + * @class +*/ +module.exports = class CertificateBaseTemplatesHelper { + + /** + * Create certificate base template. + * @method create + * @name create + * @param {Object} data - certificate base template creation data. + * @returns {JSON} created certificate base template details. + */ + + static create( data, file, userId ) { + return new Promise(async (resolve, reject) => { + try { + let dir = "BaseTemplate"; + let uploadFile = await certificateTemplateHelper.uploadToCloud( file, dir, userId, false ); + if( !uploadFile.success ) { + throw ({ + message: constants.apiResponses.COULD_NOT_UPLOAD_CONTENT + }) + } + data.url = uploadFile.data.templateUrl; + let certificateTemplateCreated = + await database.models.certificateBaseTemplates.create( + data + ); + return resolve({ + message : constants.apiResponses.CERTIFICATE_BASE_TEMPLATE_ADDED, + data : { + id : certificateTemplateCreated._id + } + }); + + } catch (error) { + return reject(error); + } + }); + } + + /** + * Update certificate base template. + * @method update + * @name update + * @param {Object} data - certificate template updation data. + * @param {String} baseTemplateId - certificate template Id. + * @param {String} file - file. + * @param {String} userId - userId. + * @returns {JSON} Updated certificate template details. + */ + + static update( baseTemplateId, data, file = {}, userId ) { + return new Promise(async (resolve, reject) => { + try { + if ( Object.keys(file).length > 0 ) { + let dir = "BaseTemplate"; + let uploadFile = await certificateTemplateHelper.uploadToCloud( file, dir, userId, false ); + if( !uploadFile.success ) { + throw ({ + message: constants.apiResponses.COULD_NOT_UPLOAD_CONTENT + }) + } + data.url = uploadFile.data.templateUrl; + } + + let updateObject = { + "$set" : data + }; + let certificateBaseTemplateUpdated = + await database.models.certificateBaseTemplates.findOneAndUpdate( + baseTemplateId, + updateObject + ); + if ( certificateBaseTemplateUpdated == null ) { + throw{ + message: constants.apiResponses.CERTIFICATE_BASE_TEMPLATE_NOT_UPDATED + } + } + return resolve({ + message : constants.apiResponses.CERTIFICATE_BASE_TEMPLATE_UPDATED, + data : { + id : certificateBaseTemplateUpdated._id + } + }); + + } catch (error) { + return reject(error); + } + }); + } + +} diff --git a/module/certificateBaseTemplates/validator/v1.js b/module/certificateBaseTemplates/validator/v1.js new file mode 100644 index 00000000..428cde70 --- /dev/null +++ b/module/certificateBaseTemplates/validator/v1.js @@ -0,0 +1,27 @@ +/** + * name : v1.js + * author : Vishnu + * created-date : 11-Jan-2023 + * Description : Certificate Base Template Validation. +*/ + +module.exports = (req) => { + + let certificateBaseTemplatesValidator = { + + createOrUpdate : function () { + if ( req.method === "POST" ) { + req.checkBody("code").exists().withMessage("Base template code required"); + req.checkBody("name").exists().withMessage("Base template name required"); + } else if ( req.method === "PATCH" ) { + req.checkParams("_id").exists().withMessage("Base template Id required"); + req.checkParams("_id").isMongoId().withMessage("Base template Id is not valid"); + } + } + } + + if (certificateBaseTemplatesValidator[req.params.method]) { + certificateBaseTemplatesValidator[req.params.method](); + } + +}; \ No newline at end of file diff --git a/module/certificateTemplates/helper.js b/module/certificateTemplates/helper.js index 38333a7b..7371093d 100644 --- a/module/certificateTemplates/helper.js +++ b/module/certificateTemplates/helper.js @@ -188,15 +188,25 @@ module.exports = class CertificateTemplatesHelper { /** * create svg template by editing base template. * @method - * @name editSvg + * @name createSvg * @param {Object} files - file to replace. * @param {Object} textData - texts to edit. - * @param {String} templateUrl - Base template filepath. + * @param {String} baseTemplateId - Base template Id. * @returns {JSON} Uploaded certificate template details. */ - static editSvg( files, textData, templateUrl ) { + static createSvg( files, textData, baseTemplateId ) { return new Promise(async (resolve, reject) => { try { + let baseTemplateData = await database.models.certificateBaseTemplates.find({ + _id: baseTemplateId + },["url"]).lean(); + + if ( !baseTemplateData.length > 0 || !baseTemplateData[0].url || baseTemplateData[0].url == "" ) { + throw { + message: constants.apiResponses.BASE_CERTIFICATE_TEMPLATE_NOT_FOUND + } + } + let templateUrl = baseTemplateData[0].url; // getDownloadable url of svg file that we are using as template let baseTemplateDownloadableUrl = await filesHelpers.getDownloadableUrl([templateUrl]); let baseTemplate = await getBaseTemplate( baseTemplateDownloadableUrl.result[0].url) diff --git a/module/certificateTemplates/validator/v1.js b/module/certificateTemplates/validator/v1.js index 54b541ed..0d7c1681 100644 --- a/module/certificateTemplates/validator/v1.js +++ b/module/certificateTemplates/validator/v1.js @@ -24,8 +24,9 @@ module.exports = (req) => { uploadCertificateTemplate : function () { req.checkParams("_id").exists().withMessage("required certificate templateId"); }, - editSvg : function () { - req.checkQuery("baseTemplateFilePath").not().isEmpty().withMessage("Please provide base template filepath as baseTemplateFilePath. This cannot be empty") + createSvg : function () { + req.checkQuery("baseTemplateId").not().isEmpty().withMessage("Please provide base template Id. This cannot be empty"); + req.checkQuery("baseTemplateId").isMongoId().withMessage("Base template Id is not valid"); } } From a8117845cc8ae6727fa74c635dae71da91850d16 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 12 Jan 2023 08:27:40 +0530 Subject: [PATCH 223/331] index for code removed, not querying anywhere using code --- models/certificateBaseTemplates.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/models/certificateBaseTemplates.js b/models/certificateBaseTemplates.js index 910ec841..2901f51f 100644 --- a/models/certificateBaseTemplates.js +++ b/models/certificateBaseTemplates.js @@ -3,11 +3,11 @@ module.exports = { schema: { code: { type : String, - required : true, - index: true + required : true }, name: { - type : String + type : String, + required : true }, url: { type : String, From c6fcda793ab4a59642547730cba6b354d14899e1 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 12 Jan 2023 09:11:27 +0530 Subject: [PATCH 224/331] url changes --- module/certificateBaseTemplates/helper.js | 6 ++---- module/certificateTemplates/helper.js | 17 +++++++++++++++-- module/cloud-services/files/helper.js | 3 +++ 3 files changed, 20 insertions(+), 6 deletions(-) diff --git a/module/certificateBaseTemplates/helper.js b/module/certificateBaseTemplates/helper.js index 28e912b4..87521306 100644 --- a/module/certificateBaseTemplates/helper.js +++ b/module/certificateBaseTemplates/helper.js @@ -24,8 +24,7 @@ module.exports = class CertificateBaseTemplatesHelper { static create( data, file, userId ) { return new Promise(async (resolve, reject) => { try { - let dir = "BaseTemplate"; - let uploadFile = await certificateTemplateHelper.uploadToCloud( file, dir, userId, false ); + let uploadFile = await certificateTemplateHelper.uploadToCloud( file, "", userId, false ); if( !uploadFile.success ) { throw ({ message: constants.apiResponses.COULD_NOT_UPLOAD_CONTENT @@ -64,8 +63,7 @@ module.exports = class CertificateBaseTemplatesHelper { return new Promise(async (resolve, reject) => { try { if ( Object.keys(file).length > 0 ) { - let dir = "BaseTemplate"; - let uploadFile = await certificateTemplateHelper.uploadToCloud( file, dir, userId, false ); + let uploadFile = await certificateTemplateHelper.uploadToCloud( file, "", userId, false ); if( !uploadFile.success ) { throw ({ message: constants.apiResponses.COULD_NOT_UPLOAD_CONTENT diff --git a/module/certificateTemplates/helper.js b/module/certificateTemplates/helper.js index 7371093d..d75434d8 100644 --- a/module/certificateTemplates/helper.js +++ b/module/certificateTemplates/helper.js @@ -109,19 +109,32 @@ module.exports = class CertificateTemplatesHelper { static uploadToCloud(fileData, templateId, userId = "", updateTemplate) { return new Promise(async (resolve, reject) => { try { + let fileName; const now = new Date(); const date = now.getDate() + "-"+ now.getMonth() + "-" + now.getFullYear() + "-" + now.getTime(); - const fileName = templateId + '/' + userId + "_" + date + ".svg"; + if ( updateTemplate == false ) { + fileName = userId + "_" + date + ".svg"; + } else { + fileName = templateId + '/' + userId + "_" + date + ".svg"; + } + const requestData = { "templates": { "files": [fileName] } }; + let referenceType; + if ( updateTemplate == false ) { + referenceType = "baseTemplates" + } else { + referenceType = constants.common.CERTIFICATE + } + let signedUrl = await filesHelpers.preSignedUrls( requestData, // data to upload - constants.common.CERTIFICATE, // referenceType + referenceType, // referenceType ); // upload file using signed Url diff --git a/module/cloud-services/files/helper.js b/module/cloud-services/files/helper.js index 6b2fb387..6f568c01 100644 --- a/module/cloud-services/files/helper.js +++ b/module/cloud-services/files/helper.js @@ -89,6 +89,9 @@ module.exports = class FilesHelper { } else if (referenceType == constants.common.CERTIFICATE) { // Folder path specifically for project certificates folderPath = "certificateTemplates/"; + } else if (referenceType == "baseTemplates") { + // Folder path specifically for project certificates + folderPath = "certificateBaseTemplates/"; } else { folderPath = "survey/" + payloadIds[0] + "/" + userId + "/" + gen.utils.generateUniqueId() + "/"; } From ce2f22d25cbcc156b345455f7322012594457d6a Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 12 Jan 2023 12:18:03 +0530 Subject: [PATCH 225/331] ED-599 programUsers helper added and db operations triggering from this helper --- generics/constants/api-responses.js | 5 +- module/programUsers/helper.js | 103 ++++++++++++++++++++++++++++ module/programs/helper.js | 38 +++++----- module/users/helper.js | 5 +- 4 files changed, 131 insertions(+), 20 deletions(-) create mode 100644 module/programUsers/helper.js diff --git a/generics/constants/api-responses.js b/generics/constants/api-responses.js index 52c580d5..89bdff31 100644 --- a/generics/constants/api-responses.js +++ b/generics/constants/api-responses.js @@ -192,5 +192,8 @@ module.exports = { "CERTIFICATE_TEMPLATE_NOT_UPDATED" : "Template updation failed", "BASE_CERTIFICATE_TEMPLATE_NOT_FOUND" : "Base certificate template not found", "PROGRAM_JOIN_FAILED" : "Failed to join program", - "JOINED_PROGRAM" : "You have joined this program successfully" + "JOINED_PROGRAM" : "You have joined this program successfully", + "PROGRAM_NOT_CREATED" : "Program not created", + "PROGRAM_USERS_NOT_CREATED" : "Program users not created", + "PROGRAM_USERS_NOT_UPDATED" : "Program users not updated" }; diff --git a/module/programUsers/helper.js b/module/programUsers/helper.js new file mode 100644 index 00000000..e82f2714 --- /dev/null +++ b/module/programUsers/helper.js @@ -0,0 +1,103 @@ +/** + * name : helper.js + * author : Vishnu + * created-date : 12-Jan-2023 + * Description : Programs users related helper functionality. + */ + +// Dependencies + +/** + * ProgramUsersHelper + * @class +*/ +module.exports = class ProgramUsersHelper { + /** + * Create program users + * @method + * @name create + * @param {Object} data + * @returns {JSON} - create programUsers. + */ + + static create(data) { + return new Promise(async (resolve, reject) => { + try { + + let programUsers = await database.models.programUsers.create( + data + ); + + if( !programUsers._id ) { + throw { + message : constants.apiResponses.PROGRAM_USERS_NOT_CREATED + }; + } + return resolve(programUsers); + + } catch (error) { + return reject(error); + } + }) + } + + /** + * Update program users + * @method + * @name update + * @param {Object} query + * @param {Object} data + * @param {Object} options + * @returns {JSON} - create programUsers. + */ + + static update(query, data, options = {}) { + return new Promise(async (resolve, reject) => { + try { + + let programUsers = await database.models.programUsers.findOneAndUpdate( + query, + data, + options + ); + + if( !programUsers._id ) { + throw { + message : constants.apiResponses.PROGRAM_USERS_NOT_UPDATED + }; + } + return resolve(programUsers); + + } catch (error) { + return reject(error); + } + }) + } + + /** + * find program users details + * @method + * @name find + * @param {Object} query + * @param {Array} projection + * @returns {JSON} - create programUsers. + */ + + static find(query, projection = []) { + return new Promise(async (resolve, reject) => { + try { + + let programUsers = await database.models.programUsers.find( + query, + projection + ).lean(); + + return resolve(programUsers); + + } catch (error) { + return reject(error); + } + }) + } + +} \ No newline at end of file diff --git a/module/programs/helper.js b/module/programs/helper.js index 1b7db92b..2487083f 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -12,6 +12,7 @@ const entitiesHelper = require(MODULES_BASE_PATH + "/entities/helper"); const userRolesHelper = require(MODULES_BASE_PATH + "/user-roles/helper"); const userService = require(ROOT_PATH + "/generics/services/users"); const kafkaProducersHelper = require(ROOT_PATH + "/generics/kafka/producers"); +const programUsersHelper = require(MODULES_BASE_PATH + "/programUsers/helper"); /** * ProgramsHelper @@ -66,13 +67,13 @@ module.exports = class ProgramsHelper { }); } - /** - * Create program - * @method - * @name create - * @param {Array} data - * @returns {JSON} - create program. - */ + /** + * Create program + * @method + * @name create + * @param {Array} data + * @returns {JSON} - create program. + */ static create(data) { @@ -1007,12 +1008,16 @@ module.exports = class ProgramsHelper { } let programUsersData = {}; - //Fetch user profile information by calling sunbird's user read api. - //!Important check specific fields of userProfile. + // Fetch user profile information by calling sunbird's user read api. + // !Important check specific fields of userProfile. let userProfile = await userService.profile(userToken, userId); - if ( !userProfile.success || - !userProfile.data || - !userProfile.data.response + if (!userProfile.success || + !userProfile.data || + !userProfile.data.response || + !userProfile.data.response.profileUserTypes || + !userProfile.data.response.profileUserTypes.length > 0 || + !userProfile.data.response.userLocations || + !userProfile.data.response.userLocations.length > 0 ) { throw ({ status: httpStatusCode.bad_request.status, @@ -1047,10 +1052,10 @@ module.exports = class ProgramsHelper { }; //Check data already present in db. - const programUsers = await database.models.programUsers.find( + const programUsers = await programUsersHelper.find( query, ["consentForPIIDataSharing"] - ).lean(); + ); // Data already present in programUsers collection, Require updation, else create new entry. let joinProgram; @@ -1061,12 +1066,12 @@ module.exports = class ProgramsHelper { update['$push'] = { consentHistory: programUsers[0].consentForPIIDataSharing } } update['$set'] = programUsersData; - joinProgram = await database.models.programUsers.findOneAndUpdate(query, update, {new:true}); + joinProgram = await programUsersHelper.update(query, update, {new:true}); } else { joinProgram = - await database.models.programUsers.create( + await programUsersHelper.create( programUsersData ); @@ -1091,7 +1096,6 @@ module.exports = class ProgramsHelper { }); } catch (error) { - console.log("error:",error) return resolve({ success: false, status: error.status diff --git a/module/users/helper.js b/module/users/helper.js index 24c6fe68..14a0c598 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -13,6 +13,7 @@ const entitiesHelper = require(MODULES_BASE_PATH + "/entities/helper"); const improvementProjectService = require(ROOT_PATH + "/generics/services/improvement-project"); const userService = require(ROOT_PATH + "/generics/services/users"); const formService = require(ROOT_PATH + '/generics/services/form'); +const programUsersHelper = require(MODULES_BASE_PATH + "/programUsers/helper"); /** @@ -547,13 +548,13 @@ module.exports = class UsersHelper { }; //check programUsers collection for consentForPIIDataSharing - let programUsersData = await database.models.programUsers.find( + let programUsersData = await programUsersHelper.find( { programId: programId, userId: userId }, ["consentForPIIDataSharing"] - ).lean(); + ); //if consentForPIIDataSharing is present append with response if( programUsersData.length > 0 && programUsersData[0].consentForPIIDataSharing ) { From bd09107eb21d77b459ad98268592187d9b02732a Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Tue, 17 Jan 2023 14:30:36 +0530 Subject: [PATCH 226/331] program externalId also pushing to kafka --- module/programs/helper.js | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/module/programs/helper.js b/module/programs/helper.js index 2487083f..18510f64 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -449,7 +449,6 @@ module.exports = class ProgramsHelper { facetQuery["$facet"]["totalCount"] = [ { "$count": "count" } ]; - facetQuery["$facet"]["data"] = [ { $skip: pageSize * (pageNo - 1) }, { $limit: pageSize } @@ -515,7 +514,7 @@ module.exports = class ProgramsHelper { pageSize, searchText, queryData.data, - ["name", "externalId","components"] + ["name", "externalId","components","metaInformation"] ); if ( targetedPrograms.success && targetedPrograms.data && targetedPrograms.data.data.length > 0) { @@ -998,7 +997,7 @@ module.exports = class ProgramsHelper { let programData = await this.programDocuments({ _id: programId, status: constants.common.ACTIVE - },["name"]); + },["name", "externalId"]); if ( !programData.length > 0 ) { throw ({ @@ -1083,7 +1082,7 @@ module.exports = class ProgramsHelper { } } joinProgram.programName = programData[0].name; - + joinProgram.programExternalId = programData[0].externalId; // push programUsers details to kafka await kafkaProducersHelper.pushProgramUsersToKafka(joinProgram); From 6734addf86f0fdd3c29ae62ae9a45a872037b9ae Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Tue, 17 Jan 2023 17:49:06 +0530 Subject: [PATCH 227/331] consent history changes --- module/programs/helper.js | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/module/programs/helper.js b/module/programs/helper.js index 18510f64..12e506e2 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -466,7 +466,7 @@ module.exports = class ProgramsHelper { let programDocuments = await database.models.programs.aggregate(programDocument); - + return resolve({ success : true, message : constants.apiResponses.PROGRAM_LIST, @@ -1042,6 +1042,7 @@ module.exports = class ProgramsHelper { agree: data.consentForPIIDataSharing, date: new Date() } + } //create or update query @@ -1053,7 +1054,7 @@ module.exports = class ProgramsHelper { //Check data already present in db. const programUsers = await programUsersHelper.find( query, - ["consentForPIIDataSharing"] + ["_id"] ); // Data already present in programUsers collection, Require updation, else create new entry. @@ -1061,13 +1062,16 @@ module.exports = class ProgramsHelper { if( programUsers.length > 0 ) { let update = {}; - if( programUsers[0].consentForPIIDataSharing && (data.consentForPIIDataSharing == true || data.consentForPIIDataSharing == false )) { - update['$push'] = { consentHistory: programUsers[0].consentForPIIDataSharing } + if( data.consentForPIIDataSharing == true || data.consentForPIIDataSharing == false ) { + update['$push'] = { consentHistory: programUsersData.consentForPIIDataSharing } } update['$set'] = programUsersData; joinProgram = await programUsersHelper.update(query, update, {new:true}); } else { + if( data.consentForPIIDataSharing == true || data.consentForPIIDataSharing == false ) { + programUsersData.consentHistory = programUsersData.consentForPIIDataSharing; + } joinProgram = await programUsersHelper.create( From 736e06edb838744adb60ef8f344f7f95142ed42f Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 20 Jan 2023 12:25:57 +0530 Subject: [PATCH 228/331] baseTemplateFix --- module/certificateBaseTemplates/helper.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/module/certificateBaseTemplates/helper.js b/module/certificateBaseTemplates/helper.js index 87521306..38a8ff51 100644 --- a/module/certificateBaseTemplates/helper.js +++ b/module/certificateBaseTemplates/helper.js @@ -77,7 +77,7 @@ module.exports = class CertificateBaseTemplatesHelper { }; let certificateBaseTemplateUpdated = await database.models.certificateBaseTemplates.findOneAndUpdate( - baseTemplateId, + { _id : baseTemplateId }, updateObject ); if ( certificateBaseTemplateUpdated == null ) { From a8e6db832590838b6c693d224f173f9c0255b145 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Tue, 24 Jan 2023 17:13:05 +0530 Subject: [PATCH 229/331] program join changes --- models/programUsers.js | 11 ++--------- module/programs/helper.js | 16 ++-------------- 2 files changed, 4 insertions(+), 23 deletions(-) diff --git a/models/programUsers.js b/models/programUsers.js index 29f1cb28..ebb04b3e 100644 --- a/models/programUsers.js +++ b/models/programUsers.js @@ -6,21 +6,14 @@ module.exports = { required: true, index: true }, - consentForPIIDataSharing: { - agree: Boolean, - date: Date - }, - consentHistory: { - type: Array, - default: [] - }, userId: { type: String, index: true }, noOfResourcesStarted: { type:Number, - index: true + index: true, + default: 0 }, userProfile: Object, userRoleInformation: Object, diff --git a/module/programs/helper.js b/module/programs/helper.js index 12e506e2..bca7bc4b 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -1036,14 +1036,8 @@ module.exports = class ProgramsHelper { programUsersData['appInformation.appVersion'] = appVersion; } - //consentForPIIDataSharing is optional. - if( data.consentForPIIDataSharing == true || data.consentForPIIDataSharing == false ) { - programUsersData.consentForPIIDataSharing = { - agree: data.consentForPIIDataSharing, - date: new Date() - } - - } + //For internal calls add consent using sunbird api-----------> + //create or update query const query = { @@ -1062,16 +1056,10 @@ module.exports = class ProgramsHelper { if( programUsers.length > 0 ) { let update = {}; - if( data.consentForPIIDataSharing == true || data.consentForPIIDataSharing == false ) { - update['$push'] = { consentHistory: programUsersData.consentForPIIDataSharing } - } update['$set'] = programUsersData; joinProgram = await programUsersHelper.update(query, update, {new:true}); } else { - if( data.consentForPIIDataSharing == true || data.consentForPIIDataSharing == false ) { - programUsersData.consentHistory = programUsersData.consentForPIIDataSharing; - } joinProgram = await programUsersHelper.create( From 850d8d6de30a04a145de2cc85537b68b79bd2f9f Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Wed, 25 Jan 2023 17:19:57 +0530 Subject: [PATCH 230/331] saving changes --- controllers/v1/programs.js | 5 ++- controllers/v1/solutions.js | 2 + generics/constants/endpoints.js | 3 +- generics/constants/enum.utils.txt | 8 ++++ generics/services/consent.js | 62 +++++++++++++++++++++++++++++++ module/programs/helper.js | 56 +++++++++++++++++++--------- module/solutions/helper.js | 2 +- routes/index.js | 1 + 8 files changed, 119 insertions(+), 20 deletions(-) create mode 100644 generics/constants/enum.utils.txt create mode 100644 generics/services/consent.js diff --git a/controllers/v1/programs.js b/controllers/v1/programs.js index 6f2fd5ea..6b240e89 100644 --- a/controllers/v1/programs.js +++ b/controllers/v1/programs.js @@ -529,7 +529,10 @@ module.exports = class Programs extends Abstract { req.headers.appname ? req.headers.appname : "", req.headers["x-app-ver"] ? req.headers["x-app-ver"] : - req.headers.appversion ? req.headers.appversion : "" + req.headers.appversion ? req.headers.appversion : "", + req.headers["internal-access-token"] ? + req.headers["internal-access-token"] : + req.headers.internalAccessToken ? req.headers.internalAccessToken : "" ); programJoin["result"] = programJoin.data; return resolve(programJoin); diff --git a/controllers/v1/solutions.js b/controllers/v1/solutions.js index 3dedfef4..1aa055f7 100644 --- a/controllers/v1/solutions.js +++ b/controllers/v1/solutions.js @@ -316,6 +316,7 @@ module.exports = class Solutions extends Abstract { async detailsBasedOnRoleAndLocation(req) { return new Promise(async (resolve, reject) => { try { + console.log("request Reched to this location") let solutionDetails = await solutionsHelper.detailsBasedOnRoleAndLocation( @@ -324,6 +325,7 @@ module.exports = class Solutions extends Abstract { ); solutionDetails.result = solutionDetails.data; + console.log(solutionDetails) return resolve(solutionDetails); } catch (error) { diff --git a/generics/constants/endpoints.js b/generics/constants/endpoints.js index 8e9ae543..8238a9d6 100644 --- a/generics/constants/endpoints.js +++ b/generics/constants/endpoints.js @@ -34,5 +34,6 @@ module.exports = { GET_LOCATION_DATA : "/v1/location/search", GET_FORM_DATA : "/plugin/v1/form/read", GET_SCHOOL_DATA : "/v1/org/search", - USER_READ_V5 : "/v5/user/read" + USER_READ_V5 : "/v5/user/read", + CONSENT_API: "/api/user/v1/consent/update" } \ No newline at end of file diff --git a/generics/constants/enum.utils.txt b/generics/constants/enum.utils.txt new file mode 100644 index 00000000..ec654242 --- /dev/null +++ b/generics/constants/enum.utils.txt @@ -0,0 +1,8 @@ +// exports.Consent = { +// ACTIVE:"ACTIVE", +// REVOKED:"REVOKED" +// } + +// exports.objectType = { +// PROGRAM:"Program" +// } \ No newline at end of file diff --git a/generics/services/consent.js b/generics/services/consent.js new file mode 100644 index 00000000..33c26aa9 --- /dev/null +++ b/generics/services/consent.js @@ -0,0 +1,62 @@ +/** + * name : users.js + * author : Aman Jung Karki + * Date : 11-Nov-2019 + * Description : All users related api call. + */ + +//dependencies +const request = require('request'); +const sunbirdServiceUrl = process.env.SUNBIRD_SERVICE_URL; + +const consent = function ( token,consentData ) { + return new Promise(async (resolve, reject) => { + try { + + let url = sunbirdServiceUrl + constants.endpoints.CONSENT_API; + + const options = { + headers : { + "content-type": "application/json", + "x-authenticated-user-token" : token, + "Authorization" : process.env.SUNBIRD_SERVICE_AUTHERIZATION + }, + json: consentData + }; + + request.post(url,options,kendraCallback); + + function kendraCallback(err, data) { + + let result = { + success : true + }; + + if (err) { + result.success = false; + } else { + + let response = JSON.parse(data.body); + console.log("consentData>>>>>>>>>>>",response) + if( response.status === httpStatusCode['ok'].status ) { + result["data"] = response.result.response; + } else { + result["message"] = response.message; + result.success = false; + } + + } + + return resolve(result); + } + + } catch (error) { + return reject(error); + } + }) +} + + +module.exports = { + consent : consent +} diff --git a/module/programs/helper.js b/module/programs/helper.js index bca7bc4b..92085a1a 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -11,6 +11,7 @@ const entityTypesHelper = require(MODULES_BASE_PATH + "/entityTypes/helper"); const entitiesHelper = require(MODULES_BASE_PATH + "/entities/helper"); const userRolesHelper = require(MODULES_BASE_PATH + "/user-roles/helper"); const userService = require(ROOT_PATH + "/generics/services/users"); +const consentService = require(ROOT_PATH + "/generics/services/consent"); const kafkaProducersHelper = require(ROOT_PATH + "/generics/kafka/producers"); const programUsersHelper = require(MODULES_BASE_PATH + "/programUsers/helper"); @@ -990,7 +991,7 @@ module.exports = class ProgramsHelper { * @returns {Object} - Details of the program join. */ - static join( programId, data, userId, userToken, appName = "", appVersion = "" ) { + static join( programId, data, userId, userToken, appName = "", appVersion = "", internalAccessToken = "" ) { return new Promise(async (resolve, reject) => { try { //Using programId fetch program name. Also checking the program status in the query. @@ -1009,25 +1010,25 @@ module.exports = class ProgramsHelper { let programUsersData = {}; // Fetch user profile information by calling sunbird's user read api. // !Important check specific fields of userProfile. - let userProfile = await userService.profile(userToken, userId); - if (!userProfile.success || - !userProfile.data || - !userProfile.data.response || - !userProfile.data.response.profileUserTypes || - !userProfile.data.response.profileUserTypes.length > 0 || - !userProfile.data.response.userLocations || - !userProfile.data.response.userLocations.length > 0 - ) { - throw ({ - status: httpStatusCode.bad_request.status, - message: constants.apiResponses.PROGRAM_JOIN_FAILED - }); - } + // let userProfile = await userService.profile(userToken, userId); + // if (!userProfile.success || + // !userProfile.data || + // !userProfile.data.response || + // !userProfile.data.response.profileUserTypes || + // !userProfile.data.response.profileUserTypes.length > 0 || + // !userProfile.data.response.userLocations || + // !userProfile.data.response.userLocations.length > 0 + // ) { + // throw ({ + // status: httpStatusCode.bad_request.status, + // message: constants.apiResponses.PROGRAM_JOIN_FAILED + // }); + // } programUsersData = { programId: programId, userRoleInformation: data.userRoleInformation, userId: userId, - userProfile: userProfile.data.response + // userProfile: userProfile.data.response } if( appName != "" ) { programUsersData['appInformation.appName'] = appName; @@ -1037,7 +1038,28 @@ module.exports = class ProgramsHelper { } //For internal calls add consent using sunbird api-----------> - + + if(internalAccessToken !== ""){ + let consent = { + "request": { + "consent": { + // "status": constants.Consent.REVOKED, + // "userId": userProfile.data.response.id, + // "consumerId": userProfile.data.response.organisations.organisationId, + // "objectId": programId, + // "objectType": constants.objectType.PROGRAM + "status": "ACTIVE", + "userId": "4d472816-49ba-4a57-872d-f887f7cbfec8", + "consumerId": "01269878797503692810", + "objectId": "63a948aef09e45000907597e", + "objectType": "Program" + } + } + } + let consentResponse = await consentService.consent(userToken, consent) + console.log(consentResponse) + } + //create or update query const query = { diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 648b1421..134843e5 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -840,7 +840,7 @@ module.exports = class SolutionsHelper { "certificateTemplateId" ] ); - + console.log(">>>>>>>>>>>>>>>>>>>",targetedSolutionDetails) if( !targetedSolutionDetails.length > 0 ) { throw { status : httpStatusCode["bad_request"].status, diff --git a/routes/index.js b/routes/index.js index 81e661de..8de40919 100644 --- a/routes/index.js +++ b/routes/index.js @@ -19,6 +19,7 @@ module.exports = function (app) { app.use(pagination); var router = async function (req, res, next) { + console.log("Request reched to route") if (!req.params.version) { next(); From 8c2ffac482a5d449a8ba608079fc69cb820f555f Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Thu, 26 Jan 2023 22:04:26 +0530 Subject: [PATCH 231/331] Added consent API --- controllers/v1/solutions.js | 2 -- generics/http-status-codes/index.js | 3 ++ generics/services/consent.js | 15 ++++----- module/programs/helper.js | 52 ++++++++++++++--------------- routes/index.js | 1 - 5 files changed, 36 insertions(+), 37 deletions(-) diff --git a/controllers/v1/solutions.js b/controllers/v1/solutions.js index 1aa055f7..3dedfef4 100644 --- a/controllers/v1/solutions.js +++ b/controllers/v1/solutions.js @@ -316,7 +316,6 @@ module.exports = class Solutions extends Abstract { async detailsBasedOnRoleAndLocation(req) { return new Promise(async (resolve, reject) => { try { - console.log("request Reched to this location") let solutionDetails = await solutionsHelper.detailsBasedOnRoleAndLocation( @@ -325,7 +324,6 @@ module.exports = class Solutions extends Abstract { ); solutionDetails.result = solutionDetails.data; - console.log(solutionDetails) return resolve(solutionDetails); } catch (error) { diff --git a/generics/http-status-codes/index.js b/generics/http-status-codes/index.js index 82aa9978..1c68a696 100644 --- a/generics/http-status-codes/index.js +++ b/generics/http-status-codes/index.js @@ -187,5 +187,8 @@ module.exports = { 'insufficient_storage': { status: 507, message: "Insufficient Storage" + }, + 'http_responsecode_ok':{ + message:"OK" } }; diff --git a/generics/services/consent.js b/generics/services/consent.js index 33c26aa9..f90170e7 100644 --- a/generics/services/consent.js +++ b/generics/services/consent.js @@ -21,9 +21,10 @@ const consent = function ( token,consentData ) { "x-authenticated-user-token" : token, "Authorization" : process.env.SUNBIRD_SERVICE_AUTHERIZATION }, - json: consentData + body: JSON.stringify(consentData) }; - + console.log(url) + console.log(JSON.stringify(options)) request.post(url,options,kendraCallback); function kendraCallback(err, data) { @@ -35,18 +36,16 @@ const consent = function ( token,consentData ) { if (err) { result.success = false; } else { - + let response = JSON.parse(data.body); - console.log("consentData>>>>>>>>>>>",response) - if( response.status === httpStatusCode['ok'].status ) { - result["data"] = response.result.response; + if( response.responseCode === httpStatusCode['http_responsecode_ok'].message ) { + result["data"] = response; } else { - result["message"] = response.message; + result["message"] = response; result.success = false; } } - return resolve(result); } diff --git a/module/programs/helper.js b/module/programs/helper.js index 92085a1a..604e579a 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -1010,25 +1010,25 @@ module.exports = class ProgramsHelper { let programUsersData = {}; // Fetch user profile information by calling sunbird's user read api. // !Important check specific fields of userProfile. - // let userProfile = await userService.profile(userToken, userId); - // if (!userProfile.success || - // !userProfile.data || - // !userProfile.data.response || - // !userProfile.data.response.profileUserTypes || - // !userProfile.data.response.profileUserTypes.length > 0 || - // !userProfile.data.response.userLocations || - // !userProfile.data.response.userLocations.length > 0 - // ) { - // throw ({ - // status: httpStatusCode.bad_request.status, - // message: constants.apiResponses.PROGRAM_JOIN_FAILED - // }); - // } + let userProfile = await userService.profile(userToken, userId); + if (!userProfile.success || + !userProfile.data || + !userProfile.data.response || + !userProfile.data.response.profileUserTypes || + !userProfile.data.response.profileUserTypes.length > 0 || + !userProfile.data.response.userLocations || + !userProfile.data.response.userLocations.length > 0 + ) { + throw ({ + status: httpStatusCode.bad_request.status, + message: constants.apiResponses.PROGRAM_JOIN_FAILED + }); + } programUsersData = { programId: programId, userRoleInformation: data.userRoleInformation, userId: userId, - // userProfile: userProfile.data.response + userProfile: userProfile.data.response } if( appName != "" ) { programUsersData['appInformation.appName'] = appName; @@ -1043,21 +1043,21 @@ module.exports = class ProgramsHelper { let consent = { "request": { "consent": { - // "status": constants.Consent.REVOKED, - // "userId": userProfile.data.response.id, - // "consumerId": userProfile.data.response.organisations.organisationId, - // "objectId": programId, - // "objectType": constants.objectType.PROGRAM - "status": "ACTIVE", - "userId": "4d472816-49ba-4a57-872d-f887f7cbfec8", - "consumerId": "01269878797503692810", - "objectId": "63a948aef09e45000907597e", - "objectType": "Program" + "status": constants.Consent.REVOKED, + "userId": userProfile.data.response.id, + "consumerId": userProfile.data.response.organisations.organisationId, + "objectId": programId, + "objectType": constants.objectType.PROGRAM } } } let consentResponse = await consentService.consent(userToken, consent) - console.log(consentResponse) + if(!consentResponse.success){ + throw { + message: constants.apiResponses.PROGRAM_JOIN_FAILED, + status: httpStatusCode.bad_request.status + } + } } diff --git a/routes/index.js b/routes/index.js index 8de40919..81e661de 100644 --- a/routes/index.js +++ b/routes/index.js @@ -19,7 +19,6 @@ module.exports = function (app) { app.use(pagination); var router = async function (req, res, next) { - console.log("Request reched to route") if (!req.params.version) { next(); From 6248b7aa77a16bf9281470264544e0124d258a62 Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Thu, 26 Jan 2023 22:09:48 +0530 Subject: [PATCH 232/331] Added Consent API --- generics/constants/enum.utils.js | 16 ++++++++++++++++ generics/constants/enum.utils.txt | 8 -------- generics/services/consent.js | 8 ++++---- module/solutions/helper.js | 1 - 4 files changed, 20 insertions(+), 13 deletions(-) create mode 100644 generics/constants/enum.utils.js delete mode 100644 generics/constants/enum.utils.txt diff --git a/generics/constants/enum.utils.js b/generics/constants/enum.utils.js new file mode 100644 index 00000000..19b659f0 --- /dev/null +++ b/generics/constants/enum.utils.js @@ -0,0 +1,16 @@ +/** + * name : enum.utils.js + * author : Ankit Shahu + * Date : 24-jan-2023 + * Description : Enums are stored in this file. + */ + + +exports.Consent = { + ACTIVE:"ACTIVE", + REVOKED:"REVOKED" +} + +exports.objectType = { + PROGRAM:"Program" +} \ No newline at end of file diff --git a/generics/constants/enum.utils.txt b/generics/constants/enum.utils.txt deleted file mode 100644 index ec654242..00000000 --- a/generics/constants/enum.utils.txt +++ /dev/null @@ -1,8 +0,0 @@ -// exports.Consent = { -// ACTIVE:"ACTIVE", -// REVOKED:"REVOKED" -// } - -// exports.objectType = { -// PROGRAM:"Program" -// } \ No newline at end of file diff --git a/generics/services/consent.js b/generics/services/consent.js index f90170e7..98374229 100644 --- a/generics/services/consent.js +++ b/generics/services/consent.js @@ -1,8 +1,8 @@ /** - * name : users.js - * author : Aman Jung Karki - * Date : 11-Nov-2019 - * Description : All users related api call. + * name : consent.js + * author : Ankit Shahu + * Date : 24-jan-2023 + * Description : Sunbird Consent API. */ //dependencies diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 134843e5..f4335bf7 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -840,7 +840,6 @@ module.exports = class SolutionsHelper { "certificateTemplateId" ] ); - console.log(">>>>>>>>>>>>>>>>>>>",targetedSolutionDetails) if( !targetedSolutionDetails.length > 0 ) { throw { status : httpStatusCode["bad_request"].status, From 80db856b1e5a6f8a92c9fb50ee7d3c31577e043f Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Thu, 26 Jan 2023 22:11:33 +0530 Subject: [PATCH 233/331] Added Consent API --- module/solutions/helper.js | 1 + 1 file changed, 1 insertion(+) diff --git a/module/solutions/helper.js b/module/solutions/helper.js index f4335bf7..648b1421 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -840,6 +840,7 @@ module.exports = class SolutionsHelper { "certificateTemplateId" ] ); + if( !targetedSolutionDetails.length > 0 ) { throw { status : httpStatusCode["bad_request"].status, From a8f5d732ca133d9613668614841b1a8059ec9c28 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Sun, 29 Jan 2023 19:48:32 +0530 Subject: [PATCH 234/331] PII join api changes --- generics/constants/common.js | 5 ++- generics/constants/enum.utils.js | 16 --------- generics/constants/schema.js | 15 -------- generics/services/consent.js | 61 -------------------------------- generics/services/users.js | 61 +++++++++++++++++++++++++++++++- module/programs/helper.js | 21 ++++++----- 6 files changed, 76 insertions(+), 103 deletions(-) delete mode 100644 generics/constants/enum.utils.js delete mode 100644 generics/constants/schema.js delete mode 100644 generics/services/consent.js diff --git a/generics/constants/common.js b/generics/constants/common.js index bac7594f..9160c321 100644 --- a/generics/constants/common.js +++ b/generics/constants/common.js @@ -72,5 +72,8 @@ module.exports = { "PROFILE_CONFIG_FORM_KEY" : "profileConfig_v2", "SERVER_TIME_OUT" : 5000, "CERTIFICATE" : "certificate", - "ORACLE_CLOUD_SERVICE" : "OCI" + "ORACLE_CLOUD_SERVICE" : "OCI", + "REVOKED" : "REVOKED", + "PROGRAM" : "Program" + }; diff --git a/generics/constants/enum.utils.js b/generics/constants/enum.utils.js deleted file mode 100644 index 19b659f0..00000000 --- a/generics/constants/enum.utils.js +++ /dev/null @@ -1,16 +0,0 @@ -/** - * name : enum.utils.js - * author : Ankit Shahu - * Date : 24-jan-2023 - * Description : Enums are stored in this file. - */ - - -exports.Consent = { - ACTIVE:"ACTIVE", - REVOKED:"REVOKED" -} - -exports.objectType = { - PROGRAM:"Program" -} \ No newline at end of file diff --git a/generics/constants/schema.js b/generics/constants/schema.js deleted file mode 100644 index 63c9972c..00000000 --- a/generics/constants/schema.js +++ /dev/null @@ -1,15 +0,0 @@ -/** - * name : constants/schema.js - * author : Aman - * Date : 28-feb-2020 - * Description : All common schema information. - */ - -module.exports = { - METAINFORMATION : "metaInformation", - EXTERNALID : "externalId", - NAME : "name", - ENTITYTYPE : "entityType", - GROUPS : "groups", - ID : "_id" -} \ No newline at end of file diff --git a/generics/services/consent.js b/generics/services/consent.js deleted file mode 100644 index 98374229..00000000 --- a/generics/services/consent.js +++ /dev/null @@ -1,61 +0,0 @@ -/** - * name : consent.js - * author : Ankit Shahu - * Date : 24-jan-2023 - * Description : Sunbird Consent API. - */ - -//dependencies -const request = require('request'); -const sunbirdServiceUrl = process.env.SUNBIRD_SERVICE_URL; - -const consent = function ( token,consentData ) { - return new Promise(async (resolve, reject) => { - try { - - let url = sunbirdServiceUrl + constants.endpoints.CONSENT_API; - - const options = { - headers : { - "content-type": "application/json", - "x-authenticated-user-token" : token, - "Authorization" : process.env.SUNBIRD_SERVICE_AUTHERIZATION - }, - body: JSON.stringify(consentData) - }; - console.log(url) - console.log(JSON.stringify(options)) - request.post(url,options,kendraCallback); - - function kendraCallback(err, data) { - - let result = { - success : true - }; - - if (err) { - result.success = false; - } else { - - let response = JSON.parse(data.body); - if( response.responseCode === httpStatusCode['http_responsecode_ok'].message ) { - result["data"] = response; - } else { - result["message"] = response; - result.success = false; - } - - } - return resolve(result); - } - - } catch (error) { - return reject(error); - } - }) -} - - -module.exports = { - consent : consent -} diff --git a/generics/services/users.js b/generics/services/users.js index c1ce2fbb..d869c7c0 100644 --- a/generics/services/users.js +++ b/generics/services/users.js @@ -345,11 +345,70 @@ async function getParentEntities( entityId, iteration = 0, parentEntities ) { return parentEntities; } + +/** + * update user consent for sharing the PII. + * @method + * @name consent + * @param {String} token - user token + * @returns {Object} consentData - consent data. +*/ + +const consent = function ( token, consentData ) { + return new Promise(async (resolve, reject) => { + try { + + let url = userServiceUrl + constants.endpoints.CONSENT_API; + + const options = { + headers : { + "content-type": "application/json", + "x-authenticated-user-token" : token, + "Authorization" : process.env.SUNBIRD_SERVICE_AUTHERIZATION + }, + body: JSON.stringify(consentData) + }; + + request.post(url,options,kendraCallback); + + function kendraCallback(err, data) { + + let result = { + success : true + }; + + if (err) { + result.success = false; + } else { + + let response = JSON.parse(data.body); + if( response.responseCode === httpStatusCode['http_responsecode_ok'].message ) { + result["data"] = response; + } else { + result["message"] = response; + result.success = false; + } + + } + return resolve(result); + } + setTimeout(function () { + return resolve (result = { + success : false + }); + }, constants.common.SERVER_TIME_OUT); + + } catch (error) { + return reject(error); + } + }) +} module.exports = { profile : profile, locationSearch : locationSearch, orgSchoolSearch :orgSchoolSearch, getSubEntitiesBasedOnEntityType : getSubEntitiesBasedOnEntityType, - getParentEntities : getParentEntities + getParentEntities : getParentEntities, + consent : consent } diff --git a/module/programs/helper.js b/module/programs/helper.js index 604e579a..586c2a7b 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -11,7 +11,6 @@ const entityTypesHelper = require(MODULES_BASE_PATH + "/entityTypes/helper"); const entitiesHelper = require(MODULES_BASE_PATH + "/entities/helper"); const userRolesHelper = require(MODULES_BASE_PATH + "/user-roles/helper"); const userService = require(ROOT_PATH + "/generics/services/users"); -const consentService = require(ROOT_PATH + "/generics/services/consent"); const kafkaProducersHelper = require(ROOT_PATH + "/generics/kafka/producers"); const programUsersHelper = require(MODULES_BASE_PATH + "/programUsers/helper"); @@ -1037,21 +1036,20 @@ module.exports = class ProgramsHelper { programUsersData['appInformation.appVersion'] = appVersion; } - //For internal calls add consent using sunbird api-----------> - + //For internal calls add consent using sunbird api if(internalAccessToken !== ""){ let consent = { "request": { "consent": { - "status": constants.Consent.REVOKED, + "status": constants.common.REVOKED, "userId": userProfile.data.response.id, "consumerId": userProfile.data.response.organisations.organisationId, "objectId": programId, - "objectType": constants.objectType.PROGRAM + "objectType": constants.common.PROGRAM } } } - let consentResponse = await consentService.consent(userToken, consent) + let consentResponse = await userService.consent(userToken, consent) if(!consentResponse.success){ throw { message: constants.apiResponses.PROGRAM_JOIN_FAILED, @@ -1060,7 +1058,6 @@ module.exports = class ProgramsHelper { } } - //create or update query const query = { programId: programId, @@ -1076,13 +1073,19 @@ module.exports = class ProgramsHelper { // Data already present in programUsers collection, Require updation, else create new entry. let joinProgram; if( programUsers.length > 0 ) { - + //Update the collection let update = {}; update['$set'] = programUsersData; + if ( data.isResource ) { + update['$inc'] = { noOfResourcesStarted : 1 } + } joinProgram = await programUsersHelper.update(query, update, {new:true}); } else { - + //Create new entry to collection + if ( data.isResource ) { + programUsersData.noOfResourcesStarted = 1; + } joinProgram = await programUsersHelper.create( programUsersData From 03492619d2a20daff31ae954456b8ad528bc253a Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 30 Jan 2023 09:59:14 +0530 Subject: [PATCH 235/331] ED-430-program listing changes --- controllers/v1/users.js | 3 +- models/programs.js | 3 +- module/users/helper.js | 154 +++++++++++++++++++++++++++++++++++++--- 3 files changed, 147 insertions(+), 13 deletions(-) diff --git a/controllers/v1/users.js b/controllers/v1/users.js index b99dc11c..5d26d1c8 100644 --- a/controllers/v1/users.js +++ b/controllers/v1/users.js @@ -366,7 +366,8 @@ module.exports = class Users extends Abstract { req.body, req.pageNo, req.pageSize, - req.searchText + req.searchText, + req.userDetails.userId ); programs.result = programs.data; diff --git a/models/programs.js b/models/programs.js index abedc577..cfb877f9 100644 --- a/models/programs.js +++ b/models/programs.js @@ -51,7 +51,8 @@ module.exports = { requestForPIIConsent: { type: Boolean, default: false - } + }, + metaInformation: Object } }; \ No newline at end of file diff --git a/module/users/helper.js b/module/users/helper.js index 14a0c598..1b6ebef2 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -16,6 +16,7 @@ const formService = require(ROOT_PATH + '/generics/services/form'); const programUsersHelper = require(MODULES_BASE_PATH + "/programUsers/helper"); + /** * UsersHelper * @class @@ -553,12 +554,12 @@ module.exports = class UsersHelper { programId: programId, userId: userId }, - ["consentForPIIDataSharing"] + ["_id"] ); - //if consentForPIIDataSharing is present append with response - if( programUsersData.length > 0 && programUsersData[0].consentForPIIDataSharing ) { - result.consentForPIIDataSharing = programUsersData[0].consentForPIIDataSharing; + //if already joined the program + if( programUsersData.length > 0 ) { + result.programJoined = true; } return resolve({ @@ -590,29 +591,75 @@ module.exports = class UsersHelper { * @returns {Array} - Get user targeted programs. */ - static programs(bodyData, pageNo, pageSize, searchText) { + static programs(bodyData, pageNo, pageSize, searchText, userId) { return new Promise(async (resolve, reject) => { try { - let targetedProgrms = await programsHelper.forUserRoleAndLocation( + + let targetedPrograms = await programsHelper.forUserRoleAndLocation( bodyData, pageSize, pageNo, searchText ); - if (!targetedProgrms.success) { + if (!targetedPrograms.success) { throw { message: constants.apiResponses.PROGRAM_NOT_FOUND, }; } - - targetedProgrms.data["description"] = + targetedPrograms.data["description"] = constants.apiResponses.PROGRAM_DESCRIPTION; - + + let nontargetedJoinedPrograms = await this.getNonTargetedJoinedProgram( + bodyData, + 1, + targetedPrograms.data.count, + searchText, + userId + ); + let targetedProgramCount = (targetedPrograms.data.count) ? targetedPrograms.data.count : 0 + targetedPrograms.data.count = targetedPrograms.data.count + nontargetedJoinedPrograms.count; + + if ( !nontargetedJoinedPrograms.count > 0 || (pageSize*pageNo) <= targetedProgramCount ) { + return resolve({ + success: true, + message: constants.apiResponses.USER_TARGETED_PROGRAMS_FETCHED, + data: targetedPrograms.data + }); + } else { + let maxLimit = 0; + let minLimit = 0; + if ( targetedPrograms.data.data.length == 0 ) { + maxLimit = (pageNo*pageSize)-targetedProgramCount; + minLimit = maxLimit-pageSize; + } else if ( targetedPrograms.data.data.length < pageSize ) { + maxLimit = pageSize-targetedPrograms.data.data.length; + } + + let maxIndex = (maxLimit <= nontargetedJoinedPrograms.data.length) ? maxLimit : nontargetedJoinedPrograms.data.length; + if ( minLimit <= nontargetedJoinedPrograms.data.length ) { + for( let index = minLimit; index < maxIndex; index++ ) { + //fetch resourse started details + let programUsersData = await programUsersHelper.find( + { + userId: userId, + programId: nontargetedJoinedPrograms.data[index]._id + }, + ["noOfResourcesStarted"] + ); + if ( programUsersData.length > 0 ) { + nontargetedJoinedPrograms.data[index].solutions = programUsersData[0].noOfResourcesStarted; + } + + targetedPrograms.data.data.push(nontargetedJoinedPrograms.data[index]); + } + } + } + return resolve({ success: true, message: constants.apiResponses.USER_TARGETED_PROGRAMS_FETCHED, - data: targetedProgrms.data + data: targetedPrograms.data }); } catch (error) { return resolve({ @@ -893,6 +940,89 @@ module.exports = class UsersHelper { } + /** + * Find non-targeted joined program. + * @method + * @name getNonTargetedJoinedProgram + * @param {Object} requestedData - requested data + * @returns {Object} - non-targeted joined program details. + */ + + static getNonTargetedJoinedProgram( bodyData, pageNo, pageSize, searchText, userId ) { + return new Promise(async (resolve, reject) => { + try { + let queryData = await programsHelper.queryBasedOnRoleAndLocation( + bodyData + ); + + if( !queryData.success ) { + return resolve(queryData); + } + + // get all targeted program ids + let allTargetedPrograms = await programsHelper.list( + pageNo, + pageSize, + "", + queryData.data, + ["_id"] + ); + let targettedProgramIds = []; + let programUsersIds = []; + if ( allTargetedPrograms.success && allTargetedPrograms.data && allTargetedPrograms.data.data.length > 0) { + targettedProgramIds = allTargetedPrograms.data.data.map(function (obj) { + return obj._id; + }); + } + + //find programs joined by the user + let programUsersData = await programUsersHelper.find( + { + userId: userId + }, + ["programId"] + ); + + if ( programUsersData.length > 0 ) { + programUsersIds = programUsersData.map(function (obj) { + return obj.programId; + }); + } + + let nonTargettedPrograms = _.differenceWith(programUsersIds, targettedProgramIds,_.isEqual) + let nonTargettedProgramDetails = []; + if ( nonTargettedPrograms.length > 0 ) { + + let findQuery = { + "_id": { "$in" : nonTargettedPrograms } + } + //get non-targeted program details + nonTargettedProgramDetails = await programsHelper.list( + 1, + nonTargettedPrograms.length, + searchText, + findQuery, + ["name", "externalId","metaInformation"] + ); + } + + return resolve({ + success: true, + data: nonTargettedProgramDetails.data.data, + count: nonTargettedProgramDetails.data.data.length + }); + } catch (error) { + return resolve({ + success: false, + status: error.status + ? error.status + : httpStatusCode['internal_server_error'].status, + message: error.message + }); + } + }); + } + }; @@ -953,3 +1083,5 @@ function _createSolutionData(name = "", externalId = "", isAPrivateProgram = "", } + + From 0b212795f4a98aadf56c06ae2183250cb16f4afc Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Tue, 7 Feb 2023 09:54:37 +0530 Subject: [PATCH 236/331] Added user Role check from userExtension --- controllers/v1/solutions.js | 40 ++++---- controllers/v1/user-extension.js | 69 ++++++++++++- generics/constants/api-responses.js | 1 + module/solutions/helper.js | 144 ++++++++++++++-------------- 4 files changed, 161 insertions(+), 93 deletions(-) diff --git a/controllers/v1/solutions.js b/controllers/v1/solutions.js index 3dedfef4..1a7bf8a5 100644 --- a/controllers/v1/solutions.js +++ b/controllers/v1/solutions.js @@ -1033,25 +1033,25 @@ module.exports = class Solutions extends Abstract { * @returns {JSON} */ - async read(req) { - return new Promise(async (resolve, reject) => { - try { - - let solutionData = await solutionsHelper.read( - req.params._id, - req.userDetails.userId - ); - - return resolve(solutionData); - } - catch (error) { - reject({ - status: error.status || httpStatusCode.internal_server_error.status, - message: error.message || httpStatusCode.internal_server_error.message, - errorObject: error - }) - } - }) - } + // async read(req) { + // return new Promise(async (resolve, reject) => { + // try { + + // let solutionData = await solutionsHelper.read( + // req.params._id, + // req.userDetails.userId + // ); + + // return resolve(solutionData); + // } + // catch (error) { + // reject({ + // status: error.status || httpStatusCode.internal_server_error.status, + // message: error.message || httpStatusCode.internal_server_error.message, + // errorObject: error + // }) + // } + // }) + // } } \ No newline at end of file diff --git a/controllers/v1/user-extension.js b/controllers/v1/user-extension.js index 6de2add9..be590eb1 100644 --- a/controllers/v1/user-extension.js +++ b/controllers/v1/user-extension.js @@ -7,7 +7,7 @@ // Dependencies const userExtensionHelper = require(ROOT_PATH+"/module/user-extension/helper"); - +const userExtensionsHelperV2 = require(ROOT_PATH+"/module/user-extension/helperv2"); /** * UserExtension * @class @@ -264,4 +264,71 @@ module.exports = class UserExtension extends Abstract { }) } + + + /** + * @api {get} /kendra/api/v1/user-extension/read + * @apiVersion 1.0.0 + * @apiName user Extension List + * @apiGroup User Extension + * @apiHeader {String} X-authenticated-user-token Authenticity token + * @apiSampleRequest /kendra/api/v1/user-extension/read + * @apiUse successBody + * @apiUse errorBody + * @apiParamExample {json} Response: + * { + "status":200, + "message":"User extension fetched successfully", + "success":true, + "result":{ + "_id":"60a777528b5424712b5faec3", + "platformRoles":[ + { + "programs":[ + "5f34ec17585244939f89f90c", + "5f34e44681871d939950bca6" + ] + }, + { + "programs":[ + "5f34ec17585244939f89f90c", + "5f75b90454670074deacf087" + ] + }, + { + "programs":[ + "5f34ec17585244939f89f90c", + "5f75b90454670074deacf087" + ] + } + ] + } +} +**/ + read(req){ + return new Promise(async (resolve, reject) => { + let userInformation = await userExtensionsHelperV2.userExtensionDocument({ + userId: req.userDetails.userId, + // userId: "fca2925f-1eee-4654-9177-fece3fd6afc9", + "platformRoles.code" : { $in : ["PROGRAM_MANAGER","PROGRAM_DESIGNER"]}, + status: constants.common.ACTIVE, + isDeleted: false + }, { _id: 1, "platformRoles.programs" :1}); + + if ( !userInformation ) { + return resolve({ + status: httpStatusCode.bad_request.status, + message: constants.apiResponses.NOT_AUTHORIZED_TO_ACCESS + }) + }else { + return resolve({ + status: httpStatusCode.ok.status, + message: constants.apiResponses.USER_EXTENSION_FTECHED, + success: true, + result: userInformation + }) + } + }); + } + }; diff --git a/generics/constants/api-responses.js b/generics/constants/api-responses.js index 0fa43321..af5388b4 100644 --- a/generics/constants/api-responses.js +++ b/generics/constants/api-responses.js @@ -193,4 +193,5 @@ module.exports = { "BASE_CERTIFICATE_TEMPLATE_NOT_FOUND" : "Base certificate template not found", "CERTIFICATE_BASE_TEMPLATE_UPDATED" : "Base template updated successfully", "CERTIFICATE_BASE_TEMPLATE_NOT_UPDATED" : "Base template updation failed", + "USER_EXTENSION_FTECHED":"User extension fetched successfully", }; diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 648b1421..3dff5b05 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -1946,79 +1946,79 @@ module.exports = class SolutionsHelper { * @returns {Object} - Report Information of the solution. */ - static read(solutionId, userId) { - return new Promise(async (resolve, reject) => { - try { - - let userInformation = await userExtensionsHelperV2.userExtensionDocument({ - userId: userId, - "platformRoles.code" : { $in : ["PROGRAM_MANAGER","PROGRAM_DESIGNER"]}, - status: constants.common.ACTIVE, - isDeleted: false - }, { _id: 1, "platformRoles.programs" :1}); - - if ( !userInformation ) { - return resolve({ - status: httpStatusCode.bad_request.status, - message: constants.apiResponses.NOT_AUTHORIZED_TO_ACCESS - }) - } - - let userPrograms = userInformation.platformRoles ? userInformation.platformRoles : []; - let programs = []; - - if ( !userPrograms.length > 0 ) { - return resolve({ - status: httpStatusCode.bad_request.status, - message: constants.apiResponses.NOT_AUTHORIZED_TO_ACCESS - }) - } - - userPrograms.map(eachProgram => { - if ( eachProgram["programs"] && eachProgram["programs"].length > 0 ) { - programs.push(...eachProgram["programs"]); - } - }); - - if ( !programs.length > 0 ) { - return resolve({ - status: httpStatusCode.bad_request.status, - message: constants.apiResponses.NOT_AUTHORIZED_TO_ACCESS - }) - } - - let solutionData = await this.solutionDocuments({ - _id: solutionId, - isDeleted: false, - programId : { $in : programs } - },["reportInformation"]); - - if ( !Array.isArray(solutionData) || solutionData.length < 1 ) { - return resolve({ - message: constants.apiResponses.SOLUTION_NOT_FOUND, - result: {}, - }); - } - - solutionData = solutionData[0]; + // static read(solutionId, userId) { + // return new Promise(async (resolve, reject) => { + // try { + + // let userInformation = await userExtensionsHelperV2.userExtensionDocument({ + // userId: userId, + // "platformRoles.code" : { $in : ["PROGRAM_MANAGER","PROGRAM_DESIGNER"]}, + // status: constants.common.ACTIVE, + // isDeleted: false + // }, { _id: 1, "platformRoles.programs" :1}); + + // if ( !userInformation ) { + // return resolve({ + // status: httpStatusCode.bad_request.status, + // message: constants.apiResponses.NOT_AUTHORIZED_TO_ACCESS + // }) + // } + + // let userPrograms = userInformation.platformRoles ? userInformation.platformRoles : []; + // let programs = []; + + // if ( !userPrograms.length > 0 ) { + // return resolve({ + // status: httpStatusCode.bad_request.status, + // message: constants.apiResponses.NOT_AUTHORIZED_TO_ACCESS + // }) + // } + + // userPrograms.map(eachProgram => { + // if ( eachProgram["programs"] && eachProgram["programs"].length > 0 ) { + // programs.push(...eachProgram["programs"]); + // } + // }); + + // if ( !programs.length > 0 ) { + // return resolve({ + // status: httpStatusCode.bad_request.status, + // message: constants.apiResponses.NOT_AUTHORIZED_TO_ACCESS + // }) + // } + + // let solutionData = await this.solutionDocuments({ + // _id: solutionId, + // isDeleted: false, + // programId : { $in : programs } + // },["reportInformation"]); + + // if ( !Array.isArray(solutionData) || solutionData.length < 1 ) { + // return resolve({ + // message: constants.apiResponses.SOLUTION_NOT_FOUND, + // result: {}, + // }); + // } + + // solutionData = solutionData[0]; - return resolve({ - message: constants.apiResponses.SOLUTION_DETAILS_FETCHED, - success: true, - result: solutionData.reportInformation ? solutionData.reportInformation : {}, - }); - - } catch (error) { - return resolve({ - success: false, - status: error.status - ? error.status - : httpStatusCode['internal_server_error'].status, - message: error.message, - }); - } - }); - } + // return resolve({ + // message: constants.apiResponses.SOLUTION_DETAILS_FETCHED, + // success: true, + // result: solutionData.reportInformation ? solutionData.reportInformation : {}, + // }); + + // } catch (error) { + // return resolve({ + // success: false, + // status: error.status + // ? error.status + // : httpStatusCode['internal_server_error'].status, + // message: error.message, + // }); + // } + // }); + // } }; From ce8e2b534497fff628f8b65c6efdcd89ea17cc26 Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Tue, 7 Feb 2023 09:58:00 +0530 Subject: [PATCH 237/331] done with this pr --- controllers/v1/user-extension.js | 1 - 1 file changed, 1 deletion(-) diff --git a/controllers/v1/user-extension.js b/controllers/v1/user-extension.js index be590eb1..02b1aefa 100644 --- a/controllers/v1/user-extension.js +++ b/controllers/v1/user-extension.js @@ -309,7 +309,6 @@ module.exports = class UserExtension extends Abstract { return new Promise(async (resolve, reject) => { let userInformation = await userExtensionsHelperV2.userExtensionDocument({ userId: req.userDetails.userId, - // userId: "fca2925f-1eee-4654-9177-fece3fd6afc9", "platformRoles.code" : { $in : ["PROGRAM_MANAGER","PROGRAM_DESIGNER"]}, status: constants.common.ACTIVE, isDeleted: false From 947efc8312a6324bdd499c5bee655efe9fec420d Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 13 Feb 2023 11:46:55 +0530 Subject: [PATCH 238/331] schema.js added. it was removed by mistake --- generics/constants/schema.js | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 generics/constants/schema.js diff --git a/generics/constants/schema.js b/generics/constants/schema.js new file mode 100644 index 00000000..63c9972c --- /dev/null +++ b/generics/constants/schema.js @@ -0,0 +1,15 @@ +/** + * name : constants/schema.js + * author : Aman + * Date : 28-feb-2020 + * Description : All common schema information. + */ + +module.exports = { + METAINFORMATION : "metaInformation", + EXTERNALID : "externalId", + NAME : "name", + ENTITYTYPE : "entityType", + GROUPS : "groups", + ID : "_id" +} \ No newline at end of file From c1a80cd3d5f6a4b3c6f240f2f3d9d93570559370 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Tue, 14 Feb 2023 14:47:12 +0530 Subject: [PATCH 239/331] validation changes added for userRoleInformation --- module/programs/helper.js | 3 ++- module/programs/validator/v1.js | 4 +++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/module/programs/helper.js b/module/programs/helper.js index 586c2a7b..bdca8839 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -993,6 +993,7 @@ module.exports = class ProgramsHelper { static join( programId, data, userId, userToken, appName = "", appVersion = "", internalAccessToken = "" ) { return new Promise(async (resolve, reject) => { try { + //Using programId fetch program name. Also checking the program status in the query. let programData = await this.programDocuments({ _id: programId, @@ -1025,7 +1026,7 @@ module.exports = class ProgramsHelper { } programUsersData = { programId: programId, - userRoleInformation: data.userRoleInformation, + userRoleInformation: data.userRoleInformation ? data.userRoleInformation : {}, userId: userId, userProfile: userProfile.data.response } diff --git a/module/programs/validator/v1.js b/module/programs/validator/v1.js index a5da3c80..d9fa9b9f 100644 --- a/module/programs/validator/v1.js +++ b/module/programs/validator/v1.js @@ -35,7 +35,9 @@ module.exports = (req) => { join : function () { req.checkParams("_id").exists().withMessage("required program id"); req.checkParams("_id").isMongoId().withMessage("invalid Mongo Id"); - req.checkBody("userRoleInformation").exists().withMessage("required userRoleInformation to be added"); + if ( !req.headers["internal-access-token"] || req.headers["internal-access-token"]=== "" ) { + req.checkBody("userRoleInformation").exists().withMessage("required userRoleInformation to be added"); + } }, } From f6a3383cd8e15f073494363018bc6ed903888c56 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 17 Feb 2023 12:44:57 +0530 Subject: [PATCH 240/331] fix for survey solution list via programs tile --- generics/services/survey.js | 7 ++++++- module/users/helper.js | 27 +++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/generics/services/survey.js b/generics/services/survey.js index ac884d13..1414e1d5 100644 --- a/generics/services/survey.js +++ b/generics/services/survey.js @@ -77,10 +77,11 @@ var assignedObservations = function ( token,search = "",filter = "" ) { * @param {String} token - logged in user token. * @param {String} [search = ""] - search data. * @param {String} [filter = ""] - filter key. + * @param {String} solutionId - survey solution Id. * @returns {Promise} returns a promise. */ -var assignedSurveys = function ( token,search = "",filter = "", surveyReportPage = "" ) { +var assignedSurveys = function ( token,search = "",filter = "", surveyReportPage = "",solutionId = "" ) { let userAssignedUrl = process.env.ML_SURVEY_SERVICE_URL + @@ -93,6 +94,10 @@ var assignedSurveys = function ( token,search = "",filter = "", surveyReportPage if( surveyReportPage !== "" ) { userAssignedUrl = userAssignedUrl + "&surveyReportPage=" + surveyReportPage; } + + if( solutionId !== "" ) { + userAssignedUrl = userAssignedUrl + "&solutionId=" + solutionId; + } return new Promise(async (resolve, reject) => { try { diff --git a/module/users/helper.js b/module/users/helper.js index b7d3c3b1..15bc26be 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -5,6 +5,7 @@ * Description : All User related information including sys_admin. */ + // Dependencies const programsHelper = require(MODULES_BASE_PATH + "/programs/helper"); const solutionsHelper = require(MODULES_BASE_PATH + "/solutions/helper"); @@ -13,6 +14,7 @@ const entitiesHelper = require(MODULES_BASE_PATH + "/entities/helper"); const improvementProjectService = require(ROOT_PATH + "/generics/services/improvement-project"); const userService = require(ROOT_PATH + "/generics/services/users"); const formService = require(ROOT_PATH + '/generics/services/form'); +const surveyService = require(ROOT_PATH + '/generics/services/survey'); /** @@ -535,6 +537,31 @@ module.exports = class UsersHelper { mergedData = mergedData.slice(startIndex, endIndex); } + // find submission for survey submission + for ( let solutionPointer = 0; solutionPointer < mergedData.length; solutionPointer++ ) { + if ( mergedData[solutionPointer].type && mergedData[solutionPointer].type === constants.common.SURVEY ) { + let userSurveySubmission = + await surveyService.assignedSurveys( + token, + "", + "", + false, + mergedData[solutionPointer]._id + ); + + // If survey solution has any submission by user add it's id to response + if ( userSurveySubmission.success && + userSurveySubmission.data && + userSurveySubmission.data.data && + userSurveySubmission.data.data.length > 0 && + userSurveySubmission.data.data[0].submissionId && + userSurveySubmission.data.data[0].submissionId !== "" + ) { + mergedData[solutionPointer].submissionId = userSurveySubmission.data.data[0].submissionId; + } + } + } + let result = { programName: programData[0].name, programId: programId, From f20755142fa3b4c7e38b63894780d9031b34cd10 Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Mon, 20 Feb 2023 12:01:57 +0530 Subject: [PATCH 241/331] splited name and desgination in two line --- module/certificateTemplates/helper.js | 6 ++++++ test.js | 8 ++++++++ 2 files changed, 14 insertions(+) create mode 100644 test.js diff --git a/module/certificateTemplates/helper.js b/module/certificateTemplates/helper.js index d75434d8..49955260 100644 --- a/module/certificateTemplates/helper.js +++ b/module/certificateTemplates/helper.js @@ -251,6 +251,12 @@ module.exports = class CertificateTemplatesHelper { if ( textData[textKeys[textKeysIndex]] ) { let updateText = textData[textKeys[textKeysIndex]]; + if(textKeys[textKeysIndex] != "stateTitle"){ + let nameAndDesignation = updateText.split(",") + let name = nameAndDesignation.shift(); + let designation = nameAndDesignation.reduce((acc,cuu) => acc + "," + cuu) + updateText = name +"\n"+ designation + } const element = $('#' + textKeys[textKeysIndex]); element.text(updateText); } diff --git a/test.js b/test.js new file mode 100644 index 00000000..da35b093 --- /dev/null +++ b/test.js @@ -0,0 +1,8 @@ +let name = "సుబాష్ చంద్రస్వామి మాచిరాజు(ವರದಿಗಾರ from the रिपोर्टर),Senior QA engineer(ஆய்வாளர்,digital marketing,BBC ವರದಿಗಾರ)" + +let split = name.split(",") + +let Name = split.shift() +let Designation = split.reduce((acc,cuu) => acc + "," + cuu) +let newData = Name + "\n" + Designation +console.log(newData, Name, Designation) From d5e995e5170e49bac30e876b34967383db55dea3 Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Mon, 20 Feb 2023 12:02:21 +0530 Subject: [PATCH 242/331] splited name and desgination in two line --- test.js | 8 -------- 1 file changed, 8 deletions(-) delete mode 100644 test.js diff --git a/test.js b/test.js deleted file mode 100644 index da35b093..00000000 --- a/test.js +++ /dev/null @@ -1,8 +0,0 @@ -let name = "సుబాష్ చంద్రస్వామి మాచిరాజు(ವರದಿಗಾರ from the रिपोर्टर),Senior QA engineer(ஆய்வாளர்,digital marketing,BBC ವರದಿಗಾರ)" - -let split = name.split(",") - -let Name = split.shift() -let Designation = split.reduce((acc,cuu) => acc + "," + cuu) -let newData = Name + "\n" + Designation -console.log(newData, Name, Designation) From 6a96691b6135b21ad9d098650dba7fe7ec679dcb Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Mon, 20 Feb 2023 15:56:12 +0530 Subject: [PATCH 243/331] fixed template problem --- generics/constants/api-responses.js | 1 + module/certificateTemplates/helper.js | 13 ++++++------- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/generics/constants/api-responses.js b/generics/constants/api-responses.js index 0fa43321..ee68059a 100644 --- a/generics/constants/api-responses.js +++ b/generics/constants/api-responses.js @@ -193,4 +193,5 @@ module.exports = { "BASE_CERTIFICATE_TEMPLATE_NOT_FOUND" : "Base certificate template not found", "CERTIFICATE_BASE_TEMPLATE_UPDATED" : "Base template updated successfully", "CERTIFICATE_BASE_TEMPLATE_NOT_UPDATED" : "Base template updation failed", + "BASE_CERTIFICATE_TEMPLATE_NAME_AND_DESIGNATION_ERROR":"Name or Designation character are above limit. Please keep till 28 characters." }; diff --git a/module/certificateTemplates/helper.js b/module/certificateTemplates/helper.js index 49955260..afff153c 100644 --- a/module/certificateTemplates/helper.js +++ b/module/certificateTemplates/helper.js @@ -213,7 +213,7 @@ module.exports = class CertificateTemplatesHelper { let baseTemplateData = await database.models.certificateBaseTemplates.find({ _id: baseTemplateId },["url"]).lean(); - + if ( !baseTemplateData.length > 0 || !baseTemplateData[0].url || baseTemplateData[0].url == "" ) { throw { message: constants.apiResponses.BASE_CERTIFICATE_TEMPLATE_NOT_FOUND @@ -232,7 +232,7 @@ module.exports = class CertificateTemplatesHelper { const $ = cheerio.load(baseTemplate.result); let htmltags = ["","","","","",""]; let imageNames = ["stateLogo1","stateLogo2","signatureImg1","signatureImg2"]; - let textKeys = ["stateTitle","signatureTitle1a","signatureTitle2a"]; + let textKeys = ["stateTitle","signatureTitleName1","signatureTitleDesignation1","signatureTitleName2","signatureTitleDesignation2"]; // edit image elements for ( let imageNamesIndex = 0; imageNamesIndex < imageNames.length; imageNamesIndex++ ) { @@ -251,11 +251,10 @@ module.exports = class CertificateTemplatesHelper { if ( textData[textKeys[textKeysIndex]] ) { let updateText = textData[textKeys[textKeysIndex]]; - if(textKeys[textKeysIndex] != "stateTitle"){ - let nameAndDesignation = updateText.split(",") - let name = nameAndDesignation.shift(); - let designation = nameAndDesignation.reduce((acc,cuu) => acc + "," + cuu) - updateText = name +"\n"+ designation + if(updateText.length > 28){ + throw { + message: constants.apiResponses.BASE_CERTIFICATE_TEMPLATE_NAME_AND_DESIGNATION_ERROR + } } const element = $('#' + textKeys[textKeysIndex]); element.text(updateText); From 1658d1c0705898e80b3bbcf9152d7ba97ff38493 Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Mon, 20 Feb 2023 16:03:08 +0530 Subject: [PATCH 244/331] Done with template changes --- generics/constants/api-responses.js | 1 - module/certificateTemplates/helper.js | 5 ----- 2 files changed, 6 deletions(-) diff --git a/generics/constants/api-responses.js b/generics/constants/api-responses.js index ee68059a..0fa43321 100644 --- a/generics/constants/api-responses.js +++ b/generics/constants/api-responses.js @@ -193,5 +193,4 @@ module.exports = { "BASE_CERTIFICATE_TEMPLATE_NOT_FOUND" : "Base certificate template not found", "CERTIFICATE_BASE_TEMPLATE_UPDATED" : "Base template updated successfully", "CERTIFICATE_BASE_TEMPLATE_NOT_UPDATED" : "Base template updation failed", - "BASE_CERTIFICATE_TEMPLATE_NAME_AND_DESIGNATION_ERROR":"Name or Designation character are above limit. Please keep till 28 characters." }; diff --git a/module/certificateTemplates/helper.js b/module/certificateTemplates/helper.js index afff153c..113fd124 100644 --- a/module/certificateTemplates/helper.js +++ b/module/certificateTemplates/helper.js @@ -251,11 +251,6 @@ module.exports = class CertificateTemplatesHelper { if ( textData[textKeys[textKeysIndex]] ) { let updateText = textData[textKeys[textKeysIndex]]; - if(updateText.length > 28){ - throw { - message: constants.apiResponses.BASE_CERTIFICATE_TEMPLATE_NAME_AND_DESIGNATION_ERROR - } - } const element = $('#' + textKeys[textKeysIndex]); element.text(updateText); } From 0e62b80a7105c2ae1ab9b35e9eadb42bb5f2f299 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 20 Feb 2023 22:17:35 +0530 Subject: [PATCH 245/331] PR review-1 Resolves --- config/kafka.js | 8 ++--- controllers/v1/programs.js | 4 +-- envVariables.js | 9 +++-- generics/constants/endpoints.js | 2 +- generics/kafka/producers.js | 2 +- generics/services/users.js | 15 ++++---- models/programUsers.js | 6 +++- models/programs.js | 6 +++- module/programUsers/helper.js | 56 +++++++++++++++++++---------- module/programs/helper.js | 62 +++++++++++++-------------------- module/programs/validator/v1.js | 4 +-- module/solutions/helper.js | 2 +- module/users/helper.js | 51 +++++++++++++++------------ 13 files changed, 125 insertions(+), 102 deletions(-) diff --git a/config/kafka.js b/config/kafka.js index 732d0c73..cddcc3e7 100644 --- a/config/kafka.js +++ b/config/kafka.js @@ -8,7 +8,7 @@ //dependencies const kafka = require('kafka-node'); -const PROGRAM_USERS_SUBMISSION_TOPIC = process.env.PROGRAM_USERS_SUBMISSION_TOPIC; +const PROGRAM_USERS_JOINED_TOPIC = process.env.PROGRAM_USERS_JOINED_TOPIC; /** * Kafka configurations. @@ -40,7 +40,7 @@ const connect = function() { }) _sendToKafkaConsumers( - PROGRAM_USERS_SUBMISSION_TOPIC, + PROGRAM_USERS_JOINED_TOPIC, process.env.KAFKA_URL ); @@ -79,14 +79,14 @@ var _sendToKafkaConsumers = function (topic,host) { console.log("-------Kafka consumer log ends here------------------"); - if (message && message.topic === PROGRAM_USERS_SUBMISSION_TOPIC) { + if (message && message.topic === PROGRAM_USERS_JOINED_TOPIC) { submissionsConsumer.messageReceived(message); } }); consumer.on('error', async function (error) { - if(error.topics && error.topics[0] === PROGRAM_USERS_SUBMISSION_TOPIC) { + if(error.topics && error.topics[0] === PROGRAM_USERS_JOINED_TOPIC) { submissionsConsumer.errorTriggered(error); } diff --git a/controllers/v1/programs.js b/controllers/v1/programs.js index 6b240e89..fa431e3e 100644 --- a/controllers/v1/programs.js +++ b/controllers/v1/programs.js @@ -531,8 +531,8 @@ module.exports = class Programs extends Abstract { req.headers["x-app-ver"] : req.headers.appversion ? req.headers.appversion : "", req.headers["internal-access-token"] ? - req.headers["internal-access-token"] : - req.headers.internalAccessToken ? req.headers.internalAccessToken : "" + true : + req.headers.internalAccessToken ? true : false ); programJoin["result"] = programJoin.data; return resolve(programJoin); diff --git a/envVariables.js b/envVariables.js index a5ea3486..b4e3f14d 100644 --- a/envVariables.js +++ b/envVariables.js @@ -195,8 +195,13 @@ let enviromentVariables = { "optional" : false }, "KAFKA_URL" : { - "message" : "Required", - "optional" : false + "message" : "Required Kafka Url", + "optional" : true, + "requiredIf" : { + "key": "KAFKA_COMMUNICATIONS_ON_OFF", + "operator": "EQUALS", + "value" : "ON" + } }, } diff --git a/generics/constants/endpoints.js b/generics/constants/endpoints.js index 8238a9d6..e64fb4a4 100644 --- a/generics/constants/endpoints.js +++ b/generics/constants/endpoints.js @@ -35,5 +35,5 @@ module.exports = { GET_FORM_DATA : "/plugin/v1/form/read", GET_SCHOOL_DATA : "/v1/org/search", USER_READ_V5 : "/v5/user/read", - CONSENT_API: "/api/user/v1/consent/update" + USER_CONSENT_API: "/user/v1/consent/update" } \ No newline at end of file diff --git a/generics/kafka/producers.js b/generics/kafka/producers.js index 4b9646c1..19d72948 100644 --- a/generics/kafka/producers.js +++ b/generics/kafka/producers.js @@ -7,7 +7,7 @@ // Dependencies const kafkaCommunicationsOnOff = (!process.env.KAFKA_COMMUNICATIONS_ON_OFF || process.env.KAFKA_COMMUNICATIONS_ON_OFF != "OFF") ? "ON" : "OFF"; -const programUsersSubmissionTopic = (process.env.PROGRAM_USERS_SUBMISSION_TOPIC && process.env.PROGRAM_USERS_SUBMISSION_TOPIC != "OFF") ? process.env.PROGRAM_USERS_SUBMISSION_TOPIC : "sl-improvement-project-submission-dev"; +const programUsersSubmissionTopic = (process.env.PROGRAM_USERS_JOINED_TOPIC && process.env.PROGRAM_USERS_JOINED_TOPIC != "OFF") ? process.env.PROGRAM_USERS_JOINED_TOPIC : "sl-improvement-project-submission-dev"; /** * Push program users to kafka. diff --git a/generics/services/users.js b/generics/services/users.js index d869c7c0..4e3ea701 100644 --- a/generics/services/users.js +++ b/generics/services/users.js @@ -349,29 +349,28 @@ async function getParentEntities( entityId, iteration = 0, parentEntities ) { /** * update user consent for sharing the PII. * @method - * @name consent + * @name setUserConsent * @param {String} token - user token * @returns {Object} consentData - consent data. */ -const consent = function ( token, consentData ) { +const setUserConsent = function ( token, consentData ) { return new Promise(async (resolve, reject) => { try { - let url = userServiceUrl + constants.endpoints.CONSENT_API; + let url = userServiceUrl + constants.endpoints.USER_CONSENT_API; const options = { headers : { "content-type": "application/json", - "x-authenticated-user-token" : token, - "Authorization" : process.env.SUNBIRD_SERVICE_AUTHERIZATION + "x-authenticated-user-token" : token }, body: JSON.stringify(consentData) }; - request.post(url,options,kendraCallback); + request.post(url,options,requestCallback); - function kendraCallback(err, data) { + function requestCallback(err, data) { let result = { success : true @@ -410,5 +409,5 @@ module.exports = { orgSchoolSearch :orgSchoolSearch, getSubEntitiesBasedOnEntityType : getSubEntitiesBasedOnEntityType, getParentEntities : getParentEntities, - consent : consent + setUserConsent : setUserConsent } diff --git a/models/programUsers.js b/models/programUsers.js index ebb04b3e..78b95fd7 100644 --- a/models/programUsers.js +++ b/models/programUsers.js @@ -8,6 +8,7 @@ module.exports = { }, userId: { type: String, + required: true, index: true }, noOfResourcesStarted: { @@ -15,7 +16,10 @@ module.exports = { index: true, default: 0 }, - userProfile: Object, + userProfile: { + type : "ObjectId", + required: true + }, userRoleInformation: Object, appInformation: Object }, diff --git a/models/programs.js b/models/programs.js index cfb877f9..4ecaa156 100644 --- a/models/programs.js +++ b/models/programs.js @@ -52,7 +52,11 @@ module.exports = { type: Boolean, default: false }, - metaInformation: Object + metaInformation: Object, + programAuthorOrgId: { + type: String, + required: true + } } }; \ No newline at end of file diff --git a/module/programUsers/helper.js b/module/programUsers/helper.js index e82f2714..4f4d010b 100644 --- a/module/programUsers/helper.js +++ b/module/programUsers/helper.js @@ -46,21 +46,20 @@ module.exports = class ProgramUsersHelper { * @method * @name update * @param {Object} query - * @param {Object} data + * @param {Object} update * @param {Object} options * @returns {JSON} - create programUsers. */ - static update(query, data, options = {}) { + static update(query, update, options = {}) { return new Promise(async (resolve, reject) => { try { let programUsers = await database.models.programUsers.findOneAndUpdate( query, - data, + update, options ); - if( !programUsers._id ) { throw { message : constants.apiResponses.PROGRAM_USERS_NOT_UPDATED @@ -77,27 +76,46 @@ module.exports = class ProgramUsersHelper { /** * find program users details * @method - * @name find - * @param {Object} query - * @param {Array} projection - * @returns {JSON} - create programUsers. + * @name programUsersDocuments + * @param {Array} [filterData = "all"] - template filter query. + * @param {Array} [fieldsArray = "all"] - projected fields. + * @param {Array} [skipFields = "none"] - field not to include + * @returns {Array} Lists of program user. */ - - static find(query, projection = []) { + static programUsersDocuments( + filterData = "all", + fieldsArray = "all", + skipFields = "none" + ) { return new Promise(async (resolve, reject) => { try { - - let programUsers = await database.models.programUsers.find( - query, - projection - ).lean(); - return resolve(programUsers); - + let queryObject = (filterData != "all") ? filterData : {}; + let projection = {} + + if (fieldsArray != "all") { + fieldsArray.forEach(field => { + projection[field] = 1; + }); + } + + if( skipFields !== "none" ) { + skipFields.forEach(field=>{ + projection[field] = 0; + }); + } + + let programUsers = + await database.models.programUsers.find( + queryObject, + projection + ).lean(); + + return resolve(programUsers); + } catch (error) { return reject(error); } - }) + }); } - } \ No newline at end of file diff --git a/module/programs/helper.js b/module/programs/helper.js index bdca8839..abe44e0a 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -982,23 +982,25 @@ module.exports = class ProgramsHelper { * @method * @name join * @param {String} programId - Program Id. - * @param {Object} data - body data. + * @param {Object} data - body data (can include isResourse flag && userRoleInformation). * @param {String} userId - Logged in user id. * @param {String} userToken - User token. * @param {String} [appName = ""] - App Name. * @param {String} [appVersion = ""] - App Version. + * @param {Boolean} callConsetAPIOnBehalfOfUser - required to call consent api or not * @returns {Object} - Details of the program join. */ - static join( programId, data, userId, userToken, appName = "", appVersion = "", internalAccessToken = "" ) { + static join( programId, data, userId, userToken, appName = "", appVersion = "", callConsetAPIOnBehalfOfUser = false ) { return new Promise(async (resolve, reject) => { try { //Using programId fetch program name. Also checking the program status in the query. let programData = await this.programDocuments({ _id: programId, - status: constants.common.ACTIVE - },["name", "externalId"]); + status: constants.common.ACTIVE, + deleted: false + },["name", "externalId","programAuthorOrgId"]); if ( !programData.length > 0 ) { throw ({ @@ -1026,9 +1028,9 @@ module.exports = class ProgramsHelper { } programUsersData = { programId: programId, - userRoleInformation: data.userRoleInformation ? data.userRoleInformation : {}, + userRoleInformation: data.userRoleInformation, userId: userId, - userProfile: userProfile.data.response + // userProfile: userProfile.data.response } if( appName != "" ) { programUsersData['appInformation.appName'] = appName; @@ -1038,19 +1040,25 @@ module.exports = class ProgramsHelper { } //For internal calls add consent using sunbird api - if(internalAccessToken !== ""){ - let consent = { + if(callConsetAPIOnBehalfOfUser){ + if( !programData[0].programAuthorOrgId || programData[0].programAuthorOrgId == "" ) { + throw { + message: constants.apiResponses.PROGRAM_JOIN_FAILED, + status: httpStatusCode.bad_request.status + } + } + let userConsentRequestBody = { "request": { "consent": { "status": constants.common.REVOKED, "userId": userProfile.data.response.id, - "consumerId": userProfile.data.response.organisations.organisationId, + "consumerId": programData[0].programAuthorOrgId, "objectId": programId, "objectType": constants.common.PROGRAM } } } - let consentResponse = await userService.consent(userToken, consent) + let consentResponse = await userService.setUserConsent(userToken, userConsentRequestBody) if(!consentResponse.success){ throw { message: constants.apiResponses.PROGRAM_JOIN_FAILED, @@ -1064,35 +1072,15 @@ module.exports = class ProgramsHelper { programId: programId, userId: userId }; - - //Check data already present in db. - const programUsers = await programUsersHelper.find( - query, - ["_id"] - ); - - // Data already present in programUsers collection, Require updation, else create new entry. let joinProgram; - if( programUsers.length > 0 ) { - //Update the collection - let update = {}; - update['$set'] = programUsersData; - if ( data.isResource ) { - update['$inc'] = { noOfResourcesStarted : 1 } - } - joinProgram = await programUsersHelper.update(query, update, {new:true}); - - } else { - //Create new entry to collection - if ( data.isResource ) { - programUsersData.noOfResourcesStarted = 1; - } - joinProgram = - await programUsersHelper.create( - programUsersData - ); - + let update = {}; + update['$set'] = programUsersData; + if ( data.isResource ) { + update['$inc'] = { noOfResourcesStarted : 1 } } + // add record to programUsers collection + joinProgram = await programUsersHelper.update(query, update, { new:true, upsert:true }); + if (!joinProgram._id) { throw { message: constants.apiResponses.PROGRAM_JOIN_FAILED, diff --git a/module/programs/validator/v1.js b/module/programs/validator/v1.js index d9fa9b9f..a5da3c80 100644 --- a/module/programs/validator/v1.js +++ b/module/programs/validator/v1.js @@ -35,9 +35,7 @@ module.exports = (req) => { join : function () { req.checkParams("_id").exists().withMessage("required program id"); req.checkParams("_id").isMongoId().withMessage("invalid Mongo Id"); - if ( !req.headers["internal-access-token"] || req.headers["internal-access-token"]=== "" ) { - req.checkBody("userRoleInformation").exists().withMessage("required userRoleInformation to be added"); - } + req.checkBody("userRoleInformation").exists().withMessage("required userRoleInformation to be added"); }, } diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 648b1421..fa96448a 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -584,7 +584,7 @@ module.exports = class SolutionsHelper { facetQuery, projection2 ]); - + return resolve({ success : true, message : constants.apiResponses.SOLUTIONS_LIST, diff --git a/module/users/helper.js b/module/users/helper.js index 1b6ebef2..badbe2e3 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -549,10 +549,10 @@ module.exports = class UsersHelper { }; //check programUsers collection for consentForPIIDataSharing - let programUsersData = await programUsersHelper.find( + let programUsersData = await programUsersHelper.programUsersDocuments( { - programId: programId, - userId: userId + userId: userId, + programId: programId }, ["_id"] ); @@ -594,7 +594,7 @@ module.exports = class UsersHelper { static programs(bodyData, pageNo, pageSize, searchText, userId) { return new Promise(async (resolve, reject) => { try { - + // Here program details matching the user profile is retrieved. let targetedPrograms = await programsHelper.forUserRoleAndLocation( bodyData, pageSize, @@ -607,10 +607,10 @@ module.exports = class UsersHelper { message: constants.apiResponses.PROGRAM_NOT_FOUND, }; } - targetedPrograms.data["description"] = - constants.apiResponses.PROGRAM_DESCRIPTION; - - let nontargetedJoinedPrograms = await this.getNonTargetedJoinedProgram( + targetedPrograms.data["description"] = constants.apiResponses.PROGRAM_DESCRIPTION; + + // In case user changed profile after joined a program, we need to find the such program details. (programs not targeted to user profile anymore) + let nontargetedJoinedPrograms = await this.getUserJoinedProgramDetailsWithPreviousProfiles( bodyData, 1, targetedPrograms.data.count, @@ -618,8 +618,10 @@ module.exports = class UsersHelper { userId ); let targetedProgramCount = (targetedPrograms.data.count) ? targetedPrograms.data.count : 0 + // need to update count. targetedPrograms.data.count = targetedPrograms.data.count + nontargetedJoinedPrograms.count; + // if user hasn't changed profile or request pagination doesn't exceed total targeted programs if ( !nontargetedJoinedPrograms.count > 0 || (pageSize*pageNo) <= targetedProgramCount ) { return resolve({ success: true, @@ -629,10 +631,11 @@ module.exports = class UsersHelper { } else { let maxLimit = 0; let minLimit = 0; - if ( targetedPrograms.data.data.length == 0 ) { + // if no targeted program for user + if ( targetedPrograms.data.data.length === 0 ) { maxLimit = (pageNo*pageSize)-targetedProgramCount; minLimit = maxLimit-pageSize; - } else if ( targetedPrograms.data.data.length < pageSize ) { + } else if ( targetedPrograms.data.data.length < pageSize ) { maxLimit = pageSize-targetedPrograms.data.data.length; } @@ -640,7 +643,7 @@ module.exports = class UsersHelper { if ( minLimit <= nontargetedJoinedPrograms.data.length ) { for( let index = minLimit; index < maxIndex; index++ ) { //fetch resourse started details - let programUsersData = await programUsersHelper.find( + let programUsersData = await programUsersHelper.programUsersDocuments( { userId: userId, programId: nontargetedJoinedPrograms.data[index]._id @@ -943,14 +946,15 @@ module.exports = class UsersHelper { /** * Find non-targeted joined program. * @method - * @name getNonTargetedJoinedProgram + * @name getUserJoinedProgramDetailsWithPreviousProfiles * @param {Object} requestedData - requested data * @returns {Object} - non-targeted joined program details. */ - static getNonTargetedJoinedProgram( bodyData, pageNo, pageSize, searchText, userId ) { + static getUserJoinedProgramDetailsWithPreviousProfiles( bodyData, pageNo, pageSize, searchText, userId ) { return new Promise(async (resolve, reject) => { try { + // step 1 -> get all targeted program's Id, to the user profile. let queryData = await programsHelper.queryBasedOnRoleAndLocation( bodyData ); @@ -959,7 +963,8 @@ module.exports = class UsersHelper { return resolve(queryData); } - // get all targeted program ids + // get all targeted program ids. + // we have to recall this function here because we need to get all program details. ie) pageNo := 1 && pageSize:= toatal targeted program count. let allTargetedPrograms = await programsHelper.list( pageNo, pageSize, @@ -969,14 +974,16 @@ module.exports = class UsersHelper { ); let targettedProgramIds = []; let programUsersIds = []; + if ( allTargetedPrograms.success && allTargetedPrograms.data && allTargetedPrograms.data.data.length > 0) { targettedProgramIds = allTargetedPrograms.data.data.map(function (obj) { return obj._id; }); } - //find programs joined by the user - let programUsersData = await programUsersHelper.find( + // find all programs joined by the user + // programUsersData will contain list of programs joined by user from all the profiles. This can be considered as the super set of user programs + let programUsersData = await programUsersHelper.programUsersDocuments( { userId: userId }, @@ -988,18 +995,18 @@ module.exports = class UsersHelper { return obj.programId; }); } - - let nonTargettedPrograms = _.differenceWith(programUsersIds, targettedProgramIds,_.isEqual) + // if we find the difference between programUsersData and targettedProgramIds we will get program details joined by user other than the current profile + let previousProfilesJoinedProgramIds = _.differenceWith(programUsersIds, targettedProgramIds,_.isEqual) let nonTargettedProgramDetails = []; - if ( nonTargettedPrograms.length > 0 ) { - + if ( previousProfilesJoinedProgramIds.length > 0 ) { + // We only have prograIds of user joined from old profiles. Need to get program details using these Ids let findQuery = { - "_id": { "$in" : nonTargettedPrograms } + "_id": { "$in" : previousProfilesJoinedProgramIds } } //get non-targeted program details nonTargettedProgramDetails = await programsHelper.list( 1, - nonTargettedPrograms.length, + previousProfilesJoinedProgramIds.length, searchText, findQuery, ["name", "externalId","metaInformation"] From 87508af8b1dd95a78f74e13d9df09cda179fd167 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 20 Feb 2023 22:25:53 +0530 Subject: [PATCH 246/331] isDelete filter added to program fetch --- module/programs/helper.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/module/programs/helper.js b/module/programs/helper.js index abe44e0a..579b4335 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -999,7 +999,7 @@ module.exports = class ProgramsHelper { let programData = await this.programDocuments({ _id: programId, status: constants.common.ACTIVE, - deleted: false + isDeleted: false },["name", "externalId","programAuthorOrgId"]); if ( !programData.length > 0 ) { From 1f38ec73db269e972a75900f3242b69c487f9c34 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 20 Feb 2023 22:34:23 +0530 Subject: [PATCH 247/331] kafka consumer function removed --- config/kafka.js | 49 ------------------------------------------------- 1 file changed, 49 deletions(-) diff --git a/config/kafka.js b/config/kafka.js index cddcc3e7..07f50d82 100644 --- a/config/kafka.js +++ b/config/kafka.js @@ -39,11 +39,6 @@ const connect = function() { console.log("kafka producer creation error!") }) - _sendToKafkaConsumers( - PROGRAM_USERS_JOINED_TOPIC, - process.env.KAFKA_URL - ); - return { kafkaProducer: producer, kafkaClient: client @@ -51,48 +46,4 @@ const connect = function() { }; -/** - * Send data based on topic to kafka consumers - * @function - * @name _sendToKafkaConsumers - * @param {String} topic - name of kafka topic. - * @param {String} host - kafka host -*/ - -var _sendToKafkaConsumers = function (topic,host) { - - if (topic && topic != "") { - - let consumer = new kafka.ConsumerGroup( - { - kafkaHost : host, - groupId : process.env.KAFKA_GROUP_ID, - autoCommit : true - },topic - ); - - consumer.on('message', async function (message) { - - console.log("-------Kafka consumer log starts here------------------"); - console.log("Topic Name: ", topic); - console.log("Message: ", JSON.stringify(message)); - console.log("-------Kafka consumer log ends here------------------"); - - - if (message && message.topic === PROGRAM_USERS_JOINED_TOPIC) { - submissionsConsumer.messageReceived(message); - } - }); - - consumer.on('error', async function (error) { - - if(error.topics && error.topics[0] === PROGRAM_USERS_JOINED_TOPIC) { - submissionsConsumer.errorTriggered(error); - } - - }); - - } -}; - module.exports = connect; From 3d24079ee97d0a489d46848f2ec40d0d13e818fd Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 20 Feb 2023 23:30:29 +0530 Subject: [PATCH 248/331] comment removed --- module/programs/helper.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/module/programs/helper.js b/module/programs/helper.js index 579b4335..dac862dc 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -1030,7 +1030,7 @@ module.exports = class ProgramsHelper { programId: programId, userRoleInformation: data.userRoleInformation, userId: userId, - // userProfile: userProfile.data.response + userProfile: userProfile.data.response } if( appName != "" ) { programUsersData['appInformation.appName'] = appName; From 07cb64bb856213aa2e1478ccd9629bc6b5cf0f91 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Tue, 21 Feb 2023 03:36:52 +0530 Subject: [PATCH 249/331] pass array of solutionIds to survey list call --- generics/services/survey.js | 15 +++++++------ module/users/helper.js | 42 +++++++++++++++++++++++-------------- 2 files changed, 35 insertions(+), 22 deletions(-) diff --git a/generics/services/survey.js b/generics/services/survey.js index 1414e1d5..0663361b 100644 --- a/generics/services/survey.js +++ b/generics/services/survey.js @@ -77,11 +77,11 @@ var assignedObservations = function ( token,search = "",filter = "" ) { * @param {String} token - logged in user token. * @param {String} [search = ""] - search data. * @param {String} [filter = ""] - filter key. - * @param {String} solutionId - survey solution Id. + * @param {Array} - solutionIds - survey solutionIds * @returns {Promise} returns a promise. */ -var assignedSurveys = function ( token,search = "",filter = "", surveyReportPage = "",solutionId = "" ) { +var assignedSurveys = function ( token,search = "",filter = "", surveyReportPage = "", solutionIds = []) { let userAssignedUrl = process.env.ML_SURVEY_SERVICE_URL + @@ -94,11 +94,12 @@ var assignedSurveys = function ( token,search = "",filter = "", surveyReportPage if( surveyReportPage !== "" ) { userAssignedUrl = userAssignedUrl + "&surveyReportPage=" + surveyReportPage; } - - if( solutionId !== "" ) { - userAssignedUrl = userAssignedUrl + "&solutionId=" + solutionId; + let requestBody = {} + if (solutionIds.length > 0) { + requestBody.solutionIds = solutionIds; } + return new Promise(async (resolve, reject) => { try { @@ -127,7 +128,9 @@ var assignedSurveys = function ( token,search = "",filter = "", surveyReportPage headers : { "content-type": "application/json", "x-authenticated-user-token" : token - } + }, + body: JSON.stringify(requestBody) + }; request.get(userAssignedUrl,options,assessmentCallback) diff --git a/module/users/helper.js b/module/users/helper.js index 15bc26be..36091235 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -472,7 +472,6 @@ module.exports = class UsersHelper { let totalCount = 0; let mergedData = []; - let projectSolutionIdIndexMap = {} if ( @@ -536,30 +535,41 @@ module.exports = class UsersHelper { let endIndex = startIndex + pageSize; mergedData = mergedData.slice(startIndex, endIndex); } - - // find submission for survey submission - for ( let solutionPointer = 0; solutionPointer < mergedData.length; solutionPointer++ ) { - if ( mergedData[solutionPointer].type && mergedData[solutionPointer].type === constants.common.SURVEY ) { - let userSurveySubmission = + + // get all solutionIds of type survey + let surveySolutionIds = []; + mergedData.forEach( element => { + if( element.type === constants.common.SURVEY ) { + surveySolutionIds.push(element._id) + } + }); + + + if ( surveySolutionIds.length > 0 ) { + let userSurveySubmission = await surveyService.assignedSurveys( token, "", "", false, - mergedData[solutionPointer]._id + surveySolutionIds ); - - // If survey solution has any submission by user add it's id to response + if ( userSurveySubmission.success && - userSurveySubmission.data && - userSurveySubmission.data.data && - userSurveySubmission.data.data.length > 0 && - userSurveySubmission.data.data[0].submissionId && - userSurveySubmission.data.data[0].submissionId !== "" + userSurveySubmission.data && + userSurveySubmission.data.data && + userSurveySubmission.data.data.length > 0 ) { - mergedData[solutionPointer].submissionId = userSurveySubmission.data.data[0].submissionId; + for ( let surveySubmissionPointer = 0; surveySubmissionPointer < userSurveySubmission.data.data.length; surveySubmissionPointer++ ) { + for ( let mergedDataPointer = 0; mergedDataPointer < mergedData.length; mergedDataPointer++ ) { + if ( mergedData[mergedDataPointer].type == constants.common.SURVEY && userSurveySubmission.data.data[surveySubmissionPointer].solutionId == mergedData[mergedDataPointer]._id ) { + mergedData[mergedDataPointer].submissionId = userSurveySubmission.data.data[surveySubmissionPointer].submissionId; + break; + } + + } + } } - } } let result = { From 78a8822c068120b0334de1b4f728472f07cf80b7 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Wed, 22 Feb 2023 11:09:21 +0530 Subject: [PATCH 250/331] fix for Azure warning throwing if no Azure env found --- generics/services/azure.js | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/generics/services/azure.js b/generics/services/azure.js index 553408e8..00cfcd7c 100644 --- a/generics/services/azure.js +++ b/generics/services/azure.js @@ -10,25 +10,25 @@ let blobServiceClient; let containerClient; (async () => { + if( process.env.CLOUD_STORAGE === "AZURE" ) { + const sharedKeyCredential = new StorageSharedKeyCredential(AZURE_ACCOUNT_NAME, AZURE_ACCOUNT_KEY); - const sharedKeyCredential = new StorageSharedKeyCredential(AZURE_ACCOUNT_NAME, AZURE_ACCOUNT_KEY); + // Create the BlobServiceClient object which will be used to create a container client + blobServiceClient = new BlobServiceClient( + `https://${AZURE_ACCOUNT_NAME}.blob.core.windows.net`, + sharedKeyCredential + ); - // Create the BlobServiceClient object which will be used to create a container client - blobServiceClient = new BlobServiceClient( - `https://${AZURE_ACCOUNT_NAME}.blob.core.windows.net`, - sharedKeyCredential - ); + // Get a reference to a container + containerClient = await blobServiceClient.getContainerClient(AZURE_STORAGE_CONTAINER); - // Get a reference to a container - containerClient = await blobServiceClient.getContainerClient(AZURE_STORAGE_CONTAINER); + const checkIfContainerExists = await containerClient.exists(); - const checkIfContainerExists = await containerClient.exists(); - - if (!checkIfContainerExists) { - // Create the container - const createContainerResponse = await containerClient.create(); + if (!checkIfContainerExists) { + // Create the container + const createContainerResponse = await containerClient.create(); + } } - })(); /** From fd533b299749adf06af885a4a083a6ecfc6c4675 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 23 Feb 2023 12:25:45 +0530 Subject: [PATCH 251/331] env samples updated --- .env.sample | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.env.sample b/.env.sample index b4ecd4b2..e994c0b8 100644 --- a/.env.sample +++ b/.env.sample @@ -51,3 +51,8 @@ OCI_BUCKET_NAME = 'oracle cloud bucket name' OCI_BUCKET_REGION = 'ap-hyderabad-1' // Oracle cloud bucket region OCI_BUCKET_ENDPOINT = 'https://pmt5.compat.storage.ap-h1.oraclecloud.com' // Oracle cloud bucket endPoint +# KAFKA Configurations +KAFKA_COMMUNICATIONS_ON_OFF = ON // Kafka enable or disable communication flag +KAFKA_URL = 192.168.100.27:9092 // IP address of kafka server with port without HTTP +KAFKA_GROUP_ID = projects // Kafka group id +PROGRAM_USERS_JOINED_TOPIC = "ml.programUsers.raw" // Kafka submission topic for pushing program joined user's data \ No newline at end of file From c8bd3d796e30e8f835af03b30eaa1aea700464c7 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 24 Feb 2023 14:40:28 +0530 Subject: [PATCH 252/331] rootOrganisations used for consent api req body --- models/programs.js | 6 ++---- module/programs/helper.js | 8 ++++---- module/users/helper.js | 3 ++- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/models/programs.js b/models/programs.js index 4ecaa156..5c46bc90 100644 --- a/models/programs.js +++ b/models/programs.js @@ -53,10 +53,8 @@ module.exports = { default: false }, metaInformation: Object, - programAuthorOrgId: { - type: String, - required: true - } + rootOrganisations : Array, + createdFor : Array } }; \ No newline at end of file diff --git a/module/programs/helper.js b/module/programs/helper.js index dac862dc..b077afa7 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -1000,7 +1000,7 @@ module.exports = class ProgramsHelper { _id: programId, status: constants.common.ACTIVE, isDeleted: false - },["name", "externalId","programAuthorOrgId"]); + },["name", "externalId","rootOrganisations"]); if ( !programData.length > 0 ) { throw ({ @@ -1038,10 +1038,10 @@ module.exports = class ProgramsHelper { if( appVersion != "" ) { programUsersData['appInformation.appVersion'] = appVersion; } - + //For internal calls add consent using sunbird api if(callConsetAPIOnBehalfOfUser){ - if( !programData[0].programAuthorOrgId || programData[0].programAuthorOrgId == "" ) { + if( !programData[0].rootOrganisations || !programData[0].rootOrganisations.length > 0 ) { throw { message: constants.apiResponses.PROGRAM_JOIN_FAILED, status: httpStatusCode.bad_request.status @@ -1052,7 +1052,7 @@ module.exports = class ProgramsHelper { "consent": { "status": constants.common.REVOKED, "userId": userProfile.data.response.id, - "consumerId": programData[0].programAuthorOrgId, + "consumerId": programData[0].rootOrganisations[0], "objectId": programId, "objectType": constants.common.PROGRAM } diff --git a/module/users/helper.js b/module/users/helper.js index 1bd5a087..90c55d5e 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -453,7 +453,7 @@ module.exports = class UsersHelper { { _id: programId }, - ["name","requestForPIIConsent"] + ["name","requestForPIIConsent","rootOrganisations"] ); if (!programData.length > 0) { @@ -570,6 +570,7 @@ module.exports = class UsersHelper { programName: programData[0].name, programId: programId, description: constants.common.TARGETED_SOLUTION_TEXT, + rootOrganisations: programData[0].rootOrganisations, requestForPIIConsent: programData[0].requestForPIIConsent ? programData[0].requestForPIIConsent : false, data: mergedData, count: totalCount From 94cca83d4594df4f51338055d8acb327a7df6acb Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Sat, 25 Feb 2023 21:24:37 +0530 Subject: [PATCH 253/331] rootOrganisations array passed --- module/users/helper.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/module/users/helper.js b/module/users/helper.js index 90c55d5e..1008e2e9 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -570,7 +570,7 @@ module.exports = class UsersHelper { programName: programData[0].name, programId: programId, description: constants.common.TARGETED_SOLUTION_TEXT, - rootOrganisations: programData[0].rootOrganisations, + rootOrganisations : ( programData[0].rootOrganisations && programData[0].rootOrganisations.length > 0 ) ? programData[0].rootOrganisations : [], requestForPIIConsent: programData[0].requestForPIIConsent ? programData[0].requestForPIIConsent : false, data: mergedData, count: totalCount From e69ffc8dd3df3c1f9937b97d468179a40a6675bb Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Tue, 7 Mar 2023 14:08:47 +0530 Subject: [PATCH 254/331] resolves --- models/programUsers.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/models/programUsers.js b/models/programUsers.js index 78b95fd7..1386abd4 100644 --- a/models/programUsers.js +++ b/models/programUsers.js @@ -17,7 +17,7 @@ module.exports = { default: 0 }, userProfile: { - type : "ObjectId", + type : Object, required: true }, userRoleInformation: Object, From 0a97dbbed6983676b2a9ea25035317e06fd2da19 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 10 Mar 2023 17:20:52 +0530 Subject: [PATCH 255/331] requestForPIIConsent is added to kafka --- module/programs/helper.js | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/module/programs/helper.js b/module/programs/helper.js index b077afa7..f83dc524 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -1000,7 +1000,7 @@ module.exports = class ProgramsHelper { _id: programId, status: constants.common.ACTIVE, isDeleted: false - },["name", "externalId","rootOrganisations"]); + },["name", "externalId","requestForPIIConsent","rootOrganisations"]); if ( !programData.length > 0 ) { throw ({ @@ -1010,8 +1010,8 @@ module.exports = class ProgramsHelper { } let programUsersData = {}; - // Fetch user profile information by calling sunbird's user read api. - // !Important check specific fields of userProfile. + Fetch user profile information by calling sunbird's user read api. + !Important check specific fields of userProfile. let userProfile = await userService.profile(userToken, userId); if (!userProfile.success || !userProfile.data || @@ -1030,7 +1030,7 @@ module.exports = class ProgramsHelper { programId: programId, userRoleInformation: data.userRoleInformation, userId: userId, - userProfile: userProfile.data.response + userProfile:userProfile.data.response } if( appName != "" ) { programUsersData['appInformation.appName'] = appName; @@ -1089,6 +1089,7 @@ module.exports = class ProgramsHelper { } joinProgram.programName = programData[0].name; joinProgram.programExternalId = programData[0].externalId; + joinProgram.requestForPIIConsent =programData[0].requestForPIIConsent // push programUsers details to kafka await kafkaProducersHelper.pushProgramUsersToKafka(joinProgram); From a6429cbec5ee376f9d4eeb4c0588fba8a03dd72e Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 10 Mar 2023 17:22:05 +0530 Subject: [PATCH 256/331] comments added --- module/programs/helper.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/module/programs/helper.js b/module/programs/helper.js index f83dc524..af1a244d 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -1010,8 +1010,8 @@ module.exports = class ProgramsHelper { } let programUsersData = {}; - Fetch user profile information by calling sunbird's user read api. - !Important check specific fields of userProfile. + // Fetch user profile information by calling sunbird's user read api. + // !Important check specific fields of userProfile. let userProfile = await userService.profile(userToken, userId); if (!userProfile.success || !userProfile.data || From 80121c8c7dbe9b64c327f97eb3cc4869f4f62b2e Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 13 Mar 2023 11:17:20 +0530 Subject: [PATCH 257/331] kafkaCommunicationsOnOff unwanted check removed --- generics/kafka/producers.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/generics/kafka/producers.js b/generics/kafka/producers.js index 19d72948..2a62bcf9 100644 --- a/generics/kafka/producers.js +++ b/generics/kafka/producers.js @@ -6,7 +6,7 @@ */ // Dependencies -const kafkaCommunicationsOnOff = (!process.env.KAFKA_COMMUNICATIONS_ON_OFF || process.env.KAFKA_COMMUNICATIONS_ON_OFF != "OFF") ? "ON" : "OFF"; +const kafkaCommunicationsOnOff = process.env.KAFKA_COMMUNICATIONS_ON_OFF; const programUsersSubmissionTopic = (process.env.PROGRAM_USERS_JOINED_TOPIC && process.env.PROGRAM_USERS_JOINED_TOPIC != "OFF") ? process.env.PROGRAM_USERS_JOINED_TOPIC : "sl-improvement-project-submission-dev"; /** From dbf80a1dea3950491f47216177bfe8651d8c3e4e Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 13 Mar 2023 11:24:05 +0530 Subject: [PATCH 258/331] program join validation message changed --- module/programs/validator/v1.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/module/programs/validator/v1.js b/module/programs/validator/v1.js index a5da3c80..15bf62bd 100644 --- a/module/programs/validator/v1.js +++ b/module/programs/validator/v1.js @@ -34,7 +34,7 @@ module.exports = (req) => { }, join : function () { req.checkParams("_id").exists().withMessage("required program id"); - req.checkParams("_id").isMongoId().withMessage("invalid Mongo Id"); + req.checkParams("_id").isMongoId().withMessage("Invalid program ID"); req.checkBody("userRoleInformation").exists().withMessage("required userRoleInformation to be added"); }, } From bce3b83449ce7d1595864085eb485c201bac8077 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 13 Mar 2023 12:39:12 +0530 Subject: [PATCH 259/331] comments added to understand pagination logic --- module/users/helper.js | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/module/users/helper.js b/module/users/helper.js index 1008e2e9..f8fff1ce 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -661,13 +661,33 @@ module.exports = class UsersHelper { let minLimit = 0; // if no targeted program for user if ( targetedPrograms.data.data.length === 0 ) { - maxLimit = (pageNo*pageSize)-targetedProgramCount; + /** + * {case: 1} + * if targeted programs is 0 and nontargetedJoinedPrograms := 3 + * example : pageNo := 1 + * pageSize : 5 + * maxLimit = 5 + * minLimit = 0 + */ + maxLimit = (pageNo*pageSize)-targetedProgramCount; minLimit = maxLimit-pageSize; } else if ( targetedPrograms.data.data.length < pageSize ) { + /** + * {case: 2} + * targetedPrograms: 3 + * example : pageNo := 4 + * pageSize : 5 + * and profile has nontargetedJoinedPrograms:= 3 + * maxLimit := 2 + */ maxLimit = pageSize-targetedPrograms.data.data.length; } let maxIndex = (maxLimit <= nontargetedJoinedPrograms.data.length) ? maxLimit : nontargetedJoinedPrograms.data.length; + /** + * {case 1: maxIndex : 3} + * {case 2: maxIndex : 2} + */ if ( minLimit <= nontargetedJoinedPrograms.data.length ) { for( let index = minLimit; index < maxIndex; index++ ) { //fetch resourse started details From b3254a81f717aecb65d74cd48e88aad9b18e7b7c Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 13 Mar 2023 12:56:04 +0530 Subject: [PATCH 260/331] review resolves --- module/users/helper.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/module/users/helper.js b/module/users/helper.js index f8fff1ce..20341ad7 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -1013,6 +1013,7 @@ module.exports = class UsersHelper { // get all targeted program ids. // we have to recall this function here because we need to get all program details. ie) pageNo := 1 && pageSize:= toatal targeted program count. + // allTargetedPrograms.data contain query based on user location and role. let allTargetedPrograms = await programsHelper.list( pageNo, pageSize, @@ -1022,7 +1023,7 @@ module.exports = class UsersHelper { ); let targettedProgramIds = []; let programUsersIds = []; - + // allTargetedPrograms.data contain all programIds targeted to current user profile. if ( allTargetedPrograms.success && allTargetedPrograms.data && allTargetedPrograms.data.data.length > 0) { targettedProgramIds = allTargetedPrograms.data.data.map(function (obj) { return obj._id; @@ -1047,7 +1048,7 @@ module.exports = class UsersHelper { let previousProfilesJoinedProgramIds = _.differenceWith(programUsersIds, targettedProgramIds,_.isEqual) let nonTargettedProgramDetails = []; if ( previousProfilesJoinedProgramIds.length > 0 ) { - // We only have prograIds of user joined from old profiles. Need to get program details using these Ids + // We only have programIds of user joined from old profiles. Need to get program details using these Ids let findQuery = { "_id": { "$in" : previousProfilesJoinedProgramIds } } From 4e1941964559e6044f1655d190b25fc965163aa4 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 13 Mar 2023 17:09:31 +0530 Subject: [PATCH 261/331] on update only changing noOfResourcesStarted --- module/programs/helper.js | 75 ++++++++++++++++++++++----------------- 1 file changed, 43 insertions(+), 32 deletions(-) diff --git a/module/programs/helper.js b/module/programs/helper.js index af1a244d..b3ded981 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -1002,41 +1002,54 @@ module.exports = class ProgramsHelper { isDeleted: false },["name", "externalId","requestForPIIConsent","rootOrganisations"]); - if ( !programData.length > 0 ) { + if ( !programData.length > 0 || !programData[0].requestForPIIConsent || programData[0].requestForPIIConsent == false ) { throw ({ status: httpStatusCode.bad_request.status, message: constants.apiResponses.PROGRAM_NOT_FOUND }); } - let programUsersData = {}; - // Fetch user profile information by calling sunbird's user read api. - // !Important check specific fields of userProfile. - let userProfile = await userService.profile(userToken, userId); - if (!userProfile.success || - !userProfile.data || - !userProfile.data.response || - !userProfile.data.response.profileUserTypes || - !userProfile.data.response.profileUserTypes.length > 0 || - !userProfile.data.response.userLocations || - !userProfile.data.response.userLocations.length > 0 - ) { - throw ({ - status: httpStatusCode.bad_request.status, - message: constants.apiResponses.PROGRAM_JOIN_FAILED - }); - } - programUsersData = { - programId: programId, - userRoleInformation: data.userRoleInformation, - userId: userId, - userProfile:userProfile.data.response - } - if( appName != "" ) { - programUsersData['appInformation.appName'] = appName; - } - if( appVersion != "" ) { - programUsersData['appInformation.appVersion'] = appVersion; + let update = {}; + + // check if user already joined for program or not + const programUsersDetails = await programUsersHelper.programUsersDocuments( + { + userId: userId, + programId: programId + }, + ["_id"] + ); + // if user not joined for program + if ( !programUsersDetails.length > 0 ) { + // Fetch user profile information by calling sunbird's user read api. + // !Important check specific fields of userProfile. + let userProfile = await userService.profile(userToken, userId); + if (!userProfile.success || + !userProfile.data || + !userProfile.data.response || + !userProfile.data.response.profileUserTypes || + !userProfile.data.response.profileUserTypes.length > 0 || + !userProfile.data.response.userLocations || + !userProfile.data.response.userLocations.length > 0 + ) { + throw ({ + status: httpStatusCode.bad_request.status, + message: constants.apiResponses.PROGRAM_JOIN_FAILED + }); + } + programUsersData = { + programId: programId, + userRoleInformation: data.userRoleInformation, + userId: userId, + userProfile:userProfile.data.response + } + if( appName != "" ) { + programUsersData['appInformation.appName'] = appName; + } + if( appVersion != "" ) { + programUsersData['appInformation.appVersion'] = appVersion; + } + update['$set'] = programUsersData; } //For internal calls add consent using sunbird api @@ -1073,8 +1086,6 @@ module.exports = class ProgramsHelper { userId: userId }; let joinProgram; - let update = {}; - update['$set'] = programUsersData; if ( data.isResource ) { update['$inc'] = { noOfResourcesStarted : 1 } } @@ -1089,7 +1100,7 @@ module.exports = class ProgramsHelper { } joinProgram.programName = programData[0].name; joinProgram.programExternalId = programData[0].externalId; - joinProgram.requestForPIIConsent =programData[0].requestForPIIConsent + joinProgram.requestForPIIConsent = programData[0].requestForPIIConsent // push programUsers details to kafka await kafkaProducersHelper.pushProgramUsersToKafka(joinProgram); From d8710065b345617ac3c81767cd9f24ac9a057708 Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Fri, 24 Mar 2023 18:50:06 +0530 Subject: [PATCH 262/331] added api check solution is targeted or not --- controllers/v1/solutions.js | 60 +++++++++++++++++++++++++++++++++ module/solutions/helper.js | 66 +++++++++++++++++++++++++++++++++++++ 2 files changed, 126 insertions(+) diff --git a/controllers/v1/solutions.js b/controllers/v1/solutions.js index 3dedfef4..109faebf 100644 --- a/controllers/v1/solutions.js +++ b/controllers/v1/solutions.js @@ -862,6 +862,66 @@ module.exports = class Solutions extends Abstract { }) } + + + /** + * @api {post} /kendra/api/v1/solutions/verifySolution/:Id + * @apiVersion 1.0.0 + * @apiName verify Solutions targeted + * @apiGroup Solutions + * @apiSampleRequest /kendra/api/v1/solutions/verifySolution/5f6853f293734140ccce90cf + * @apiHeader {String} X-authenticated-user-token Authenticity token + * @apiUse successBody + * @apiUse errorBody + * @apiParamExample {json} Request: + * { + * "role" : "HM,DEO", + "state" : "236f5cff-c9af-4366-b0b6-253a1789766a", + "district" : "1dcbc362-ec4c-4559-9081-e0c2864c2931", + "school" : "c5726207-4f9f-4f45-91f1-3e9e8e84d824" + } + * @apiParamExample {json} Response: + * { + "message": "Solution Link verified successfully", + "status": 200, + "result": { + isATargetedSolution : true/false, + _id : “5f6853f293734140ccce90cf”, + } + } + */ + + /** + * verify Solution + * @method + * @name verifySolution + * @param {Object} req - requested data. + * @param {String} req.params._id - solution id + * @returns {Array} + */ + + async verfiySolution(req) { + return new Promise(async (resolve, reject) => { + try { + + let solutionData = await solutionsHelper.verifySolution( + req.params._id, + req.body, + ); + + return resolve(solutionData); + + } + catch (error) { + return reject({ + status: error.status || httpStatusCode.internal_server_error.status, + message: error.message || httpStatusCode.internal_server_error.message, + errorObject: error + }) + } + }) + } + /** * @api {post} /kendra/api/v1/solutions/details/:solutionId * @apiVersion 1.0.0 diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 648b1421..4f43541c 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -1693,6 +1693,72 @@ module.exports = class SolutionsHelper { }); } + + /** + * Verify solution id + * @method + * @name verifySolution + * @param {String} solutionId - solution Id. + * @param {String} userId - user Id. + * @param {String} userToken - user token. + * @param {Boolean} createProject - create project. + * @param {Object} bodyData - Req Body. + * @returns {Object} - Details of the solution. + */ + + static verifySolution(solutionId = "", bodyData = {}) { + return new Promise(async (resolve, reject) => { + try { + + let response = { + isATargetedSolution: false, + _id: solutionId, + }; + + let queryData = await this.queryBasedOnRoleAndLocation(bodyData); + if ( !queryData.success ) { + return resolve(queryData); + } + + queryData.data["_id"] = solutionId; + let matchQuery = queryData.data; + console.log(JSON.stringify(matchQuery)); + let solutionData = await this.solutionDocuments(matchQuery, [ + "_id", + "type", + "programId", + "name", + ]); + + if ( !Array.isArray(solutionData) || solutionData.length < 1 ) { + + + return resolve({ + success: true, + message: + constants.apiResponses.SOLUTION_NOT_FOUND_OR_NOT_A_TARGETED, + result: response + }); + } + + response.isATargetedSolution = true; + return resolve({ + success: true, + message: constants.apiResponses.SOLUTION_DETAILS_VERIFIED, + result: response, + }); + } catch (error) { + return resolve({ + success: false, + status: error.status + ? error.status + : httpStatusCode['internal_server_error'].status, + message: error.message + }); + } + }); + } + /** * Verify Solution details. * @method From e08e5866020587ce8aefeb323c65a36db2ec91e5 Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Fri, 24 Mar 2023 19:07:46 +0530 Subject: [PATCH 263/331] added api check solution is targeted or not --- controllers/v1/solutions.js | 4 ++-- module/solutions/helper.js | 12 ++++++++++-- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/controllers/v1/solutions.js b/controllers/v1/solutions.js index 109faebf..35fdbb49 100644 --- a/controllers/v1/solutions.js +++ b/controllers/v1/solutions.js @@ -900,11 +900,11 @@ module.exports = class Solutions extends Abstract { * @returns {Array} */ - async verfiySolution(req) { + async isTargetedBasedOnUserProfile(req) { return new Promise(async (resolve, reject) => { try { - let solutionData = await solutionsHelper.verifySolution( + let solutionData = await solutionsHelper.isTargetedBasedOnUserProfile( req.params._id, req.body, ); diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 4f43541c..c1c1bab4 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -1704,9 +1704,18 @@ module.exports = class SolutionsHelper { * @param {Boolean} createProject - create project. * @param {Object} bodyData - Req Body. * @returns {Object} - Details of the solution. + * Takes SolutionId and userRoleInformation as parameters. + * @return {Object} - { + "message": "Solution is not targeted to the role", + "status": 200, + "result": { + "isATargetedSolution": false/true, + "_id": "63987b5d26a3620009a1142d" + } + } */ - static verifySolution(solutionId = "", bodyData = {}) { + static isTargetedBasedOnUserProfile(solutionId = "", bodyData = {}) { return new Promise(async (resolve, reject) => { try { @@ -1722,7 +1731,6 @@ module.exports = class SolutionsHelper { queryData.data["_id"] = solutionId; let matchQuery = queryData.data; - console.log(JSON.stringify(matchQuery)); let solutionData = await this.solutionDocuments(matchQuery, [ "_id", "type", From 482ac0ec836bf942fa555eed1059397acf785612 Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Mon, 27 Mar 2023 16:54:10 +0530 Subject: [PATCH 264/331] done with changes --- README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/README.md b/README.md index 8e2db83d..9b2a8d0c 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,3 @@ # ml-core-service Centralised Service to support other Services. -It is used by ml-survey and ml-project - - +It is used by ml-survey, ml-project \ No newline at end of file From a1540af4be5be3a996d83a6c089fa09d6d3b2346 Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Mon, 27 Mar 2023 16:55:33 +0530 Subject: [PATCH 265/331] Added few comments --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8e2db83d..16672448 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # ml-core-service Centralised Service to support other Services. -It is used by ml-survey and ml-project +It is used by ml-survey, ml-project From 888184c79d60f369392d4459a39852ec8e12aa37 Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Mon, 27 Mar 2023 17:00:01 +0530 Subject: [PATCH 266/331] Added few comments --- module/certificateTemplates/helper.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/module/certificateTemplates/helper.js b/module/certificateTemplates/helper.js index 113fd124..f7460edc 100644 --- a/module/certificateTemplates/helper.js +++ b/module/certificateTemplates/helper.js @@ -248,8 +248,8 @@ module.exports = class CertificateTemplatesHelper { // edit text elements for ( let textKeysIndex = 0; textKeysIndex < textKeys.length; textKeysIndex++ ) { - if ( textData[textKeys[textKeysIndex]] ) { + console.log(textData[textKeys[textKeysIndex]]) let updateText = textData[textKeys[textKeysIndex]]; const element = $('#' + textKeys[textKeysIndex]); element.text(updateText); From 00f85c91a0f74a0cac8e1f592000586b4fab9aa1 Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Mon, 27 Mar 2023 17:04:45 +0530 Subject: [PATCH 267/331] Added few comments --- app.js | 4 ++-- module/certificateTemplates/helper.js | 1 - 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/app.js b/app.js index ba73c659..09c40a81 100644 --- a/app.js +++ b/app.js @@ -46,12 +46,12 @@ app.use(express.static("public")); app.all("*", (req, res, next) => { console.log({"Debugging ML Core Service": true}); - console.log("-------Request log starts here------------------"); + console.log("<------------Request log starts here------------------>"); console.log("Request URL: ", req.url); console.log("Request Headers: ", JSON.stringify(req.headers)); console.log("Request Body: ", JSON.stringify(req.body)); // console.log("Request Files: ", req.files); - console.log("-------Request log ends here------------------"); + console.log("<--------------Request log ends here------------------>"); next(); }); diff --git a/module/certificateTemplates/helper.js b/module/certificateTemplates/helper.js index f7460edc..0f4bf252 100644 --- a/module/certificateTemplates/helper.js +++ b/module/certificateTemplates/helper.js @@ -249,7 +249,6 @@ module.exports = class CertificateTemplatesHelper { // edit text elements for ( let textKeysIndex = 0; textKeysIndex < textKeys.length; textKeysIndex++ ) { if ( textData[textKeys[textKeysIndex]] ) { - console.log(textData[textKeys[textKeysIndex]]) let updateText = textData[textKeys[textKeysIndex]]; const element = $('#' + textKeys[textKeysIndex]); element.text(updateText); From 2900a44866316b3ffb0d941000661ee58d170cd7 Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Tue, 28 Mar 2023 02:09:23 +0530 Subject: [PATCH 268/331] Fixed Public And Private Project --- generics/services/improvement-project.js | 4 ++-- module/solutions/helper.js | 7 ++++++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/generics/services/improvement-project.js b/generics/services/improvement-project.js index cbfa5ff8..77251bdf 100644 --- a/generics/services/improvement-project.js +++ b/generics/services/improvement-project.js @@ -209,11 +209,11 @@ var getProjectDetail = function ( solutionId, token, bodyData = {} ) { * @returns {Promise} returns a promise. */ -var getTemplateDetail = function ( templateId, token ) { +var getTemplateDetail = function ( templateId, token , isAPrivateProgram ) { let url = process.env.ML_PROJECT_SERVICE_URL + - constants.endpoints.GET_TEMPLATE_DETAILS + "/" + templateId; + constants.endpoints.GET_TEMPLATE_DETAILS + "/" + templateId+"?isAPrivateProgram="+isAPrivateProgram; return new Promise(async (resolve, reject) => { try { diff --git a/module/solutions/helper.js b/module/solutions/helper.js index c1c1bab4..723b7db5 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -1956,6 +1956,8 @@ module.exports = class SolutionsHelper { "type", "projectTemplateId", ]); + + console.log(solutionData); if ( !Array.isArray(solutionData) || solutionData.length < 1 ) { return resolve({ @@ -1966,6 +1968,8 @@ module.exports = class SolutionsHelper { solutionData = solutionData[0]; let templateOrQuestionDetails; + //this will get wether user is targeted to the solution or not based on user Role Information + const isSolutionTargeted = await this.isTargetedBasedOnUserProfile(solutionId, bodyData) if ( solutionData.type === constants.common.IMPROVEMENT_PROJECT ) { if ( !solutionData.projectTemplateId ) { @@ -1977,7 +1981,8 @@ module.exports = class SolutionsHelper { templateOrQuestionDetails = await improvementProjectService.getTemplateDetail( solutionData.projectTemplateId, - userToken + userToken, + isSolutionTargeted.result.isATargetedSolution ? false : true ); } else if ( solutionData.type === constants.common.OBSERVATION ) { From ab40083398df074d9025ee2b34644d39676cc054 Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Tue, 28 Mar 2023 02:12:44 +0530 Subject: [PATCH 269/331] Fixed Public And Private Project --- module/solutions/helper.js | 1 - 1 file changed, 1 deletion(-) diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 723b7db5..33e77e4d 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -1957,7 +1957,6 @@ module.exports = class SolutionsHelper { "projectTemplateId", ]); - console.log(solutionData); if ( !Array.isArray(solutionData) || solutionData.length < 1 ) { return resolve({ From 79494b2d0eeedfd00f0dc56f3e70493aacbdfb33 Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Tue, 28 Mar 2023 02:13:47 +0530 Subject: [PATCH 270/331] Fixed Public And Private Project --- README.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/README.md b/README.md index dc2c43ac..16672448 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,5 @@ # ml-core-service Centralised Service to support other Services. -<<<<<<< HEAD -It is used by ml-survey, ml-project -======= It is used by ml-survey, ml-project ->>>>>>> refs/remotes/origin/master From 2ab502095a265a5767fbc5979995274e9e936d55 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Wed, 5 Apr 2023 14:41:27 +0530 Subject: [PATCH 271/331] changes added to not use hard coded app version --- module/programs/helper.js | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/module/programs/helper.js b/module/programs/helper.js index b3ded981..7f6faac1 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -995,14 +995,20 @@ module.exports = class ProgramsHelper { return new Promise(async (resolve, reject) => { try { - //Using programId fetch program name. Also checking the program status in the query. + //Using programId fetch program details. Also checking the program status in the query. let programData = await this.programDocuments({ _id: programId, status: constants.common.ACTIVE, isDeleted: false - },["name", "externalId","requestForPIIConsent","rootOrganisations"]); + },[ + "name", + "externalId", + "requestForPIIConsent", + "rootOrganisations" + ] + ); - if ( !programData.length > 0 || !programData[0].requestForPIIConsent || programData[0].requestForPIIConsent == false ) { + if ( !programData.length > 0 ) { throw ({ status: httpStatusCode.bad_request.status, message: constants.apiResponses.PROGRAM_NOT_FOUND @@ -1036,7 +1042,7 @@ module.exports = class ProgramsHelper { status: httpStatusCode.bad_request.status, message: constants.apiResponses.PROGRAM_JOIN_FAILED }); - } + } programUsersData = { programId: programId, userRoleInformation: data.userRoleInformation, @@ -1053,7 +1059,7 @@ module.exports = class ProgramsHelper { } //For internal calls add consent using sunbird api - if(callConsetAPIOnBehalfOfUser){ + if( callConsetAPIOnBehalfOfUser && !programUsersDetails.length > 0 && !programData[0].requestForPIIConsent && programData[0].requestForPIIConsent == true ){ if( !programData[0].rootOrganisations || !programData[0].rootOrganisations.length > 0 ) { throw { message: constants.apiResponses.PROGRAM_JOIN_FAILED, @@ -1069,7 +1075,7 @@ module.exports = class ProgramsHelper { "objectId": programId, "objectType": constants.common.PROGRAM } - } + } } let consentResponse = await userService.setUserConsent(userToken, userConsentRequestBody) if(!consentResponse.success){ @@ -1100,7 +1106,8 @@ module.exports = class ProgramsHelper { } joinProgram.programName = programData[0].name; joinProgram.programExternalId = programData[0].externalId; - joinProgram.requestForPIIConsent = programData[0].requestForPIIConsent + joinProgram.requestForPIIConsent = (programData[0].requestForPIIConsent && programData[0].requestForPIIConsent == true) ? true : false; + // push programUsers details to kafka await kafkaProducersHelper.pushProgramUsersToKafka(joinProgram); From 76503d7aa35e2d6f1acd784ef6bee049b3230bd0 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Wed, 5 Apr 2023 17:05:09 +0530 Subject: [PATCH 272/331] no of solutions added --- module/users/helper.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/module/users/helper.js b/module/users/helper.js index 20341ad7..1b720a95 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -699,7 +699,7 @@ module.exports = class UsersHelper { ["noOfResourcesStarted"] ); if ( programUsersData.length > 0 ) { - nontargetedJoinedPrograms.data[index].solutions = programUsersData[0].noOfResourcesStarted; + nontargetedJoinedPrograms.data[index].solutions = (programUsersData[0].noOfResourcesStarted) ? programUsersData[0].noOfResourcesStarted : 0; } targetedPrograms.data.data.push(nontargetedJoinedPrograms.data[index]); From 0aa695162406678eec2379e5e1f36ef51e265718 Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Thu, 6 Apr 2023 11:18:11 +0530 Subject: [PATCH 273/331] saving some changes --- generics/constants/endpoints.js | 2 +- generics/services/users.js | 7 +- helper.js | 1374 +++++++++++++++++ ...Rxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA | 3 + models/programs.js | 9 + module/programs/helper.js | 9 + 6 files changed, 1401 insertions(+), 3 deletions(-) create mode 100644 helper.js create mode 100644 keycloak-public-keys/GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA diff --git a/generics/constants/endpoints.js b/generics/constants/endpoints.js index 2deb5488..be019336 100644 --- a/generics/constants/endpoints.js +++ b/generics/constants/endpoints.js @@ -31,7 +31,7 @@ module.exports = { LIST_PROJECT : "/v1/userProjects/list", GET_QUESTIONS : "/v1/solutions/questions", GET_OBSERVATION : "/v1/observations/details", - GET_LOCATION_DATA : "/v1/location/search", + GET_LOCATION_DATA : "/api/data/v1/location/search", GET_FORM_DATA : "/plugin/v1/form/read", GET_SCHOOL_DATA : "/v1/org/search" } \ No newline at end of file diff --git a/generics/services/users.js b/generics/services/users.js index dad76493..b2d4fca1 100644 --- a/generics/services/users.js +++ b/generics/services/users.js @@ -96,10 +96,13 @@ const locationSearch = function ( filterData, pageSize = "", pageNo = "", search userServiceUrl + constants.endpoints.GET_LOCATION_DATA; const options = { headers : { - "content-type": "application/json", + "content-type": "application/json", + "Authorization":"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJSbTBGOTlnMnd4SmZKelJwa2YzTnRlaE5CYlJnZXRCaCJ9.CjDN6GufxylpAM5J_6j9fD0wq7S2qr1F6FOzAZtQ6XU", }, json : bodyData }; + console.log( JSON.stringify(options) ); + console.log(url) request.post(url,options,requestCallback); let result = { @@ -108,10 +111,10 @@ const locationSearch = function ( filterData, pageSize = "", pageNo = "", search function requestCallback(err, data) { if (err) { + console.log(err); result.success = false; } else { let response = data.body; - if( response.responseCode === constants.common.OK && response.result && response.result.response && diff --git a/helper.js b/helper.js new file mode 100644 index 00000000..26081a25 --- /dev/null +++ b/helper.js @@ -0,0 +1,1374 @@ +/** + * name : helper.js + * author : Aman + * created-date : 16-July-2020 + * Description : Project templates helper functionality. + */ + +/** + * ProjectTemplatesHelper + * @class +*/ + +// Dependencies + +const libraryCategoriesHelper = require(MODULES_BASE_PATH + "/library/categories/helper"); +const coreService = require(GENERICS_FILES_PATH + "/services/core"); +const kafkaProducersHelper = require(GENERICS_FILES_PATH + "/kafka/producers"); +const learningResourcesHelper = require(MODULES_BASE_PATH + "/learningResources/helper"); +const surveyService = require(GENERICS_FILES_PATH + "/services/survey"); +const projectTemplateQueries = require(DB_QUERY_BASE_PATH + "/projectTemplates"); +const projectTemplateTaskQueries = require(DB_QUERY_BASE_PATH + "/projectTemplateTask"); +const projectQueries = require(DB_QUERY_BASE_PATH + "/projects"); +const projectCategoriesQueries = require(DB_QUERY_BASE_PATH + "/projectCategories"); +const solutionsQueries = require(DB_QUERY_BASE_PATH + "/solutions"); +const certificateTemplateQueries = require(DB_QUERY_BASE_PATH + "/certificateTemplates"); + +module.exports = class ProjectTemplatesHelper { + + /** + * Extract csv information. + * @method + * @name extractCsvInformation + * @param {Object} csvData - csv data. + * @returns {Object} Extra csv information. + */ + + static extractCsvInformation(csvData) { + return new Promise(async (resolve, reject) => { + try { + + let categoryIds = []; + let roleIds = []; + let tasksIds = []; + // <- Entitytype validation removed {release-5.0.0} - entity generalisation + // let entityTypes = []; + + csvData.forEach(template=>{ + + let parsedData = UTILS.valueParser(template); + + categoryIds = _.concat( + categoryIds, + parsedData.categories + ); + + tasksIds = _.concat( + tasksIds, + parsedData.tasks + ); + + if( parsedData.recommendedFor ) { + + parsedData.recommendedFor = + parsedData.recommendedFor.map(role=>{ + return role.toUpperCase() + }); + + roleIds = _.concat( + roleIds, + parsedData.recommendedFor + ); + } + // <- Entitytype validation removed {release-5.0.0} - entity generalisation + // if( parsedData.entityType ) { + // entityTypes.push(parsedData.entityType); + // } + + }); + + let categoriesData = {}; + + if( categoryIds.length > 0 ) { + + let categories = + await projectCategoriesQueries.categoryDocuments({ + externalId : { $in : categoryIds } + },["externalId","name"]); + + if( !categories.length > 0 ) { + throw { + status : HTTP_STATUS_CODE['bad_request'].status, + message : CONSTANTS.apiResponses.LIBRARY_CATEGORIES_NOT_FOUND + } + } + + categoriesData = categories.reduce((ac,category)=> ({ + ...ac, + [category.externalId] : { + _id : ObjectId(category._id), + externalId : category.externalId, + name : category.name + } + }),{}); + } + + let recommendedFor = {}; + + if( roleIds.length > 0 ) { + + let userRolesData = + await coreService.rolesDocuments({ + code : { $in : roleIds } + },["code"]); + + if( !userRolesData.success ) { + throw { + message : CONSTANTS.apiResponses.USER_ROLES_NOT_FOUND, + status : HTTP_STATUS_CODE['bad_request'].status + } + } + + recommendedFor = userRolesData.data.reduce((ac,role)=> ({ + ...ac, + [role.code] : { + roleId : ObjectId(role._id), + code : role.code + } + }),{}); + } + // <- Entitytype validation removed {release-5.0.0} - entity generalisation + // let entityTypesData = {}; + + // if( entityTypes.length > 0 ) { + + // let entityTypesDocument = + // await coreService.entityTypesDocuments(); + + // if( !entityTypesDocument.success ) { + // throw { + // message : CONSTANTS.apiResponses.ENTITY_TYPES_NOT_FOUND, + // status : HTTP_STATUS_CODE['bad_request'].status + // } + // } + + // entityTypesData = entityTypesDocument.data.reduce((ac,entityType)=> ({ + // ...ac, + // [entityType.name] : { + // _id : ObjectId(entityType._id), + // name : entityType.name + // } + // }),{}); + + // } + + return resolve({ + success : true, + data : { + categories : categoriesData, + roles : recommendedFor, + // <- Entitytype validation removed {release-5.0.0} - entity generalisation + // entityTypes : entityTypesData + } + }); + + } catch(error) { + return resolve({ + success : false, + message : error.message, + status : error.status ? error.status : HTTP_STATUS_CODE['internal_server_error'].status + }); + } + }) + } + + /** + * Template data. + * @method + * @name templateData + * @param {Object} data - csv data. + * @param {Object} csvInformation - csv information. + * @returns {Object} Template data. + */ + + static templateData(data,csvInformation) { + return new Promise(async (resolve, reject) => { + try { + + let templatesDataModel = + Object.keys(schemas["project-templates"].schema); + let parsedData = UTILS.valueParser(data); + delete parsedData._arrayFields; + + let categories = []; + + if( parsedData.categories && parsedData.categories.length > 0 ) { + + parsedData.categories.forEach( category => { + if( csvInformation.categories[category] ) { + return categories.push( + csvInformation.categories[category] + ); + } + }); + } + + parsedData.categories = categories; + + let recommendedFor = []; + + if( parsedData.recommendedFor && parsedData.recommendedFor.length > 0 ) { + parsedData.recommendedFor.forEach(recommended => { + if( csvInformation.roles[recommended] ) { + return recommendedFor.push( + csvInformation.roles[recommended] + ); + } + }); + } + + parsedData.recommendedFor = recommendedFor; + // <- Entitytype validation removed {release-5.0.0} - entity generalisation + // if( parsedData.entityType && parsedData.entityType !== "" ) { + // parsedData.entityType = csvInformation.entityTypes[parsedData.entityType].name; + // } + + let learningResources = + await learningResourcesHelper.extractLearningResourcesFromCsv(parsedData); + parsedData.learningResources = learningResources.data; + + parsedData.metaInformation = {}; + let booleanData = + UTILS.getAllBooleanDataFromModels( + schemas["project-templates"].schema + ); + + Object.keys(parsedData).forEach( eachParsedData => { + if( + !templatesDataModel.includes(eachParsedData) + ) { + + if( !eachParsedData.startsWith("learningResources") ) { + parsedData.metaInformation[eachParsedData] = + parsedData[eachParsedData]; + delete parsedData[eachParsedData]; + } + + } else { + if( booleanData.includes(eachParsedData) ) { + parsedData[eachParsedData] = + UTILS.convertStringToBoolean(parsedData[eachParsedData]); + } + } + }); + + parsedData.isReusable = true; + + return resolve(parsedData); + + } catch(error) { + return reject(error); + } + }) + } + + /** + * Bulk created project templates. + * @method + * @name bulkCreate - bulk create project templates. + * @param {Array} templates - csv templates data. + * @param {String} userId - logged in user id. + * @returns {Object} Bulk create project templates. + */ + + static bulkCreate(templates,userId) { + + return new Promise(async (resolve, reject) => { + + try { + + const fileName = `project-templates-creation`; + let fileStream = new CSV_FILE_STREAM(fileName); + let input = fileStream.initStream(); + + (async function () { + await fileStream.getProcessorPromise(); + return resolve({ + isResponseAStream: true, + fileNameWithPath: fileStream.fileNameWithPath() + }); + })(); + + let csvInformation = await this.extractCsvInformation(templates); + + if( !csvInformation.success ) { + return resolve(csvInformation); + } + + for ( let template = 0; template < templates.length ; template ++ ) { + + let currentData = templates[template]; + + let templateData = + await projectTemplateQueries.templateDocument({ + status : CONSTANTS.common.PUBLISHED, + externalId : currentData.externalId, + isReusable : true + },["_id"]); + + if( templateData.length > 0 && templateData[0]._id ) { + currentData["_SYSTEM_ID"] = + CONSTANTS.apiResponses.PROJECT_TEMPLATE_EXISTS; + } else { + + let templateData = await this.templateData( + currentData, + csvInformation.data, + userId + ); + + templateData.status = CONSTANTS.common.PUBLISHED_STATUS; + templateData.createdBy = templateData.updatedBy = templateData.userId = userId; + templateData.isReusable = true; + + let createdTemplate = await projectTemplateQueries.createTemplate(templateData); + + if( !createdTemplate._id ) { + currentData["_SYSTEM_ID"] = CONSTANTS.apiResponses.PROJECT_TEMPLATE_NOT_FOUND; + } else { + + currentData["_SYSTEM_ID"] = createdTemplate._id; + + if( + templateData.categories && + templateData.categories.length > 0 + ) { + + let categories = templateData.categories.map(category => { + return category._id; + }); + + let updatedCategories = + await libraryCategoriesHelper.update({ + _id : { $in : categories } + },{ + $inc : { noOfProjects : 1 } + }); + + if( !updatedCategories.success ) { + currentData["_SYSTEM_ID"] = updatedCategories.message; + } + } + + // <- Dirty fix . Not required + // const kafkaMessage = + // await kafkaProducersHelper.pushProjectToKafka({ + // internal : false, + // text : + // templateData.categories.length === 1 ? + // `A new project has been added under ${templateData.categories[0].name} category in library.` : + // `A new project has been added in library`, + // type : "information", + // action : "mapping", + // payload : { + // project_id: createdTemplate._id + // }, + // is_read : false, + // internal : false, + // title : "New project Available!", + // created_at : new Date(), + // appType : process.env.IMPROVEMENT_PROJECT_APP_TYPE, + // inApp:false, + // push: true, + // pushToTopic: true, + // topicName : process.env.NODE_ENV + "-" + process.env.IMPROVEMENT_PROJECT_APP_NAME + process.env.TOPIC_FOR_ALL_USERS + // }); + + // if (kafkaMessage.status !== CONSTANTS.common.SUCCESS) { + // currentData["_SYSTEM_ID"] = CONSTANTS.apiResponses.COULD_NOT_PUSHED_TO_KAFKA; + // } + + } + + } + + input.push(currentData); + + } + + input.push(null); + + } catch (error) { + return reject(error); + } + }) + } + + /** + * Bulk update project templates. + * @method + * @name bulkUpdate - bulk update project templates. + * @param {Array} templates - csv templates data. + * @param {String} userId - logged in user id. + * @returns {Object} Bulk Update Project templates. + */ + + static bulkUpdate(templates,userId) { + return new Promise(async (resolve, reject) => { + try { + + const fileName = `project-templates-updation`; + let fileStream = new CSV_FILE_STREAM(fileName); + let input = fileStream.initStream(); + + (async function () { + await fileStream.getProcessorPromise(); + return resolve({ + isResponseAStream: true, + fileNameWithPath: fileStream.fileNameWithPath() + }); + })(); + + let csvInformation = await this.extractCsvInformation(templates); + + if( !csvInformation.success ) { + return resolve(csvInformation); + } + + for ( let template = 0; template < templates.length ; template ++ ) { + + const currentData = templates[template]; + + if ( !currentData._SYSTEM_ID ) { + currentData["UPDATE_STATUS"] = + CONSTANTS.apiResponses.MISSING_PROJECT_TEMPLATE_ID; + } else { + + const template = + await projectTemplateQueries.templateDocument({ + status : CONSTANTS.common.PUBLISHED, + _id : currentData._SYSTEM_ID, + status : CONSTANTS.common.PUBLISHED + },["_id","categories", "isReusable"]); + + if ( !(template.length > 0 && template[0]._id) ) { + currentData["UPDATE_STATUS"] = + CONSTANTS.apiResponses.PROJECT_TEMPLATE_NOT_FOUND; + } else { + + let templateData = await this.templateData( + _.omit(currentData,["_SYSTEM_ID"]), + csvInformation.data, + userId + ); + + if(template[0].isReusable === false) { + templateData.isReusable = false; + } + + templateData.updatedBy = userId; + + let projectTemplateUpdated = + await projectTemplateQueries.findOneAndUpdate({ + _id : currentData._SYSTEM_ID + },{ + $set : templateData + },{ + new : true + }); + + if( !projectTemplateUpdated || !projectTemplateUpdated._id ) { + currentData["UPDATE_STATUS"] = + CONSTANTS.apiResponses.PROJECT_TEMPLATE_NOT_UPDATED; + } + + // Add projects count to categories + if( + templateData.categories && + templateData.categories.length > 0 + ) { + + let categories = + templateData.categories.map(category => { + return category._id; + }); + + let updatedCategories = + await libraryCategoriesHelper.update({ + _id : { $in : categories } + },{ + $inc : { noOfProjects : 1 } + }); + + if( !updatedCategories.success ) { + currentData["UPDATE_STATUS"] = updatedCategories.message; + } + } + + // Remove project count from existing categories + if( + template[0].categories && + template[0].categories.length > 0 + ) { + + const categoriesIds = + template[0].categories.map(category=>{ + return category._id; + }); + + let categoriesUpdated = + await libraryCategoriesHelper.update({ + _id : { $in : categoriesIds } + },{ + $inc : { noOfProjects : -1 } + }); + + if( !categoriesUpdated.success ) { + currentData["UPDATE_STATUS"] = updatedCategories.message; + } + } + + currentData["UPDATE_STATUS"] = CONSTANTS.common.SUCCESS; + } + + } + + input.push(templates[template]); + + } + + input.push(null); + + } catch (error) { + return reject(error); + } + }) + } + + /** + * Bulk update project templates. + * @method + * @name importProjectTemplate - import templates from existing project templates. + * @param {String} templateId - project template id. + * @param {String} userId - logged in user id. + * @param {String} userToken - logged in user token. + * @param {String} solutionId - solution id. + * @param {Object} updateData - template update data. + * @returns {Object} imported templates data. + */ + + static importProjectTemplate( templateId,userId,userToken,solutionId,updateData = {} ) { + return new Promise(async (resolve, reject) => { + try { + + let projectTemplateData = + await projectTemplateQueries.templateDocument({ + status : CONSTANTS.common.PUBLISHED, + externalId : templateId, + isReusable : true + }); + + if ( !projectTemplateData.length > 0 ) { + throw new Error(CONSTANTS.apiResponses.PROJECT_TEMPLATE_NOT_FOUND) + } + + let newProjectTemplate = {...projectTemplateData[0]}; + newProjectTemplate.externalId = + projectTemplateData[0].externalId +"-"+ UTILS.epochTime(); + newProjectTemplate.createdBy = newProjectTemplate.updatedBy = userId; + + let solutionData = + await surveyService.listSolutions([solutionId]); + + if( !solutionData.success ) { + throw { + message : CONSTANTS.apiResponses.SOLUTION_NOT_FOUND, + status : HTTP_STATUS_CODE['bad_request'].status + } + } + + if( solutionData.data[0].type !== CONSTANTS.common.IMPROVEMENT_PROJECT ) { + throw { + message : CONSTANTS.apiResponses.IMPROVEMENT_PROJECT_SOLUTION_NOT_FOUND, + status : HTTP_STATUS_CODE['bad_request'].status + } + } + + if( solutionData.data[0].projectTemplateId ) { + throw { + message : CONSTANTS.apiResponses.PROJECT_TEMPLATE_EXISTS_IN_SOLUTION, + status : HTTP_STATUS_CODE['bad_request'].status + } + } + + if( + projectTemplateData[0].entityType && + projectTemplateData[0].entityType !== "" && + projectTemplateData[0].entityType !== solutionData.data[0].entityType + ) { + throw { + message : CONSTANTS.apiResponses.ENTITY_TYPE_MIS_MATCHED, + status : HTTP_STATUS_CODE['bad_request'].status + } + } + + newProjectTemplate.solutionId = solutionData.data[0]._id; + newProjectTemplate.solutionExternalId = solutionData.data[0].externalId; + newProjectTemplate.programId = solutionData.data[0].programId; + newProjectTemplate.programExternalId = solutionData.data[0].programExternalId; + + + newProjectTemplate.parentTemplateId = projectTemplateData[0]._id; + + let updationKeys = Object.keys(updateData); + if( updationKeys.length > 0 ) { + updationKeys.forEach(singleKey => { + if( newProjectTemplate[singleKey] ) { + newProjectTemplate[singleKey] = updateData[singleKey]; + } + }) + } + + let tasksIds; + + if(projectTemplateData[0].tasks){ + tasksIds = projectTemplateData[0].tasks; + } + + newProjectTemplate.isReusable = false; + + let duplicateTemplateDocument = + await projectTemplateQueries.createTemplate( + _.omit(newProjectTemplate, ["_id"]) + ); + + if ( !duplicateTemplateDocument._id ) { + throw new Error(CONSTANTS.apiResponses.PROJECT_TEMPLATES_NOT_CREATED) + } + + //duplicate task + if(Array.isArray(tasksIds) && tasksIds.length > 0 ){ + await this.duplicateTemplateTasks( + tasksIds, + duplicateTemplateDocument._id, + duplicateTemplateDocument.externalId + ); + } + + await surveyService.updateSolution( + userToken, + { + projectTemplateId : duplicateTemplateDocument._id, + name : duplicateTemplateDocument.title + }, + newProjectTemplate.solutionExternalId + ); + + await this.ratings( + projectTemplateData[0]._id, + updateData.rating, + userToken + ); + + return resolve({ + success: true, + message : CONSTANTS.apiResponses.DUPLICATE_PROJECT_TEMPLATES_CREATED, + data : { + _id : duplicateTemplateDocument._id + } + }) + + } catch (error) { + return resolve({ + status : + error.status ? + error.status : HTTP_STATUS_CODE['internal_server_error'].status, + success: false, + message: error.message, + data: {} + }); + } + }) + } + + /** + * Create ratings. + * @method + * @name ratings + * @param {String} templateId - project template id. + * @param {String} rating - rating for template. + * @returns {Object} rating object. + */ + + static ratings( templateId,rating,userToken ) { + return new Promise(async (resolve, reject) => { + try { + + let userProfileData = await coreService.getProfile(userToken); + + if( !userProfileData.success ) { + throw { + status : HTTP_STATUS_CODE['bad_request'].status, + message : CONSTANTS.apiResponses.USER_PROFILE_NOT_FOUND + } + } + + let templateData = + await projectTemplateQueries.templateDocument({ + status : CONSTANTS.common.PUBLISHED, + _id : templateId, + isReusable : true + },[ + "averageRating", + "noOfRatings", + "ratings" + ]); + + let updateRating = { + ratings : {...templateData[0].ratings} + }; + + updateRating.ratings[rating] += 1; + + let userCurrentRating = 0; + let projectIndex = -1; + + if( + userProfileData.data && + userProfileData.data.ratings && + userProfileData.data.ratings.length > 0 + ) { + + projectIndex = + userProfileData.data.ratings.findIndex( + project => project._id.toString() === templateId.toString() + ); + + if( !(projectIndex < 0) ) { + userCurrentRating = userProfileData.data.ratings[projectIndex].rating; + updateRating.ratings[userCurrentRating] -= 1; + } + } else { + userProfileData.data.ratings = []; + } + + let ratingUpdated = {}; + + if( userCurrentRating === rating ) { + + ratingUpdated = templateData[0]; + + } else { + + let calculateRating = _calculateRating(updateRating.ratings); + updateRating.averageRating = calculateRating.averageRating; + updateRating.noOfRatings = calculateRating.noOfRatings; + + ratingUpdated = + await projectTemplateQueries.findOneAndUpdate({ + _id : templateId + },{ + $set : updateRating + }, { + new : true + }); + + let improvementProjects = [...userProfileData.data.ratings]; + if( projectIndex >= 0 ) { + improvementProjects[projectIndex].rating = rating; + } else { + improvementProjects.push({ + _id : ObjectId(templateId), + externalId : ratingUpdated.externalId, + rating : rating, + type : CONSTANTS.common.IMPROVEMENT_PROJECT + }); + } + + await coreService.updateUserProfile( + userToken, + { + "ratings" : improvementProjects + } + ); + } + + return resolve( + _.pick( + ratingUpdated, + ["averageRating","noOfRatings","ratings"] + ) + ); + + } catch (error) { + return resolve({ + success : false, + message : error.message, + status : error.status ? error.status : HTTP_STATUS_CODE['internal_server_error'].status + }); + } + }) + } + + /** + * Project template tasks + * @method + * @name duplicateTemplateTasks + * @param {Array} taskIds - Task ids + * @returns {Object} Duplicated tasks. + */ + + static duplicateTemplateTasks( taskIds=[], duplicateTemplateId, duplicateTemplateExternalId ) { + return new Promise(async (resolve, reject) => { + try { + + let newTaskId = []; + + for ( let pointerToTask = 0; pointerToTask < taskIds.length; pointerToTask++ ) { + + let taskId = taskIds[pointerToTask]; + let taskData = await projectTemplateTaskQueries.taskDocuments( + { + _id : taskId, + parentId : { $exists : false } + }); + + if( taskData && taskData.length > 0 ) { + taskData = taskData[0]; + } + + if ( taskData && Object.keys(taskData).length > 0 ) { + + //duplicate parent task + let newProjectTemplateTask = {...taskData}; + newProjectTemplateTask.projectTemplateId = duplicateTemplateId; + newProjectTemplateTask.projectTemplateExternalId = duplicateTemplateExternalId; + newProjectTemplateTask.externalId = taskData.externalId +"-"+ UTILS.epochTime(); + + let duplicateTemplateTask = + await database.models.projectTemplateTasks.create( + _.omit(newProjectTemplateTask, ["_id"]) + ); + + newTaskId.push(duplicateTemplateTask._id); + + //duplicate child task + if ( duplicateTemplateTask.children && duplicateTemplateTask.children.length > 0 ) { + + let childTaskIdArray = []; + let childTaskIds = duplicateTemplateTask.children; + + if ( childTaskIds && childTaskIds.length > 0 ) { + + for ( let pointerToChild = 0 ; pointerToChild < childTaskIds.length ; pointerToChild++ ) { + + let childtaskId = childTaskIds[pointerToChild]; + let childTaskData = await projectTemplateTaskQueries.taskDocuments( + { + _id : childtaskId + }); + + if ( childTaskData && childTaskData.length > 0 ) { + childTaskData = childTaskData[0]; + } + + if ( childTaskData && Object.keys(childTaskData).length > 0 ) { + + let newProjectTemplateChildTask = {...childTaskData}; + newProjectTemplateChildTask.projectTemplateId = duplicateTemplateId; + newProjectTemplateChildTask.projectTemplateExternalId = duplicateTemplateExternalId; + newProjectTemplateChildTask.parentId = duplicateTemplateTask._id; + newProjectTemplateChildTask.externalId = childTaskData.externalId +"-"+ UTILS.epochTime(); + + let duplicateChildTemplateTask = + await database.models.projectTemplateTasks.create( + _.omit(newProjectTemplateChildTask, ["_id"]) + ); + + childTaskIdArray.push(duplicateChildTemplateTask._id); + newTaskId.push(duplicateChildTemplateTask._id); + } + } + //update new subtask ids to parent task + if(childTaskIdArray && childTaskIdArray.length > 0){ + let updateTaskData = await projectTemplateTaskQueries.updateTaskDocument( + { + _id : duplicateTemplateTask._id + }, + { + $set : { + children : childTaskIdArray + } + }) + } + } + } + } + } + + let updateDuplicateTemplate; + //adding duplicate tasj to duplicate template + if(newTaskId && newTaskId.length > 0){ + + updateDuplicateTemplate = await projectTemplateQueries.findOneAndUpdate( + { + _id : duplicateTemplateId + }, + { + $set : { + tasks : newTaskId + } + }) + } + + return resolve( + updateDuplicateTemplate + ); + + } catch (error) { + return reject(error); + } + }) + } + + /** + * Templates list. + * @method + * @name listByIds + * @param {Array} externalIds - External ids + * @returns {Array} List of templates data. + */ + + static listByIds( externalIds ) { + return new Promise(async (resolve, reject) => { + try { + + let templateData = await projectTemplateQueries.templateDocument({ + externalId : { $in : externalIds } + },["title","metaInformation.goal","externalId"]); + + if ( !templateData.length > 0 ) { + throw { + status : HTTP_STATUS_CODE.bad_request.status, + message : CONSTANTS.apiResponses.PROJECT_TEMPLATE_NOT_FOUND + } + } + + templateData = templateData.map( template => { + if( template.metaInformation && template.metaInformation.goal ) { + template.goal = template.metaInformation.goal; + delete template.metaInformation; + } + + return template; + }) + + return resolve({ + success : false, + data : templateData, + message : CONSTANTS.apiResponses.PROJECT_TEMPLATES_FETCHED + }); + + } catch (error) { + return reject(error); + } + }) + } + + /** + * Template details. + * @method + * @name details + * @param {String} templateId - Project template id. + * @param {String} userId - logged in user id. + * @params {String} link - solution link. + * @returns {Array} Project templates data. + */ + + static details( templateId="", link="", userId="", isAPrivateProgram ) { + return new Promise(async (resolve, reject) => { + try { + let solutionsResult = {}; + let findQuery = {}; + //get data when link is given + if( link ){ + + let queryData = {}; + queryData["link"] =link; + + let solutionDocument = await solutionsQueries.solutionsDocument(queryData, + [ + "_id", + "name", + "programId", + "programName", + "projectTemplateId", + "link" + ] + ); + + if( !solutionDocument.length > 0 ) { + throw { + message : CONSTANTS.apiResponses.SOLUTION_NOT_FOUND, + status : HTTP_STATUS_CODE['bad_request'].status + } + } + let solutiondata = solutionDocument; + templateId = solutiondata[0].projectTemplateId; + if( !templateId ){ + return resolve({ + success : false, + data : solutiondata, + message : CONSTANTS.apiResponses.TEMPLATE_ID_NOT_FOUND_IN_SOLUTION + }); + } + solutionsResult = solutiondata; + templateId=templateId.toString(); + } + + if( templateId ){ + let validateTemplateId = UTILS.isValidMongoId(templateId); + if( validateTemplateId ) { + findQuery["_id"] = templateId; + } else { + findQuery["externalId"] = templateId; + } + + } + //getting template data using templateId + + let templateData = await projectTemplateQueries.templateDocument(findQuery,"all", + [ + "ratings", + "noOfRatings", + "averageRating", + "parentTemplateId", + "userId", + "createdBy", + "updatedBy", + "createdAt", + "updatedAt", + "__v" + ] + ); + + if ( !templateData.length > 0 ) { + throw { + status : HTTP_STATUS_CODE.bad_request.status, + message :CONSTANTS.apiResponses.PROJECT_TEMPLATE_NOT_FOUND + } + } + if ( templateData[0].certificateTemplateId && templateData[0].certificateTemplateId !== "" ){ + let certificateTemplateDetails = await certificateTemplateQueries.certificateTemplateDocument({ + _id : templateData[0].certificateTemplateId + },["criteria"]); + + //certificate template data do not exists. + if ( !certificateTemplateDetails.length > 0 ) { + throw { + message: CONSTANTS.apiResponses.CERTIFICATE_TEMPLATE_NOT_FOUND + }; + } + templateData[0].criteria = certificateTemplateDetails[0].criteria + } + + if (templateData[0].tasks && templateData[0].tasks.length > 0) { + templateData[0].tasks = + await this.tasksAndSubTasks(templateData[0]._id); + } + let result = await _templateInformation(templateData[0]) + if( !result.success ) { + return resolve(result); + } + + if( !templateData[0].isReusable && userId !== "") { + + templateData[0].projectId = ""; + + let project = await projectQueries.projectDocument({ + userId : userId, + projectTemplateId : templateData[0]._id, + isAPrivateProgram : isAPrivateProgram + },["_id"]); + + if(project && project.length > 0){ + templateData[0].projectId = project[0]._id; + } + } + if( !result.data.programInformation ){ + result.data.programInformation = { + programId : solutionsResult.programId, + programName : solutionsResult.programName + } + } + result.data.solutionInformation = { + _id : solutionsResult._id, + name : solutionsResult.name, + link : solutionsResult.link + } + return resolve({ + success : false, + data : result.data, + message : CONSTANTS.apiResponses.PROJECT_TEMPLATE_DETAILS_FETCHED + }); + + } catch (error) { + return reject(error); + } + }) + } + + /** + * Tasks and sub tasks. + * @method + * @name tasksAndSubTasks + * @param {Array} templateId - Template id. + * @returns {Array} Tasks and sub task. + */ + + static tasksAndSubTasks(templateId) { + return new Promise(async (resolve, reject) => { + try { + + const templateDocument = + await projectTemplateQueries.templateDocument({ + _id : templateId, + status : CONSTANTS.common.PUBLISHED + },["tasks", "taskSequence"]); + + let tasks = []; + + if ( templateDocument[0].taskSequence && templateDocument[0].taskSequence.length > 0 ) { + + let projectionKey = CONSTANTS.common.TASK_SEQUENCE; + let findQuery = { + externalId : { + $in : templateDocument[0].taskSequence + } + } + + tasks = await _taskAndSubTaskinSequence(findQuery, projectionKey); + } else { + if ( templateDocument[0].tasks && templateDocument[0].tasks.length > 0 ){ + let projectionKey = CONSTANTS.common.CHILDREN; + if( templateDocument[0].tasks ) { + let findQuery = { + _id : { + $in : templateDocument[0].tasks + }, + parentId : { $exists : false } + } + + tasks = await _taskAndSubTaskinSequence(findQuery, projectionKey); + } + } + + } + + return resolve(tasks); + + } catch (error) { + return reject(error); + } + }); + } + + /** + * Template update. + * @method + * @name update + * @param {String} templateId - Project template id. + * @param {Object} templateData - template updation data + * @param {String} userId - logged in user id. + * @returns {Array} Project templates data. + */ + + static update( templateId, templateData, userId ) { + return new Promise(async (resolve, reject) => { + try { + + let findQuery = {}; + + let validateTemplateId = UTILS.isValidMongoId(templateId); + + if( validateTemplateId ) { + findQuery["_id"] = templateId; + } else { + findQuery["externalId"] = templateId; + } + + let templateDocument = await projectTemplateQueries.templateDocument(findQuery, ["_id"]); + + if ( !templateDocument.length > 0 ) { + throw { + status : HTTP_STATUS_CODE.bad_request.status, + message : CONSTANTS.apiResponses.PROJECT_TEMPLATE_NOT_FOUND + } + } + + let updateObject = { + "$set" : {} + }; + + let templateUpdateData = templateData; + + Object.keys(templateUpdateData).forEach(updationData=>{ + updateObject["$set"][updationData] = templateUpdateData[updationData]; + }); + + updateObject["$set"]["updatedBy"] = userId; + + let templateUpdatedData = await projectTemplateQueries.findOneAndUpdate({ + _id : templateDocument[0]._id + }, updateObject, { new : true }); + + if( !templateUpdatedData._id ) { + throw { + message : CONSTANTS.apiResponses.PROJECT_TEMPLATE_NOT_UPDATED + } + } + + return resolve({ + success : true, + data : templateUpdatedData, + message : CONSTANTS.apiResponses.PROJECT_TEMPLATE_UPDATED + }); + + } catch (error) { + return reject(error); + } + }) + } + +}; + +/** + * Calculate average rating and no of ratings. + * @method + * @name _calculateRating + * @param {Object} ratings - Ratings data. + * @returns {Object} rating object. +*/ + +function _calculateRating(ratings) { + let sum = 0; + let noOfRatings = 0; + + Object.keys(ratings).forEach(rating => { + sum += rating * ratings[rating]; + noOfRatings += ratings[rating]; + }); + + return { + averageRating : (sum/noOfRatings).toFixed(2), + noOfRatings : noOfRatings + } +} + +/** + * Project information. + * @method + * @name _templateInformation + * @param {Object} project - Project data. + * @returns {Object} Project information. +*/ + +function _templateInformation(project) { + + return new Promise(async (resolve, reject) => { + try { + + if( project.programId ) { + + let programs = + await surveyService.listProgramsBasedOnIds([project.programId]); + + if( !programs.success ) { + throw { + message : CONSTANTS.apiResponses.PROGRAM_NOT_FOUND, + status : HTTP_STATUS_CODE['bad_request'].status + } + } + + project.programInformation = { + programId : project.programId, + programName : programs.data[0].name + } + + delete project.programId; + delete project.programExternalId; + } + + if (project.metaInformation) { + Object.keys(project.metaInformation).forEach(projectMetaKey => { + project[projectMetaKey] = project.metaInformation[projectMetaKey]; + }); + } + delete project.metaInformation; + delete project.__v; + + project.status = + project.status ? project.status : CONSTANTS.common.NOT_STARTED_STATUS; + + return resolve({ + success: true, + data: project + }); + + } catch (error) { + return resolve({ + message: error.message, + success: false, + status: + error.status ? + error.status : HTTP_STATUS_CODE['internal_server_error'].status + }) + } + }) +} + +/** + * Task and SubTask In Order. + * @method + * @name _taskAndSubTaskinSequence + * @param {Object} query - template Query. + * @param {String} projectionValue - children or taskSequence. + * @returns {Object} Task and SubTask information. +*/ + +function _taskAndSubTaskinSequence(query, projectionValue) { + + return new Promise(async (resolve, reject) => { + try { + + let tasks = []; + tasks = await projectTemplateTaskQueries.taskDocuments(query,"all", ["projectTemplateId","__v","projectTemplateExternalId"]); + + for( let task = 0 ; task < tasks.length ; task++ ) { + if ( tasks[task][projectionValue] && tasks[task][projectionValue].length > 0 ) { + let subTaskQuery; + if ( projectionValue == CONSTANTS.common.CHILDREN ) { + subTaskQuery = { + "_id" : { + $in : tasks[task][projectionValue] + } + } + + } else { + subTaskQuery = { + "externalId" : { + $in : tasks[task][projectionValue] + } + } + } + + let subTasks = await projectTemplateTaskQueries.taskDocuments(subTaskQuery, "all", ["projectTemplateId","__v","projectTemplateExternalId"]); + tasks[task].children = subTasks; + } + } + + return resolve(tasks); + + } catch (error) { + return resolve({ + message: error.message, + success: false, + status: + error.status ? + error.status : HTTP_STATUS_CODE['internal_server_error'].status + }) + } + }) +} + + diff --git a/keycloak-public-keys/GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA b/keycloak-public-keys/GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA new file mode 100644 index 00000000..44c17f6c --- /dev/null +++ b/keycloak-public-keys/GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA @@ -0,0 +1,3 @@ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoRbRlp/1x0h5a9Rb3E7+nU17mdnU1Grv2/a6ixhdBr1f9mjKEn7F/5eIfCQL3H82stxZyskeWaetL1mNJkAHFcJx+03DoKnGP6K+PZ3Svbw67ehgqyp+OozZCNXHzrM1DUVpvhYgsnvkqm+E1QyrsmrghSE+bAHqJep4S/70z12t8rwMNB6OxcbhrHBU93TxszxHHLZL9eaa2DCwGsTbYml0V2vFPsN4HUhXtnht9uoC2bjAXyBsrSNy/aoCsoI0erV8Vyw2FKfwEGBDFROjcWhKOdwb36TmEDf+g4OBSqAhEyewhTwcP7ESpjhyA3Ae1cH9cKOBmQTU+OmzS89h8QIDAQAB +-----END PUBLIC KEY----- diff --git a/models/programs.js b/models/programs.js index 233fd9d6..c9998a3a 100644 --- a/models/programs.js +++ b/models/programs.js @@ -17,6 +17,15 @@ module.exports = { type : String, index : true }, + startDate:{ + type: Date, + index: true, + require:true + }, + endDate: { + type : Date, + index : true + }, resourceType: [String], language: [String], keywords: [String], diff --git a/module/programs/helper.js b/module/programs/helper.js index 7698b109..8e65fe0b 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -11,6 +11,7 @@ const entityTypesHelper = require(MODULES_BASE_PATH + "/entityTypes/helper"); const entitiesHelper = require(MODULES_BASE_PATH + "/entities/helper"); const userRolesHelper = require(MODULES_BASE_PATH + "/user-roles/helper"); const userService = require(ROOT_PATH + "/generics/services/users"); +const moment = require('moment'); /** * ProgramsHelper @@ -78,6 +79,9 @@ module.exports = class ProgramsHelper { return new Promise(async (resolve, reject) => { try { + + + let programData = { "externalId" : data.externalId, @@ -86,6 +90,8 @@ module.exports = class ProgramsHelper { "owner" : data.userId, "createdBy" : data.userId, "updatedBy" : data.userId, + "startDate" : data.startDate, + "endDate" : data.endDate, "isDeleted" : false, "status" : "active", "resourceType" : [ @@ -105,6 +111,8 @@ module.exports = class ProgramsHelper { "components" : [], "isAPrivateProgram" : data.isAPrivateProgram ? data.isAPrivateProgram : false } + + console.log(programData) let program = await database.models.programs.create( programData @@ -314,6 +322,7 @@ module.exports = class ProgramsHelper { }); } catch (error) { + console.error(error); return reject(error); } From bb849512ee5910669e08c9ac194f9313cb800c3d Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 6 Apr 2023 14:23:08 +0530 Subject: [PATCH 274/331] changes added for observation link join and project join --- module/solutions/helper.js | 20 ++++++++++++++++++++ module/users/helper.js | 2 ++ 2 files changed, 22 insertions(+) diff --git a/module/solutions/helper.js b/module/solutions/helper.js index fa96448a..248c5327 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -14,6 +14,7 @@ const improvementProjectService = require(ROOT_PATH + '/generics/services/improv const appsPortalBaseUrl = process.env.APP_PORTAL_BASE_URL + "/" ; const userExtensionsHelperV2 = require(MODULES_BASE_PATH + "/user-extension/helperv2"); const userService = require(ROOT_PATH + "/generics/services/users"); +const programUsersHelper = require(MODULES_BASE_PATH + "/programUsers/helper"); /** * SolutionsHelper @@ -1881,6 +1882,7 @@ module.exports = class SolutionsHelper { let solutionData = await this.solutionDocuments({ _id: solutionId }, [ "type", "projectTemplateId", + "programId" ]); if ( !Array.isArray(solutionData) || solutionData.length < 1 ) { @@ -1922,7 +1924,25 @@ module.exports = class SolutionsHelper { } } + // add ["rootOrganisations","requestForPIIConsent","programJoined"] values to response. Based on these values front end calls PII consent + let programData = await programsHelper.programDocuments({ + _id : solutionData.programId + },["rootOrganisations","requestForPIIConsent"]); + + if ( programData.length > 0 ) { + templateOrQuestionDetails.result.rootOrganisations = (programData[0].rootOrganisations) ? programData[0].rootOrganisations : []; + templateOrQuestionDetails.result.requestForPIIConsent = (programData[0].requestForPIIConsent) ? programData[0].requestForPIIConsent : false; + } + let programUsersData = await programUsersHelper.programUsersDocuments( + { + userId: userId, + programId: solutionData.programId + }, + ["_id"] + ); + templateOrQuestionDetails.result.programJoined = ( programUsersData.length > 0 ) ? true : false; + return resolve(templateOrQuestionDetails); } catch (error) { diff --git a/module/users/helper.js b/module/users/helper.js index 1b720a95..839ee7eb 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -588,6 +588,8 @@ module.exports = class UsersHelper { //if already joined the program if( programUsersData.length > 0 ) { result.programJoined = true; + } else { + result.programJoined = false; } return resolve({ From 5e8132070b364e197562c5d904001efb762b123c Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 7 Apr 2023 10:51:51 +0530 Subject: [PATCH 275/331] program endDate sending with program solutions listing api call response --- module/users/helper.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/module/users/helper.js b/module/users/helper.js index 839ee7eb..8cb94146 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -453,7 +453,7 @@ module.exports = class UsersHelper { { _id: programId }, - ["name","requestForPIIConsent","rootOrganisations"] + ["name","requestForPIIConsent","rootOrganisations","endDate"] ); if (!programData.length > 0) { @@ -569,6 +569,7 @@ module.exports = class UsersHelper { let result = { programName: programData[0].name, programId: programId, + programEndDate : programData[0].endDate ? programData[0].endDate : "", description: constants.common.TARGETED_SOLUTION_TEXT, rootOrganisations : ( programData[0].rootOrganisations && programData[0].rootOrganisations.length > 0 ) ? programData[0].rootOrganisations : [], requestForPIIConsent: programData[0].requestForPIIConsent ? programData[0].requestForPIIConsent : false, From 43088427f84f9c56d2f238c845e7ce6a422fbac8 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 7 Apr 2023 15:26:22 +0530 Subject: [PATCH 276/331] updated condition to call consent api --- module/programs/helper.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/module/programs/helper.js b/module/programs/helper.js index 7f6faac1..bca636ea 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -1059,7 +1059,7 @@ module.exports = class ProgramsHelper { } //For internal calls add consent using sunbird api - if( callConsetAPIOnBehalfOfUser && !programUsersDetails.length > 0 && !programData[0].requestForPIIConsent && programData[0].requestForPIIConsent == true ){ + if( callConsetAPIOnBehalfOfUser && !programUsersDetails.length > 0 && programData[0].hasOwnProperty('requestForPIIConsent') && programData[0].requestForPIIConsent === true ){ if( !programData[0].rootOrganisations || !programData[0].rootOrganisations.length > 0 ) { throw { message: constants.apiResponses.PROGRAM_JOIN_FAILED, From fea9fb5580db369da385f0588f2896d8b985db08 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 7 Apr 2023 16:36:21 +0530 Subject: [PATCH 277/331] migration script required for story ED-523 added --- .../programs-startDate-EndDate-6.0/README.md | 5 ++ .../setProgramsStartDateAndEndDate.js | 50 +++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 migrations/programs-startDate-EndDate-6.0/README.md create mode 100644 migrations/programs-startDate-EndDate-6.0/setProgramsStartDateAndEndDate.js diff --git a/migrations/programs-startDate-EndDate-6.0/README.md b/migrations/programs-startDate-EndDate-6.0/README.md new file mode 100644 index 00000000..48f65eb8 --- /dev/null +++ b/migrations/programs-startDate-EndDate-6.0/README.md @@ -0,0 +1,5 @@ +## Migrations for ED-523 program startDate and endDate +Steps to run the migration files +- Navigate to migrations/programs-startDate-EndDate-6.0/ folder +- Run the script which will add startDate and endDate to programs. + > node setProgramsStartDateAndEndDate.js \ No newline at end of file diff --git a/migrations/programs-startDate-EndDate-6.0/setProgramsStartDateAndEndDate.js b/migrations/programs-startDate-EndDate-6.0/setProgramsStartDateAndEndDate.js new file mode 100644 index 00000000..208c52a4 --- /dev/null +++ b/migrations/programs-startDate-EndDate-6.0/setProgramsStartDateAndEndDate.js @@ -0,0 +1,50 @@ +let _ = require("lodash"); +const path = require("path"); +let MongoClient = require("mongodb").MongoClient; +let mongoUrl = process.env.MONGODB_URL; +let dbName = mongoUrl.split("/").pop(); +let url = mongoUrl.split(dbName)[0]; + +(async () => { + + let connection = await MongoClient.connect(url, { useNewUrlParser: true }); + let db = connection.db(dbName); + try { + // get all active programs with createdAt value + let collectionDocs = await db.collection("programs").find({ + status: "active", + createdAt: {"$exists": true}, + }).project({_id:1,createdAt:1}).toArray(); + + //reduce array to small chunks + let chunkOfprogramsDetails = _.chunk(collectionDocs, 5); + + //loop each chunk + for ( let chunkPointer = 0; chunkPointer < chunkOfprogramsDetails.length; chunkPointer++ ) { + + let currentChunk = chunkOfprogramsDetails[chunkPointer]; + //loop each program details + for ( let currentChunkIndex = 0 ; currentChunkIndex < currentChunk.length; currentChunkIndex++ ) { + + let monthToAdd = 12; // ---------------------set to one year ----------------------------- + let id = currentChunk[currentChunkIndex]._id; + const startDate = currentChunk[currentChunkIndex].createdAt + const endDate = new Date(currentChunk[currentChunkIndex].createdAt); + endDate.setFullYear( endDate.getFullYear(), endDate.getMonth() + monthToAdd ); + + //update programs + await db.collection("programs").findOneAndUpdate( + { '_id': id }, + { $set: { startDate: startDate, endDate : endDate} } + ); + } + } + console.log("-----------------------Finished----------------------") + console.log(" finished programs updation of startDate and endDate") + console.log("-----------------------------------------------------") + connection.close(); + } + catch (error) { + console.log(error) + } +})().catch(err => console.error(err)); From 75d5bd77fb1556bcddc61705e71f097f79e5b014 Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Mon, 10 Apr 2023 08:29:30 +0530 Subject: [PATCH 278/331] ED-523 added start date --- module/programs/helper.js | 36 +++++++++++++++++++++++++++++++++--- module/users/helper.js | 5 ++++- 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/module/programs/helper.js b/module/programs/helper.js index 8e65fe0b..0288412a 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -80,8 +80,10 @@ module.exports = class ProgramsHelper { try { - - + if(!data.hasOwnProperty('endDate')){ + data.startDate = new Date(data.startDate) + data.endDate = data.startDate.setFullYear( data.startDate.getFullYear(), data.startDate.getMonth() + 12 ); + } let programData = { "externalId" : data.externalId, @@ -516,7 +518,8 @@ module.exports = class ProgramsHelper { if( !queryData.success ) { return resolve(queryData); } - + queryData.data.startDate ={"$lte": new Date()} + queryData.data.endDate ={"$gte": new Date()} let targetedPrograms = await this.list( pageNo, pageSize, @@ -985,6 +988,33 @@ module.exports = class ProgramsHelper { }); } + static verifyProgram(programId){ + return new Promise(async (resolve, reject) => { + try{ + let programData = + await this.programDocuments({ + _id : programId, + startDate:{$lte: new Date()}, + endDate:{$gte: new Date()} + },["_id"]); + if(programData.length > 0){ + resolve({success: true}) + }else{ + resolve({success: false}) + } + }catch(error){ + return resolve({ + success: false, + status: error.status + ? error.status + : httpStatusCode['internal_server_error'].status, + message: error.message + }); + } + }); + } }; + + const solutionsHelper = require(MODULES_BASE_PATH + "/solutions/helper"); \ No newline at end of file diff --git a/module/users/helper.js b/module/users/helper.js index 36091235..f5d37d81 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -449,7 +449,7 @@ module.exports = class UsersHelper { { _id: programId }, - ["name"] + ["name","endDate"] ); if (!programData.length > 0) { @@ -580,6 +580,9 @@ module.exports = class UsersHelper { count: totalCount }; + if(programData[0].hasOwnProperty("endDate")){ + result.programEndDate = programData[0].endDate; + } return resolve({ message: constants.apiResponses.PROGRAM_SOLUTIONS_FETCHED, success: true, From 2fccac9536d1ec9c97a41ad907259dfeb0826f25 Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Mon, 10 Apr 2023 08:36:40 +0530 Subject: [PATCH 279/331] ED-523 added start date --- generics/constants/endpoints.js | 2 +- generics/services/users.js | 4 - helper.js | 1374 ----------------- ...Rxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA | 3 - module/programs/helper.js | 28 - 5 files changed, 1 insertion(+), 1410 deletions(-) delete mode 100644 helper.js delete mode 100644 keycloak-public-keys/GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA diff --git a/generics/constants/endpoints.js b/generics/constants/endpoints.js index be019336..2deb5488 100644 --- a/generics/constants/endpoints.js +++ b/generics/constants/endpoints.js @@ -31,7 +31,7 @@ module.exports = { LIST_PROJECT : "/v1/userProjects/list", GET_QUESTIONS : "/v1/solutions/questions", GET_OBSERVATION : "/v1/observations/details", - GET_LOCATION_DATA : "/api/data/v1/location/search", + GET_LOCATION_DATA : "/v1/location/search", GET_FORM_DATA : "/plugin/v1/form/read", GET_SCHOOL_DATA : "/v1/org/search" } \ No newline at end of file diff --git a/generics/services/users.js b/generics/services/users.js index b2d4fca1..23c0c55c 100644 --- a/generics/services/users.js +++ b/generics/services/users.js @@ -97,12 +97,9 @@ const locationSearch = function ( filterData, pageSize = "", pageNo = "", search const options = { headers : { "content-type": "application/json", - "Authorization":"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJSbTBGOTlnMnd4SmZKelJwa2YzTnRlaE5CYlJnZXRCaCJ9.CjDN6GufxylpAM5J_6j9fD0wq7S2qr1F6FOzAZtQ6XU", }, json : bodyData }; - console.log( JSON.stringify(options) ); - console.log(url) request.post(url,options,requestCallback); let result = { @@ -111,7 +108,6 @@ const locationSearch = function ( filterData, pageSize = "", pageNo = "", search function requestCallback(err, data) { if (err) { - console.log(err); result.success = false; } else { let response = data.body; diff --git a/helper.js b/helper.js deleted file mode 100644 index 26081a25..00000000 --- a/helper.js +++ /dev/null @@ -1,1374 +0,0 @@ -/** - * name : helper.js - * author : Aman - * created-date : 16-July-2020 - * Description : Project templates helper functionality. - */ - -/** - * ProjectTemplatesHelper - * @class -*/ - -// Dependencies - -const libraryCategoriesHelper = require(MODULES_BASE_PATH + "/library/categories/helper"); -const coreService = require(GENERICS_FILES_PATH + "/services/core"); -const kafkaProducersHelper = require(GENERICS_FILES_PATH + "/kafka/producers"); -const learningResourcesHelper = require(MODULES_BASE_PATH + "/learningResources/helper"); -const surveyService = require(GENERICS_FILES_PATH + "/services/survey"); -const projectTemplateQueries = require(DB_QUERY_BASE_PATH + "/projectTemplates"); -const projectTemplateTaskQueries = require(DB_QUERY_BASE_PATH + "/projectTemplateTask"); -const projectQueries = require(DB_QUERY_BASE_PATH + "/projects"); -const projectCategoriesQueries = require(DB_QUERY_BASE_PATH + "/projectCategories"); -const solutionsQueries = require(DB_QUERY_BASE_PATH + "/solutions"); -const certificateTemplateQueries = require(DB_QUERY_BASE_PATH + "/certificateTemplates"); - -module.exports = class ProjectTemplatesHelper { - - /** - * Extract csv information. - * @method - * @name extractCsvInformation - * @param {Object} csvData - csv data. - * @returns {Object} Extra csv information. - */ - - static extractCsvInformation(csvData) { - return new Promise(async (resolve, reject) => { - try { - - let categoryIds = []; - let roleIds = []; - let tasksIds = []; - // <- Entitytype validation removed {release-5.0.0} - entity generalisation - // let entityTypes = []; - - csvData.forEach(template=>{ - - let parsedData = UTILS.valueParser(template); - - categoryIds = _.concat( - categoryIds, - parsedData.categories - ); - - tasksIds = _.concat( - tasksIds, - parsedData.tasks - ); - - if( parsedData.recommendedFor ) { - - parsedData.recommendedFor = - parsedData.recommendedFor.map(role=>{ - return role.toUpperCase() - }); - - roleIds = _.concat( - roleIds, - parsedData.recommendedFor - ); - } - // <- Entitytype validation removed {release-5.0.0} - entity generalisation - // if( parsedData.entityType ) { - // entityTypes.push(parsedData.entityType); - // } - - }); - - let categoriesData = {}; - - if( categoryIds.length > 0 ) { - - let categories = - await projectCategoriesQueries.categoryDocuments({ - externalId : { $in : categoryIds } - },["externalId","name"]); - - if( !categories.length > 0 ) { - throw { - status : HTTP_STATUS_CODE['bad_request'].status, - message : CONSTANTS.apiResponses.LIBRARY_CATEGORIES_NOT_FOUND - } - } - - categoriesData = categories.reduce((ac,category)=> ({ - ...ac, - [category.externalId] : { - _id : ObjectId(category._id), - externalId : category.externalId, - name : category.name - } - }),{}); - } - - let recommendedFor = {}; - - if( roleIds.length > 0 ) { - - let userRolesData = - await coreService.rolesDocuments({ - code : { $in : roleIds } - },["code"]); - - if( !userRolesData.success ) { - throw { - message : CONSTANTS.apiResponses.USER_ROLES_NOT_FOUND, - status : HTTP_STATUS_CODE['bad_request'].status - } - } - - recommendedFor = userRolesData.data.reduce((ac,role)=> ({ - ...ac, - [role.code] : { - roleId : ObjectId(role._id), - code : role.code - } - }),{}); - } - // <- Entitytype validation removed {release-5.0.0} - entity generalisation - // let entityTypesData = {}; - - // if( entityTypes.length > 0 ) { - - // let entityTypesDocument = - // await coreService.entityTypesDocuments(); - - // if( !entityTypesDocument.success ) { - // throw { - // message : CONSTANTS.apiResponses.ENTITY_TYPES_NOT_FOUND, - // status : HTTP_STATUS_CODE['bad_request'].status - // } - // } - - // entityTypesData = entityTypesDocument.data.reduce((ac,entityType)=> ({ - // ...ac, - // [entityType.name] : { - // _id : ObjectId(entityType._id), - // name : entityType.name - // } - // }),{}); - - // } - - return resolve({ - success : true, - data : { - categories : categoriesData, - roles : recommendedFor, - // <- Entitytype validation removed {release-5.0.0} - entity generalisation - // entityTypes : entityTypesData - } - }); - - } catch(error) { - return resolve({ - success : false, - message : error.message, - status : error.status ? error.status : HTTP_STATUS_CODE['internal_server_error'].status - }); - } - }) - } - - /** - * Template data. - * @method - * @name templateData - * @param {Object} data - csv data. - * @param {Object} csvInformation - csv information. - * @returns {Object} Template data. - */ - - static templateData(data,csvInformation) { - return new Promise(async (resolve, reject) => { - try { - - let templatesDataModel = - Object.keys(schemas["project-templates"].schema); - let parsedData = UTILS.valueParser(data); - delete parsedData._arrayFields; - - let categories = []; - - if( parsedData.categories && parsedData.categories.length > 0 ) { - - parsedData.categories.forEach( category => { - if( csvInformation.categories[category] ) { - return categories.push( - csvInformation.categories[category] - ); - } - }); - } - - parsedData.categories = categories; - - let recommendedFor = []; - - if( parsedData.recommendedFor && parsedData.recommendedFor.length > 0 ) { - parsedData.recommendedFor.forEach(recommended => { - if( csvInformation.roles[recommended] ) { - return recommendedFor.push( - csvInformation.roles[recommended] - ); - } - }); - } - - parsedData.recommendedFor = recommendedFor; - // <- Entitytype validation removed {release-5.0.0} - entity generalisation - // if( parsedData.entityType && parsedData.entityType !== "" ) { - // parsedData.entityType = csvInformation.entityTypes[parsedData.entityType].name; - // } - - let learningResources = - await learningResourcesHelper.extractLearningResourcesFromCsv(parsedData); - parsedData.learningResources = learningResources.data; - - parsedData.metaInformation = {}; - let booleanData = - UTILS.getAllBooleanDataFromModels( - schemas["project-templates"].schema - ); - - Object.keys(parsedData).forEach( eachParsedData => { - if( - !templatesDataModel.includes(eachParsedData) - ) { - - if( !eachParsedData.startsWith("learningResources") ) { - parsedData.metaInformation[eachParsedData] = - parsedData[eachParsedData]; - delete parsedData[eachParsedData]; - } - - } else { - if( booleanData.includes(eachParsedData) ) { - parsedData[eachParsedData] = - UTILS.convertStringToBoolean(parsedData[eachParsedData]); - } - } - }); - - parsedData.isReusable = true; - - return resolve(parsedData); - - } catch(error) { - return reject(error); - } - }) - } - - /** - * Bulk created project templates. - * @method - * @name bulkCreate - bulk create project templates. - * @param {Array} templates - csv templates data. - * @param {String} userId - logged in user id. - * @returns {Object} Bulk create project templates. - */ - - static bulkCreate(templates,userId) { - - return new Promise(async (resolve, reject) => { - - try { - - const fileName = `project-templates-creation`; - let fileStream = new CSV_FILE_STREAM(fileName); - let input = fileStream.initStream(); - - (async function () { - await fileStream.getProcessorPromise(); - return resolve({ - isResponseAStream: true, - fileNameWithPath: fileStream.fileNameWithPath() - }); - })(); - - let csvInformation = await this.extractCsvInformation(templates); - - if( !csvInformation.success ) { - return resolve(csvInformation); - } - - for ( let template = 0; template < templates.length ; template ++ ) { - - let currentData = templates[template]; - - let templateData = - await projectTemplateQueries.templateDocument({ - status : CONSTANTS.common.PUBLISHED, - externalId : currentData.externalId, - isReusable : true - },["_id"]); - - if( templateData.length > 0 && templateData[0]._id ) { - currentData["_SYSTEM_ID"] = - CONSTANTS.apiResponses.PROJECT_TEMPLATE_EXISTS; - } else { - - let templateData = await this.templateData( - currentData, - csvInformation.data, - userId - ); - - templateData.status = CONSTANTS.common.PUBLISHED_STATUS; - templateData.createdBy = templateData.updatedBy = templateData.userId = userId; - templateData.isReusable = true; - - let createdTemplate = await projectTemplateQueries.createTemplate(templateData); - - if( !createdTemplate._id ) { - currentData["_SYSTEM_ID"] = CONSTANTS.apiResponses.PROJECT_TEMPLATE_NOT_FOUND; - } else { - - currentData["_SYSTEM_ID"] = createdTemplate._id; - - if( - templateData.categories && - templateData.categories.length > 0 - ) { - - let categories = templateData.categories.map(category => { - return category._id; - }); - - let updatedCategories = - await libraryCategoriesHelper.update({ - _id : { $in : categories } - },{ - $inc : { noOfProjects : 1 } - }); - - if( !updatedCategories.success ) { - currentData["_SYSTEM_ID"] = updatedCategories.message; - } - } - - // <- Dirty fix . Not required - // const kafkaMessage = - // await kafkaProducersHelper.pushProjectToKafka({ - // internal : false, - // text : - // templateData.categories.length === 1 ? - // `A new project has been added under ${templateData.categories[0].name} category in library.` : - // `A new project has been added in library`, - // type : "information", - // action : "mapping", - // payload : { - // project_id: createdTemplate._id - // }, - // is_read : false, - // internal : false, - // title : "New project Available!", - // created_at : new Date(), - // appType : process.env.IMPROVEMENT_PROJECT_APP_TYPE, - // inApp:false, - // push: true, - // pushToTopic: true, - // topicName : process.env.NODE_ENV + "-" + process.env.IMPROVEMENT_PROJECT_APP_NAME + process.env.TOPIC_FOR_ALL_USERS - // }); - - // if (kafkaMessage.status !== CONSTANTS.common.SUCCESS) { - // currentData["_SYSTEM_ID"] = CONSTANTS.apiResponses.COULD_NOT_PUSHED_TO_KAFKA; - // } - - } - - } - - input.push(currentData); - - } - - input.push(null); - - } catch (error) { - return reject(error); - } - }) - } - - /** - * Bulk update project templates. - * @method - * @name bulkUpdate - bulk update project templates. - * @param {Array} templates - csv templates data. - * @param {String} userId - logged in user id. - * @returns {Object} Bulk Update Project templates. - */ - - static bulkUpdate(templates,userId) { - return new Promise(async (resolve, reject) => { - try { - - const fileName = `project-templates-updation`; - let fileStream = new CSV_FILE_STREAM(fileName); - let input = fileStream.initStream(); - - (async function () { - await fileStream.getProcessorPromise(); - return resolve({ - isResponseAStream: true, - fileNameWithPath: fileStream.fileNameWithPath() - }); - })(); - - let csvInformation = await this.extractCsvInformation(templates); - - if( !csvInformation.success ) { - return resolve(csvInformation); - } - - for ( let template = 0; template < templates.length ; template ++ ) { - - const currentData = templates[template]; - - if ( !currentData._SYSTEM_ID ) { - currentData["UPDATE_STATUS"] = - CONSTANTS.apiResponses.MISSING_PROJECT_TEMPLATE_ID; - } else { - - const template = - await projectTemplateQueries.templateDocument({ - status : CONSTANTS.common.PUBLISHED, - _id : currentData._SYSTEM_ID, - status : CONSTANTS.common.PUBLISHED - },["_id","categories", "isReusable"]); - - if ( !(template.length > 0 && template[0]._id) ) { - currentData["UPDATE_STATUS"] = - CONSTANTS.apiResponses.PROJECT_TEMPLATE_NOT_FOUND; - } else { - - let templateData = await this.templateData( - _.omit(currentData,["_SYSTEM_ID"]), - csvInformation.data, - userId - ); - - if(template[0].isReusable === false) { - templateData.isReusable = false; - } - - templateData.updatedBy = userId; - - let projectTemplateUpdated = - await projectTemplateQueries.findOneAndUpdate({ - _id : currentData._SYSTEM_ID - },{ - $set : templateData - },{ - new : true - }); - - if( !projectTemplateUpdated || !projectTemplateUpdated._id ) { - currentData["UPDATE_STATUS"] = - CONSTANTS.apiResponses.PROJECT_TEMPLATE_NOT_UPDATED; - } - - // Add projects count to categories - if( - templateData.categories && - templateData.categories.length > 0 - ) { - - let categories = - templateData.categories.map(category => { - return category._id; - }); - - let updatedCategories = - await libraryCategoriesHelper.update({ - _id : { $in : categories } - },{ - $inc : { noOfProjects : 1 } - }); - - if( !updatedCategories.success ) { - currentData["UPDATE_STATUS"] = updatedCategories.message; - } - } - - // Remove project count from existing categories - if( - template[0].categories && - template[0].categories.length > 0 - ) { - - const categoriesIds = - template[0].categories.map(category=>{ - return category._id; - }); - - let categoriesUpdated = - await libraryCategoriesHelper.update({ - _id : { $in : categoriesIds } - },{ - $inc : { noOfProjects : -1 } - }); - - if( !categoriesUpdated.success ) { - currentData["UPDATE_STATUS"] = updatedCategories.message; - } - } - - currentData["UPDATE_STATUS"] = CONSTANTS.common.SUCCESS; - } - - } - - input.push(templates[template]); - - } - - input.push(null); - - } catch (error) { - return reject(error); - } - }) - } - - /** - * Bulk update project templates. - * @method - * @name importProjectTemplate - import templates from existing project templates. - * @param {String} templateId - project template id. - * @param {String} userId - logged in user id. - * @param {String} userToken - logged in user token. - * @param {String} solutionId - solution id. - * @param {Object} updateData - template update data. - * @returns {Object} imported templates data. - */ - - static importProjectTemplate( templateId,userId,userToken,solutionId,updateData = {} ) { - return new Promise(async (resolve, reject) => { - try { - - let projectTemplateData = - await projectTemplateQueries.templateDocument({ - status : CONSTANTS.common.PUBLISHED, - externalId : templateId, - isReusable : true - }); - - if ( !projectTemplateData.length > 0 ) { - throw new Error(CONSTANTS.apiResponses.PROJECT_TEMPLATE_NOT_FOUND) - } - - let newProjectTemplate = {...projectTemplateData[0]}; - newProjectTemplate.externalId = - projectTemplateData[0].externalId +"-"+ UTILS.epochTime(); - newProjectTemplate.createdBy = newProjectTemplate.updatedBy = userId; - - let solutionData = - await surveyService.listSolutions([solutionId]); - - if( !solutionData.success ) { - throw { - message : CONSTANTS.apiResponses.SOLUTION_NOT_FOUND, - status : HTTP_STATUS_CODE['bad_request'].status - } - } - - if( solutionData.data[0].type !== CONSTANTS.common.IMPROVEMENT_PROJECT ) { - throw { - message : CONSTANTS.apiResponses.IMPROVEMENT_PROJECT_SOLUTION_NOT_FOUND, - status : HTTP_STATUS_CODE['bad_request'].status - } - } - - if( solutionData.data[0].projectTemplateId ) { - throw { - message : CONSTANTS.apiResponses.PROJECT_TEMPLATE_EXISTS_IN_SOLUTION, - status : HTTP_STATUS_CODE['bad_request'].status - } - } - - if( - projectTemplateData[0].entityType && - projectTemplateData[0].entityType !== "" && - projectTemplateData[0].entityType !== solutionData.data[0].entityType - ) { - throw { - message : CONSTANTS.apiResponses.ENTITY_TYPE_MIS_MATCHED, - status : HTTP_STATUS_CODE['bad_request'].status - } - } - - newProjectTemplate.solutionId = solutionData.data[0]._id; - newProjectTemplate.solutionExternalId = solutionData.data[0].externalId; - newProjectTemplate.programId = solutionData.data[0].programId; - newProjectTemplate.programExternalId = solutionData.data[0].programExternalId; - - - newProjectTemplate.parentTemplateId = projectTemplateData[0]._id; - - let updationKeys = Object.keys(updateData); - if( updationKeys.length > 0 ) { - updationKeys.forEach(singleKey => { - if( newProjectTemplate[singleKey] ) { - newProjectTemplate[singleKey] = updateData[singleKey]; - } - }) - } - - let tasksIds; - - if(projectTemplateData[0].tasks){ - tasksIds = projectTemplateData[0].tasks; - } - - newProjectTemplate.isReusable = false; - - let duplicateTemplateDocument = - await projectTemplateQueries.createTemplate( - _.omit(newProjectTemplate, ["_id"]) - ); - - if ( !duplicateTemplateDocument._id ) { - throw new Error(CONSTANTS.apiResponses.PROJECT_TEMPLATES_NOT_CREATED) - } - - //duplicate task - if(Array.isArray(tasksIds) && tasksIds.length > 0 ){ - await this.duplicateTemplateTasks( - tasksIds, - duplicateTemplateDocument._id, - duplicateTemplateDocument.externalId - ); - } - - await surveyService.updateSolution( - userToken, - { - projectTemplateId : duplicateTemplateDocument._id, - name : duplicateTemplateDocument.title - }, - newProjectTemplate.solutionExternalId - ); - - await this.ratings( - projectTemplateData[0]._id, - updateData.rating, - userToken - ); - - return resolve({ - success: true, - message : CONSTANTS.apiResponses.DUPLICATE_PROJECT_TEMPLATES_CREATED, - data : { - _id : duplicateTemplateDocument._id - } - }) - - } catch (error) { - return resolve({ - status : - error.status ? - error.status : HTTP_STATUS_CODE['internal_server_error'].status, - success: false, - message: error.message, - data: {} - }); - } - }) - } - - /** - * Create ratings. - * @method - * @name ratings - * @param {String} templateId - project template id. - * @param {String} rating - rating for template. - * @returns {Object} rating object. - */ - - static ratings( templateId,rating,userToken ) { - return new Promise(async (resolve, reject) => { - try { - - let userProfileData = await coreService.getProfile(userToken); - - if( !userProfileData.success ) { - throw { - status : HTTP_STATUS_CODE['bad_request'].status, - message : CONSTANTS.apiResponses.USER_PROFILE_NOT_FOUND - } - } - - let templateData = - await projectTemplateQueries.templateDocument({ - status : CONSTANTS.common.PUBLISHED, - _id : templateId, - isReusable : true - },[ - "averageRating", - "noOfRatings", - "ratings" - ]); - - let updateRating = { - ratings : {...templateData[0].ratings} - }; - - updateRating.ratings[rating] += 1; - - let userCurrentRating = 0; - let projectIndex = -1; - - if( - userProfileData.data && - userProfileData.data.ratings && - userProfileData.data.ratings.length > 0 - ) { - - projectIndex = - userProfileData.data.ratings.findIndex( - project => project._id.toString() === templateId.toString() - ); - - if( !(projectIndex < 0) ) { - userCurrentRating = userProfileData.data.ratings[projectIndex].rating; - updateRating.ratings[userCurrentRating] -= 1; - } - } else { - userProfileData.data.ratings = []; - } - - let ratingUpdated = {}; - - if( userCurrentRating === rating ) { - - ratingUpdated = templateData[0]; - - } else { - - let calculateRating = _calculateRating(updateRating.ratings); - updateRating.averageRating = calculateRating.averageRating; - updateRating.noOfRatings = calculateRating.noOfRatings; - - ratingUpdated = - await projectTemplateQueries.findOneAndUpdate({ - _id : templateId - },{ - $set : updateRating - }, { - new : true - }); - - let improvementProjects = [...userProfileData.data.ratings]; - if( projectIndex >= 0 ) { - improvementProjects[projectIndex].rating = rating; - } else { - improvementProjects.push({ - _id : ObjectId(templateId), - externalId : ratingUpdated.externalId, - rating : rating, - type : CONSTANTS.common.IMPROVEMENT_PROJECT - }); - } - - await coreService.updateUserProfile( - userToken, - { - "ratings" : improvementProjects - } - ); - } - - return resolve( - _.pick( - ratingUpdated, - ["averageRating","noOfRatings","ratings"] - ) - ); - - } catch (error) { - return resolve({ - success : false, - message : error.message, - status : error.status ? error.status : HTTP_STATUS_CODE['internal_server_error'].status - }); - } - }) - } - - /** - * Project template tasks - * @method - * @name duplicateTemplateTasks - * @param {Array} taskIds - Task ids - * @returns {Object} Duplicated tasks. - */ - - static duplicateTemplateTasks( taskIds=[], duplicateTemplateId, duplicateTemplateExternalId ) { - return new Promise(async (resolve, reject) => { - try { - - let newTaskId = []; - - for ( let pointerToTask = 0; pointerToTask < taskIds.length; pointerToTask++ ) { - - let taskId = taskIds[pointerToTask]; - let taskData = await projectTemplateTaskQueries.taskDocuments( - { - _id : taskId, - parentId : { $exists : false } - }); - - if( taskData && taskData.length > 0 ) { - taskData = taskData[0]; - } - - if ( taskData && Object.keys(taskData).length > 0 ) { - - //duplicate parent task - let newProjectTemplateTask = {...taskData}; - newProjectTemplateTask.projectTemplateId = duplicateTemplateId; - newProjectTemplateTask.projectTemplateExternalId = duplicateTemplateExternalId; - newProjectTemplateTask.externalId = taskData.externalId +"-"+ UTILS.epochTime(); - - let duplicateTemplateTask = - await database.models.projectTemplateTasks.create( - _.omit(newProjectTemplateTask, ["_id"]) - ); - - newTaskId.push(duplicateTemplateTask._id); - - //duplicate child task - if ( duplicateTemplateTask.children && duplicateTemplateTask.children.length > 0 ) { - - let childTaskIdArray = []; - let childTaskIds = duplicateTemplateTask.children; - - if ( childTaskIds && childTaskIds.length > 0 ) { - - for ( let pointerToChild = 0 ; pointerToChild < childTaskIds.length ; pointerToChild++ ) { - - let childtaskId = childTaskIds[pointerToChild]; - let childTaskData = await projectTemplateTaskQueries.taskDocuments( - { - _id : childtaskId - }); - - if ( childTaskData && childTaskData.length > 0 ) { - childTaskData = childTaskData[0]; - } - - if ( childTaskData && Object.keys(childTaskData).length > 0 ) { - - let newProjectTemplateChildTask = {...childTaskData}; - newProjectTemplateChildTask.projectTemplateId = duplicateTemplateId; - newProjectTemplateChildTask.projectTemplateExternalId = duplicateTemplateExternalId; - newProjectTemplateChildTask.parentId = duplicateTemplateTask._id; - newProjectTemplateChildTask.externalId = childTaskData.externalId +"-"+ UTILS.epochTime(); - - let duplicateChildTemplateTask = - await database.models.projectTemplateTasks.create( - _.omit(newProjectTemplateChildTask, ["_id"]) - ); - - childTaskIdArray.push(duplicateChildTemplateTask._id); - newTaskId.push(duplicateChildTemplateTask._id); - } - } - //update new subtask ids to parent task - if(childTaskIdArray && childTaskIdArray.length > 0){ - let updateTaskData = await projectTemplateTaskQueries.updateTaskDocument( - { - _id : duplicateTemplateTask._id - }, - { - $set : { - children : childTaskIdArray - } - }) - } - } - } - } - } - - let updateDuplicateTemplate; - //adding duplicate tasj to duplicate template - if(newTaskId && newTaskId.length > 0){ - - updateDuplicateTemplate = await projectTemplateQueries.findOneAndUpdate( - { - _id : duplicateTemplateId - }, - { - $set : { - tasks : newTaskId - } - }) - } - - return resolve( - updateDuplicateTemplate - ); - - } catch (error) { - return reject(error); - } - }) - } - - /** - * Templates list. - * @method - * @name listByIds - * @param {Array} externalIds - External ids - * @returns {Array} List of templates data. - */ - - static listByIds( externalIds ) { - return new Promise(async (resolve, reject) => { - try { - - let templateData = await projectTemplateQueries.templateDocument({ - externalId : { $in : externalIds } - },["title","metaInformation.goal","externalId"]); - - if ( !templateData.length > 0 ) { - throw { - status : HTTP_STATUS_CODE.bad_request.status, - message : CONSTANTS.apiResponses.PROJECT_TEMPLATE_NOT_FOUND - } - } - - templateData = templateData.map( template => { - if( template.metaInformation && template.metaInformation.goal ) { - template.goal = template.metaInformation.goal; - delete template.metaInformation; - } - - return template; - }) - - return resolve({ - success : false, - data : templateData, - message : CONSTANTS.apiResponses.PROJECT_TEMPLATES_FETCHED - }); - - } catch (error) { - return reject(error); - } - }) - } - - /** - * Template details. - * @method - * @name details - * @param {String} templateId - Project template id. - * @param {String} userId - logged in user id. - * @params {String} link - solution link. - * @returns {Array} Project templates data. - */ - - static details( templateId="", link="", userId="", isAPrivateProgram ) { - return new Promise(async (resolve, reject) => { - try { - let solutionsResult = {}; - let findQuery = {}; - //get data when link is given - if( link ){ - - let queryData = {}; - queryData["link"] =link; - - let solutionDocument = await solutionsQueries.solutionsDocument(queryData, - [ - "_id", - "name", - "programId", - "programName", - "projectTemplateId", - "link" - ] - ); - - if( !solutionDocument.length > 0 ) { - throw { - message : CONSTANTS.apiResponses.SOLUTION_NOT_FOUND, - status : HTTP_STATUS_CODE['bad_request'].status - } - } - let solutiondata = solutionDocument; - templateId = solutiondata[0].projectTemplateId; - if( !templateId ){ - return resolve({ - success : false, - data : solutiondata, - message : CONSTANTS.apiResponses.TEMPLATE_ID_NOT_FOUND_IN_SOLUTION - }); - } - solutionsResult = solutiondata; - templateId=templateId.toString(); - } - - if( templateId ){ - let validateTemplateId = UTILS.isValidMongoId(templateId); - if( validateTemplateId ) { - findQuery["_id"] = templateId; - } else { - findQuery["externalId"] = templateId; - } - - } - //getting template data using templateId - - let templateData = await projectTemplateQueries.templateDocument(findQuery,"all", - [ - "ratings", - "noOfRatings", - "averageRating", - "parentTemplateId", - "userId", - "createdBy", - "updatedBy", - "createdAt", - "updatedAt", - "__v" - ] - ); - - if ( !templateData.length > 0 ) { - throw { - status : HTTP_STATUS_CODE.bad_request.status, - message :CONSTANTS.apiResponses.PROJECT_TEMPLATE_NOT_FOUND - } - } - if ( templateData[0].certificateTemplateId && templateData[0].certificateTemplateId !== "" ){ - let certificateTemplateDetails = await certificateTemplateQueries.certificateTemplateDocument({ - _id : templateData[0].certificateTemplateId - },["criteria"]); - - //certificate template data do not exists. - if ( !certificateTemplateDetails.length > 0 ) { - throw { - message: CONSTANTS.apiResponses.CERTIFICATE_TEMPLATE_NOT_FOUND - }; - } - templateData[0].criteria = certificateTemplateDetails[0].criteria - } - - if (templateData[0].tasks && templateData[0].tasks.length > 0) { - templateData[0].tasks = - await this.tasksAndSubTasks(templateData[0]._id); - } - let result = await _templateInformation(templateData[0]) - if( !result.success ) { - return resolve(result); - } - - if( !templateData[0].isReusable && userId !== "") { - - templateData[0].projectId = ""; - - let project = await projectQueries.projectDocument({ - userId : userId, - projectTemplateId : templateData[0]._id, - isAPrivateProgram : isAPrivateProgram - },["_id"]); - - if(project && project.length > 0){ - templateData[0].projectId = project[0]._id; - } - } - if( !result.data.programInformation ){ - result.data.programInformation = { - programId : solutionsResult.programId, - programName : solutionsResult.programName - } - } - result.data.solutionInformation = { - _id : solutionsResult._id, - name : solutionsResult.name, - link : solutionsResult.link - } - return resolve({ - success : false, - data : result.data, - message : CONSTANTS.apiResponses.PROJECT_TEMPLATE_DETAILS_FETCHED - }); - - } catch (error) { - return reject(error); - } - }) - } - - /** - * Tasks and sub tasks. - * @method - * @name tasksAndSubTasks - * @param {Array} templateId - Template id. - * @returns {Array} Tasks and sub task. - */ - - static tasksAndSubTasks(templateId) { - return new Promise(async (resolve, reject) => { - try { - - const templateDocument = - await projectTemplateQueries.templateDocument({ - _id : templateId, - status : CONSTANTS.common.PUBLISHED - },["tasks", "taskSequence"]); - - let tasks = []; - - if ( templateDocument[0].taskSequence && templateDocument[0].taskSequence.length > 0 ) { - - let projectionKey = CONSTANTS.common.TASK_SEQUENCE; - let findQuery = { - externalId : { - $in : templateDocument[0].taskSequence - } - } - - tasks = await _taskAndSubTaskinSequence(findQuery, projectionKey); - } else { - if ( templateDocument[0].tasks && templateDocument[0].tasks.length > 0 ){ - let projectionKey = CONSTANTS.common.CHILDREN; - if( templateDocument[0].tasks ) { - let findQuery = { - _id : { - $in : templateDocument[0].tasks - }, - parentId : { $exists : false } - } - - tasks = await _taskAndSubTaskinSequence(findQuery, projectionKey); - } - } - - } - - return resolve(tasks); - - } catch (error) { - return reject(error); - } - }); - } - - /** - * Template update. - * @method - * @name update - * @param {String} templateId - Project template id. - * @param {Object} templateData - template updation data - * @param {String} userId - logged in user id. - * @returns {Array} Project templates data. - */ - - static update( templateId, templateData, userId ) { - return new Promise(async (resolve, reject) => { - try { - - let findQuery = {}; - - let validateTemplateId = UTILS.isValidMongoId(templateId); - - if( validateTemplateId ) { - findQuery["_id"] = templateId; - } else { - findQuery["externalId"] = templateId; - } - - let templateDocument = await projectTemplateQueries.templateDocument(findQuery, ["_id"]); - - if ( !templateDocument.length > 0 ) { - throw { - status : HTTP_STATUS_CODE.bad_request.status, - message : CONSTANTS.apiResponses.PROJECT_TEMPLATE_NOT_FOUND - } - } - - let updateObject = { - "$set" : {} - }; - - let templateUpdateData = templateData; - - Object.keys(templateUpdateData).forEach(updationData=>{ - updateObject["$set"][updationData] = templateUpdateData[updationData]; - }); - - updateObject["$set"]["updatedBy"] = userId; - - let templateUpdatedData = await projectTemplateQueries.findOneAndUpdate({ - _id : templateDocument[0]._id - }, updateObject, { new : true }); - - if( !templateUpdatedData._id ) { - throw { - message : CONSTANTS.apiResponses.PROJECT_TEMPLATE_NOT_UPDATED - } - } - - return resolve({ - success : true, - data : templateUpdatedData, - message : CONSTANTS.apiResponses.PROJECT_TEMPLATE_UPDATED - }); - - } catch (error) { - return reject(error); - } - }) - } - -}; - -/** - * Calculate average rating and no of ratings. - * @method - * @name _calculateRating - * @param {Object} ratings - Ratings data. - * @returns {Object} rating object. -*/ - -function _calculateRating(ratings) { - let sum = 0; - let noOfRatings = 0; - - Object.keys(ratings).forEach(rating => { - sum += rating * ratings[rating]; - noOfRatings += ratings[rating]; - }); - - return { - averageRating : (sum/noOfRatings).toFixed(2), - noOfRatings : noOfRatings - } -} - -/** - * Project information. - * @method - * @name _templateInformation - * @param {Object} project - Project data. - * @returns {Object} Project information. -*/ - -function _templateInformation(project) { - - return new Promise(async (resolve, reject) => { - try { - - if( project.programId ) { - - let programs = - await surveyService.listProgramsBasedOnIds([project.programId]); - - if( !programs.success ) { - throw { - message : CONSTANTS.apiResponses.PROGRAM_NOT_FOUND, - status : HTTP_STATUS_CODE['bad_request'].status - } - } - - project.programInformation = { - programId : project.programId, - programName : programs.data[0].name - } - - delete project.programId; - delete project.programExternalId; - } - - if (project.metaInformation) { - Object.keys(project.metaInformation).forEach(projectMetaKey => { - project[projectMetaKey] = project.metaInformation[projectMetaKey]; - }); - } - delete project.metaInformation; - delete project.__v; - - project.status = - project.status ? project.status : CONSTANTS.common.NOT_STARTED_STATUS; - - return resolve({ - success: true, - data: project - }); - - } catch (error) { - return resolve({ - message: error.message, - success: false, - status: - error.status ? - error.status : HTTP_STATUS_CODE['internal_server_error'].status - }) - } - }) -} - -/** - * Task and SubTask In Order. - * @method - * @name _taskAndSubTaskinSequence - * @param {Object} query - template Query. - * @param {String} projectionValue - children or taskSequence. - * @returns {Object} Task and SubTask information. -*/ - -function _taskAndSubTaskinSequence(query, projectionValue) { - - return new Promise(async (resolve, reject) => { - try { - - let tasks = []; - tasks = await projectTemplateTaskQueries.taskDocuments(query,"all", ["projectTemplateId","__v","projectTemplateExternalId"]); - - for( let task = 0 ; task < tasks.length ; task++ ) { - if ( tasks[task][projectionValue] && tasks[task][projectionValue].length > 0 ) { - let subTaskQuery; - if ( projectionValue == CONSTANTS.common.CHILDREN ) { - subTaskQuery = { - "_id" : { - $in : tasks[task][projectionValue] - } - } - - } else { - subTaskQuery = { - "externalId" : { - $in : tasks[task][projectionValue] - } - } - } - - let subTasks = await projectTemplateTaskQueries.taskDocuments(subTaskQuery, "all", ["projectTemplateId","__v","projectTemplateExternalId"]); - tasks[task].children = subTasks; - } - } - - return resolve(tasks); - - } catch (error) { - return resolve({ - message: error.message, - success: false, - status: - error.status ? - error.status : HTTP_STATUS_CODE['internal_server_error'].status - }) - } - }) -} - - diff --git a/keycloak-public-keys/GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA b/keycloak-public-keys/GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA deleted file mode 100644 index 44c17f6c..00000000 --- a/keycloak-public-keys/GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA +++ /dev/null @@ -1,3 +0,0 @@ ------BEGIN PUBLIC KEY----- -MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoRbRlp/1x0h5a9Rb3E7+nU17mdnU1Grv2/a6ixhdBr1f9mjKEn7F/5eIfCQL3H82stxZyskeWaetL1mNJkAHFcJx+03DoKnGP6K+PZ3Svbw67ehgqyp+OozZCNXHzrM1DUVpvhYgsnvkqm+E1QyrsmrghSE+bAHqJep4S/70z12t8rwMNB6OxcbhrHBU93TxszxHHLZL9eaa2DCwGsTbYml0V2vFPsN4HUhXtnht9uoC2bjAXyBsrSNy/aoCsoI0erV8Vyw2FKfwEGBDFROjcWhKOdwb36TmEDf+g4OBSqAhEyewhTwcP7ESpjhyA3Ae1cH9cKOBmQTU+OmzS89h8QIDAQAB ------END PUBLIC KEY----- diff --git a/module/programs/helper.js b/module/programs/helper.js index 0288412a..d32e4967 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -11,7 +11,6 @@ const entityTypesHelper = require(MODULES_BASE_PATH + "/entityTypes/helper"); const entitiesHelper = require(MODULES_BASE_PATH + "/entities/helper"); const userRolesHelper = require(MODULES_BASE_PATH + "/user-roles/helper"); const userService = require(ROOT_PATH + "/generics/services/users"); -const moment = require('moment'); /** * ProgramsHelper @@ -114,7 +113,6 @@ module.exports = class ProgramsHelper { "isAPrivateProgram" : data.isAPrivateProgram ? data.isAPrivateProgram : false } - console.log(programData) let program = await database.models.programs.create( programData @@ -324,7 +322,6 @@ module.exports = class ProgramsHelper { }); } catch (error) { - console.error(error); return reject(error); } @@ -988,31 +985,6 @@ module.exports = class ProgramsHelper { }); } - static verifyProgram(programId){ - return new Promise(async (resolve, reject) => { - try{ - let programData = - await this.programDocuments({ - _id : programId, - startDate:{$lte: new Date()}, - endDate:{$gte: new Date()} - },["_id"]); - if(programData.length > 0){ - resolve({success: true}) - }else{ - resolve({success: false}) - } - }catch(error){ - return resolve({ - success: false, - status: error.status - ? error.status - : httpStatusCode['internal_server_error'].status, - message: error.message - }); - } - }); - } }; From 511730207ef148e6924ccd3c3b93619b11e29e80 Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Mon, 10 Apr 2023 08:38:07 +0530 Subject: [PATCH 280/331] ED-523 added start date --- generics/services/users.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/generics/services/users.js b/generics/services/users.js index 23c0c55c..5da28fea 100644 --- a/generics/services/users.js +++ b/generics/services/users.js @@ -96,7 +96,7 @@ const locationSearch = function ( filterData, pageSize = "", pageNo = "", search userServiceUrl + constants.endpoints.GET_LOCATION_DATA; const options = { headers : { - "content-type": "application/json", + "content-type": "application/json", }, json : bodyData }; @@ -111,6 +111,7 @@ const locationSearch = function ( filterData, pageSize = "", pageNo = "", search result.success = false; } else { let response = data.body; + if( response.responseCode === constants.common.OK && response.result && response.result.response && From 868744a81c9e40673630451015d3ddc9e9716b8c Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Mon, 10 Apr 2023 08:38:36 +0530 Subject: [PATCH 281/331] ED-523 added start date --- generics/services/users.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/generics/services/users.js b/generics/services/users.js index 5da28fea..ee169d09 100644 --- a/generics/services/users.js +++ b/generics/services/users.js @@ -96,7 +96,7 @@ const locationSearch = function ( filterData, pageSize = "", pageNo = "", search userServiceUrl + constants.endpoints.GET_LOCATION_DATA; const options = { headers : { - "content-type": "application/json", + "content-type": "application/json", }, json : bodyData }; @@ -111,7 +111,7 @@ const locationSearch = function ( filterData, pageSize = "", pageNo = "", search result.success = false; } else { let response = data.body; - + if( response.responseCode === constants.common.OK && response.result && response.result.response && From f8267771b71dddd39c23cb21015177d4a7179ddf Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Mon, 10 Apr 2023 08:39:12 +0530 Subject: [PATCH 282/331] ED-523 added start date --- generics/services/users.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/generics/services/users.js b/generics/services/users.js index ee169d09..e9456bfd 100644 --- a/generics/services/users.js +++ b/generics/services/users.js @@ -111,7 +111,7 @@ const locationSearch = function ( filterData, pageSize = "", pageNo = "", search result.success = false; } else { let response = data.body; - + if( response.responseCode === constants.common.OK && response.result && response.result.response && From 5bbb6437d0acf2f993024087c89e95aac6147802 Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Mon, 10 Apr 2023 08:39:39 +0530 Subject: [PATCH 283/331] ED-523 added start date --- generics/services/users.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/generics/services/users.js b/generics/services/users.js index e9456bfd..dad76493 100644 --- a/generics/services/users.js +++ b/generics/services/users.js @@ -111,7 +111,7 @@ const locationSearch = function ( filterData, pageSize = "", pageNo = "", search result.success = false; } else { let response = data.body; - + if( response.responseCode === constants.common.OK && response.result && response.result.response && From ad3a7646855e669015549b088b9363b18a98ef4e Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 10 Apr 2023 11:09:26 +0530 Subject: [PATCH 284/331] Review fix --- .../setProgramsStartDateAndEndDate.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/migrations/programs-startDate-EndDate-6.0/setProgramsStartDateAndEndDate.js b/migrations/programs-startDate-EndDate-6.0/setProgramsStartDateAndEndDate.js index 208c52a4..90c2542d 100644 --- a/migrations/programs-startDate-EndDate-6.0/setProgramsStartDateAndEndDate.js +++ b/migrations/programs-startDate-EndDate-6.0/setProgramsStartDateAndEndDate.js @@ -14,10 +14,11 @@ let url = mongoUrl.split(dbName)[0]; let collectionDocs = await db.collection("programs").find({ status: "active", createdAt: {"$exists": true}, + isAPrivateProgram: false // removing private program from the set. }).project({_id:1,createdAt:1}).toArray(); //reduce array to small chunks - let chunkOfprogramsDetails = _.chunk(collectionDocs, 5); + let chunkOfprogramsDetails = _.chunk(collectionDocs, 50); //loop each chunk for ( let chunkPointer = 0; chunkPointer < chunkOfprogramsDetails.length; chunkPointer++ ) { From ec014ceab128542dc2fb02bf025a390aa545537d Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 10 Apr 2023 12:36:56 +0530 Subject: [PATCH 285/331] changes related to kafka env variables made. --- .env.sample | 8 ++++---- config/kafka.js | 1 - envVariables.js | 4 ++++ generics/kafka/producers.js | 2 +- 4 files changed, 9 insertions(+), 6 deletions(-) diff --git a/.env.sample b/.env.sample index e994c0b8..e12dd9e1 100644 --- a/.env.sample +++ b/.env.sample @@ -52,7 +52,7 @@ OCI_BUCKET_REGION = 'ap-hyderabad-1' OCI_BUCKET_ENDPOINT = 'https://pmt5.compat.storage.ap-h1.oraclecloud.com' // Oracle cloud bucket endPoint # KAFKA Configurations -KAFKA_COMMUNICATIONS_ON_OFF = ON // Kafka enable or disable communication flag -KAFKA_URL = 192.168.100.27:9092 // IP address of kafka server with port without HTTP -KAFKA_GROUP_ID = projects // Kafka group id -PROGRAM_USERS_JOINED_TOPIC = "ml.programUsers.raw" // Kafka submission topic for pushing program joined user's data \ No newline at end of file +KAFKA_COMMUNICATIONS_ON_OFF = "ON/OFF" // Kafka enable or disable communication flag +KAFKA_URL = "100.0.0.1:9092" // IP address of kafka server with port without HTTP +KAFKA_GROUP_ID = "core" // Kafka group id +PROGRAM_USERS_JOINED_TOPIC = "dev.programuser.info" // Kafka submission topic for pushing program joined user's data \ No newline at end of file diff --git a/config/kafka.js b/config/kafka.js index 07f50d82..42a14fe5 100644 --- a/config/kafka.js +++ b/config/kafka.js @@ -8,7 +8,6 @@ //dependencies const kafka = require('kafka-node'); -const PROGRAM_USERS_JOINED_TOPIC = process.env.PROGRAM_USERS_JOINED_TOPIC; /** * Kafka configurations. diff --git a/envVariables.js b/envVariables.js index b4e3f14d..64af7b67 100644 --- a/envVariables.js +++ b/envVariables.js @@ -203,6 +203,10 @@ let enviromentVariables = { "value" : "ON" } }, + "PROGRAM_USERS_JOINED_TOPIC" : { + "message" : "OFF/TOPIC_NAME", + "optional" : false + } } let success = true; diff --git a/generics/kafka/producers.js b/generics/kafka/producers.js index 2a62bcf9..9f660e12 100644 --- a/generics/kafka/producers.js +++ b/generics/kafka/producers.js @@ -7,7 +7,7 @@ // Dependencies const kafkaCommunicationsOnOff = process.env.KAFKA_COMMUNICATIONS_ON_OFF; -const programUsersSubmissionTopic = (process.env.PROGRAM_USERS_JOINED_TOPIC && process.env.PROGRAM_USERS_JOINED_TOPIC != "OFF") ? process.env.PROGRAM_USERS_JOINED_TOPIC : "sl-improvement-project-submission-dev"; +const programUsersSubmissionTopic = (process.env.PROGRAM_USERS_JOINED_TOPIC != "OFF") ? process.env.PROGRAM_USERS_JOINED_TOPIC : `${process.env.APPLICATION_ENV}.programuser.info`; /** * Push program users to kafka. From 9363f2ede1169aa3fa9bf6a5aba2d13c8bc80fe5 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 10 Apr 2023 12:59:13 +0530 Subject: [PATCH 286/331] program join condition combined && fn signature updated : Review changes --- module/programs/helper.js | 50 +++++++++++++++++++-------------------- module/users/helper.js | 1 + 2 files changed, 26 insertions(+), 25 deletions(-) diff --git a/module/programs/helper.js b/module/programs/helper.js index bca636ea..7732640c 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -1025,7 +1025,7 @@ module.exports = class ProgramsHelper { }, ["_id"] ); - // if user not joined for program + // if user not joined for program. we have add more key values to programUsersData if ( !programUsersDetails.length > 0 ) { // Fetch user profile information by calling sunbird's user read api. // !Important check specific fields of userProfile. @@ -1056,36 +1056,36 @@ module.exports = class ProgramsHelper { programUsersData['appInformation.appVersion'] = appVersion; } update['$set'] = programUsersData; - } - - //For internal calls add consent using sunbird api - if( callConsetAPIOnBehalfOfUser && !programUsersDetails.length > 0 && programData[0].hasOwnProperty('requestForPIIConsent') && programData[0].requestForPIIConsent === true ){ - if( !programData[0].rootOrganisations || !programData[0].rootOrganisations.length > 0 ) { - throw { - message: constants.apiResponses.PROGRAM_JOIN_FAILED, - status: httpStatusCode.bad_request.status + + //For internal calls add consent using sunbird api + if( callConsetAPIOnBehalfOfUser && programData[0].hasOwnProperty('requestForPIIConsent') && programData[0].requestForPIIConsent === true ){ + if( !programData[0].rootOrganisations || !programData[0].rootOrganisations.length > 0 ) { + throw { + message: constants.apiResponses.PROGRAM_JOIN_FAILED, + status: httpStatusCode.bad_request.status + } } - } - let userConsentRequestBody = { - "request": { - "consent": { - "status": constants.common.REVOKED, - "userId": userProfile.data.response.id, - "consumerId": programData[0].rootOrganisations[0], - "objectId": programId, - "objectType": constants.common.PROGRAM + let userConsentRequestBody = { + "request": { + "consent": { + "status": constants.common.REVOKED, + "userId": userProfile.data.response.id, + "consumerId": programData[0].rootOrganisations[0], + "objectId": programId, + "objectType": constants.common.PROGRAM + } } } - } - let consentResponse = await userService.setUserConsent(userToken, userConsentRequestBody) - if(!consentResponse.success){ - throw { - message: constants.apiResponses.PROGRAM_JOIN_FAILED, - status: httpStatusCode.bad_request.status + let consentResponse = await userService.setUserConsent(userToken, userConsentRequestBody) + if(!consentResponse.success){ + throw { + message: constants.apiResponses.PROGRAM_JOIN_FAILED, + status: httpStatusCode.bad_request.status + } } } } - + //create or update query const query = { programId: programId, diff --git a/module/users/helper.js b/module/users/helper.js index 8cb94146..37f862b3 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -619,6 +619,7 @@ module.exports = class UsersHelper { * @param {String} pageNo - Page number. * @param {String} pageSize - Page size. * @param {String} searchText - Search text. + * @param {String} userId - User Id. * @returns {Array} - Get user targeted programs. */ From 5272ee1e387d646279566135e5fbbe5ac86509fc Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Mon, 10 Apr 2023 14:34:10 +0530 Subject: [PATCH 287/331] Added all data source and All types of solutions --- controllers/v1/solutions.js | 3 ++ controllers/v1/user-extension.js | 9 +++--- ...Rxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA | 3 ++ test.js | 32 +++++++++++++++++++ 4 files changed, 43 insertions(+), 4 deletions(-) create mode 100644 keycloak-public-keys/GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA create mode 100644 test.js diff --git a/controllers/v1/solutions.js b/controllers/v1/solutions.js index 1a7bf8a5..215297c9 100644 --- a/controllers/v1/solutions.js +++ b/controllers/v1/solutions.js @@ -1033,6 +1033,9 @@ module.exports = class Solutions extends Abstract { * @returns {JSON} */ + // End Point is Deprecated This API is moved to Reports Services. + + // async read(req) { // return new Promise(async (resolve, reject) => { // try { diff --git a/controllers/v1/user-extension.js b/controllers/v1/user-extension.js index 02b1aefa..421fd568 100644 --- a/controllers/v1/user-extension.js +++ b/controllers/v1/user-extension.js @@ -307,13 +307,14 @@ module.exports = class UserExtension extends Abstract { **/ read(req){ return new Promise(async (resolve, reject) => { - let userInformation = await userExtensionsHelperV2.userExtensionDocument({ + let body = { userId: req.userDetails.userId, - "platformRoles.code" : { $in : ["PROGRAM_MANAGER","PROGRAM_DESIGNER"]}, status: constants.common.ACTIVE, isDeleted: false - }, { _id: 1, "platformRoles.programs" :1}); - + } + console.log(JSON.stringify(body)) + let userInformation = await userExtensionsHelperV2.userExtensionDocument(body, { _id: 1, "platformRoles.programs" :1,"platformRoles.code":1}); + console.log(JSON.stringify(userInformation)) if ( !userInformation ) { return resolve({ status: httpStatusCode.bad_request.status, diff --git a/keycloak-public-keys/GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA b/keycloak-public-keys/GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA new file mode 100644 index 00000000..44c17f6c --- /dev/null +++ b/keycloak-public-keys/GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA @@ -0,0 +1,3 @@ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoRbRlp/1x0h5a9Rb3E7+nU17mdnU1Grv2/a6ixhdBr1f9mjKEn7F/5eIfCQL3H82stxZyskeWaetL1mNJkAHFcJx+03DoKnGP6K+PZ3Svbw67ehgqyp+OozZCNXHzrM1DUVpvhYgsnvkqm+E1QyrsmrghSE+bAHqJep4S/70z12t8rwMNB6OxcbhrHBU93TxszxHHLZL9eaa2DCwGsTbYml0V2vFPsN4HUhXtnht9uoC2bjAXyBsrSNy/aoCsoI0erV8Vyw2FKfwEGBDFROjcWhKOdwb36TmEDf+g4OBSqAhEyewhTwcP7ESpjhyA3Ae1cH9cKOBmQTU+OmzS89h8QIDAQAB +-----END PUBLIC KEY----- diff --git a/test.js b/test.js new file mode 100644 index 00000000..e85f9b1a --- /dev/null +++ b/test.js @@ -0,0 +1,32 @@ +let data = { + "_id": "6233462840df0f000797a997", + "platformRoles": [ + { + "code": "PROGRAM_MANAGER", + "programs": [ + "607d320de9cce45e22ce90c0", + "61a605e20f65b90007901b9c", + "6124984e5435a115cac9f120", + "61dd77a459e49a00074aecae", + "61558efa27e9cd00077530b5" + ] + }, + { + "code": "PROGRAM_DESIGNER", + "programs": [ + "601429016a1ef53356b1d714", + "607d320de9cce45e22ce90c0", + "62034f90841a270008e82e46", + "6124984e5435a115cac9f120", + "61dd77a459e49a00074aecae", + "62611820aac5a90007683503", + "6319a4d53c40dd000978dacb", + "63a42786c0b15a0009f0505e", + "6387060c4d4db900095be3f5" + ] + } + ] + } + + + console.log(data.platformRoles === "PROGRAM_DESIGNER") \ No newline at end of file From b118c79fe2f2b0b297a33a5e98dce8abb691c15d Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Mon, 10 Apr 2023 14:38:10 +0530 Subject: [PATCH 288/331] Resolved all comments --- controllers/v1/user-extension.js | 8 ++--- ...Rxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA | 3 -- test.js | 32 ------------------- 3 files changed, 3 insertions(+), 40 deletions(-) delete mode 100644 keycloak-public-keys/GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA delete mode 100644 test.js diff --git a/controllers/v1/user-extension.js b/controllers/v1/user-extension.js index 421fd568..4e6db435 100644 --- a/controllers/v1/user-extension.js +++ b/controllers/v1/user-extension.js @@ -307,14 +307,12 @@ module.exports = class UserExtension extends Abstract { **/ read(req){ return new Promise(async (resolve, reject) => { - let body = { + let userInformation = await userExtensionsHelperV2.userExtensionDocument( { userId: req.userDetails.userId, status: constants.common.ACTIVE, isDeleted: false - } - console.log(JSON.stringify(body)) - let userInformation = await userExtensionsHelperV2.userExtensionDocument(body, { _id: 1, "platformRoles.programs" :1,"platformRoles.code":1}); - console.log(JSON.stringify(userInformation)) + }, { _id: 1, "platformRoles.programs" :1,"platformRoles.code":1}); + if ( !userInformation ) { return resolve({ status: httpStatusCode.bad_request.status, diff --git a/keycloak-public-keys/GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA b/keycloak-public-keys/GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA deleted file mode 100644 index 44c17f6c..00000000 --- a/keycloak-public-keys/GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA +++ /dev/null @@ -1,3 +0,0 @@ ------BEGIN PUBLIC KEY----- -MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoRbRlp/1x0h5a9Rb3E7+nU17mdnU1Grv2/a6ixhdBr1f9mjKEn7F/5eIfCQL3H82stxZyskeWaetL1mNJkAHFcJx+03DoKnGP6K+PZ3Svbw67ehgqyp+OozZCNXHzrM1DUVpvhYgsnvkqm+E1QyrsmrghSE+bAHqJep4S/70z12t8rwMNB6OxcbhrHBU93TxszxHHLZL9eaa2DCwGsTbYml0V2vFPsN4HUhXtnht9uoC2bjAXyBsrSNy/aoCsoI0erV8Vyw2FKfwEGBDFROjcWhKOdwb36TmEDf+g4OBSqAhEyewhTwcP7ESpjhyA3Ae1cH9cKOBmQTU+OmzS89h8QIDAQAB ------END PUBLIC KEY----- diff --git a/test.js b/test.js deleted file mode 100644 index e85f9b1a..00000000 --- a/test.js +++ /dev/null @@ -1,32 +0,0 @@ -let data = { - "_id": "6233462840df0f000797a997", - "platformRoles": [ - { - "code": "PROGRAM_MANAGER", - "programs": [ - "607d320de9cce45e22ce90c0", - "61a605e20f65b90007901b9c", - "6124984e5435a115cac9f120", - "61dd77a459e49a00074aecae", - "61558efa27e9cd00077530b5" - ] - }, - { - "code": "PROGRAM_DESIGNER", - "programs": [ - "601429016a1ef53356b1d714", - "607d320de9cce45e22ce90c0", - "62034f90841a270008e82e46", - "6124984e5435a115cac9f120", - "61dd77a459e49a00074aecae", - "62611820aac5a90007683503", - "6319a4d53c40dd000978dacb", - "63a42786c0b15a0009f0505e", - "6387060c4d4db900095be3f5" - ] - } - ] - } - - - console.log(data.platformRoles === "PROGRAM_DESIGNER") \ No newline at end of file From 1bb9c17f0df7e1faee2308b416ebe7fddaa8ff82 Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Mon, 10 Apr 2023 14:42:03 +0530 Subject: [PATCH 289/331] Resolved all comments --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 32642b16..844944c2 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,7 @@ }, "scripts": { "test": "mocha --timeout 10000", - "start": "node app.js", + "start": "app.js", "dev": "nodemon app.js", "coverage": " nyc --reporter=lcov mocha --timeout 10000 test --exit" }, From d1ae329eb2cbf1ecb6d97ad6d2c56a7b7348211b Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Mon, 10 Apr 2023 14:42:43 +0530 Subject: [PATCH 290/331] Resolved all comments --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 844944c2..32642b16 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,7 @@ }, "scripts": { "test": "mocha --timeout 10000", - "start": "app.js", + "start": "node app.js", "dev": "nodemon app.js", "coverage": " nyc --reporter=lcov mocha --timeout 10000 test --exit" }, From c7c7afc38e71cd15072dcbf369115eb0c1c050ad Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 10 Apr 2023 15:16:58 +0530 Subject: [PATCH 291/331] programs query change --- .../setProgramsStartDateAndEndDate.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/migrations/programs-startDate-EndDate-6.0/setProgramsStartDateAndEndDate.js b/migrations/programs-startDate-EndDate-6.0/setProgramsStartDateAndEndDate.js index 90c2542d..ee5ac0cb 100644 --- a/migrations/programs-startDate-EndDate-6.0/setProgramsStartDateAndEndDate.js +++ b/migrations/programs-startDate-EndDate-6.0/setProgramsStartDateAndEndDate.js @@ -13,8 +13,7 @@ let url = mongoUrl.split(dbName)[0]; // get all active programs with createdAt value let collectionDocs = await db.collection("programs").find({ status: "active", - createdAt: {"$exists": true}, - isAPrivateProgram: false // removing private program from the set. + createdAt: {"$exists": true} }).project({_id:1,createdAt:1}).toArray(); //reduce array to small chunks From 7a341e4494dbff3b6a69c7b0518f12b4238c3e56 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Tue, 11 Apr 2023 09:34:09 +0530 Subject: [PATCH 292/331] console added --- .../setProgramsStartDateAndEndDate.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/migrations/programs-startDate-EndDate-6.0/setProgramsStartDateAndEndDate.js b/migrations/programs-startDate-EndDate-6.0/setProgramsStartDateAndEndDate.js index ee5ac0cb..d278c07b 100644 --- a/migrations/programs-startDate-EndDate-6.0/setProgramsStartDateAndEndDate.js +++ b/migrations/programs-startDate-EndDate-6.0/setProgramsStartDateAndEndDate.js @@ -13,7 +13,7 @@ let url = mongoUrl.split(dbName)[0]; // get all active programs with createdAt value let collectionDocs = await db.collection("programs").find({ status: "active", - createdAt: {"$exists": true} + createdAt: {"$exists": true}, }).project({_id:1,createdAt:1}).toArray(); //reduce array to small chunks From 1f8d8129ce15545d02f6f1b383ba942fbf1bd182 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Tue, 11 Apr 2023 11:03:22 +0530 Subject: [PATCH 293/331] console and outpu log added --- .../setProgramsStartDateAndEndDate.js | 23 ++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/migrations/programs-startDate-EndDate-6.0/setProgramsStartDateAndEndDate.js b/migrations/programs-startDate-EndDate-6.0/setProgramsStartDateAndEndDate.js index d278c07b..51afbbbe 100644 --- a/migrations/programs-startDate-EndDate-6.0/setProgramsStartDateAndEndDate.js +++ b/migrations/programs-startDate-EndDate-6.0/setProgramsStartDateAndEndDate.js @@ -4,12 +4,15 @@ let MongoClient = require("mongodb").MongoClient; let mongoUrl = process.env.MONGODB_URL; let dbName = mongoUrl.split("/").pop(); let url = mongoUrl.split(dbName)[0]; +var fs = require('fs'); (async () => { let connection = await MongoClient.connect(url, { useNewUrlParser: true }); let db = connection.db(dbName); + let updatedProgramIds = []; try { + console.log("-----------------------Started----------------------"); // get all active programs with createdAt value let collectionDocs = await db.collection("programs").find({ status: "active", @@ -37,11 +40,25 @@ let url = mongoUrl.split(dbName)[0]; { '_id': id }, { $set: { startDate: startDate, endDate : endDate} } ); + console.log("program Updated : ",id) + updatedProgramIds.push(id) } } - console.log("-----------------------Finished----------------------") - console.log(" finished programs updation of startDate and endDate") - console.log("-----------------------------------------------------") + //write updated program ids to file + fs.writeFile( + 'updatedProgramIds.json', + + JSON.stringify(updatedProgramIds), + + function (err) { + if (err) { + console.error('Crap happens'); + } + } + ); + console.log("-----------------------Finished----------------------"); + console.log(" finished programs updation of startDate and endDate"); + console.log("-----------------------------------------------------"); connection.close(); } catch (error) { From fea181dcb404404b895d8eebf0cdc19559547f00 Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Tue, 11 Apr 2023 11:54:52 +0530 Subject: [PATCH 294/331] Resolving all the comments to PR ED-523 --- .gitignore | 1 + controllers/v1/programs.js | 4 ++++ controllers/v1/users.js | 3 ++- models/programs.js | 3 ++- module/programs/helper.js | 27 +++++++++++++++------------ module/users/helper.js | 17 ++++++++++------- 6 files changed, 34 insertions(+), 21 deletions(-) diff --git a/.gitignore b/.gitignore index f9092570..16dd564f 100644 --- a/.gitignore +++ b/.gitignore @@ -72,3 +72,4 @@ public/* *.DS_Store package-lock.json +keycloak-public-keys/ diff --git a/controllers/v1/programs.js b/controllers/v1/programs.js index 9992ab31..58bece5e 100644 --- a/controllers/v1/programs.js +++ b/controllers/v1/programs.js @@ -112,6 +112,8 @@ module.exports = class Programs extends Abstract { "entities" : ["5d6609ef81a57a6173a79e78"], "roles" : ["HM"] } + "startDate" : "2023-04-06T09:35:00.000Z", + "endDate" : ""2024-04-06T09:35:00.000Z" // optional } * @apiParamExample {json} Response: { @@ -192,6 +194,8 @@ module.exports = class Programs extends Abstract { "entities" : ["5d6609ef81a57a6173a79e78"], "roles" : ["HM"] } + "startDate" : "2023-04-06T09:35:00.000Z", + "endDate" : ""2024-04-06T09:35:00.000Z" // optional } * @apiParamExample {json} Response: { diff --git a/controllers/v1/users.js b/controllers/v1/users.js index 813416ff..d0dea414 100644 --- a/controllers/v1/users.js +++ b/controllers/v1/users.js @@ -255,7 +255,8 @@ module.exports = class Users extends Abstract { "count": 3, "programName": "TEST_SCOPE_PROGRAM", "programId": "5ff438b04698083dbfab7284", - "description": "View and participate in educational programs active in your location and designed for your role." + "description": "View and participate in educational programs active in your location and designed for your role.", + "programEndDate": "2023-04-06T09:35:00.000Z" }} **/ diff --git a/models/programs.js b/models/programs.js index c9998a3a..6211f1c2 100644 --- a/models/programs.js +++ b/models/programs.js @@ -24,7 +24,8 @@ module.exports = { }, endDate: { type : Date, - index : true + index : true, + require: true }, resourceType: [String], language: [String], diff --git a/module/programs/helper.js b/module/programs/helper.js index d32e4967..bd6790be 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -11,7 +11,7 @@ const entityTypesHelper = require(MODULES_BASE_PATH + "/entityTypes/helper"); const entitiesHelper = require(MODULES_BASE_PATH + "/entities/helper"); const userRolesHelper = require(MODULES_BASE_PATH + "/user-roles/helper"); const userService = require(ROOT_PATH + "/generics/services/users"); - +let _ = require("lodash"); /** * ProgramsHelper * @class @@ -83,16 +83,10 @@ module.exports = class ProgramsHelper { data.startDate = new Date(data.startDate) data.endDate = data.startDate.setFullYear( data.startDate.getFullYear(), data.startDate.getMonth() + 12 ); } + + let programData = { - "externalId" : data.externalId, - "name" : data.name, - "description" : data.description , - "owner" : data.userId, - "createdBy" : data.userId, - "updatedBy" : data.userId, - "startDate" : data.startDate, - "endDate" : data.endDate, "isDeleted" : false, "status" : "active", "resourceType" : [ @@ -110,10 +104,19 @@ module.exports = class ProgramsHelper { "quality" : 10 }, "components" : [], - "isAPrivateProgram" : data.isAPrivateProgram ? data.isAPrivateProgram : false + } - - + _.assign(programData, { + "externalId" : data.externalId, + "name" : data.name, + "description" : data.description , + "owner" : data.userId, + "createdBy" : data.userId, + "updatedBy" : data.userId, + "startDate" : data.startDate, + "endDate" : data.endDate, + "isAPrivateProgram" : data.isAPrivateProgram ? data.isAPrivateProgram : false + }); let program = await database.models.programs.create( programData ); diff --git a/module/users/helper.js b/module/users/helper.js index f5d37d81..10933774 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -113,6 +113,8 @@ module.exports = class UsersHelper { constants.common.ACTIVE, duplicateProgram.description, userId, + duplicateProgram.startDate, + duplicateProgram.endDate, userId ); @@ -135,7 +137,9 @@ module.exports = class UsersHelper { data.programDescription ? data.programDescription : data.programName, - userId + userId, + duplicateProgram.startDate, + duplicateProgram.endDate ); userPrivateProgram = await programsHelper.create(programData); @@ -577,12 +581,9 @@ module.exports = class UsersHelper { programId: programId, description: constants.common.TARGETED_SOLUTION_TEXT, data: mergedData, - count: totalCount + count: totalCount, + programEndDate = programData[0].endDate }; - - if(programData[0].hasOwnProperty("endDate")){ - result.programEndDate = programData[0].endDate; - } return resolve({ message: constants.apiResponses.PROGRAM_SOLUTIONS_FETCHED, success: true, @@ -925,7 +926,7 @@ module.exports = class UsersHelper { * @returns {Object} - program creation data */ -function _createProgramData(name, externalId, isAPrivateProgram, status, description, userId, createdBy = "") { +function _createProgramData(name, externalId, isAPrivateProgram, status, description, userId, startDate, endDate, createdBy = "") { let programData = {}; programData.name = name; @@ -935,6 +936,8 @@ function _createProgramData(name, externalId, isAPrivateProgram, status, descrip programData.description = description; programData.userId = userId; programData.createdBy = createdBy; + programData.startDate = startDate; + programData.endDate = endDate; return programData; } From 938eba45d02883c38307b5e2fecc38199abcdb09 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Tue, 11 Apr 2023 13:53:16 +0530 Subject: [PATCH 295/331] review resolve : env changes , fn added to determine program joined --- .env.sample | 2 +- envVariables.js | 4 ++++ module/programUsers/helper.js | 34 ++++++++++++++++++++++++++++++++++ module/users/helper.js | 20 +++----------------- 4 files changed, 42 insertions(+), 18 deletions(-) diff --git a/.env.sample b/.env.sample index e12dd9e1..d736d733 100644 --- a/.env.sample +++ b/.env.sample @@ -54,5 +54,5 @@ OCI_BUCKET_ENDPOINT = 'https://pmt5.compat.storage.ap-h1.oraclecloud.com' # KAFKA Configurations KAFKA_COMMUNICATIONS_ON_OFF = "ON/OFF" // Kafka enable or disable communication flag KAFKA_URL = "100.0.0.1:9092" // IP address of kafka server with port without HTTP -KAFKA_GROUP_ID = "core" // Kafka group id +KAFKA_GROUP_ID = "mlcore" // Kafka group id PROGRAM_USERS_JOINED_TOPIC = "dev.programuser.info" // Kafka submission topic for pushing program joined user's data \ No newline at end of file diff --git a/envVariables.js b/envVariables.js index 64af7b67..10e78659 100644 --- a/envVariables.js +++ b/envVariables.js @@ -203,6 +203,10 @@ let enviromentVariables = { "value" : "ON" } }, + "KAFKA_GROUP_ID" : { + "message" : "Required kafka group id", + "optional" : false + }, "PROGRAM_USERS_JOINED_TOPIC" : { "message" : "OFF/TOPIC_NAME", "optional" : false diff --git a/module/programUsers/helper.js b/module/programUsers/helper.js index 4f4d010b..39f15f1b 100644 --- a/module/programUsers/helper.js +++ b/module/programUsers/helper.js @@ -118,4 +118,38 @@ module.exports = class ProgramUsersHelper { } }); } + + /** + * check if user joined a program or not + * @method + * @name checkForUserJoinedProgram + * @param {String} programId + * @param {String} userId + * @returns {Boolean} - true/false. + */ + + static checkForUserJoinedProgram( + programId, + userId + ) { + return new Promise(async (resolve, reject) => { + try { + const query = { + userId: userId, + programId: programId + } + + //Check data present in programUsers collection. + let programUsers = await this.programUsersDocuments( + query, + ["_id"] + ); + let joinedProgram = programUsers.length > 0 ? true :false + return resolve(joinedProgram); + + } catch (error) { + return reject(error); + } + }); + } } \ No newline at end of file diff --git a/module/users/helper.js b/module/users/helper.js index 37f862b3..2b68a67d 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -576,23 +576,9 @@ module.exports = class UsersHelper { data: mergedData, count: totalCount }; - - //check programUsers collection for consentForPIIDataSharing - let programUsersData = await programUsersHelper.programUsersDocuments( - { - userId: userId, - programId: programId - }, - ["_id"] - ); - - //if already joined the program - if( programUsersData.length > 0 ) { - result.programJoined = true; - } else { - result.programJoined = false; - } - + //Check data present in programUsers collection. + //checkForUserJoinedProgram will check for data and if its present return true else false. + result.programJoined = await programUsersHelper.checkForUserJoinedProgram(programId,userId); return resolve({ message: constants.apiResponses.PROGRAM_SOLUTIONS_FETCHED, success: true, From b731bb7eb7fc99bcb9bfa4df0c94fd85fd98f7b0 Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Tue, 11 Apr 2023 17:42:38 +0530 Subject: [PATCH 296/331] Removed UserExtensionHelperV2 --- controllers/v1/user-extension.js | 3 +- ...Rxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA | 3 ++ module/solutions/helper.js | 1 - module/user-extension/helperv2.js | 45 ------------------- 4 files changed, 4 insertions(+), 48 deletions(-) create mode 100644 keycloak-public-keys/GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA delete mode 100644 module/user-extension/helperv2.js diff --git a/controllers/v1/user-extension.js b/controllers/v1/user-extension.js index 4e6db435..e5295db0 100644 --- a/controllers/v1/user-extension.js +++ b/controllers/v1/user-extension.js @@ -7,7 +7,6 @@ // Dependencies const userExtensionHelper = require(ROOT_PATH+"/module/user-extension/helper"); -const userExtensionsHelperV2 = require(ROOT_PATH+"/module/user-extension/helperv2"); /** * UserExtension * @class @@ -307,7 +306,7 @@ module.exports = class UserExtension extends Abstract { **/ read(req){ return new Promise(async (resolve, reject) => { - let userInformation = await userExtensionsHelperV2.userExtensionDocument( { + let userInformation = await userExtensionHelper.userExtensionDocument( { userId: req.userDetails.userId, status: constants.common.ACTIVE, isDeleted: false diff --git a/keycloak-public-keys/GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA b/keycloak-public-keys/GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA new file mode 100644 index 00000000..44c17f6c --- /dev/null +++ b/keycloak-public-keys/GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA @@ -0,0 +1,3 @@ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoRbRlp/1x0h5a9Rb3E7+nU17mdnU1Grv2/a6ixhdBr1f9mjKEn7F/5eIfCQL3H82stxZyskeWaetL1mNJkAHFcJx+03DoKnGP6K+PZ3Svbw67ehgqyp+OozZCNXHzrM1DUVpvhYgsnvkqm+E1QyrsmrghSE+bAHqJep4S/70z12t8rwMNB6OxcbhrHBU93TxszxHHLZL9eaa2DCwGsTbYml0V2vFPsN4HUhXtnht9uoC2bjAXyBsrSNy/aoCsoI0erV8Vyw2FKfwEGBDFROjcWhKOdwb36TmEDf+g4OBSqAhEyewhTwcP7ESpjhyA3Ae1cH9cKOBmQTU+OmzS89h8QIDAQAB +-----END PUBLIC KEY----- diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 3dff5b05..ac4744b1 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -12,7 +12,6 @@ const userRolesHelper = require(MODULES_BASE_PATH + "/user-roles/helper"); const surveyService = require(ROOT_PATH + '/generics/services/survey'); const improvementProjectService = require(ROOT_PATH + '/generics/services/improvement-project'); const appsPortalBaseUrl = process.env.APP_PORTAL_BASE_URL + "/" ; -const userExtensionsHelperV2 = require(MODULES_BASE_PATH + "/user-extension/helperv2"); const userService = require(ROOT_PATH + "/generics/services/users"); /** diff --git a/module/user-extension/helperv2.js b/module/user-extension/helperv2.js deleted file mode 100644 index 49de8d84..00000000 --- a/module/user-extension/helperv2.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * name : module//user-extension/helper.js - * author : Priyanka Pradeep - * Date : 22-Apr-2022 - * Description : User extension helper. - */ - - -/** - * UserExtensionHelperV2 - * @class -*/ - -module.exports = class UserExtensionHelperV2 { - - /** - * Get userExtension document based on userid. - * @method - * @name userExtensionDocument - * @name userExtensionDocument - * @param {Object} filterQueryObject - filter query data. - * @param {Object} [projection = {}] - projected data. - * @returns {Promise} returns a promise. - */ - - static userExtensionDocument(filterQueryObject, projection = {}) { - return new Promise(async (resolve, reject) => { - try { - - let userExtensionData = await database.models.userExtension.findOne(filterQueryObject, projection).lean(); - - return resolve(userExtensionData); - - } catch (error) { - return reject(error); - } - }) - - - } -}; - - - - From 13615e078438edbf58a817cb43586d23392e8a8f Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Tue, 11 Apr 2023 17:43:02 +0530 Subject: [PATCH 297/331] Removed UserExtensionHelperV2 --- .../GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 keycloak-public-keys/GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA diff --git a/keycloak-public-keys/GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA b/keycloak-public-keys/GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA deleted file mode 100644 index 44c17f6c..00000000 --- a/keycloak-public-keys/GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA +++ /dev/null @@ -1,3 +0,0 @@ ------BEGIN PUBLIC KEY----- -MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoRbRlp/1x0h5a9Rb3E7+nU17mdnU1Grv2/a6ixhdBr1f9mjKEn7F/5eIfCQL3H82stxZyskeWaetL1mNJkAHFcJx+03DoKnGP6K+PZ3Svbw67ehgqyp+OozZCNXHzrM1DUVpvhYgsnvkqm+E1QyrsmrghSE+bAHqJep4S/70z12t8rwMNB6OxcbhrHBU93TxszxHHLZL9eaa2DCwGsTbYml0V2vFPsN4HUhXtnht9uoC2bjAXyBsrSNy/aoCsoI0erV8Vyw2FKfwEGBDFROjcWhKOdwb36TmEDf+g4OBSqAhEyewhTwcP7ESpjhyA3Ae1cH9cKOBmQTU+OmzS89h8QIDAQAB ------END PUBLIC KEY----- From bfe6e64ac29b114406a155119840d45271fd25e3 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Tue, 11 Apr 2023 20:11:36 +0530 Subject: [PATCH 298/331] Review changes: resourcesStarted key added --- models/programUsers.js | 6 +++--- module/programs/helper.js | 25 +++++++++++++++---------- module/users/helper.js | 5 +++-- 3 files changed, 21 insertions(+), 15 deletions(-) diff --git a/models/programUsers.js b/models/programUsers.js index 1386abd4..b6115dd4 100644 --- a/models/programUsers.js +++ b/models/programUsers.js @@ -11,10 +11,10 @@ module.exports = { required: true, index: true }, - noOfResourcesStarted: { - type:Number, + resourcesStarted: { + type: Boolean, index: true, - default: 0 + default: false }, userProfile: { type : Object, diff --git a/module/programs/helper.js b/module/programs/helper.js index 7732640c..381c7c50 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -994,7 +994,7 @@ module.exports = class ProgramsHelper { static join( programId, data, userId, userToken, appName = "", appVersion = "", callConsetAPIOnBehalfOfUser = false ) { return new Promise(async (resolve, reject) => { try { - + let pushProgramUsersDetailsToKafka = false; //Using programId fetch program details. Also checking the program status in the query. let programData = await this.programDocuments({ _id: programId, @@ -1047,7 +1047,8 @@ module.exports = class ProgramsHelper { programId: programId, userRoleInformation: data.userRoleInformation, userId: userId, - userProfile:userProfile.data.response + userProfile:userProfile.data.response, + resourcesStarted : false } if( appName != "" ) { programUsersData['appInformation.appName'] = appName; @@ -1056,6 +1057,7 @@ module.exports = class ProgramsHelper { programUsersData['appInformation.appVersion'] = appVersion; } update['$set'] = programUsersData; + //For internal calls add consent using sunbird api if( callConsetAPIOnBehalfOfUser && programData[0].hasOwnProperty('requestForPIIConsent') && programData[0].requestForPIIConsent === true ){ @@ -1084,6 +1086,7 @@ module.exports = class ProgramsHelper { } } } + pushProgramUsersDetailsToKafka = true; } //create or update query @@ -1091,12 +1094,12 @@ module.exports = class ProgramsHelper { programId: programId, userId: userId }; - let joinProgram; if ( data.isResource ) { - update['$inc'] = { noOfResourcesStarted : 1 } + update['$set'] = { resourcesStarted : true } } + // add record to programUsers collection - joinProgram = await programUsersHelper.update(query, update, { new:true, upsert:true }); + let joinProgram = await programUsersHelper.update(query, update, { new:true, upsert:true }); if (!joinProgram._id) { throw { @@ -1104,12 +1107,14 @@ module.exports = class ProgramsHelper { status: httpStatusCode.bad_request.status } } - joinProgram.programName = programData[0].name; - joinProgram.programExternalId = programData[0].externalId; - joinProgram.requestForPIIConsent = (programData[0].requestForPIIConsent && programData[0].requestForPIIConsent == true) ? true : false; + if ( pushProgramUsersDetailsToKafka ) { + joinProgram.programName = programData[0].name; + joinProgram.programExternalId = programData[0].externalId; + joinProgram.requestForPIIConsent = (programData[0].requestForPIIConsent && programData[0].requestForPIIConsent == true) ? true : false; - // push programUsers details to kafka - await kafkaProducersHelper.pushProgramUsersToKafka(joinProgram); + // push programUsers details to kafka + await kafkaProducersHelper.pushProgramUsersToKafka(joinProgram); + } return resolve({ message: constants.apiResponses.JOINED_PROGRAM, diff --git a/module/users/helper.js b/module/users/helper.js index 2b68a67d..920b54d5 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -686,10 +686,11 @@ module.exports = class UsersHelper { userId: userId, programId: nontargetedJoinedPrograms.data[index]._id }, - ["noOfResourcesStarted"] + ["resourcesStarted"] ); + // need to pass resourcesStarted with nontargetedJoinedPrograms data if ( programUsersData.length > 0 ) { - nontargetedJoinedPrograms.data[index].solutions = (programUsersData[0].noOfResourcesStarted) ? programUsersData[0].noOfResourcesStarted : 0; + nontargetedJoinedPrograms.data[index].resourcesStarted = (programUsersData[0].resourcesStarted) ? programUsersData[0].resourcesStarted : false; } targetedPrograms.data.data.push(nontargetedJoinedPrograms.data[index]); From 455c145e11b097d29e95c8b170c2c1b64813db98 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Wed, 12 Apr 2023 14:10:54 +0530 Subject: [PATCH 299/331] fn used for programJoined logic --- module/solutions/helper.js | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 248c5327..5c35a7c8 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -1933,16 +1933,10 @@ module.exports = class SolutionsHelper { templateOrQuestionDetails.result.rootOrganisations = (programData[0].rootOrganisations) ? programData[0].rootOrganisations : []; templateOrQuestionDetails.result.requestForPIIConsent = (programData[0].requestForPIIConsent) ? programData[0].requestForPIIConsent : false; } + //Check data present in programUsers collection. + //checkForUserJoinedProgram will check for data and if its present return true else false. + templateOrQuestionDetails.result.programJoined = await programUsersHelper.checkForUserJoinedProgram(solutionData.programId,userId); - let programUsersData = await programUsersHelper.programUsersDocuments( - { - userId: userId, - programId: solutionData.programId - }, - ["_id"] - ); - templateOrQuestionDetails.result.programJoined = ( programUsersData.length > 0 ) ? true : false; - return resolve(templateOrQuestionDetails); } catch (error) { From 2c0b15b7ef8ef91b66a0670bd1962c91ba857b50 Mon Sep 17 00:00:00 2001 From: VISHNUDAS <95604247+VISHNUDAS-tunerlabs@users.noreply.github.com> Date: Wed, 12 Apr 2023 14:19:50 +0530 Subject: [PATCH 300/331] fn used for programJoin logic --- module/solutions/helper.js | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/module/solutions/helper.js b/module/solutions/helper.js index d4ac6654..8f285f0f 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -2011,14 +2011,9 @@ module.exports = class SolutionsHelper { templateOrQuestionDetails.result.requestForPIIConsent = (programData[0].requestForPIIConsent) ? programData[0].requestForPIIConsent : false; } - let programUsersData = await programUsersHelper.programUsersDocuments( - { - userId: userId, - programId: solutionData.programId - }, - ["_id"] - ); - templateOrQuestionDetails.result.programJoined = ( programUsersData.length > 0 ) ? true : false; + //Check data present in programUsers collection. + //checkForUserJoinedProgram will check for data and if its present return true else false. + templateOrQuestionDetails.result.programJoined = await programUsersHelper.checkForUserJoinedProgram(solutionData.programId,userId); return resolve(templateOrQuestionDetails); @@ -2159,4 +2154,4 @@ function _generateLink(appsPortalBaseUrl, prefix, solutionLink, solutionType) { return link; -} \ No newline at end of file +} From 675dbbccba5fb90f52e09678b993d11540d64407 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 14 Apr 2023 00:22:34 +0530 Subject: [PATCH 301/331] presents of programId in solution checked --- module/solutions/helper.js | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/module/solutions/helper.js b/module/solutions/helper.js index fdc0ffc1..e7dd9b3f 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -2001,15 +2001,19 @@ module.exports = class SolutionsHelper { } } - // add ["rootOrganisations","requestForPIIConsent","programJoined"] values to response. Based on these values front end calls PII consent - let programData = await programsHelper.programDocuments({ - _id : solutionData.programId - },["rootOrganisations","requestForPIIConsent"]); - if ( programData.length > 0 ) { - templateOrQuestionDetails.result.rootOrganisations = (programData[0].rootOrganisations) ? programData[0].rootOrganisations : []; - templateOrQuestionDetails.result.requestForPIIConsent = (programData[0].requestForPIIConsent) ? programData[0].requestForPIIConsent : false; + if ( solutionData.programId ) { + // add ["rootOrganisations","requestForPIIConsent","programJoined"] values to response. Based on these values front end calls PII consent + let programData = await programsHelper.programDocuments({ + _id : solutionData.programId + },["rootOrganisations","requestForPIIConsent"]); + + if ( programData.length > 0 ) { + templateOrQuestionDetails.result.rootOrganisations = (programData[0].rootOrganisations) ? programData[0].rootOrganisations : []; + templateOrQuestionDetails.result.requestForPIIConsent = (programData[0].requestForPIIConsent) ? programData[0].requestForPIIConsent : false; + } } + //Check data present in programUsers collection. //checkForUserJoinedProgram will check for data and if its present return true else false. templateOrQuestionDetails.result.programJoined = await programUsersHelper.checkForUserJoinedProgram(solutionData.programId,userId); From 475dec313151ff80cc8815fa234baec90261d143 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 14 Apr 2023 08:19:07 +0530 Subject: [PATCH 302/331] user/programs fn changes added --- generics/helpers/utils.js | 14 ++- module/programs/helper.js | 126 ++++++++++++++++++++----- module/users/helper.js | 190 +++++++++++++++----------------------- 3 files changed, 190 insertions(+), 140 deletions(-) diff --git a/generics/helpers/utils.js b/generics/helpers/utils.js index fed2c4a7..bfcefbd1 100644 --- a/generics/helpers/utils.js +++ b/generics/helpers/utils.js @@ -273,6 +273,17 @@ function checkIfStringIsNumber(str) { return /^[0-9]+$/.test(str); } +/** + * array of object to array objectId + * @function + * @name arrayOfObjectToArrayOfObjectId + * @returns {Boolean} returns a Boolean value true/false +*/ + +function arrayOfObjectToArrayOfObjectId(ids) { + return ids.map(obj => obj._id); +} + module.exports = { camelCaseToTitleCase : camelCaseToTitleCase, lowerCase : lowerCase, @@ -290,5 +301,6 @@ module.exports = { md5Hash : md5Hash, filterLocationIdandCode : filterLocationIdandCode, arrayIdsTobjectIds : arrayIdsTobjectIds, - checkIfStringIsNumber : checkIfStringIsNumber + checkIfStringIsNumber : checkIfStringIsNumber, + arrayOfObjectToArrayOfObjectId : arrayOfObjectToArrayOfObjectId }; diff --git a/module/programs/helper.js b/module/programs/helper.js index b8abad69..d57285af 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -375,17 +375,18 @@ module.exports = class ProgramsHelper { * @method * @name list * @param {Number} pageNo - page no. - * @param {Nmber} pageSize - page size. + * @param {Number} pageSize - page size. * @param {String} searchText - text to search. + * @param {Object} filter - filter. + * @param {Array} projection - projection. * @returns {Object} - Programs list. */ - static list(pageNo,pageSize,searchText,filter = {},projection) { + static list(pageNo="",pageSize="",searchText,filter = {},projection) { return new Promise( async (resolve, reject) => { try { - let programDocument = []; let matchQuery = { status : constants.common.ACTIVE }; @@ -434,10 +435,17 @@ module.exports = class ProgramsHelper { facetQuery["$facet"]["totalCount"] = [ { "$count": "count" } ]; - facetQuery["$facet"]["data"] = [ - { $skip: pageSize * (pageNo - 1) }, - { $limit: pageSize } - ]; + + if ( pageSize === "" && pageNo === "" ) { + facetQuery["$facet"]["data"] = [ + { $skip: 0 } + ]; + } else { + facetQuery["$facet"]["data"] = [ + { $skip: pageSize * (pageNo - 1) }, + { $limit: pageSize } + ]; + } let projection2 = {}; projection2["$project"] = { @@ -451,7 +459,6 @@ module.exports = class ProgramsHelper { let programDocuments = await database.models.programs.aggregate(programDocument); - return resolve({ success : true, message : constants.apiResponses.PROGRAM_LIST, @@ -469,7 +476,7 @@ module.exports = class ProgramsHelper { }) } - /** + /** * List of programs based on role and location. * @method * @name forUserRoleAndLocation @@ -480,7 +487,7 @@ module.exports = class ProgramsHelper { * @returns {JSON} - List of programs based on role and location. */ - static forUserRoleAndLocation( bodyData, pageSize, pageNo,searchText = "" ) { + static forUserRoleAndLocation( bodyData, pageSize, pageNo, searchText = "", projection ) { return new Promise(async (resolve, reject) => { @@ -495,21 +502,72 @@ module.exports = class ProgramsHelper { } queryData.data.startDate ={"$lte": new Date()} queryData.data.endDate ={"$gte": new Date()} + let targetedPrograms = await this.list( pageNo, pageSize, searchText, queryData.data, - ["name", "externalId","components","metaInformation"] + projection + ); + + return resolve({ + success: true, + message: constants.apiResponses.TARGETED_PROGRAMS_FETCHED, + data: targetedPrograms.data + }); + + } catch (error) { + + return resolve({ + success : false, + message : error.message, + data : {} + }); + + } + + }) + } + + /** + * List of programs related to a user. + * @method + * @name userRelatedProgramsDetails + * @param {Array} programIds - program Ids. + * @param {String} pageSize - Page size. + * @param {String} pageNo - Page no. + * @param {String} searchText - search text. + * @param {Array} projection - projection. + * @param {String} userId - userId. + * @returns {JSON} - List of programs related to the user. + */ + + static userRelatedProgramsDetails( programIds, pageNo, pageSize, searchText = "", projection, userId ) { + return new Promise(async (resolve, reject) => { + try { + let findQuery = { + "_id": { "$in" : programIds }, + } + + let userRelatedProgramsDetails = await this.list( + pageNo, + pageSize, + searchText, + findQuery, + projection ); - - if ( targetedPrograms.success && targetedPrograms.data && targetedPrograms.data.data.length > 0) { + + // add solutions and resourcesStarted + if ( userRelatedProgramsDetails.success && userRelatedProgramsDetails.data && userRelatedProgramsDetails.data.data.length > 0 ) { let componentsIds = []; - targetedPrograms.data.data.forEach(targetedProgram => { - if( targetedProgram.components.length > 0 ) { - componentsIds = componentsIds.concat(targetedProgram.components); + let userRelatedProgramIds = []; + userRelatedProgramsDetails.data.data.forEach(program => { + if( program.components.length > 0 ) { + componentsIds = componentsIds.concat(program.components); } + userRelatedProgramIds.push(program._id); }); let solutions = await solutionsHelper.solutionDocuments({ @@ -521,26 +579,48 @@ module.exports = class ProgramsHelper { const solutionsIds = [] solutions.forEach(solution => solutionsIds.push(solution._id.toString())); - targetedPrograms.data.data.forEach(targetedProgram => { + userRelatedProgramsDetails.data.data.forEach(program => { - if( targetedProgram.components.length > 0 ) { + if( program.components.length > 0 ) { let countSolutions = 0; - targetedProgram.components.forEach(component => { + program.components.forEach(component => { if (solutionsIds.includes(component.toString())) { countSolutions++; } }); - targetedProgram.solutions = countSolutions; - delete targetedProgram.components; + program.solutions = countSolutions; + delete program.components; } }); + + const programUsersDetails = await programUsersHelper.programUsersDocuments( + { + userId: userId, + programId: { "$in" : userRelatedProgramIds } + }, + ["programId","resourcesStarted"] + ); + + // add resourcesStarted key to response if its available + if( programUsersDetails.length > 0 ) { + for ( let programUsersIndex = 0; programUsersIndex < programUsersDetails.length; programUsersIndex++ ) { + if (programUsersDetails[programUsersIndex].hasOwnProperty("resourcesStarted")) { + for ( let programIndex = 0; programIndex < userRelatedProgramsDetails.data.data.length; programIndex++ ) { + if( programUsersDetails[programUsersIndex].programId == (userRelatedProgramsDetails.data.data[programIndex]._id).toString() ) { + userRelatedProgramsDetails.data.data[programIndex].resourcesStarted = programUsersDetails[programUsersIndex].resourcesStarted; + } + } + } + + } + } } return resolve({ success: true, - message: constants.apiResponses.TARGETED_PROGRAMS_FETCHED, - data: targetedPrograms.data + message: constants.apiResponses.PROGRAMS_FETCHED, + data: userRelatedProgramsDetails.data }); } catch (error) { diff --git a/module/users/helper.js b/module/users/helper.js index 5503a6f0..9ab36ae0 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -583,7 +583,7 @@ module.exports = class UsersHelper { let result = { programName: programData[0].name, programId: programId, - programEndDate : programData[0].endDate ? programData[0].endDate : "", + programEndDate : programData[0].endDate, description: constants.common.TARGETED_SOLUTION_TEXT, rootOrganisations : ( programData[0].rootOrganisations && programData[0].rootOrganisations.length > 0 ) ? programData[0].rootOrganisations : [], requestForPIIConsent: programData[0].requestForPIIConsent ? programData[0].requestForPIIConsent : false, @@ -629,96 +629,70 @@ module.exports = class UsersHelper { static programs(bodyData, pageNo, pageSize, searchText, userId) { return new Promise(async (resolve, reject) => { try { - // Here program details matching the user profile is retrieved. - let targetedPrograms = await programsHelper.forUserRoleAndLocation( + + let targetedProgramIds = []; + let nonTargetedProgramIds = [] + let programCount; + + // getting all program details matching the user profile. not passing pageSize and pageNo to get all data. + let targetedPrograms = await programsHelper.forUserRoleAndLocation( bodyData, - pageSize, - pageNo, - searchText + "", + "", + searchText, + ["_id"] ); - if (!targetedPrograms.success) { - throw { - message: constants.apiResponses.PROGRAM_NOT_FOUND, - }; + // targetedPrograms.data contain all programIds targeted to current user profile. + if ( targetedPrograms.success && targetedPrograms.data && targetedPrograms.data.data.length > 0) { + targetedProgramIds = gen.utils.arrayOfObjectToArrayOfObjectId(targetedPrograms.data.data); + programCount = targetedPrograms.count; } - targetedPrograms.data["description"] = constants.apiResponses.PROGRAM_DESCRIPTION; // In case user changed profile after joined a program, we need to find the such program details. (programs not targeted to user profile anymore) let nontargetedJoinedPrograms = await this.getUserJoinedProgramDetailsWithPreviousProfiles( - bodyData, - 1, - targetedPrograms.data.count, + targetedProgramIds, searchText, userId ); - let targetedProgramCount = (targetedPrograms.data.count) ? targetedPrograms.data.count : 0 - // need to update count. - targetedPrograms.data.count = targetedPrograms.data.count + nontargetedJoinedPrograms.count; - // if user hasn't changed profile or request pagination doesn't exceed total targeted programs - if ( !nontargetedJoinedPrograms.count > 0 || (pageSize*pageNo) <= targetedProgramCount ) { - return resolve({ - success: true, - message: constants.apiResponses.USER_TARGETED_PROGRAMS_FETCHED, - data: targetedPrograms.data - }); - } else { - let maxLimit = 0; - let minLimit = 0; - // if no targeted program for user - if ( targetedPrograms.data.data.length === 0 ) { - /** - * {case: 1} - * if targeted programs is 0 and nontargetedJoinedPrograms := 3 - * example : pageNo := 1 - * pageSize : 5 - * maxLimit = 5 - * minLimit = 0 - */ - maxLimit = (pageNo*pageSize)-targetedProgramCount; - minLimit = maxLimit-pageSize; - } else if ( targetedPrograms.data.data.length < pageSize ) { - /** - * {case: 2} - * targetedPrograms: 3 - * example : pageNo := 4 - * pageSize : 5 - * and profile has nontargetedJoinedPrograms:= 3 - * maxLimit := 2 - */ - maxLimit = pageSize-targetedPrograms.data.data.length; - } - - let maxIndex = (maxLimit <= nontargetedJoinedPrograms.data.length) ? maxLimit : nontargetedJoinedPrograms.data.length; - /** - * {case 1: maxIndex : 3} - * {case 2: maxIndex : 2} - */ - if ( minLimit <= nontargetedJoinedPrograms.data.length ) { - for( let index = minLimit; index < maxIndex; index++ ) { - //fetch resourse started details - let programUsersData = await programUsersHelper.programUsersDocuments( - { - userId: userId, - programId: nontargetedJoinedPrograms.data[index]._id - }, - ["resourcesStarted"] - ); - // need to pass resourcesStarted with nontargetedJoinedPrograms data - if ( programUsersData.length > 0 ) { - nontargetedJoinedPrograms.data[index].resourcesStarted = (programUsersData[0].resourcesStarted) ? programUsersData[0].resourcesStarted : false; - } - - targetedPrograms.data.data.push(nontargetedJoinedPrograms.data[index]); - } - } + if ( nontargetedJoinedPrograms.success && nontargetedJoinedPrograms.data ) { + nonTargetedProgramIds = nontargetedJoinedPrograms.data; + programCount = programCount + nontargetedJoinedPrograms.count; // update program count } + + //find total number of programs related to user + let userRelatedPrograms = targetedProgramIds.concat(nonTargetedProgramIds); + + if (!userRelatedPrograms.length > 0) { + throw { + message: constants.apiResponses.PROGRAM_NOT_FOUND, + }; + } + + // get program details. also applying pagination here + let userRelatedProgramsData = await programsHelper.userRelatedProgramsDetails( + userRelatedPrograms, + pageNo, + pageSize, + "", + ["name", "externalId","components","metaInformation"], + userId + ); + if (!userRelatedProgramsData.success) { + throw { + message: constants.apiResponses.PROGRAM_NOT_FOUND, + }; + } + + targetedPrograms.data["description"] = constants.apiResponses.PROGRAM_DESCRIPTION; + userRelatedProgramsData.data.data.count = programCount; + return resolve({ success: true, - message: constants.apiResponses.USER_TARGETED_PROGRAMS_FETCHED, - data: targetedPrograms.data + message: constants.apiResponses.PROGRAMS_FETCHED, + data: userRelatedProgramsData.data }); } catch (error) { return resolve({ @@ -1003,40 +977,16 @@ module.exports = class UsersHelper { * Find non-targeted joined program. * @method * @name getUserJoinedProgramDetailsWithPreviousProfiles - * @param {Object} requestedData - requested data + * @param {Array} targetedProgramIds - programIds + * @param {String} searchText - search text + * @param {String} userId - userId * @returns {Object} - non-targeted joined program details. */ - - static getUserJoinedProgramDetailsWithPreviousProfiles( bodyData, pageNo, pageSize, searchText, userId ) { + static getUserJoinedProgramDetailsWithPreviousProfiles( targetedProgramIds, searchText = "", userId ) { return new Promise(async (resolve, reject) => { try { - // step 1 -> get all targeted program's Id, to the user profile. - let queryData = await programsHelper.queryBasedOnRoleAndLocation( - bodyData - ); - - if( !queryData.success ) { - return resolve(queryData); - } - - // get all targeted program ids. - // we have to recall this function here because we need to get all program details. ie) pageNo := 1 && pageSize:= toatal targeted program count. - // allTargetedPrograms.data contain query based on user location and role. - let allTargetedPrograms = await programsHelper.list( - pageNo, - pageSize, - "", - queryData.data, - ["_id"] - ); - let targettedProgramIds = []; let programUsersIds = []; - // allTargetedPrograms.data contain all programIds targeted to current user profile. - if ( allTargetedPrograms.success && allTargetedPrograms.data && allTargetedPrograms.data.data.length > 0) { - targettedProgramIds = allTargetedPrograms.data.data.map(function (obj) { - return obj._id; - }); - } + let nonTargettedProgramDetails = []; // find all programs joined by the user // programUsersData will contain list of programs joined by user from all the profiles. This can be considered as the super set of user programs @@ -1052,28 +1002,36 @@ module.exports = class UsersHelper { return obj.programId; }); } + // if we find the difference between programUsersData and targettedProgramIds we will get program details joined by user other than the current profile - let previousProfilesJoinedProgramIds = _.differenceWith(programUsersIds, targettedProgramIds,_.isEqual) - let nonTargettedProgramDetails = []; + let previousProfilesJoinedProgramIds = _.differenceWith(programUsersIds, targetedProgramIds,_.isEqual); + if ( previousProfilesJoinedProgramIds.length > 0 ) { - // We only have programIds of user joined from old profiles. Need to get program details using these Ids let findQuery = { - "_id": { "$in" : previousProfilesJoinedProgramIds } + "_id": { "$in" : previousProfilesJoinedProgramIds }, + "startDate": {"$lte": new Date()}, + "endDate": {"$gte": new Date()} } - //get non-targeted program details - nonTargettedProgramDetails = await programsHelper.list( - 1, - previousProfilesJoinedProgramIds.length, + + //call program details to check if the program is active or not + let programDetails = await programsHelper.list( + "", + "", searchText, findQuery, - ["name", "externalId","metaInformation"] + ["_id"] ); + + // get _ids to array + if ( programDetails.success > 0 && programDetails.data && programDetails.data.data && programDetails.data.data.length > 0 ) { + nonTargettedProgramDetails = gen.utils.arrayOfObjectToArrayOfObjectId(programDetails.data.data); + } } return resolve({ success: true, - data: nonTargettedProgramDetails.data.data, - count: nonTargettedProgramDetails.data.data.length + data: nonTargettedProgramDetails, + count: nonTargettedProgramDetails.length }); } catch (error) { return resolve({ From 77c61455df42d2d70bcbeffdf6d13a2d379cfbde Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Tue, 18 Apr 2023 09:05:47 +0530 Subject: [PATCH 303/331] merge code issue resolved --- module/solutions/helper.js | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/module/solutions/helper.js b/module/solutions/helper.js index e7dd9b3f..652c6378 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -2001,23 +2001,17 @@ module.exports = class SolutionsHelper { } } - + if ( solutionData.programId ) { // add ["rootOrganisations","requestForPIIConsent","programJoined"] values to response. Based on these values front end calls PII consent let programData = await programsHelper.programDocuments({ _id : solutionData.programId },["rootOrganisations","requestForPIIConsent"]); - if ( programData.length > 0 ) { - templateOrQuestionDetails.result.rootOrganisations = (programData[0].rootOrganisations) ? programData[0].rootOrganisations : []; - templateOrQuestionDetails.result.requestForPIIConsent = (programData[0].requestForPIIConsent) ? programData[0].requestForPIIConsent : false; - } + templateOrQuestionDetails.result.rootOrganisations = (programData[0].rootOrganisations) ? programData[0].rootOrganisations : []; + templateOrQuestionDetails.result.requestForPIIConsent = (programData[0].requestForPIIConsent) ? programData[0].requestForPIIConsent : false; } - //Check data present in programUsers collection. - //checkForUserJoinedProgram will check for data and if its present return true else false. - templateOrQuestionDetails.result.programJoined = await programUsersHelper.checkForUserJoinedProgram(solutionData.programId,userId); - //Check data present in programUsers collection. //checkForUserJoinedProgram will check for data and if its present return true else false. templateOrQuestionDetails.result.programJoined = await programUsersHelper.checkForUserJoinedProgram(solutionData.programId,userId); From cc6ffacd614fbeecfb1df0538e636b4647d09edb Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Tue, 18 Apr 2023 16:17:40 +0530 Subject: [PATCH 304/331] facet query changed at list api --- module/programs/helper.js | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/module/programs/helper.js b/module/programs/helper.js index d57285af..545f1a0c 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -435,11 +435,9 @@ module.exports = class ProgramsHelper { facetQuery["$facet"]["totalCount"] = [ { "$count": "count" } ]; - + if ( pageSize === "" && pageNo === "" ) { - facetQuery["$facet"]["data"] = [ - { $skip: 0 } - ]; + facetQuery["$facet"]["data"] = []; } else { facetQuery["$facet"]["data"] = [ { $skip: pageSize * (pageNo - 1) }, From 239627875b9a7465b9c80d1e1e2aa8c4e44106fd Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Tue, 18 Apr 2023 21:21:23 +0530 Subject: [PATCH 305/331] programlistin api review changes --- module/programs/helper.js | 115 ++------------------------------------ module/users/helper.js | 38 ++++++------- 2 files changed, 24 insertions(+), 129 deletions(-) diff --git a/module/programs/helper.js b/module/programs/helper.js index 545f1a0c..7a1fd277 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -26,14 +26,16 @@ module.exports = class ProgramsHelper { * @name programDocuments * @param {Array} [filterQuery = "all"] - solution ids. * @param {Array} [fieldsArray = "all"] - projected fields. - * @param {Array} [skipFields = "none"] - field not to include + * @param {Array} [skipFields = "none"] - field not to include. + * @param {Object} pagination - pagination object. * @returns {Array} List of programs. */ static programDocuments( filterQuery = "all", fieldsArray = "all", - skipFields = "none" + skipFields = "none", + pagination = {} ) { return new Promise(async (resolve, reject) => { try { @@ -56,7 +58,8 @@ module.exports = class ProgramsHelper { let programData = await database.models.programs.find( queryObject, - projection + projection, + pagination ).lean(); return resolve(programData); @@ -528,112 +531,6 @@ module.exports = class ProgramsHelper { }) } - /** - * List of programs related to a user. - * @method - * @name userRelatedProgramsDetails - * @param {Array} programIds - program Ids. - * @param {String} pageSize - Page size. - * @param {String} pageNo - Page no. - * @param {String} searchText - search text. - * @param {Array} projection - projection. - * @param {String} userId - userId. - * @returns {JSON} - List of programs related to the user. - */ - - static userRelatedProgramsDetails( programIds, pageNo, pageSize, searchText = "", projection, userId ) { - return new Promise(async (resolve, reject) => { - try { - let findQuery = { - "_id": { "$in" : programIds }, - } - - let userRelatedProgramsDetails = await this.list( - pageNo, - pageSize, - searchText, - findQuery, - projection - ); - - // add solutions and resourcesStarted - if ( userRelatedProgramsDetails.success && userRelatedProgramsDetails.data && userRelatedProgramsDetails.data.data.length > 0 ) { - - let componentsIds = []; - let userRelatedProgramIds = []; - userRelatedProgramsDetails.data.data.forEach(program => { - if( program.components.length > 0 ) { - componentsIds = componentsIds.concat(program.components); - } - userRelatedProgramIds.push(program._id); - }); - - let solutions = await solutionsHelper.solutionDocuments({ - _id : { $in : componentsIds }, - isDeleted : false, - status : constants.common.ACTIVE - },["_id"]); - - const solutionsIds = [] - solutions.forEach(solution => solutionsIds.push(solution._id.toString())); - - userRelatedProgramsDetails.data.data.forEach(program => { - - if( program.components.length > 0 ) { - - let countSolutions = 0; - program.components.forEach(component => { - if (solutionsIds.includes(component.toString())) { - countSolutions++; - } - }); - program.solutions = countSolutions; - delete program.components; - } - }); - - const programUsersDetails = await programUsersHelper.programUsersDocuments( - { - userId: userId, - programId: { "$in" : userRelatedProgramIds } - }, - ["programId","resourcesStarted"] - ); - - // add resourcesStarted key to response if its available - if( programUsersDetails.length > 0 ) { - for ( let programUsersIndex = 0; programUsersIndex < programUsersDetails.length; programUsersIndex++ ) { - if (programUsersDetails[programUsersIndex].hasOwnProperty("resourcesStarted")) { - for ( let programIndex = 0; programIndex < userRelatedProgramsDetails.data.data.length; programIndex++ ) { - if( programUsersDetails[programUsersIndex].programId == (userRelatedProgramsDetails.data.data[programIndex]._id).toString() ) { - userRelatedProgramsDetails.data.data[programIndex].resourcesStarted = programUsersDetails[programUsersIndex].resourcesStarted; - } - } - } - - } - } - } - - return resolve({ - success: true, - message: constants.apiResponses.PROGRAMS_FETCHED, - data: userRelatedProgramsDetails.data - }); - - } catch (error) { - - return resolve({ - success : false, - message : error.message, - data : {} - }); - - } - - }) - } - /** * Query data based on role and location. * @method diff --git a/module/users/helper.js b/module/users/helper.js index 9ab36ae0..147d99df 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -630,15 +630,16 @@ module.exports = class UsersHelper { return new Promise(async (resolve, reject) => { try { + let programDetails = {}; let targetedProgramIds = []; let nonTargetedProgramIds = [] - let programCount; + let programCount= 0; // getting all program details matching the user profile. not passing pageSize and pageNo to get all data. let targetedPrograms = await programsHelper.forUserRoleAndLocation( bodyData, - "", - "", + "", // not passing page size + "", // not passing page number searchText, ["_id"] ); @@ -646,7 +647,7 @@ module.exports = class UsersHelper { // targetedPrograms.data contain all programIds targeted to current user profile. if ( targetedPrograms.success && targetedPrograms.data && targetedPrograms.data.data.length > 0) { targetedProgramIds = gen.utils.arrayOfObjectToArrayOfObjectId(targetedPrograms.data.data); - programCount = targetedPrograms.count; + programCount = targetedPrograms.data.count; } // In case user changed profile after joined a program, we need to find the such program details. (programs not targeted to user profile anymore) @@ -670,29 +671,26 @@ module.exports = class UsersHelper { }; } - // get program details. also applying pagination here - let userRelatedProgramsData = await programsHelper.userRelatedProgramsDetails( - userRelatedPrograms, - pageNo, - pageSize, - "", - ["name", "externalId","components","metaInformation"], - userId + let userRelatedProgramsData = await programsHelper.programDocuments( + {_id : {$in:userRelatedPrograms}}, + ["name", "externalId","metaInformation"], + "none", //not passing skip fields + {skip: pageSize * (pageNo - 1),limit: pageSize} ); - if (!userRelatedProgramsData.success) { + if (!userRelatedProgramsData.length > 0) { throw { message: constants.apiResponses.PROGRAM_NOT_FOUND, }; } - - targetedPrograms.data["description"] = constants.apiResponses.PROGRAM_DESCRIPTION; - userRelatedProgramsData.data.data.count = programCount; - + programDetails.data = userRelatedProgramsData; + programDetails.count = programCount; + programDetails.description = constants.apiResponses.PROGRAM_DESCRIPTION; + return resolve({ success: true, message: constants.apiResponses.PROGRAMS_FETCHED, - data: userRelatedProgramsData.data + data: programDetails }); } catch (error) { return resolve({ @@ -1015,8 +1013,8 @@ module.exports = class UsersHelper { //call program details to check if the program is active or not let programDetails = await programsHelper.list( - "", - "", + "", // not passing page number + "", // not passing page size searchText, findQuery, ["_id"] From 632e32c6d75f392d93e753c3a89086d136a43bcd Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Tue, 18 Apr 2023 21:57:23 +0530 Subject: [PATCH 306/331] pagination generalised --- module/programs/helper.js | 14 +++++++++++--- module/users/helper.js | 3 ++- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/module/programs/helper.js b/module/programs/helper.js index 7a1fd277..3d0a7cf4 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -27,7 +27,8 @@ module.exports = class ProgramsHelper { * @param {Array} [filterQuery = "all"] - solution ids. * @param {Array} [fieldsArray = "all"] - projected fields. * @param {Array} [skipFields = "none"] - field not to include. - * @param {Object} pagination - pagination object. + * @param {Number} pageNo - page no. + * @param {Number} pageSize - page size. * @returns {Array} List of programs. */ @@ -35,7 +36,8 @@ module.exports = class ProgramsHelper { filterQuery = "all", fieldsArray = "all", skipFields = "none", - pagination = {} + pageNo = "", + pageSize = "" ) { return new Promise(async (resolve, reject) => { try { @@ -43,7 +45,7 @@ module.exports = class ProgramsHelper { let queryObject = (filterQuery != "all") ? filterQuery : {}; let projection = {} - + let pagination = {}; if (fieldsArray != "all") { fieldsArray.forEach(field => { projection[field] = 1; @@ -55,6 +57,12 @@ module.exports = class ProgramsHelper { projection[field] = 0; }) } + if( pageNo !== "" && pageSize !== "" ) { + pagination = { + skip: pageSize * (pageNo - 1), + limit: pageSize + } + } let programData = await database.models.programs.find( queryObject, diff --git a/module/users/helper.js b/module/users/helper.js index 147d99df..60c010c7 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -675,7 +675,8 @@ module.exports = class UsersHelper { {_id : {$in:userRelatedPrograms}}, ["name", "externalId","metaInformation"], "none", //not passing skip fields - {skip: pageSize * (pageNo - 1),limit: pageSize} + pageNo, + pageSize ); if (!userRelatedProgramsData.length > 0) { From 2459bfd5ec13626790ff17fa7240295fd84abf9a Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Thu, 20 Apr 2023 11:08:01 +0530 Subject: [PATCH 307/331] Added PR checklist --- .github/pull_request_template.md | 35 +++++++++++++++++++ ...Rxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA | 3 ++ 2 files changed, 38 insertions(+) create mode 100644 .github/pull_request_template.md create mode 100644 keycloak-public-keys/GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 00000000..6a041dd8 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,35 @@ + +# Description +These recommendations are intended to promote code quality and team communication during software development. They cover a variety of topics, including ensuring that pull requests are submitted to the correct branch, documenting new methods, preserving consistency across many services, and avoiding typical blunders like accessing APIs or DB queries within loops. Sensitive data should not be uploaded, and changes to environment variables or database models should be executed consistently. Teams may work more effectively and develop higher-quality software by adhering to these standards. + + +## Type of change +Please choose appropriate options. + +- [ ] Bug fix (non-breaking change which fixes an issue) +- [ ] New feature (non-breaking change which adds functionality) +- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) +- [ ] Enhancement (additive changes to improve performance) +- [ ] This change requires a documentation update + +## Checklist + +- [ ] It's critical to avoid making needless file modifications in contributions, such as adding new lines, console logs, or additional spaces, to guarantee cleaner and more efficient code. Furthermore, eliminating unnecessary imports from a file might enhance code readability and efficiency. +- [ ] Ensure that the pull request is assigned to the right branch and that the branch name contains the JIRA Task Id. Furthermore, each commit message should include the JIRA Task Id in the manner "ED-100: message". +- [ ] Only update packages if it is mentioned and authorized in the design document, and make sure that you have the required permissions. +- [ ] Avoid making API and database queries inside a loop as it can lead to performance issues and slow down the system. +- [ ] When calling another function inside a given function, add comments explaining the purpose and meaning of the passed arguments and expected return values. +- [ ] If adding a blank argument in a function, add a comment explaining the reason for the blank argument. +- [ ] Before submitting a pull request, do a self-review of your code to ensure there are no conflicts with the base branch and all comments have been addressed. +- [ ] Before merging a pull request, it's important to have other team members review it to catch any potential errors or issues +- [ ] To maintain code integrity, it's important to remove all related changes when removing code during a code review. +- [ ] If new constants, endpoints, or utility functions are introduced, it is important to check if they already exist in the service to avoid any duplication. +- [ ] Whenever a new environment variable is added to a service, it's important to ensure that the necessary changes are made to related files such as ".env.sample" and "envVariables.js" to maintain consistency and avoid errors. Additionally, the new environment variable should be added to the devops repository to ensure that it is properly documented and accessible to the team. +- [ ] When adding a new function to a service, it is important to document it with relevant information such as the name, parameters, and return value in a consistent format across all services. Additionally, if there are any changes to the API response, ensure that the documentation in the controllers is updated accordingly. +- [ ] Write a clear and concise commit message that describes the changes made. +- [ ] Maintain consistent function signature and code across all services when adding a function to multiple services. Implement changes to database models in all services that use the same model. +- [ ] Use only let and const. Do not use var. +- [ ] Make common functions for repetitive code blocks. +- [ ] Avoid uploading sensitive information such as secret tokens or passwords in pull requests to ensure data security. + + diff --git a/keycloak-public-keys/GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA b/keycloak-public-keys/GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA new file mode 100644 index 00000000..44c17f6c --- /dev/null +++ b/keycloak-public-keys/GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA @@ -0,0 +1,3 @@ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoRbRlp/1x0h5a9Rb3E7+nU17mdnU1Grv2/a6ixhdBr1f9mjKEn7F/5eIfCQL3H82stxZyskeWaetL1mNJkAHFcJx+03DoKnGP6K+PZ3Svbw67ehgqyp+OozZCNXHzrM1DUVpvhYgsnvkqm+E1QyrsmrghSE+bAHqJep4S/70z12t8rwMNB6OxcbhrHBU93TxszxHHLZL9eaa2DCwGsTbYml0V2vFPsN4HUhXtnht9uoC2bjAXyBsrSNy/aoCsoI0erV8Vyw2FKfwEGBDFROjcWhKOdwb36TmEDf+g4OBSqAhEyewhTwcP7ESpjhyA3Ae1cH9cKOBmQTU+OmzS89h8QIDAQAB +-----END PUBLIC KEY----- From a015e843547ee9c5f941fa77fb32111dd7d91bcb Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Thu, 20 Apr 2023 11:11:54 +0530 Subject: [PATCH 308/331] Added deleted keyclockfile --- .../GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 keycloak-public-keys/GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA diff --git a/keycloak-public-keys/GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA b/keycloak-public-keys/GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA deleted file mode 100644 index 44c17f6c..00000000 --- a/keycloak-public-keys/GRxx8ur43pXH3_QMzBWerQPWrX02PJkK9Czl3hc60fA +++ /dev/null @@ -1,3 +0,0 @@ ------BEGIN PUBLIC KEY----- -MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoRbRlp/1x0h5a9Rb3E7+nU17mdnU1Grv2/a6ixhdBr1f9mjKEn7F/5eIfCQL3H82stxZyskeWaetL1mNJkAHFcJx+03DoKnGP6K+PZ3Svbw67ehgqyp+OozZCNXHzrM1DUVpvhYgsnvkqm+E1QyrsmrghSE+bAHqJep4S/70z12t8rwMNB6OxcbhrHBU93TxszxHHLZL9eaa2DCwGsTbYml0V2vFPsN4HUhXtnht9uoC2bjAXyBsrSNy/aoCsoI0erV8Vyw2FKfwEGBDFROjcWhKOdwb36TmEDf+g4OBSqAhEyewhTwcP7ESpjhyA3Ae1cH9cKOBmQTU+OmzS89h8QIDAQAB ------END PUBLIC KEY----- From b530fb92c6e3633e1ac9d14b79c9fde4be2a96b9 Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Thu, 20 Apr 2023 11:16:45 +0530 Subject: [PATCH 309/331] Added PR One more point --- .github/pull_request_template.md | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 6a041dd8..4e579d48 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -31,5 +31,6 @@ Please choose appropriate options. - [ ] Use only let and const. Do not use var. - [ ] Make common functions for repetitive code blocks. - [ ] Avoid uploading sensitive information such as secret tokens or passwords in pull requests to ensure data security. +- [ ] Maintain consistent indentation and spacing throughout the code. From bfac16133786447a18eab68468ec85c54125db10 Mon Sep 17 00:00:00 2001 From: ankitshahu Date: Thu, 20 Apr 2023 11:28:05 +0530 Subject: [PATCH 310/331] Changed Pr checklist point --- .github/pull_request_template.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 4e579d48..bb5dc77f 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -15,7 +15,7 @@ Please choose appropriate options. ## Checklist - [ ] It's critical to avoid making needless file modifications in contributions, such as adding new lines, console logs, or additional spaces, to guarantee cleaner and more efficient code. Furthermore, eliminating unnecessary imports from a file might enhance code readability and efficiency. -- [ ] Ensure that the pull request is assigned to the right branch and that the branch name contains the JIRA Task Id. Furthermore, each commit message should include the JIRA Task Id in the manner "ED-100: message". +- [ ] Ensure that the pull request is assigned to the right base branch and that the development branch name contains the JIRA Task Id. Furthermore, each commit message should include the JIRA Task Id in the manner "ED-100: message". - [ ] Only update packages if it is mentioned and authorized in the design document, and make sure that you have the required permissions. - [ ] Avoid making API and database queries inside a loop as it can lead to performance issues and slow down the system. - [ ] When calling another function inside a given function, add comments explaining the purpose and meaning of the passed arguments and expected return values. From ef2c8348819ded319597d77bb8f50cb4cbfe1060 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 4 May 2023 10:50:23 +0530 Subject: [PATCH 311/331] console added --- generics/services/users.js | 4 +++- module/programs/helper.js | 1 + module/solutions/helper.js | 2 +- module/users/helper.js | 2 +- 4 files changed, 6 insertions(+), 3 deletions(-) diff --git a/generics/services/users.js b/generics/services/users.js index 4e3ea701..8e8441a4 100644 --- a/generics/services/users.js +++ b/generics/services/users.js @@ -26,7 +26,7 @@ const profile = function ( token,userId = "" ) { } }; - request.post(url,options,kendraCallback); + request.get(url,options,kendraCallback); function kendraCallback(err, data) { @@ -36,9 +36,11 @@ const profile = function ( token,userId = "" ) { if (err) { result.success = false; + console.log("error occured user read api call :",err) } else { let response = JSON.parse(data.body); + console.log("response from userRead api call :",response) if( response.status === httpStatusCode['ok'].status ) { result["data"] = response.result.response; } else { diff --git a/module/programs/helper.js b/module/programs/helper.js index 3d0a7cf4..32982532 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -1076,6 +1076,7 @@ module.exports = class ProgramsHelper { status: httpStatusCode.bad_request.status } } + console.log("kafka push status :",pushProgramUsersDetailsToKafka) if ( pushProgramUsersDetailsToKafka ) { joinProgram.programName = programData[0].name; joinProgram.programExternalId = programData[0].externalId; diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 652c6378..78b2a22f 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -2008,7 +2008,7 @@ module.exports = class SolutionsHelper { _id : solutionData.programId },["rootOrganisations","requestForPIIConsent"]); - templateOrQuestionDetails.result.rootOrganisations = (programData[0].rootOrganisations) ? programData[0].rootOrganisations : []; + templateOrQuestionDetails.result.rootOrganisations = (programData[0].rootOrganisations) ? programData[0].rootOrganisations[0] : ""; templateOrQuestionDetails.result.requestForPIIConsent = (programData[0].requestForPIIConsent) ? programData[0].requestForPIIConsent : false; } diff --git a/module/users/helper.js b/module/users/helper.js index 60c010c7..24dbdd05 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -585,7 +585,7 @@ module.exports = class UsersHelper { programId: programId, programEndDate : programData[0].endDate, description: constants.common.TARGETED_SOLUTION_TEXT, - rootOrganisations : ( programData[0].rootOrganisations && programData[0].rootOrganisations.length > 0 ) ? programData[0].rootOrganisations : [], + rootOrganisations : ( programData[0].rootOrganisations && programData[0].rootOrganisations.length > 0 ) ? programData[0].rootOrganisations[0] : "", requestForPIIConsent: programData[0].requestForPIIConsent ? programData[0].requestForPIIConsent : false, data: mergedData, count: totalCount, From 75ae8c76a37179eaf81058b015d1adab6f02dc5d Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 4 May 2023 11:52:47 +0530 Subject: [PATCH 312/331] response check changes for v5/user/read added --- generics/services/users.js | 4 ++-- module/programs/helper.js | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/generics/services/users.js b/generics/services/users.js index 8e8441a4..ed6c8c92 100644 --- a/generics/services/users.js +++ b/generics/services/users.js @@ -41,10 +41,10 @@ const profile = function ( token,userId = "" ) { let response = JSON.parse(data.body); console.log("response from userRead api call :",response) - if( response.status === httpStatusCode['ok'].status ) { + if( response.responseCode === httpStatusCode['http_responsecode_ok'].message ) { result["data"] = response.result.response; } else { - result["message"] = response.message; + result["message"] = response.params.status; result.success = false; } diff --git a/module/programs/helper.js b/module/programs/helper.js index 32982532..abb386d5 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -1001,11 +1001,10 @@ module.exports = class ProgramsHelper { let userProfile = await userService.profile(userToken, userId); if (!userProfile.success || !userProfile.data || - !userProfile.data.response || - !userProfile.data.response.profileUserTypes || - !userProfile.data.response.profileUserTypes.length > 0 || - !userProfile.data.response.userLocations || - !userProfile.data.response.userLocations.length > 0 + !userProfile.data.profileUserTypes || + !userProfile.data.profileUserTypes.length > 0 || + !userProfile.data.userLocations || + !userProfile.data.userLocations.length > 0 ) { throw ({ status: httpStatusCode.bad_request.status, @@ -1048,6 +1047,7 @@ module.exports = class ProgramsHelper { } } let consentResponse = await userService.setUserConsent(userToken, userConsentRequestBody) + console.log("consentResponse ",consentResponse) if(!consentResponse.success){ throw { message: constants.apiResponses.PROGRAM_JOIN_FAILED, From 1821dca29b5e3eb9f6e9dce6bd2051e196eae8ad Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 4 May 2023 13:54:43 +0530 Subject: [PATCH 313/331] bug fix, userRoleinformation not getting added for internal calls --- module/programs/helper.js | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/module/programs/helper.js b/module/programs/helper.js index abb386d5..5c6e5cda 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -1015,7 +1015,7 @@ module.exports = class ProgramsHelper { programId: programId, userRoleInformation: data.userRoleInformation, userId: userId, - userProfile:userProfile.data.response, + userProfile:userProfile.data, resourcesStarted : false } if( appName != "" ) { @@ -1024,8 +1024,6 @@ module.exports = class ProgramsHelper { if( appVersion != "" ) { programUsersData['appInformation.appVersion'] = appVersion; } - update['$set'] = programUsersData; - //For internal calls add consent using sunbird api if( callConsetAPIOnBehalfOfUser && programData[0].hasOwnProperty('requestForPIIConsent') && programData[0].requestForPIIConsent === true ){ @@ -1039,7 +1037,7 @@ module.exports = class ProgramsHelper { "request": { "consent": { "status": constants.common.REVOKED, - "userId": userProfile.data.response.id, + "userId": userProfile.data.id, "consumerId": programData[0].rootOrganisations[0], "objectId": programId, "objectType": constants.common.PROGRAM @@ -1048,6 +1046,7 @@ module.exports = class ProgramsHelper { } let consentResponse = await userService.setUserConsent(userToken, userConsentRequestBody) console.log("consentResponse ",consentResponse) + if(!consentResponse.success){ throw { message: constants.apiResponses.PROGRAM_JOIN_FAILED, @@ -1063,10 +1062,12 @@ module.exports = class ProgramsHelper { programId: programId, userId: userId }; + if ( data.isResource ) { - update['$set'] = { resourcesStarted : true } + programUsersData.resourcesStarted = true; } - + update['$set'] = programUsersData; + // add record to programUsers collection let joinProgram = await programUsersHelper.update(query, update, { new:true, upsert:true }); From a41ae3e984823881ca40ae319132340c2282d4a4 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 4 May 2023 18:01:05 +0530 Subject: [PATCH 314/331] console added to check program listing error --- module/users/helper.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/module/users/helper.js b/module/users/helper.js index 24dbdd05..4245a5b2 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -643,9 +643,9 @@ module.exports = class UsersHelper { searchText, ["_id"] ); - + // targetedPrograms.data contain all programIds targeted to current user profile. - if ( targetedPrograms.success && targetedPrograms.data && targetedPrograms.data.data.length > 0) { + if ( targetedPrograms.success && targetedPrograms.data && targetedPrograms.data.data && targetedPrograms.data.data.length > 0) { targetedProgramIds = gen.utils.arrayOfObjectToArrayOfObjectId(targetedPrograms.data.data); programCount = targetedPrograms.data.count; } @@ -694,6 +694,7 @@ module.exports = class UsersHelper { data: programDetails }); } catch (error) { + console.log("Error :",error) return resolve({ success: false, message: error.message, From cc5e2c7a06e7eb52dfe095fca08567a012583d5c Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 4 May 2023 18:39:08 +0530 Subject: [PATCH 315/331] targetedPrograms.data.data usage avoided --- module/programs/helper.js | 5 +++-- module/users/helper.js | 6 +++--- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/module/programs/helper.js b/module/programs/helper.js index 5c6e5cda..b44ab5a2 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -523,7 +523,8 @@ module.exports = class ProgramsHelper { return resolve({ success: true, message: constants.apiResponses.TARGETED_PROGRAMS_FETCHED, - data: targetedPrograms.data + data: targetedPrograms.data.data, + count: targetedPrograms.data.count }); } catch (error) { @@ -1046,7 +1047,7 @@ module.exports = class ProgramsHelper { } let consentResponse = await userService.setUserConsent(userToken, userConsentRequestBody) console.log("consentResponse ",consentResponse) - + if(!consentResponse.success){ throw { message: constants.apiResponses.PROGRAM_JOIN_FAILED, diff --git a/module/users/helper.js b/module/users/helper.js index 4245a5b2..a90d6b23 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -645,9 +645,9 @@ module.exports = class UsersHelper { ); // targetedPrograms.data contain all programIds targeted to current user profile. - if ( targetedPrograms.success && targetedPrograms.data && targetedPrograms.data.data && targetedPrograms.data.data.length > 0) { - targetedProgramIds = gen.utils.arrayOfObjectToArrayOfObjectId(targetedPrograms.data.data); - programCount = targetedPrograms.data.count; + if ( targetedPrograms.success && targetedPrograms.data && targetedPrograms.data.length > 0) { + targetedProgramIds = gen.utils.arrayOfObjectToArrayOfObjectId(targetedPrograms.data); + programCount = targetedPrograms.count; } // In case user changed profile after joined a program, we need to find the such program details. (programs not targeted to user profile anymore) From 4179fc06c9f0c601707ee5413e8ce3142bddc8c5 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Thu, 4 May 2023 19:24:19 +0530 Subject: [PATCH 316/331] debug console added --- module/programs/helper.js | 3 ++- module/users/helper.js | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/module/programs/helper.js b/module/programs/helper.js index b44ab5a2..0e84abac 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -475,6 +475,7 @@ module.exports = class ProgramsHelper { }); } catch (error) { + console.log("error :",error) return resolve({ success : false, message : error.message, @@ -528,7 +529,7 @@ module.exports = class ProgramsHelper { }); } catch (error) { - + console.log("error :",error) return resolve({ success : false, message : error.message, diff --git a/module/users/helper.js b/module/users/helper.js index a90d6b23..5f48c7cf 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -1034,6 +1034,7 @@ module.exports = class UsersHelper { count: nonTargettedProgramDetails.length }); } catch (error) { + console.log("error :",error) return resolve({ success: false, status: error.status From 564ba729347da4082b1b79fa9c25019f878fd591 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 5 May 2023 11:13:56 +0530 Subject: [PATCH 317/331] facetQuery bug fix. Programs list function --- module/programs/helper.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/module/programs/helper.js b/module/programs/helper.js index 0e84abac..8ad235d2 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -448,7 +448,9 @@ module.exports = class ProgramsHelper { ]; if ( pageSize === "" && pageNo === "" ) { - facetQuery["$facet"]["data"] = []; + facetQuery["$facet"]["data"] = [ + { $skip: 0} + ]; } else { facetQuery["$facet"]["data"] = [ { $skip: pageSize * (pageNo - 1) }, From 6853699a81e519c82ccac7bb9cccd72640d94220 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Tue, 9 May 2023 14:05:43 +0530 Subject: [PATCH 318/331] change made to send requestForPIIConsent if it is present in programs data --- models/programs.js | 5 +---- module/programs/helper.js | 2 +- module/programs/validator/v1.js | 1 + module/solutions/helper.js | 4 +++- module/users/helper.js | 5 +++-- 5 files changed, 9 insertions(+), 8 deletions(-) diff --git a/models/programs.js b/models/programs.js index 81ba3457..402d5610 100644 --- a/models/programs.js +++ b/models/programs.js @@ -58,10 +58,7 @@ module.exports = { type : Boolean, index : true }, - requestForPIIConsent: { - type: Boolean, - default: false - }, + requestForPIIConsent: Boolean, metaInformation: Object, rootOrganisations : Array, createdFor : Array diff --git a/module/programs/helper.js b/module/programs/helper.js index 8ad235d2..aab35f4a 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -1085,7 +1085,7 @@ module.exports = class ProgramsHelper { if ( pushProgramUsersDetailsToKafka ) { joinProgram.programName = programData[0].name; joinProgram.programExternalId = programData[0].externalId; - joinProgram.requestForPIIConsent = (programData[0].requestForPIIConsent && programData[0].requestForPIIConsent == true) ? true : false; + joinProgram.requestForPIIConsent = programData[0].requestForPIIConsent; // push programUsers details to kafka await kafkaProducersHelper.pushProgramUsersToKafka(joinProgram); diff --git a/module/programs/validator/v1.js b/module/programs/validator/v1.js index 15bf62bd..4ffa98f3 100644 --- a/module/programs/validator/v1.js +++ b/module/programs/validator/v1.js @@ -12,6 +12,7 @@ module.exports = (req) => { create : function () { req.checkBody('externalId').exists().withMessage("required program externalId"); req.checkBody('name').exists().withMessage("required program name"); + req.checkBody('requestForPIIConsent').exists().withMessage("required requestForPIIConsent value of program"); }, update : function () { req.checkParams("_id").exists().withMessage("required program id"); diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 78b2a22f..d590b230 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -2009,7 +2009,9 @@ module.exports = class SolutionsHelper { },["rootOrganisations","requestForPIIConsent"]); templateOrQuestionDetails.result.rootOrganisations = (programData[0].rootOrganisations) ? programData[0].rootOrganisations[0] : ""; - templateOrQuestionDetails.result.requestForPIIConsent = (programData[0].requestForPIIConsent) ? programData[0].requestForPIIConsent : false; + if( programData[0].hasOwnProperty('requestForPIIConsent') ) { + templateOrQuestionDetails.result.requestForPIIConsent = programData[0].requestForPIIConsent; + } } //Check data present in programUsers collection. diff --git a/module/users/helper.js b/module/users/helper.js index 5f48c7cf..2ee84e70 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -586,12 +586,13 @@ module.exports = class UsersHelper { programEndDate : programData[0].endDate, description: constants.common.TARGETED_SOLUTION_TEXT, rootOrganisations : ( programData[0].rootOrganisations && programData[0].rootOrganisations.length > 0 ) ? programData[0].rootOrganisations[0] : "", - requestForPIIConsent: programData[0].requestForPIIConsent ? programData[0].requestForPIIConsent : false, data: mergedData, count: totalCount, programEndDate: programData[0].endDate }; - + if( programData[0].hasOwnProperty('requestForPIIConsent') ) { + result.requestForPIIConsent = programData[0].requestForPIIConsent; + } //Check data present in programUsers collection. //checkForUserJoinedProgram will check for data and if its present return true else false. result.programJoined = await programUsersHelper.checkForUserJoinedProgram(programId,userId); From 8333b037c1c8f43933554d70df2376686ced4ec1 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Tue, 9 May 2023 15:49:08 +0530 Subject: [PATCH 319/331] rootOrganisations in programs made mandatory --- models/programs.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/models/programs.js b/models/programs.js index 402d5610..6fc33951 100644 --- a/models/programs.js +++ b/models/programs.js @@ -60,7 +60,10 @@ module.exports = { }, requestForPIIConsent: Boolean, metaInformation: Object, - rootOrganisations : Array, + rootOrganisations : { + type : Array, + require: true + }, createdFor : Array } }; From a92f826961c6eadf51f4d245f5e112771207eb54 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Tue, 9 May 2023 15:54:11 +0530 Subject: [PATCH 320/331] code formatted --- models/programs.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/models/programs.js b/models/programs.js index 6fc33951..cabd3b92 100644 --- a/models/programs.js +++ b/models/programs.js @@ -62,7 +62,7 @@ module.exports = { metaInformation: Object, rootOrganisations : { type : Array, - require: true + require : true }, createdFor : Array } From 05b9000ab6a259428845b78bbd5cb3f77bb469a7 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Wed, 10 May 2023 14:18:55 +0530 Subject: [PATCH 321/331] requestForPIIConsent added to program doc projection in programsByPlatformRoles api --- module/user-extension/helper.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/module/user-extension/helper.js b/module/user-extension/helper.js index a468e55a..89c1d646 100644 --- a/module/user-extension/helper.js +++ b/module/user-extension/helper.js @@ -544,7 +544,7 @@ module.exports = class UserExtensionHelper { } const userInformation = await this.userExtensionDocument(findQuery,projection); - + if (!userInformation) { return resolve({ status: httpStatusCode.bad_request.status, @@ -586,7 +586,7 @@ module.exports = class UserExtensionHelper { const programData = await programsHelper.programDocuments({ _id: {$in: programIds}, status: constants.common.ACTIVE - },["externalId","name","description"]); + },["externalId","name","description","requestForPIIConsent"]); if (programData.length > 0) { programsDocuments = programData.map(program => { From 4a78181dd3a97b732d757adeb1430209417aa784 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 15 May 2023 19:24:28 +0530 Subject: [PATCH 322/331] kafka push object prototype issue resolve --- module/programs/helper.js | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/module/programs/helper.js b/module/programs/helper.js index aab35f4a..f791fa9a 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -1082,13 +1082,15 @@ module.exports = class ProgramsHelper { } } console.log("kafka push status :",pushProgramUsersDetailsToKafka) + let joinProgramDetails = joinProgram.toObject(); + if ( pushProgramUsersDetailsToKafka ) { - joinProgram.programName = programData[0].name; - joinProgram.programExternalId = programData[0].externalId; - joinProgram.requestForPIIConsent = programData[0].requestForPIIConsent; - + joinProgramDetails.programName = programData[0].name; + joinProgramDetails.programExternalId = programData[0].externalId; + joinProgramDetails.requestForPIIConsent = programData[0].requestForPIIConsent; + // push programUsers details to kafka - await kafkaProducersHelper.pushProgramUsersToKafka(joinProgram); + await kafkaProducersHelper.pushProgramUsersToKafka(joinProgramDetails); } return resolve({ From 7ba3e462bd2f8642761ac67ea6dfd1ef0d2936c9 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Tue, 16 May 2023 14:48:49 +0530 Subject: [PATCH 323/331] change in PROGRAM_DESCRIPTION constant --- generics/constants/api-responses.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/generics/constants/api-responses.js b/generics/constants/api-responses.js index b32fc19d..36dccbfb 100644 --- a/generics/constants/api-responses.js +++ b/generics/constants/api-responses.js @@ -130,7 +130,6 @@ module.exports = { "ERROR_CREATING_PROGRAM" : "Error creating program", "PROGRAM_NOT_FOUND" : "Program not found" , "PROGRAM_EXIST" : "Program exist", - "PROGRAM_DESCRIPTION" : "Program description", "USER_TARGETED_PROGRAMS_FETCHED" : "Users programs fetched successfully", "USER_TARGETED_SOLUTIONS_FETCHED" : "Users solutions fetched successfully", "ROLE_REQUIRED_IN_SCOPE" : "Required role in scope", @@ -148,7 +147,7 @@ module.exports = { "TARGETED_SOLUTIONS_FETCHED": "Successfully targeted solutions fetched", "NO_ENTITY_FOUND_IN_LOCATION": "Entity not found in location", "TARGETED_PROGRAMS_FETCHED": "Targeted programs fetched successfully", - "PROGRAM_DESCRIPTION": "View and participate in educational programs active in your location and designed for your role", + "PROGRAM_DESCRIPTION": "View and participate in educational programs active in your location and designed for the role you selected", "ENTITIES_NOT_EXIST_IN_LOCATION" : "Entities does not belongs in the location", "ROLES_ADDED_IN_PROGRAM" : "Successfully added roles in program scope", "ENTITIES_ADDED_IN_PROGRAM" : "Successfully added entities in program scope", From 9b7cc6043666bd1c93131f8ee96942dff9869e08 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Tue, 16 May 2023 15:05:38 +0530 Subject: [PATCH 324/331] admin dbUpdate api code enabled --- controllers/v1/admin.js | 96 ++++++++++++++++++++--------------------- module/admin/helper.js | 54 +++++++++++------------ 2 files changed, 75 insertions(+), 75 deletions(-) diff --git a/controllers/v1/admin.js b/controllers/v1/admin.js index 10ea5bc9..66fdaa4c 100644 --- a/controllers/v1/admin.js +++ b/controllers/v1/admin.js @@ -135,60 +135,60 @@ // }) // } - // * - // * @api {post} /kendra/api/v1/admin/dbUpdate/:collectionName - // * Update the data in collection - // * @apiVersion 1.0.0 - // * @apiGroup Admin - // * @apiSampleRequest /kendra/api/v1/admin/dbUpdate/projects - // * @param {json} Request-Body: - // * { - // "findQuery": { - // "_id": { "$in" : ["601921e86ffa9c5e9d0b53e7"] } - // }, - // "mongoIdKeys" : ["_id"], - // "updateQuery" : { - // "$set" : { "status": "started"} - // } - // } - // * @apiParamExample {json} Response: - // * { - // "message": "Data Updated successfully", - // "status": 200 - // * } - // * @apiUse successBody - // * @apiUse errorBody + /** + * @api {post} /kendra/api/v1/admin/dbUpdate/:collectionName + * Update the data in collection + * @apiVersion 1.0.0 + * @apiGroup Admin + * @apiSampleRequest /kendra/api/v1/admin/dbUpdate/projects + * @param {json} Request-Body: + * { + "findQuery": { + "_id": { "$in" : ["601921e86ffa9c5e9d0b53e7"] } + }, + "mongoIdKeys" : ["_id"], + "updateQuery" : { + "$set" : { "status": "started"} + } + } + * @apiParamExample {json} Response: + * { + "message": "Data Updated successfully", + "status": 200 + * } + * @apiUse successBody + * @apiUse errorBody - // /** - // * Update the data in collection - // * @method - // * @name dbUpdate - // * @param {String} _id - MongoDB Collection Name - // * @param {Object} req - Req Body - // * @returns {JSON} list of data. - // */ + /** + * Update the data in collection + * @method + * @name dbUpdate + * @param {String} _id - MongoDB Collection Name + * @param {Object} req - Req Body + * @returns {JSON} list of data. + */ - // async dbUpdate(req) { - // return new Promise(async (resolve, reject) => { - // try { + async dbUpdate(req) { + return new Promise(async (resolve, reject) => { + try { - // let result = await adminHelper.dbUpdate( - // req.params._id, - // req.body - // ); + let result = await adminHelper.dbUpdate( + req.params._id, + req.body + ); - // return resolve(result); + return resolve(result); - // } catch (error) { - // return reject({ - // status: error.status || httpStatusCode.internal_server_error.status, - // message: error.message || httpStatusCode.internal_server_error.message, - // errorObject: error - // }) - // } - // }) - // } + } catch (error) { + return reject({ + status: error.status || httpStatusCode.internal_server_error.status, + message: error.message || httpStatusCode.internal_server_error.message, + errorObject: error + }) + } + }) + } /** * @api {post} /kendra/api/v1/admin/dbCreate/:collectionName diff --git a/module/admin/helper.js b/module/admin/helper.js index b2afe40d..3cb1271d 100644 --- a/module/admin/helper.js +++ b/module/admin/helper.js @@ -176,38 +176,38 @@ module.exports = class adminHelper { // }) // } - // /** - // * Update the data in any model - // * @method - // * @name dbUpdate - // * @param {Object} reqBody - request body - // * @returns {Object} - collection details. - // */ + /** + * Update the data in any model + * @method + * @name dbUpdate + * @param {Object} reqBody - request body + * @returns {Object} - collection details. + */ - // static dbUpdate( collection, reqBody ) { - // return new Promise(async (resolve, reject) => { - // try { + static dbUpdate( collection, reqBody ) { + return new Promise(async (resolve, reject) => { + try { - // if ( reqBody.mongoIdKeys ) { - // reqBody.query = await this.convertStringToObjectIdInQuery(reqBody.findQuery, reqBody.mongoIdKeys); - // } + if ( reqBody.mongoIdKeys ) { + reqBody.query = await this.convertStringToObjectIdInQuery(reqBody.findQuery, reqBody.mongoIdKeys); + } - // let updateData = await database.getCollection(collection).updateMany(reqBody.findQuery, reqBody.updateQuery); + let updateData = await database.getCollection(collection).updateMany(reqBody.findQuery, reqBody.updateQuery); - // return resolve({ - // message : constants.apiResponses.DATA_UPDATED_SUCCESSFULLY, - // success : true - // }); + return resolve({ + message : constants.apiResponses.DATA_UPDATED_SUCCESSFULLY, + success : true + }); - // } catch (error) { - // return resolve({ - // success: false, - // message: error.message, - // data: false - // }); - // } - // }) - // } + } catch (error) { + return resolve({ + success: false, + message: error.message, + data: false + }); + } + }) + } /** * Create a new mongodb record From 8901499358422e5a9585fc178e027f58501db03b Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 19 May 2023 16:18:43 +0530 Subject: [PATCH 325/331] consentShared key added and kafka event trigger conditions updated --- models/programUsers.js | 6 +++++- module/programs/helper.js | 31 +++++++++++++++++++++++-------- 2 files changed, 28 insertions(+), 9 deletions(-) diff --git a/models/programUsers.js b/models/programUsers.js index b6115dd4..dbcbcd91 100644 --- a/models/programUsers.js +++ b/models/programUsers.js @@ -21,7 +21,11 @@ module.exports = { required: true }, userRoleInformation: Object, - appInformation: Object + appInformation: Object, + consentShared: { + type: Boolean, + default: false + } }, compoundIndex: [ { diff --git a/module/programs/helper.js b/module/programs/helper.js index f791fa9a..5c26992d 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -980,7 +980,7 @@ module.exports = class ProgramsHelper { "rootOrganisations" ] ); - + if ( !programData.length > 0 ) { throw ({ status: httpStatusCode.bad_request.status, @@ -996,7 +996,7 @@ module.exports = class ProgramsHelper { userId: userId, programId: programId }, - ["_id"] + ["_id","consentShared"] ); // if user not joined for program. we have add more key values to programUsersData if ( !programUsersDetails.length > 0 ) { @@ -1019,7 +1019,7 @@ module.exports = class ProgramsHelper { programId: programId, userRoleInformation: data.userRoleInformation, userId: userId, - userProfile:userProfile.data, + userProfile: userProfile.data, resourcesStarted : false } if( appName != "" ) { @@ -1057,8 +1057,16 @@ module.exports = class ProgramsHelper { status: httpStatusCode.bad_request.status } } + } - pushProgramUsersDetailsToKafka = true; + + } + + // if requestForPIIConsent Is false and user not joined program till now then set pushProgramUsersDetailsToKafka = true; + // if requestForPIIConsent == true and data.consentShared value is true which means user interacted with the consent popup set pushProgramUsersDetailsToKafka = true; + if((programData[0].hasOwnProperty('requestForPIIConsent') && programData[0].requestForPIIConsent === false && !programUsersDetails.length > 0) || + ((programData[0].hasOwnProperty('requestForPIIConsent') && programData[0].requestForPIIConsent === true) && (data.hasOwnProperty('consentShared') && data.consentShared == true) ) ){ + pushProgramUsersDetailsToKafka = true; } //create or update query @@ -1066,10 +1074,14 @@ module.exports = class ProgramsHelper { programId: programId, userId: userId }; - + //if a resource is started if ( data.isResource ) { programUsersData.resourcesStarted = true; } + //if user interacted with the consent-popup + if ( data.consentShared ) { + programUsersData.consentShared = true; + } update['$set'] = programUsersData; // add record to programUsers collection @@ -1081,14 +1093,17 @@ module.exports = class ProgramsHelper { status: httpStatusCode.bad_request.status } } - console.log("kafka push status :",pushProgramUsersDetailsToKafka) + let joinProgramDetails = joinProgram.toObject(); - + // if programUsersDetails[0].consentShared === true which means the data is already pushed to Kafka once, So revert pushProgramUsersDetailsToKafka to false + if (programUsersDetails.length > 0 && programUsersDetails[0].hasOwnProperty('consentShared') && programUsersDetails[0].consentShared === true) { + pushProgramUsersDetailsToKafka = false; + } + console.log("kafka push status :",pushProgramUsersDetailsToKafka) if ( pushProgramUsersDetailsToKafka ) { joinProgramDetails.programName = programData[0].name; joinProgramDetails.programExternalId = programData[0].externalId; joinProgramDetails.requestForPIIConsent = programData[0].requestForPIIConsent; - // push programUsers details to kafka await kafkaProducersHelper.pushProgramUsersToKafka(joinProgramDetails); } From af5422c4fe41c24945589bc38524f31d2e4aed9d Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Sat, 20 May 2023 08:51:05 +0530 Subject: [PATCH 326/331] changes added to pass consentShared value to front end --- module/programUsers/helper.js | 16 +++++++++------- module/programs/helper.js | 5 +---- module/solutions/helper.js | 6 ++++-- module/users/helper.js | 6 ++++-- 4 files changed, 18 insertions(+), 15 deletions(-) diff --git a/module/programUsers/helper.js b/module/programUsers/helper.js index 39f15f1b..3429474b 100644 --- a/module/programUsers/helper.js +++ b/module/programUsers/helper.js @@ -120,20 +120,21 @@ module.exports = class ProgramUsersHelper { } /** - * check if user joined a program or not + * check if user joined a program or not and consentShared * @method - * @name checkForUserJoinedProgram + * @name checkForUserJoinedProgramAndConsentShared * @param {String} programId * @param {String} userId - * @returns {Boolean} - true/false. + * @returns {Object} result. */ - static checkForUserJoinedProgram( + static checkForUserJoinedProgramAndConsentShared( programId, userId ) { return new Promise(async (resolve, reject) => { try { + let result = {}; const query = { userId: userId, programId: programId @@ -142,10 +143,11 @@ module.exports = class ProgramUsersHelper { //Check data present in programUsers collection. let programUsers = await this.programUsersDocuments( query, - ["_id"] + ["_id","consentShared"] ); - let joinedProgram = programUsers.length > 0 ? true :false - return resolve(joinedProgram); + result.joinProgram = programUsers.length > 0 ? true : false; + result.consentShared = programUsers.length > 0 ? programUsers[0].consentShared : false; + return resolve(result); } catch (error) { return reject(error); diff --git a/module/programs/helper.js b/module/programs/helper.js index 5c26992d..3d39bfcb 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -477,7 +477,6 @@ module.exports = class ProgramsHelper { }); } catch (error) { - console.log("error :",error) return resolve({ success : false, message : error.message, @@ -531,7 +530,6 @@ module.exports = class ProgramsHelper { }); } catch (error) { - console.log("error :",error) return resolve({ success : false, message : error.message, @@ -1049,7 +1047,6 @@ module.exports = class ProgramsHelper { } } let consentResponse = await userService.setUserConsent(userToken, userConsentRequestBody) - console.log("consentResponse ",consentResponse) if(!consentResponse.success){ throw { @@ -1099,7 +1096,7 @@ module.exports = class ProgramsHelper { if (programUsersDetails.length > 0 && programUsersDetails[0].hasOwnProperty('consentShared') && programUsersDetails[0].consentShared === true) { pushProgramUsersDetailsToKafka = false; } - console.log("kafka push status :",pushProgramUsersDetailsToKafka) + if ( pushProgramUsersDetailsToKafka ) { joinProgramDetails.programName = programData[0].name; joinProgramDetails.programExternalId = programData[0].externalId; diff --git a/module/solutions/helper.js b/module/solutions/helper.js index d590b230..798b10a6 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -2015,8 +2015,10 @@ module.exports = class SolutionsHelper { } //Check data present in programUsers collection. - //checkForUserJoinedProgram will check for data and if its present return true else false. - templateOrQuestionDetails.result.programJoined = await programUsersHelper.checkForUserJoinedProgram(solutionData.programId,userId); + //checkForUserJoinedProgramAndConsentShared will returns an object which contain joinProgram and consentShared status + let programJoinStatus = await programUsersHelper.checkForUserJoinedProgramAndConsentShared(solutionData.programId,userId); + templateOrQuestionDetails.result.programJoined = programJoinStatus.joinProgram; + templateOrQuestionDetails.result.consentShared = programJoinStatus.consentShared; return resolve(templateOrQuestionDetails); diff --git a/module/users/helper.js b/module/users/helper.js index 2ee84e70..89ab1492 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -594,8 +594,10 @@ module.exports = class UsersHelper { result.requestForPIIConsent = programData[0].requestForPIIConsent; } //Check data present in programUsers collection. - //checkForUserJoinedProgram will check for data and if its present return true else false. - result.programJoined = await programUsersHelper.checkForUserJoinedProgram(programId,userId); + //checkForUserJoinedProgramAndConsentShared will returns an object which contain joinProgram and consentShared status. + let programJoinStatus = await programUsersHelper.checkForUserJoinedProgramAndConsentShared(programId,userId); + result.programJoined = programJoinStatus.joinProgram; + result.consentShared = programJoinStatus.consentShared; return resolve({ message: constants.apiResponses.PROGRAM_SOLUTIONS_FETCHED, From f3e992888500444e67618b96655ee26f65c5992a Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 22 May 2023 08:07:31 +0530 Subject: [PATCH 327/331] pushProgramUsersDetailsToKafka determining codeblock change --- module/programs/helper.js | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/module/programs/helper.js b/module/programs/helper.js index 3d39bfcb..1dd185a5 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -1063,7 +1063,13 @@ module.exports = class ProgramsHelper { // if requestForPIIConsent == true and data.consentShared value is true which means user interacted with the consent popup set pushProgramUsersDetailsToKafka = true; if((programData[0].hasOwnProperty('requestForPIIConsent') && programData[0].requestForPIIConsent === false && !programUsersDetails.length > 0) || ((programData[0].hasOwnProperty('requestForPIIConsent') && programData[0].requestForPIIConsent === true) && (data.hasOwnProperty('consentShared') && data.consentShared == true) ) ){ + pushProgramUsersDetailsToKafka = true; + + // if programUsersDetails[0].consentShared === true which means the data is already pushed to Kafka once, So revert pushProgramUsersDetailsToKafka to false + if (programUsersDetails.length > 0 && programUsersDetails[0].hasOwnProperty('consentShared') && programUsersDetails[0].consentShared === true) { + pushProgramUsersDetailsToKafka = false; + } } //create or update query @@ -1092,11 +1098,7 @@ module.exports = class ProgramsHelper { } let joinProgramDetails = joinProgram.toObject(); - // if programUsersDetails[0].consentShared === true which means the data is already pushed to Kafka once, So revert pushProgramUsersDetailsToKafka to false - if (programUsersDetails.length > 0 && programUsersDetails[0].hasOwnProperty('consentShared') && programUsersDetails[0].consentShared === true) { - pushProgramUsersDetailsToKafka = false; - } - + if ( pushProgramUsersDetailsToKafka ) { joinProgramDetails.programName = programData[0].name; joinProgramDetails.programExternalId = programData[0].externalId; From 47a9fb31bd0f13b6a0fa5388020251cc24468166 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Mon, 22 May 2023 11:34:01 +0530 Subject: [PATCH 328/331] added changes to check pushProgramUsersDetailsToKafka==true in single if condition --- module/programs/helper.js | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/module/programs/helper.js b/module/programs/helper.js index 1dd185a5..f71fc0f4 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -1061,15 +1061,13 @@ module.exports = class ProgramsHelper { // if requestForPIIConsent Is false and user not joined program till now then set pushProgramUsersDetailsToKafka = true; // if requestForPIIConsent == true and data.consentShared value is true which means user interacted with the consent popup set pushProgramUsersDetailsToKafka = true; + // if programUsersDetails[0].consentShared === true which means the data is already pushed to Kafka once if((programData[0].hasOwnProperty('requestForPIIConsent') && programData[0].requestForPIIConsent === false && !programUsersDetails.length > 0) || - ((programData[0].hasOwnProperty('requestForPIIConsent') && programData[0].requestForPIIConsent === true) && (data.hasOwnProperty('consentShared') && data.consentShared == true) ) ){ + ((programData[0].hasOwnProperty('requestForPIIConsent') && programData[0].requestForPIIConsent === true) && (data.hasOwnProperty('consentShared') && data.consentShared == true && + (programUsersDetails.length > 0 && programUsersDetails[0].consentShared === false || !programUsersDetails.length > 0)))) { pushProgramUsersDetailsToKafka = true; - - // if programUsersDetails[0].consentShared === true which means the data is already pushed to Kafka once, So revert pushProgramUsersDetailsToKafka to false - if (programUsersDetails.length > 0 && programUsersDetails[0].hasOwnProperty('consentShared') && programUsersDetails[0].consentShared === true) { - pushProgramUsersDetailsToKafka = false; - } + } //create or update query @@ -1082,8 +1080,8 @@ module.exports = class ProgramsHelper { programUsersData.resourcesStarted = true; } //if user interacted with the consent-popup - if ( data.consentShared ) { - programUsersData.consentShared = true; + if ( data.hasOwnProperty('consentShared') ) { + programUsersData.consentShared = data.consentShared; } update['$set'] = programUsersData; @@ -1098,13 +1096,14 @@ module.exports = class ProgramsHelper { } let joinProgramDetails = joinProgram.toObject(); - + if ( pushProgramUsersDetailsToKafka ) { joinProgramDetails.programName = programData[0].name; joinProgramDetails.programExternalId = programData[0].externalId; joinProgramDetails.requestForPIIConsent = programData[0].requestForPIIConsent; // push programUsers details to kafka await kafkaProducersHelper.pushProgramUsersToKafka(joinProgramDetails); + } return resolve({ From 56ac24e19429152b3b8d98fef5e661e48249613e Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Wed, 24 May 2023 15:57:50 +0530 Subject: [PATCH 329/331] bug fix program startDate and endDate --- module/users/helper.js | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/module/users/helper.js b/module/users/helper.js index 89ab1492..4f839661 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -72,7 +72,6 @@ module.exports = class UsersHelper { ) { return new Promise(async (resolve, reject) => { try { - let userPrivateProgram = {}; let dateFormat = gen.utils.epochTime(); let parentSolutionInformation = {}; @@ -128,7 +127,13 @@ module.exports = class UsersHelper { userPrivateProgram = checkforProgramExist[0]; } } else { - + /* If the programId is not passed from the front end, we will enter this else block. + In this block, we need to provide the necessary basic details to create a new program, Including startDate and endDate.*/ + // Current date + let startDate = new Date(); + // Add one year to the current date + var endDate = new Date(); + endDate.setFullYear(endDate.getFullYear() + 1); let programData = await _createProgramData( data.programName, data.programExternalId @@ -140,12 +145,11 @@ module.exports = class UsersHelper { ? data.programDescription : data.programName, userId, - duplicateProgram.startDate, - duplicateProgram.endDate + startDate, + endDate ); userPrivateProgram = await programsHelper.create(programData); - } let solutionDataToBeUpdated = { From 8d6e22e5c5e932abf5188bd4aae3a2070ddb7f91 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Wed, 24 May 2023 16:08:34 +0530 Subject: [PATCH 330/331] datatype change --- module/users/helper.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/module/users/helper.js b/module/users/helper.js index 4f839661..35ee9c8b 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -132,7 +132,7 @@ module.exports = class UsersHelper { // Current date let startDate = new Date(); // Add one year to the current date - var endDate = new Date(); + let endDate = new Date(); endDate.setFullYear(endDate.getFullYear() + 1); let programData = await _createProgramData( data.programName, From 7ca4d90c501ddee18fb64e7255d096b351c38395 Mon Sep 17 00:00:00 2001 From: VISHNUDAS-tunerlabse Date: Fri, 26 May 2023 18:02:12 +0530 Subject: [PATCH 331/331] program/update api enhancement --- module/programs/helper.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/module/programs/helper.js b/module/programs/helper.js index f71fc0f4..dba9aa73 100644 --- a/module/programs/helper.js +++ b/module/programs/helper.js @@ -14,6 +14,7 @@ const userService = require(ROOT_PATH + "/generics/services/users"); const kafkaProducersHelper = require(ROOT_PATH + "/generics/kafka/producers"); const programUsersHelper = require(MODULES_BASE_PATH + "/programUsers/helper"); + /** * ProgramsHelper * @class @@ -336,7 +337,11 @@ module.exports = class ProgramsHelper { data.updatedBy = userId; data.updatedAt = new Date(); - + //convert components to objectedIds + if (data.components && data.components.length > 0) { + data.components = data.components.map(component => gen.utils.convertStringToObjectId(component)); + } + let program = await database.models.programs.findOneAndUpdate({ _id : programId },{ $set : _.omit(data,["scope"]) }, { new: true });