diff --git a/controllers/v1/forms.js b/controllers/v1/forms.js index 205a404e..fc0a0718 100644 --- a/controllers/v1/forms.js +++ b/controllers/v1/forms.js @@ -23,7 +23,7 @@ return "forms"; } - /** + /** * @api {get} /kendra/api/v1/forms/details/:formName * Form details * @apiVersion 0.0.1 @@ -102,5 +102,95 @@ }); } +/** + * @api {post} /kendra/api/v1/forms/create + * Form Create + * @apiVersion 0.0.1 + * @apiName Form Create + * @apiGroup Forms + * @apiHeader {String} X-authenticated-user-token Authenticity token + * @apiSampleRequest /kendra/api/v1/forms/create + * @apiUse successBody + * @apiUse errorBody + * @apiParamExample {json} Response: + * { + * "status": 200, + "message": "Forms created successfully", + "result": { + "_id": "5f33c3d85f637784791cd830" + } + } + */ + + /** + * Create form. + * @method + * @name create + * @param {Object} req - Requested data. + * @returns {JSON} Form details. + */ + + async create(req) { + return new Promise(async (resolve, reject) => { + try { + + let createForm = await formsHelper.create(req.body); + return resolve(createForm); + + } 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/forms/update/scope + * Form Update + * @apiVersion 0.0.1 + * @apiName Form Update + * @apiGroup Forms + * @apiHeader {String} X-authenticated-user-token Authenticity token + * @apiSampleRequest /kendra/api/v1/forms/update/scope + * @apiUse successBody + * @apiUse errorBody + * @apiParamExample {json} Response: + * { + * "status": 200, + "message": "Forms updated successfully" + } + */ + + /** + * Update form. + * @method + * @name update + * @param {Object} req - Requested data. + * @param {Object} req.params._id - Form name. + * @returns {JSON} Form details. + */ + + async update(req) { + return new Promise(async (resolve, reject) => { + try { + + let updateForm = await formsHelper.update( + req.params._id, + req.body + ); + return resolve(updateForm); + + } 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/solutions.js b/controllers/v1/solutions.js index 3dedfef4..8415b06f 100644 --- a/controllers/v1/solutions.js +++ b/controllers/v1/solutions.js @@ -209,10 +209,13 @@ module.exports = class Solutions extends Abstract { * @apiGroup Solutions * @apiParamExample {json} Request-Body: * { - "role" : "HM,DEO", - "state" : "236f5cff-c9af-4366-b0b6-253a1789766a", - "district" : "1dcbc362-ec4c-4559-9081-e0c2864c2931", - "school" : "c5726207-4f9f-4f45-91f1-3e9e8e84d824", + "roles" : "HM,DEO", + "entities": { + "block": "81ca90fa-e38b-4d5d-858a-20ae5b402438", + "district": "b5c35cfc-6c1e-4266-94ef-a425c43c7f4e", + "state": "bc75cc99-9205-463e-a722-5326857838f8", + "school": "28236605304" + }, "filter" : {} } * @apiHeader {String} X-authenticated-user-token Authenticity token @@ -255,7 +258,10 @@ module.exports = class Solutions extends Abstract { req.query.programId ? req.query.programId : "", req.pageSize, req.pageNo, - req.searchText + req.searchText, + req.headers["x-app-ver"] ? req.headers["x-app-ver"] : req.headers.appversion ? req.headers.appversion : "", + req.userDetails.userId, + req.userDetails.userToken ); targetedSolutions["result"] = targetedSolutions.data; @@ -278,10 +284,13 @@ module.exports = class Solutions extends Abstract { * @apiGroup Solutions * @apiParamExample {json} Request-Body: * { - "role" : "HM,DEO", - "state" : "236f5cff-c9af-4366-b0b6-253a1789766a", - "district" : "1dcbc362-ec4c-4559-9081-e0c2864c2931", - "school" : "c5726207-4f9f-4f45-91f1-3e9e8e84d824" + "roles" : "HM,DEO", + "entities": { + "block": "81ca90fa-e38b-4d5d-858a-20ae5b402438", + "district": "b5c35cfc-6c1e-4266-94ef-a425c43c7f4e", + "state": "bc75cc99-9205-463e-a722-5326857838f8", + "school": "28236605304" + } } * @apiHeader {String} X-authenticated-user-token Authenticity token * @apiSampleRequest /kendra/api/v1/solutions/detailsBasedOnRoleAndLocation/5fc3dff14ea9b44f3340afe2 @@ -320,7 +329,10 @@ module.exports = class Solutions extends Abstract { let solutionDetails = await solutionsHelper.detailsBasedOnRoleAndLocation( req.params._id, - req.body + req.body, + req.headers["x-app-ver"] ? req.headers["x-app-ver"] : req.headers.appversion ? req.headers.appversion : "", + req.userDetails.userId, + req.userDetails.userToken ); solutionDetails.result = solutionDetails.data; @@ -680,10 +692,13 @@ 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,DEO", - "state" : "236f5cff-c9af-4366-b0b6-253a1789766a", - "district" : "1dcbc362-ec4c-4559-9081-e0c2864c2931", - "school" : "c5726207-4f9f-4f45-91f1-3e9e8e84d824" + "entities": { + "block": "81ca90fa-e38b-4d5d-858a-20ae5b402438", + "district": "b5c35cfc-6c1e-4266-94ef-a425c43c7f4e", + "state": "bc75cc99-9205-463e-a722-5326857838f8", + "school": "28236605304" + }, + "roles": "DEO,HM" } * @apiParamExample {json} Response: { @@ -732,7 +747,10 @@ module.exports = class Solutions extends Abstract { req.pageNo, req.searchText, req.query.filter, - req.query.surveyReportPage ? req.query.surveyReportPage : "" + req.query.surveyReportPage ? req.query.surveyReportPage : "", + req.headers["x-app-ver"] ? req.headers["x-app-ver"] : req.headers.appversion ? req.headers.appversion : "", + req.userDetails.userId + ); observations["result"] = observations.data; @@ -808,10 +826,13 @@ module.exports = class Solutions extends Abstract { * @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" + "entities": { + "block": "81ca90fa-e38b-4d5d-858a-20ae5b402438", + "district": "b5c35cfc-6c1e-4266-94ef-a425c43c7f4e", + "state": "bc75cc99-9205-463e-a722-5326857838f8", + "school": "28236605304" + }, + "roles": "DEO,HM" } * @apiParamExample {json} Response: * { @@ -846,7 +867,8 @@ module.exports = class Solutions extends Abstract { req.body, req.userDetails.userId, req.userDetails.userToken, - req.query.hasOwnProperty("createProject") ? gen.utils.convertStringToBoolean(req.query.createProject) : true + req.query.hasOwnProperty("createProject") ? gen.utils.convertStringToBoolean(req.query.createProject) : true, + req.headers["x-app-ver"] ? req.headers["x-app-ver"] : req.headers.appversion ? req.headers.appversion : "" ); return resolve(solutionData); @@ -873,10 +895,13 @@ module.exports = class Solutions extends Abstract { * @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" + "entities": { + "block": "81ca90fa-e38b-4d5d-858a-20ae5b402438", + "district": "b5c35cfc-6c1e-4266-94ef-a425c43c7f4e", + "state": "bc75cc99-9205-463e-a722-5326857838f8", + "school": "28236605304" + }, + "roles": "DEO,HM" } * @apiParamExample {json} Response: * { diff --git a/controllers/v1/users.js b/controllers/v1/users.js index 813416ff..233c9e87 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 solutionsHelper = require(MODULES_BASE_PATH + "/solutions/helper.js"); /** * User @@ -218,10 +219,12 @@ module.exports = class Users extends Abstract { * @apiSampleRequest /kendra/api/v1/users/solutions/5ff438b04698083dbfab7284?page=1&limit=10 * @apiParamExample {json} Request-Body: * { - "role" : "HM,DEO", - "state" : "236f5cff-c9af-4366-b0b6-253a1789766a", - "district" : "1dcbc362-ec4c-4559-9081-e0c2864c2931", - "school" : "c5726207-4f9f-4f45-91f1-3e9e8e84d824" + "roles" : "HM,DEO", + "entities": { + "state" : "236f5cff-c9af-4366-b0b6-253a1789766a", + "district" : "1dcbc362-ec4c-4559-9081-e0c2864c2931", + "school" : "c5726207-4f9f-4f45-91f1-3e9e8e84d824" + } } * @apiUse successBody * @apiUse errorBody @@ -277,6 +280,8 @@ module.exports = class Users extends Abstract { req.pageSize, req.pageNo, req.searchText, + req.headers["x-app-ver"] ? req.headers["x-app-ver"] : req.headers.appversion ? req.headers.appversion : "", + req.userDetails.userId, req.userDetails.userToken ); @@ -284,7 +289,6 @@ module.exports = class Users extends Abstract { return resolve(targetedSolutions); } catch (error) { - return reject({ status: error.status || @@ -310,11 +314,13 @@ module.exports = class Users extends Abstract { * @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" - } + "roles" : "HM,DEO", + "entities": { + "state" : "236f5cff-c9af-4366-b0b6-253a1789766a", + "district" : "1dcbc362-ec4c-4559-9081-e0c2864c2931", + "school" : "c5726207-4f9f-4f45-91f1-3e9e8e84d824" + } + } * @apiParamExample {json} Response: * { * "message": "Users programs fetched successfully", @@ -351,35 +357,36 @@ module.exports = class Users extends Abstract { try { - let isAPrivateProgram = gen.utils.convertStringToBoolean(req.query.isAPrivateProgram); + let isAPrivateProgram = gen.utils.convertStringToBoolean(req.query.isAPrivateProgram); - if(isAPrivateProgram){ + if ( isAPrivateProgram ) { - let programsData = await usersHelper.privatePrograms(req.userDetails.userId); - return resolve(programsData); + let programsData = await usersHelper.privatePrograms(req.userDetails.userId); + return resolve(programsData); - } else { + } else { - let programs = - await usersHelper.programs( - req.body, - req.pageNo, - req.pageSize, - req.searchText - ); + let programs = + await usersHelper.programs( + req.body, + req.pageNo, + req.pageSize, + req.searchText, + req.headers["x-app-ver"] ? req.headers["x-app-ver"] : req.headers.appversion ? req.headers.appversion : "", + req.userDetails.userId, + req.userDetails.userToken + ); - programs.result = programs.data; - return resolve(programs); + programs.result = programs.data; + return resolve(programs); - } + } } catch (error) { - return reject({ status: error.status || httpStatusCode["internal_server_error"].status, - message: error.message || httpStatusCode["internal_server_error"].message @@ -471,10 +478,12 @@ module.exports = class Users extends Abstract { * @apiGroup Users * @apiParamExample {json} Request-Body: * { - "state" : "bc75cc99-9205-463e-a722-5326857838f8", - "district" : "b54a5c6d-98be-4313-af1c-33040b1703aa", - "school" : "2a128c91-a5a2-4e25-aa21-3d9196ad8203", - "role" : "DEO,HM" + "roles" : "HM,DEO", + "entities": { + "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 /kendra/api/v1/users/targetedEntity/601d41607d4c835cf8b724ad @@ -504,7 +513,18 @@ module.exports = class Users extends Abstract { return new Promise(async (resolve, reject) => { try { - let roleArray = req.body.role.split(","); + let convertedBodyData = await solutionsHelper.checkForConvertBodyData( + req.body, + req.headers["x-app-ver"] ? req.headers["x-app-ver"] : req.headers.appversion ? req.headers.appversion : "", + req.userDetails.userId, + req.userDetails.userToken + ); + + if( convertedBodyData.success ) { + req.body = convertedBodyData.data + } + + let roleArray = req.body.roles.split(","); let targetedEntities = {}; if ( roleArray.length === 1 ) { diff --git a/generics/constants/api-responses.js b/generics/constants/api-responses.js index ef66e329..9ae593a6 100644 --- a/generics/constants/api-responses.js +++ b/generics/constants/api-responses.js @@ -189,6 +189,8 @@ 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", + "FORM_CREATED_SUCCESSFULLY": "Form created successfully ", + "FORM_UPDATED_SUCCESSFULLY": "Form updated successfully ", + "FAILED_TO_UPDATE_FORM" : "Failed to update form", "BASE_CERTIFICATE_TEMPLATE_NOT_FOUND" : "Base certificate template not found" }; diff --git a/generics/constants/common.js b/generics/constants/common.js index bac7594f..e447de5b 100644 --- a/generics/constants/common.js +++ b/generics/constants/common.js @@ -72,5 +72,10 @@ module.exports = { "PROFILE_CONFIG_FORM_KEY" : "profileConfig_v2", "SERVER_TIME_OUT" : 5000, "CERTIFICATE" : "certificate", - "ORACLE_CLOUD_SERVICE" : "OCI" + "ORACLE_CLOUD_SERVICE" : "OCI", + "SCOPE_FORM_NAME" : "scope", + "USER_PROFILE" : "userProfile", + "ROOT" : "root", + "SUB_TYPE" : "subType", + "STRING" : "string" }; diff --git a/generics/constants/endpoints.js b/generics/constants/endpoints.js index 2deb5488..16d0fdf9 100644 --- a/generics/constants/endpoints.js +++ b/generics/constants/endpoints.js @@ -16,7 +16,7 @@ module.exports = { SUNBIRD_DIALCODE_STATUS : "/dialcode/v1/read", SUNBIRD_CONTENT_LINK : "/dialcode/v1/content/link", SUNBIRD_PUBLISH_CONTENT : "/v1/content/v1/publish", - USER_READ : "/api/user/v1/read", + USER_READ : "/v5/user/read", SUNBIRD_INDEX_SYNC : "/data/v1/index/sync", SUNBIRD_CREATE_CONTENT : "/content/v1/create", SUNBIRD_UPLOAD_CONTENT : "/content/v1/upload", diff --git a/generics/helpers/utils.js b/generics/helpers/utils.js index fed2c4a7..19fe5db9 100644 --- a/generics/helpers/utils.js +++ b/generics/helpers/utils.js @@ -273,6 +273,128 @@ function checkIfStringIsNumber(str) { return /^[0-9]+$/.test(str); } +/** + * convert user data for program targeting. + * @function + * @name convertUserRoleAndLocationData + * @param {Object} userReqBody + * @returns {Object} returns the converted req body +*/ + +function convertUserRoleAndLocationData( bodyData ) { + + if ( bodyData.entities ) { + return bodyData; + } + + let convertedData = {}; + convertedData.entities = _.omit(bodyData,["role","filter"]); + if ( bodyData.role ) { + convertedData.roles = bodyData.role; + } + + if ( bodyData.filter ) { + convertedData.filter = bodyData.filter; + } + + return convertedData; + +} + +/** + * convert userData or not + * @method + * @name convertUserDatarNot + * @param {String} appVersion - app Version. + * @returns {Boolean} - true or false +*/ + +function convertUserDataorNot( appVersion ) { + + let appVer = appVersion.split('.',2).join('.'); + let appVersionNo = Number(appVer); + if ( !isNaN(appVersionNo) && appVersionNo <= 5.1 ) { + return true + } else { + return false + } + +} + +/** + * add missing user data for program targeting. + * @function + * @name addMissingUserProfileDataToRequestBody + * @param {Object} userReqBody + * @returns {Object} returns the converted req body +*/ + +function addMissingUserProfileDataToRequestBody( bodyData, userProfile, formData ) { + + let missingFields = {}; + let keysInBodyData = Object.keys(bodyData); + + if ( userProfile && Object.keys(userProfile).length > 0 && + formData && formData.length > 0 + ) { + //loop all form fields + for ( let pointerToform = 0; pointerToform < formData.length; pointerToform++ ) { + let currentFormValue = formData[pointerToform]; + //check requestKey exist in bodyData + let keyExistInReqBody = currentFormValue.requestKey.some(key => keysInBodyData.includes(key)) + + if ( !keyExistInReqBody ) { + //add from userProfile + let api = currentFormValue.api; + //if api is userProfile + if ( api && + api.name === constants.common.USER_PROFILE && + api.responseSchema && + Object.keys(api.responseSchema).length > 0 + ) { + if ( api.responseSchema.path === constants.common.ROOT && + api.responseSchema.key != "" && + api.responseSchema.projection && + api.responseSchema.projection.length > 0 + ) { + + if ( userProfile[api.responseSchema.key] ) { + + for ( let pointerToProjection = 0 ; pointerToProjection < api.responseSchema.projection.length; pointerToProjection++ ) { + + let eachProjection = api.responseSchema.projection[pointerToProjection]; + //check key exist in api + if ( userProfile[api.responseSchema.key] && userProfile[api.responseSchema.key].length > 0 ) { + //add the projection data to scopeKey + missingFields[currentFormValue.scopeKey] = []; + + for ( let pointerToItem = 0; pointerToItem < userProfile[api.responseSchema.key].length; pointerToItem++ ) { + + let currentItem = userProfile[api.responseSchema.key][pointerToItem]; + //convert role to upper case + if ( currentItem[eachProjection] && eachProjection === constants.common.SUB_TYPE) { + missingFields[currentFormValue.scopeKey].push(currentItem[eachProjection].toUpperCase()); + } else { + missingFields[currentFormValue.scopeKey].push(currentItem[eachProjection]); + } + } + } + } + } + + } + } + } + } + } + + if ( missingFields && Object.keys(missingFields).length > 0 ) { + Object.assign(bodyData, missingFields); + } + + return bodyData; +} + module.exports = { camelCaseToTitleCase : camelCaseToTitleCase, lowerCase : lowerCase, @@ -290,5 +412,8 @@ module.exports = { md5Hash : md5Hash, filterLocationIdandCode : filterLocationIdandCode, arrayIdsTobjectIds : arrayIdsTobjectIds, - checkIfStringIsNumber : checkIfStringIsNumber + checkIfStringIsNumber : checkIfStringIsNumber, + convertUserDataorNot : convertUserDataorNot, + convertUserRoleAndLocationData : convertUserRoleAndLocationData, + addMissingUserProfileDataToRequestBody : addMissingUserProfileDataToRequestBody }; diff --git a/generics/services/users.js b/generics/services/users.js index dad76493..091b590b 100644 --- a/generics/services/users.js +++ b/generics/services/users.js @@ -9,14 +9,14 @@ const request = require('request'); const userServiceUrl = process.env.USER_SERVICE_URL; -const profile = function ( token,userId = "" ) { +const profile = function ( token, userId = "" ) { return new Promise(async (resolve, reject) => { try { let url = userServiceUrl + constants.endpoints.USER_READ; if( userId !== "" ) { - url = url + "/" + userId; + url = url + "/" + userId + "?" + "fields=organisations,roles,locations,declarations,externalIds" } const options = { diff --git a/migrations/5.1/README.md b/migrations/5.1/README.md new file mode 100644 index 00000000..6757859d --- /dev/null +++ b/migrations/5.1/README.md @@ -0,0 +1,5 @@ +## Migrations for 5.1 +Steps to run the migration files +- Navigate to migrations/5.1/ folder +- The script which convert existing scopen to another format. To run the script use the below command, + > node convertScope.js \ No newline at end of file diff --git a/migrations/5.1/convertScope.js b/migrations/5.1/convertScope.js new file mode 100644 index 00000000..5faa3dd8 --- /dev/null +++ b/migrations/5.1/convertScope.js @@ -0,0 +1,110 @@ +/** + * name : convertScope.js + * author : Priyanka Pradeep + * created-date : 21-Nov-2022 + * Description : Migration script for convert scope in programs & solutions. + */ + +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 updatedSolutionIds = []; + let updatedProgramIds = []; + let pushedToArray; + + let collections = ['programs', 'solutions']; + for ( let pointerToCollection = 0; pointerToCollection < collections.length; pointerToCollection++ ) { + let currentCollectionName = collections[pointerToCollection]; + + if ( currentCollectionName == 'programs' ) { + pushedToArray = updatedProgramIds; + } else { + pushedToArray = updatedSolutionIds; + } + + let collectionDocs = await db.collection(currentCollectionName).find({scope : {$exists: true}}).project({_id : 1}).toArray(); + let chunkOfCollection = _.chunk(collectionDocs, 2); + + for ( let chunkPointer = 0; chunkPointer < chunkOfCollection.length; chunkPointer++ ) { + collectionIds = await chunkOfCollection[chunkPointer].map( + doc => { + return doc._id; + } + ); + + let eachCollection = await db.collection(currentCollectionName).find({ + _id: { $in : collectionIds } + }).project({ + "scope":1 + }).toArray(); + + for ( let chunkCollectionPointer = 0 ; chunkCollectionPointer < eachCollection.length; chunkCollectionPointer++ ) { + + let collection = eachCollection[chunkCollectionPointer]; + let updateScope = false; + let scope = collection.scope ? collection.scope : {}; + + if ( scope && Object.keys(scope).length > 0 ) { + //remove entityTypeId from scope + if ( scope.entityTypeId ) { + delete scope.entityTypeId; + updateScope = true; + } + + //change the format of role + if ( scope.roles && scope.roles.length > 0 ) { + + let roles = []; + for ( const role of scope['roles'] ) { + if ( role && Object.keys(role).length > 0 && role.code) { + roles.push(role.code) + } + } + + if ( roles.length > 0 ) { + scope.roles = roles; + updateScope = true; + } + } + + //update scope + if ( updateScope ) { + let updateObject = { + "$set" : {} + }; + updateObject["$set"]["scope"] = scope; + + await db.collection(currentCollectionName).findOneAndUpdate({ + "_id": collection._id, + },updateObject); + + pushedToArray.push(collection._id); + } + } + } + } + } + + console.log(updatedProgramIds.length,"updatedProgramIds length") + console.log(updatedSolutionIds.length,"updatedSolutionIds length") + console.log("completed") + connection.close(); + } + catch (error) { + console.log(error) + } +})().catch(err => console.error(err)); diff --git a/models/programs.js b/models/programs.js index 233fd9d6..dbc1418f 100644 --- a/models/programs.js +++ b/models/programs.js @@ -29,20 +29,7 @@ module.exports = { type : Boolean, index : true }, - scope : { - entityType : String, - entities : { - type : Array, - index : true - }, - roles : [{ - _id : "ObjectId", - code : { - type : String, - index : true - } - }] - }, + scope : Object, isDeleted: { default : false, type : Boolean, diff --git a/models/solutions.js b/models/solutions.js index 389027a7..7a9e2ead 100644 --- a/models/solutions.js +++ b/models/solutions.js @@ -71,20 +71,7 @@ module.exports = { }, project : Object, referenceFrom : String, - scope : { - entityType : String, - entities : { - type : Array, - index : true - }, - roles : [{ - _id : "ObjectId", - code : { - type : String, - index : true - } - }] - }, + scope : Object, pageHeading: { default : "Domains", type : String diff --git a/module/forms/helper.js b/module/forms/helper.js index 19f30f05..e0b9efbb 100644 --- a/module/forms/helper.js +++ b/module/forms/helper.js @@ -77,5 +77,69 @@ module.exports = class FormHelper { } }); } + + /** + * Form Create. + * @method + * @name create + * @param {Object} - Form data. + * @returns {Object} form data. + */ + + static create( data ) { + return new Promise(async (resolve, reject) => { + try { + + let createForm = await database.models.forms.create(data); + + return resolve({ + message : constants.apiResponses.FORM_CREATED_SUCCESSFULLY, + data : { + id : createForm._id + } + }); + + } catch (error) { + return reject(error); + } + }); + } + + /** + * Form Update. + * @method + * @name update + * @param {Object} - Form data. + * @param {String} formName - form name. + * @returns {Object} form data. + */ + + static update( formName, data ) { + return new Promise(async (resolve, reject) => { + try { + + let message = constants.apiResponses.FORM_UPDATED_SUCCESSFULLY; + let updateObject = { + "$set" : {} + }; + updateObject["$set"]["value"] = data.value; + + let updateForm = await database.models.forms.findOneAndUpdate({name : formName},updateObject); + + if ( !updateForm ) { + throw { + message : constants.apiResponses.FAILED_TO_UPDATE_FORM + } + } + + return resolve({ + message : message + }); + + } catch (error) { + return reject(error); + } + }); + } } \ No newline at end of file diff --git a/module/forms/validator/v1.js b/module/forms/validator/v1.js index 7c99da6c..17a15458 100644 --- a/module/forms/validator/v1.js +++ b/module/forms/validator/v1.js @@ -11,6 +11,14 @@ module.exports = (req) => { details : function () { req.checkParams('_id').exists().withMessage("required form name") + }, + create : function () { + req.checkBody('name').exists().withMessage("required form name"); + req.checkBody('value').exists().withMessage("required form value"); + }, + update : function () { + req.checkParams('_id').exists().withMessage("required form name") + req.checkBody('value').exists().withMessage("required form value"); } } diff --git a/module/programs/helper.js b/module/programs/helper.js index 7698b109..66c7abf2 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 formHelper = require(MODULES_BASE_PATH + "/forms/helper"); /** * ProgramsHelper @@ -204,101 +205,12 @@ 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 ) { - return resolve({ - status : httpStatusCode.bad_request.status, - message : constants.apiResponses.ENTITY_TYPES_NOT_FOUND - }); - } - - scope["entityType"] = entityTypeData.data[0].type; - - } - - if( scopeData.entities && scopeData.entities.length > 0 ) { - - //call learners api for search - let entityIds = []; - let bodyData={}; - let locationData = gen.utils.filterLocationIdandCode(scopeData.entities) - - //locationIds contain id of location data. - if ( locationData.ids.length > 0 ) { - bodyData = { - "id" : locationData.ids, - "type" : scopeData.entityType - } - let entityData = await userService.locationSearch( bodyData ); - if ( entityData.success ) { - entityData.data.forEach( entity => { - entityIds.push(entity.id) - }); - } - } - - if ( locationData.codes.length > 0 ) { - let filterData = { - "code" : locationData.codes, - "type" : scopeData.entityType - } - let entityDetails = await userService.locationSearch( filterData ); - - if ( entityDetails.success ) { - let entitiesData = entityDetails.data; - entitiesData.forEach( entity => { - entityIds.push(entity.id) - }); - } - } - - if( !entityIds.length > 0 ) { - throw { - message : constants.apiResponses.ENTITIES_NOT_FOUND - }; - } - scope["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 - }); - } - - scope["roles"] = userRoles; - } else { - if( scopeData.roles === constants.common.ALL_ROLES ) { - scope["roles"] = [{ - "code" : constants.common.ALL_ROLES - }]; - } - } - } - let updateProgram = await database.models.programs.findOneAndUpdate( { _id : programId }, - { $set : { scope : scope }},{ new: true } + { $set : { scope : scopeData }},{ new: true } ).lean(); if( !updateProgram._id ) { @@ -494,16 +406,27 @@ 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 = "", appVersion, userId = "", userToken = "" ) { return new Promise(async (resolve, reject) => { try { + let convertedBodyData = await this.checkForConvertBodyData( + bodyData, + appVersion, + userId, + userToken + ); + + if ( convertedBodyData.success ) { + bodyData = convertedBodyData.data + } + let queryData = await this.queryBasedOnRoleAndLocation( bodyData ); - + if( !queryData.success ) { return resolve(queryData); } @@ -557,7 +480,6 @@ module.exports = class ProgramsHelper { }); } catch (error) { - return resolve({ success : false, message : error.message, @@ -580,25 +502,45 @@ 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 filterQuery = { + "isDeleted" : false, + status : constants.common.ACTIVE + }; + + let locationIds = []; + if ( data.entities ) { + Object.keys(data.entities).forEach( requestedDataKey => { + locationIds.push(data.entities[requestedDataKey]); + }) + } + if( !locationIds.length > 0 ) { throw { message : constants.apiResponses.NO_LOCATION_ID_FOUND_IN_DATA } } - - let filterQuery = { - "scope.roles.code" : { $in : [constants.common.ALL_ROLES,...data.role.split(",")] }, - "scope.entities" : { $in : locationIds }, - "isDeleted" : false, - status : constants.common.ACTIVE + filterQuery["scope.entities"] = { $in : locationIds }; + + //role exist in data + if ( data.roles ) { + if ( typeof(data["roles"]) === constants.common.STRING ) { + filterQuery["scope.roles"] = { $in : [constants.common.ALL_ROLES,...data.roles.split(",")] }; + } else { + filterQuery["scope.roles"] = { $in : [constants.common.ALL_ROLES,...data[roles]] }; + } } + //for all other keys except entities and roles + Object.keys(_.omit(data,["entities", "roles"])).forEach( dataKey => { + if ( typeof(data[dataKey]) === constants.common.STRING ) { + filterQuery["scope."+dataKey] = { $in : [data[dataKey].split(",")] }; + } else { + filterQuery["scope."+dataKey] = { $in : data[dataKey] }; + } + }); + if( data.filter && Object.keys(data.filter).length > 0 ) { Object.keys(data.filter).forEach( filterKey => { @@ -661,7 +603,7 @@ module.exports = class ProgramsHelper { let userRoles = await userRolesHelper.roleDocuments({ code : { $in : roles } - },["_id","code"] + },["code"] ); if( !userRoles.length > 0 ) { @@ -671,21 +613,26 @@ module.exports = class ProgramsHelper { }); } + let roleData = []; + for ( const role of userRoles ) { + roleData.push(role.code); + } + await database.models.programs.findOneAndUpdate({ _id : programId },{ - $pull : { "scope.roles" : { code : constants.common.ALL_ROLES } } + $pull : { "scope.roles" : constants.common.ALL_ROLES } },{ new : true }).lean(); updateQuery["$addToSet"] = { - "scope.roles" : { $each : userRoles } + "scope.roles" : { $each : roleData } } } else { if( roles === constants.common.ALL_ROLES ) { updateQuery["$set"] = { - "scope.roles" : [{ "code" : constants.common.ALL_ROLES }] + "scope.roles" : [constants.common.ALL_ROLES] } } } @@ -846,10 +793,15 @@ module.exports = class ProgramsHelper { }); } + let roleData = []; + for ( const role of userRoles ) { + roleData.push(role.code); + } + let updateProgram = await database.models.programs.findOneAndUpdate({ _id : programId },{ - $pull : { "scope.roles" : { $in : userRoles } } + $pull : { "scope.roles" : { $in : roleData } } },{ new : true }).lean(); if( !updateProgram || !updateProgram._id ) { @@ -974,6 +926,81 @@ module.exports = class ProgramsHelper { }); } }); + } + + /** + * Check For update data + * @method + * @name checkForConvertBodyData + * @param {Object} bodyData - Requested body data. + * @param {String} appVersion - app version. + * @param {String} userId - user id. + * @returns {JSON} - Converted Body Data. + */ + + static checkForConvertBodyData( bodyData, appVersion = "", userId = "", userToken = "" ) { + return new Promise(async (resolve, reject) => { + try { + + let updatedBodyData = {}; + let convertedBodyData = {}; + + if ( !appVersion ) { + //convert the data if appVersion is not present + updatedBodyData = await gen.utils.convertUserRoleAndLocationData(bodyData); + } else { + //check the bodyData need to convert or not + let convertUserDataorNot = await gen.utils.convertUserDataorNot(appVersion); + if ( convertUserDataorNot ) { + //update bodyData + updatedBodyData = await gen.utils.convertUserRoleAndLocationData(bodyData); + } else { + updatedBodyData = bodyData; + } + } + + let addMissingFields = false; + //check and update the missing fields in bodyData from profile + if ( userId !== "" && userToken !== "" ) { + //fetch scope form + let formData = await formHelper.formsDocument( + { + name : constants.common.SCOPE_FORM_NAME + },["value"] + ); + + //fetch userProfile + let userProfile = await userService.profile( userToken, userId ); + + if ( formData.length > 0 && userProfile.success ) { + addMissingFields = true; + } + + //add missing fields to bodyData + if ( addMissingFields ) { + convertedBodyData = await gen.utils.addMissingUserProfileDataToRequestBody( + updatedBodyData, + userProfile.data, + formData[0].value + ); + } + } + + return resolve({ + success : true, + data : ( convertedBodyData && Object.keys(convertedBodyData).length > 0 ) ? convertedBodyData : updatedBodyData + }); + + } catch(error) { + return resolve({ + success : false, + status : error.status ? + error.status : httpStatusCode['internal_server_error'].status, + message : error.message, + data : {} + }) + } + }) } }; diff --git a/module/solutions/helper.js b/module/solutions/helper.js index 11e51c58..c97635de 100644 --- a/module/solutions/helper.js +++ b/module/solutions/helper.js @@ -4,6 +4,8 @@ * created-date : 03-sep-2020 * Description : Solution related helper functionality. */ + + // Dependencies const programsHelper = require(MODULES_BASE_PATH + "/programs/helper"); const entityTypesHelper = require(MODULES_BASE_PATH + "/entityTypes/helper"); @@ -14,6 +16,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 formHelper = require(MODULES_BASE_PATH + "/forms/helper"); /** * SolutionsHelper @@ -232,21 +235,11 @@ module.exports = class SolutionsHelper { * @returns {JSON} - scope in solution. */ - static setScope( programId,solutionId,scopeData ) { + static setScope( solutionId,scopeData ) { return new Promise(async (resolve, reject) => { 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 ) { @@ -255,125 +248,22 @@ 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( scopeData.entityType ) { - let bodyData = { "type" : scopeData.entityType } - let entityTypeData = await userService.locationSearch( bodyData); - if ( entityTypeData.success ) { - currentSolutionScope.entityType = entityTypeData.data[0].type - } - } - - if( scopeData.entities && scopeData.entities.length > 0 ) { - //call learners api for search - let entityIds = []; - let bodyData={}; - let locationData = gen.utils.filterLocationIdandCode(scopeData.entities) - - if ( locationData.ids.length > 0 ) { - bodyData = { - "id" : locationData.ids, - "type" : currentSolutionScope.entityType - } - let entityData = await userService.locationSearch( bodyData ); - if ( entityData.success ) { - entityData.data.forEach( entity => { - entityIds.push(entity.id) - }); - } - } - - if ( locationData.codes.length > 0 ) { - let filterData = { - "code" : locationData.codes, - "type" : currentSolutionScope.entityType - } - let entityDetails = await userService.locationSearch( filterData ); - - if ( entityDetails.success ) { - entityDetails.data.forEach( entity => { - entityIds.push(entity.id) - }); - } - } - - if( !entityIds.length > 0 ) { - return resolve({ - status : httpStatusCode.bad_request.status, - message : constants.apiResponses.ENTITIES_NOT_FOUND - }); - } - - 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 { - entitiesData = entityIds - // } - - if( !entitiesData.length > 0 ) { - - return resolve({ - status : httpStatusCode.bad_request.status, - message : constants.apiResponses.SCOPE_ENTITY_INVALID - }); - - } - - currentSolutionScope.entities = entitiesData; - } - 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 - }]; - } - } - } - } - - let updateSolution = - await database.models.solutions.findOneAndUpdate( - { - _id : solutionId - }, - { $set : { scope : currentSolutionScope }},{ new: true } - ).lean(); + let updateSolution = + await database.models.solutions.findOneAndUpdate( + { + _id : solutionId + }, + { $set : { scope : scopeData }},{ new: true } + ).lean(); - if( !updateSolution._id ) { - throw { - status : constants.apiResponses.SOLUTION_SCOPE_NOT_ADDED - }; - } - solutionData = updateSolution; - + if( !updateSolution._id ) { + throw { + status : constants.apiResponses.SOLUTION_SCOPE_NOT_ADDED + }; } + + solutionData = updateSolution; return resolve({ success : true, @@ -450,7 +340,6 @@ module.exports = class SolutionsHelper { let solutionScope = await this.setScope( - solutionUpdatedData.programId, solutionUpdatedData._id, solutionData.scope ); @@ -622,11 +511,26 @@ module.exports = class SolutionsHelper { programId, pageSize, pageNo, - searchText = "" + searchText = "", + appVersion = "", + userId = "", + userToken = "" ) { return new Promise(async (resolve, reject) => { try { - + + //to convert the bodyData + let convertedBodyData = await this.checkForConvertBodyData( + bodyData, + appVersion, + userId, + userToken + ); + + if( convertedBodyData.success ) { + bodyData = convertedBodyData.data + } + let queryData = await this.queryBasedOnRoleAndLocation( bodyData, type, @@ -637,7 +541,7 @@ module.exports = class SolutionsHelper { if( !queryData.success ) { return resolve(queryData); } - + let matchQuery = queryData.data; if( type === "" && subType === "" ) { @@ -672,7 +576,7 @@ module.exports = class SolutionsHelper { if ( programId !== "" ) { matchQuery["programId"] = ObjectId(programId); } - + let targetedSolutions = await this.list( type, subType, @@ -728,26 +632,47 @@ module.exports = class SolutionsHelper { return new Promise(async (resolve, reject) => { try { + let filterQuery = { + "isReusable" : false, + "isDeleted" : false + }; + let registryIds = []; let entityTypes = []; + //entities exist in data + if ( data.entities ) { + Object.keys(data.entities).forEach( requestedDataKey => { + registryIds.push(data.entities[requestedDataKey]); + entityTypes.push(requestedDataKey); + }) + } - Object.keys(_.omit(data,["filter","role"])).forEach( requestedDataKey => { - registryIds.push(data[requestedDataKey]); - entityTypes.push(requestedDataKey); - }) if( !registryIds.length > 0 ) { throw { message : constants.apiResponses.NO_LOCATION_ID_FOUND_IN_DATA } } - - let filterQuery = { - "scope.roles.code" : { $in : [constants.common.ALL_ROLES,...data.role.split(",")] }, - "scope.entities" : { $in : registryIds }, - "scope.entityType" : { $in : entityTypes }, - "isReusable" : false, - "isDeleted" : false - }; + + filterQuery["scope.entities"] = { $in : registryIds }; + filterQuery["scope.entityType"] = { $in : entityTypes }; + + //role exist in data + if ( data.roles ) { + if ( typeof(data["roles"]) === constants.common.STRING ) { + filterQuery["scope.roles"] = { $in : [constants.common.ALL_ROLES,...data.roles.split(",")] }; + } else { + filterQuery["scope.roles"] = { $in : [constants.common.ALL_ROLES,...data[roles]] }; + } + } + + //for all other keys except entities and roles + Object.keys(_.omit(data,["entities", "roles","filter"])).forEach( dataKey => { + if ( typeof(data[dataKey]) === constants.common.STRING ) { + filterQuery["scope."+dataKey] = { $in : [data[dataKey].split(",")] }; + } else { + filterQuery["scope."+dataKey] = { $in : data[dataKey] }; + } + }); if( type === constants.common.SURVEY ) { @@ -806,20 +731,33 @@ module.exports = class SolutionsHelper { * @returns {JSON} - Details of solution based on role and location. */ - static detailsBasedOnRoleAndLocation( solutionId,bodyData ) { + static detailsBasedOnRoleAndLocation( solutionId, bodyData, appVersion, userId, userToken ) { return new Promise(async (resolve, reject) => { try { + //to convert the bodyData + let convertedBodyData = await this.checkForConvertBodyData( + bodyData, + appVersion, + userId, + userToken + ); + + if( convertedBodyData.success ) { + bodyData = convertedBodyData.data + } + let queryData = await this.queryBasedOnRoleAndLocation(bodyData); if( !queryData.success ) { return resolve(queryData); } queryData.data["_id"] = solutionId; + let targetedSolutionDetails = - await this.solutionDocuments( + await this.solutionDocuments( queryData.data, [ "name", @@ -839,14 +777,14 @@ module.exports = class SolutionsHelper { "certificateTemplateId" ] ); - + if( !targetedSolutionDetails.length > 0 ) { throw { status : httpStatusCode["bad_request"].status, message : constants.apiResponses.SOLUTION_NOT_FOUND } } - + return resolve({ success: true, message: constants.apiResponses.TARGETED_SOLUTIONS_FETCHED, @@ -854,7 +792,6 @@ module.exports = class SolutionsHelper { }); } catch (error) { - return resolve({ success : false, message : error.message, @@ -900,7 +837,7 @@ module.exports = class SolutionsHelper { let userRoles = await userRolesHelper.roleDocuments({ code : { $in : roles } - },["_id","code"] + },["code"] ); if( !userRoles.length > 0 ) { @@ -910,18 +847,23 @@ module.exports = class SolutionsHelper { }); } + let roleData = []; + for ( const role of userRoles ) { + roleData.push(role.code); + } + await database.models.solutions.findOneAndUpdate({ _id : solutionId - },{ $pull : { "scope.roles" : { code : constants.common.ALL_ROLES }}},{ new : true }).lean(); + },{ $pull : { "scope.roles" : constants.common.ALL_ROLES }},{ new : true }).lean(); updateQuery["$addToSet"] = { - "scope.roles" : { $each : userRoles } + "scope.roles" : { $each : roleData } }; } else { if( roles === constants.common.ALL_ROLES ) { updateQuery["$set"] = { - "scope.roles" : [{ "code" : constants.common.ALL_ROLES }] + "scope.roles" : [constants.common.ALL_ROLES ] }; } } @@ -1104,7 +1046,7 @@ module.exports = class SolutionsHelper { { code: { $in: roles }, }, - ["_id", "code"] + ["code"] ); if (!userRoles.length > 0) { @@ -1114,13 +1056,18 @@ module.exports = class SolutionsHelper { }); } + let roleData = []; + for ( const role of userRoles ) { + roleData.push(role.code); + } + let updateSolution = await database.models.solutions .findOneAndUpdate( { _id: solutionId, }, { - $pull: { "scope.roles": { $in: userRoles } }, + $pull: { "scope.roles": { $in: roleData } }, }, { new: true } ) @@ -1274,7 +1221,9 @@ module.exports = class SolutionsHelper { pageNo, search, filter, - surveyReportPage = "" + surveyReportPage = "", + appVersion = "", + userId ) { return new Promise(async (resolve, reject) => { try { @@ -1372,7 +1321,10 @@ module.exports = class SolutionsHelper { "", constants.common.DEFAULT_PAGE_SIZE, constants.common.DEFAULT_PAGE_NO, - search + search, + appVersion, + userId, + userToken ); } @@ -1565,7 +1517,7 @@ module.exports = class SolutionsHelper { * @returns {Object} - Details of the solution. */ - static verifyLink(link = "", bodyData = {}, userId = "", userToken = "", createProject = true ) { + static verifyLink(link = "", bodyData = {}, userId = "", userToken = "", createProject = true, appVersion = "" ) { return new Promise(async (resolve, reject) => { try { @@ -1579,8 +1531,10 @@ module.exports = class SolutionsHelper { link, bodyData, userId, - userToken + userToken, + appVersion ); + if( !checkForTargetedSolution || Object.keys(checkForTargetedSolution.result).length <= 0 ) { return resolve(checkForTargetedSolution); } @@ -1791,7 +1745,8 @@ module.exports = class SolutionsHelper { link = "", bodyData = {}, userId = "", - userToken = "" + userToken = "", + appVersion = "" ) { return new Promise(async (resolve, reject) => { try { @@ -1809,6 +1764,18 @@ module.exports = class SolutionsHelper { "projectTemplateId" ]); + //to convert the bodyData + let convertedBodyData = await this.checkForConvertBodyData( + bodyData, + appVersion, + userId, + userToken + ); + + if( convertedBodyData.success ) { + bodyData = convertedBodyData.data + } + let queryData = await this.queryBasedOnRoleAndLocation(bodyData); if ( !queryData.success ) { return resolve(queryData); @@ -2019,6 +1986,81 @@ module.exports = class SolutionsHelper { }); } + /** + * Check For update data + * @method + * @name checkForConvertBodyData + * @param {Object} bodyData - Requested body data. + * @param {String} appVersion - app version. + * @param {String} userId - user id. + * @returns {JSON} - Converted Body Data. + */ + + static checkForConvertBodyData( bodyData, appVersion = "", userId = "", userToken = "" ) { + return new Promise(async (resolve, reject) => { + try { + + let updatedBodyData = {}; + let convertedBodyData = {}; + + if ( !appVersion ) { + //convert the data if appVersion is not present + updatedBodyData = await gen.utils.convertUserRoleAndLocationData(bodyData); + } else { + //check the bodyData need to convert or not + let convertUserDataorNot = await gen.utils.convertUserDataorNot(appVersion); + if ( convertUserDataorNot ) { + //update bodyData + updatedBodyData = await gen.utils.convertUserRoleAndLocationData(bodyData); + } else { + updatedBodyData = bodyData; + } + } + + let addMissingFields = false; + //check and update the missing fields in bodyData from profile + if ( userId !== "" && userToken !== "" ) { + //fetch scope form + let formData = await formHelper.formsDocument( + { + name : constants.common.SCOPE_FORM_NAME + },["value"] + ); + + //fetch userProfile + let userProfile = await userService.profile( userToken, userId ); + + if ( formData.length > 0 && userProfile.success ) { + addMissingFields = true; + } + + //add missing fields to bodyData + if ( addMissingFields ) { + convertedBodyData = await gen.utils.addMissingUserProfileDataToRequestBody( + updatedBodyData, + userProfile.data, + formData[0].value + ); + } + } + + return resolve({ + success : true, + data : ( convertedBodyData && Object.keys(convertedBodyData).length > 0 ) ? convertedBodyData : updatedBodyData + }); + + } catch(error) { + return resolve({ + success : false, + status : error.status ? + error.status : httpStatusCode['internal_server_error'].status, + message : error.message, + data : {} + }) + } + }) + } + }; /** diff --git a/module/users/helper.js b/module/users/helper.js index b7d3c3b1..f0f191e5 100644 --- a/module/users/helper.js +++ b/module/users/helper.js @@ -439,10 +439,11 @@ module.exports = class UsersHelper { * @returns {Object} targeted user solutions. */ - static solutions(programId, requestedData, pageSize, pageNo, search, token) { + static solutions(programId, requestedData, pageSize, pageNo, search, appVersion = "", userId = "", token) { return new Promise(async (resolve, reject) => { try { + let programData = await programsHelper.programDocuments( { _id: programId @@ -450,7 +451,7 @@ module.exports = class UsersHelper { ["name"] ); - if (!programData.length > 0) { + if ( !programData.length > 0 ) { return resolve({ status: httpStatusCode["bad_request"].status, message: constants.apiResponses.PROGRAM_NOT_FOUND @@ -465,9 +466,12 @@ module.exports = class UsersHelper { programId, constants.common.DEFAULT_PAGE_SIZE, constants.common.DEFAULT_PAGE_NO, - search + search, + appVersion, + userId, + token ); - + let totalCount = 0; let mergedData = []; @@ -572,14 +576,18 @@ module.exports = class UsersHelper { * @returns {Array} - Get user targeted programs. */ - static programs(bodyData, pageNo, pageSize, searchText) { + static programs( bodyData, pageNo, pageSize, searchText, appVersion, userId = "", userToken = "" ) { return new Promise(async (resolve, reject) => { try { + let targetedProgrms = await programsHelper.forUserRoleAndLocation( bodyData, pageSize, pageNo, - searchText + searchText, + appVersion, + userId, + userToken ); if (!targetedProgrms.success) { @@ -596,6 +604,7 @@ module.exports = class UsersHelper { message: constants.apiResponses.USER_TARGETED_PROGRAMS_FETCHED, data: targetedProgrms.data }); + } catch (error) { return resolve({ success: false, @@ -706,6 +715,7 @@ module.exports = class UsersHelper { static targetedEntity(solutionId, requestedData) { return new Promise(async (resolve, reject) => { try { + let solutionData = await solutionsHelper.solutionDocuments( { _id: solutionId, @@ -722,7 +732,7 @@ module.exports = class UsersHelper { } let rolesDocument = await userRolesHelper.roleDocuments( { - code: requestedData.role + code: requestedData.roles }, ["entityTypes.entityType"] ); @@ -733,8 +743,9 @@ module.exports = class UsersHelper { message: constants.apiResponses.USER_ROLES_NOT_FOUND }; } - - let requestedEntityTypes = Object.keys(_.omit(requestedData, ['role'])); + + let entities = requestedData.entities; + let requestedEntityTypes = Object.keys(entities); let targetedEntityType = ""; rolesDocument[0].entityTypes.forEach((singleEntityType) => { @@ -743,7 +754,7 @@ module.exports = class UsersHelper { } }); - if (!requestedData[targetedEntityType]) { + if (!entities[targetedEntityType]) { throw { status: httpStatusCode["bad_request"].status, message: constants.apiResponses.ENTITIES_NOT_ALLOWED_IN_ROLE @@ -752,9 +763,9 @@ 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])) { + if (gen.utils.checkValidUUID(entities[targetedEntityType])) { filterData = { - "parentId" : requestedData[targetedEntityType] + "parentId" : entities[targetedEntityType] } let entitiesData = await userService.locationSearch( filterData ); if( entitiesData.success ){ @@ -765,13 +776,13 @@ module.exports = class UsersHelper { } } - if (gen.utils.checkValidUUID(requestedData[targetedEntityType])) { + if (gen.utils.checkValidUUID(entities[targetedEntityType])) { filterData = { - "id" : requestedData[targetedEntityType] + "id" : entities[targetedEntityType] }; } else { filterData = { - "code" : requestedData[targetedEntityType] + "code" : entities[targetedEntityType] }; } let entitiesDocument = await userService.locationSearch( filterData );