Skip to content

Commit

Permalink
Merge pull request #198 from borkarsaish65/feature/start_end_date_log…
Browse files Browse the repository at this point in the history
…in_1

Feature/start end date login 1
  • Loading branch information
aks30 authored Dec 19, 2024
2 parents bdbb4a0 + 29b1c55 commit fcc08ca
Show file tree
Hide file tree
Showing 9 changed files with 370 additions and 15 deletions.
6 changes: 4 additions & 2 deletions controllers/v1/programs.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,8 @@ module.exports = class Programs extends Abstract {

req.body.userId = req.userDetails.userId;
let programCreationData = await programsHelper.create(
req.body
req.body,
true
);

return resolve({
Expand Down Expand Up @@ -221,7 +222,8 @@ module.exports = class Programs extends Abstract {
let programUpdationData = await programsHelper.update(
req.params._id,
req.body,
req.userDetails.userId
req.userDetails.userId,
true
);

programUpdationData.result = programUpdationData.data;
Expand Down
6 changes: 4 additions & 2 deletions controllers/v1/solutions.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@ module.exports = class Solutions extends Abstract {
try {

let solutionData = await solutionsHelper.createSolution(
req.body
req.body,
true
);

solutionData["result"] = solutionData.data;
Expand Down Expand Up @@ -121,7 +122,8 @@ module.exports = class Solutions extends Abstract {
let solutionData = await solutionsHelper.update(
req.params._id,
req.body,
req.userDetails.id
req.userDetails.id,
true
);

return resolve(solutionData);
Expand Down
78 changes: 77 additions & 1 deletion generics/helpers/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,80 @@ function arrayIdsTobjectIds(ids) {
function checkIfStringIsNumber(str) {
return /^[0-9]+$/.test(str);
}
/**
* Returns date and time with offset
* @function
* @name addOffsetToDateTime
* @returns {date} returns date and time with offset
* example:
* input = Sun Jun 16 2024 23:59:59 GMT+0000 (Coordinated Universal Time), +05:30
* output = Sun Jun 16 2024 18:29:59 GMT+0000 (Coordinated Universal Time)
*/

function addOffsetToDateTime(time, timeZoneDifference) {
//get the offset time from env with respect UTC
let localTimeZone = timeZoneDifference;
//convert offset time to minutes
let localTime = localTimeZone.split(":");
let localHourDifference = Number(localTime[0]);
let getTimeDiffInMinutes =
localHourDifference * 60 +
(localHourDifference / Math.abs(localHourDifference)) *
Number(localTime[1]);
//get server offset time w.r.t. UTC time
let timeDifference = new Date().getTimezoneOffset();
//get actual time difference in minutes
let differenceWithLocal = timeDifference + getTimeDiffInMinutes;
// if its 0 then return same time
if (differenceWithLocal === 0) {
return time;
} else {
// set time difference
let getMinutes = differenceWithLocal % 60;
let getHours = (differenceWithLocal - getMinutes) / 60;
time.setHours(time.getHours() - getHours);
time.setMinutes(time.getMinutes() - getMinutes);
return time;
}
}

/**
* Returns startDate if time is not passed it will add default time with offset to utc
* @function
* @name getStartDate
* @returns {date} returns date and time with offset
* example:
* input = 2022-06-01, +05:30
* output = Wed Jan 31 2001 18:30:00 GMT+0000 (Coordinated Universal Time)
*/
function getStartDate(date, timeZoneDifference) {
let startDate = date.split(" ");
if (startDate[1] === "" || startDate[1] === undefined) {
date = startDate[0] + " 00:00:00";
}
date = new Date(date);
date = addOffsetToDateTime(date, timeZoneDifference);
return date;
}

/**
* Returns endDate if time is not passed it will add default time with offset to utc
* @function
* @name getEndDate
* @returns {date} returns date and time with offset
* example:
* input = 2024-06-16, +05:30
* output = Sun Jun 16 2024 18:29:59 GMT+0000 (Coordinated Universal Time)
*/
function getEndDate(date, timeZoneDifference) {
let endDate = date.split(" ");
if (endDate[1] === "" || endDate[1] === undefined) {
date = endDate[0] + " 23:59:59";
}
date = new Date(date);
date = addOffsetToDateTime(date, timeZoneDifference);
return date;
}

module.exports = {
camelCaseToTitleCase : camelCaseToTitleCase,
Expand All @@ -290,5 +364,7 @@ module.exports = {
md5Hash : md5Hash,
filterLocationIdandCode : filterLocationIdandCode,
arrayIdsTobjectIds : arrayIdsTobjectIds,
checkIfStringIsNumber : checkIfStringIsNumber
checkIfStringIsNumber : checkIfStringIsNumber,
getStartDate: getStartDate,
getEndDate: getEndDate,
};
5 changes: 5 additions & 0 deletions migrations/programs-startDate-EndDate-5.1/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
## Migrations for program startDate and endDate
Steps to run the migration files
- Navigate to migrations/programs-startDate-EndDate-5.1/ folder
- Run the script which will add startDate and endDate to programs.
> node setProgramsStartDateAndEndDate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
let _ = require("lodash");
require("dotenv").config({path: "../../.env"});
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];
var fs = require("fs");

(async () => {
let connection = await MongoClient.connect(url, { useNewUrlParser: true });
let db = connection.db(dbName);
let updatedProgramIds = [];
let updatedSolutionIds = [];
try {
console.log("-----------------------Started----------------------");
// get all active programs with createdAt value
let collectionDocs = await db
.collection("programs")
.find({
status: "active",
})
.project({ _id: 1, createdAt: 1, components: 1 })
.toArray();




//reduce array to small chunks
let chunkOfprogramsDetails = _.chunk(collectionDocs, 50);

//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 id = currentChunk[currentChunkIndex]._id;
let endDate = "";
let startDate = "";
let monthToAdd = 12; // ---------------------set to one year -----------------------------
//checking if program has components or not
if (currentChunk[currentChunkIndex].components.length === 0) {
//if it will not have components then createdAt will become startDate and endDate will 1 year from startDate
startDate = currentChunk[currentChunkIndex].createdAt;
endDate = new Date(currentChunk[currentChunkIndex].createdAt);
endDate.setFullYear(
endDate.getFullYear(),
endDate.getMonth() + monthToAdd
);
} else {

//if program has components then will query solutions for components and will get details of solutions
const solutions = await db
.collection("solutions")
.find({
_id: { $in: currentChunk[currentChunkIndex].components },
})
.project({
_id: 1,
startDate: 1,
endDate: 1,
createdAt: 1,
status: 1,
})
.sort({ endDate: -1 })
.toArray();

if(solutions.length == 0 ){
continue;
}

//looping throught each solution to check if solution need update or not
for (let i = 0; i < solutions.length; i++) {
//this will be used to check if solution needs to be updated or not
let update = false;
let query = { $set: {} };
//checking if have startdate
if (!solutions[i].hasOwnProperty("startDate")) {
//if it will not have startDate then createdAt will become startdate
update = true;
solutions[i].startDate = solutions[i].createdAt;
query["$set"].startDate = solutions[i].startDate;
}
//checking if endDate is present or not
if (!solutions[i].hasOwnProperty("endDate")) {
// if it dosent have endDate then endDate will be calculated as runTime + 1year
solutions[i].endDate = new Date();
solutions[i].endDate.setFullYear(
solutions[i].endDate.getFullYear(),
solutions[i].endDate.getMonth() + monthToAdd
);
query["$set"].endDate = solutions[i].endDate;
update = true;
}
//if update is required then it will upate the solution
if (update) {
await db
.collection("solutions")
.findOneAndUpdate({ _id: solutions[i]._id }, query);
updatedSolutionIds.push(solutions[i]._id);
}
}

//get start and end date from solution startDate and endDate
let dates = getStartAndEndDates(solutions);
startDate = dates.startDate;
endDate = dates.endDate;
}

// update programs
await db
.collection("programs")
.findOneAndUpdate(
{ _id: id },
{ $set: { startDate: startDate, endDate: endDate } }
);
console.log("program Updated : ", id);
updatedProgramIds.push(id);
}
}
//write updated program ids to file
fs.writeFile(
"updatedProgramIds.json",

JSON.stringify({
Programs: updatedProgramIds,
solutions: updatedSolutionIds,
}),

function (err) {
if (err) {
console.error("Error Encountered:",err);
}
}
);
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));
//fucntion to get start and end dates in sorted order and return index 0 of each
function getStartAndEndDates(solutions) {
const dates = {};
const startDate = solutions.sort((a, b) => a.startDate - b.startDate);
dates.startDate = startDate[0].startDate;
const endDate = solutions.sort((a, b) => b.endDate - a.endDate);
dates.endDate = endDate[0].endDate;
return dates;
}
10 changes: 10 additions & 0 deletions models/programs.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,16 @@ module.exports = {
type : String,
index : true
},
startDate:{
type: Date,
index: true,
require:true
},
endDate: {
type : Date,
index : true,
require: true
},
resourceType: [String],
language: [String],
keywords: [String],
Expand Down
42 changes: 39 additions & 3 deletions module/programs/helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ 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 timeZoneDifference =
process.env.TIMEZONE_DIFFRENECE_BETWEEN_LOCAL_TIME_AND_UTC;
/**
* ProgramsHelper
* @class
Expand Down Expand Up @@ -70,10 +71,11 @@ module.exports = class ProgramsHelper {
* @method
* @name create
* @param {Array} data
* @param {Boolean} checkDate to accommodate timezone difference in the sent date
* @returns {JSON} - create program.
*/

static create(data) {
static create(data, checkDate = false) {

return new Promise(async (resolve, reject) => {

Expand Down Expand Up @@ -105,6 +107,25 @@ module.exports = class ProgramsHelper {
"components" : [],
"isAPrivateProgram" : data.isAPrivateProgram ? data.isAPrivateProgram : false
}

if (checkDate) {
if (data.hasOwnProperty("endDate")) {
data.endDate = gen.utils.getEndDate(
data.endDate,
timeZoneDifference
);
}
if (data.hasOwnProperty("startDate")) {
data.startDate = gen.utils.getStartDate(
data.startDate,
timeZoneDifference
);
}
}

_.assign(programData, {
...data,
});

let program = await database.models.programs.create(
programData
Expand Down Expand Up @@ -327,10 +348,11 @@ module.exports = class ProgramsHelper {
* @param {String} programId - program id.
* @param {Array} data
* @param {String} userId
* @param {Boolean} checkDate to accommodate timezone difference in the sent date
* @returns {JSON} - update program.
*/

static update(programId,data,userId) {
static update(programId,data,userId, checkDate = false) {

return new Promise( async (resolve, reject) => {

Expand All @@ -339,6 +361,20 @@ module.exports = class ProgramsHelper {
data.updatedBy = userId;
data.updatedAt = new Date();

if (checkDate) {
if (data.hasOwnProperty("endDate")) {
data.endDate = gen.utils.getEndDate(
data.endDate,
timeZoneDifference
);
}
if (data.hasOwnProperty("startDate")) {
data.startDate = gen.utils.getStartDate(
data.startDate,
timeZoneDifference
);
}
}
let program = await database.models.programs.findOneAndUpdate({
_id : programId
},{ $set : _.omit(data,["scope"]) }, { new: true });
Expand Down
Loading

0 comments on commit fcc08ca

Please sign in to comment.