Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cbrelease 4.8.6 #101

Open
wants to merge 6 commits into
base: cbrelease-4.8.6_hotfix
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for requested batchId there will be only one batch record , why we changed the signature to List ?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

image

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@SaipradeepR , for single batchid , we can have multiple users enrolled in a batch(keyspace name =sunbird_courses) table name enrollment_batch_lookup.

Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public interface BatchUserDao {
* @return User batch information
*/

BatchUser readById(RequestContext requestContext, String batchId);
List<BatchUser> readById(RequestContext requestContext, String batchId);
BatchUser read(RequestContext requestContext, String batchId, String userId);
Response insertBatchLookupRecord(RequestContext requestContext, Map<String, Object> userCoursesDetails);

Expand Down

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't refactor the method readById at Dao level , it should provide all details needed. Based on need modify the response received at service level.

Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,7 @@
import org.sunbird.models.batch.user.BatchUser;
import org.sunbird.common.models.util.LoggerUtil;


import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;

public class BatchUserDaoImpl implements BatchUserDao{
protected LoggerUtil logger = new LoggerUtil(this.getClass());
Expand All @@ -37,17 +34,25 @@ public static BatchUserDao getInstance() {
}

@Override
public BatchUser readById(RequestContext requestContext, String batchId) {
public List<BatchUser> readById(RequestContext requestContext, String batchId) {
Map<String, Object> primaryKey = new HashMap<>();
primaryKey.put(JsonKey.BATCH_ID, batchId);
Response response = cassandraOperation.getRecordByIdentifier(requestContext, KEYSPACE_NAME, ENROLLMENT_BATCH, primaryKey, null);
try {
List<Map<String, Object>> batchUserList =
(List<Map<String, Object>>) response.get(JsonKey.RESPONSE);
(List<Map<String, Object>>) response.get(JsonKey.RESPONSE);
if (CollectionUtils.isEmpty(batchUserList)) {
return null;
}
return mapper.convertValue((Map<String, Object>) batchUserList.get(0), BatchUser.class);
List<BatchUser> batchUsers = new ArrayList<>();
for (Map<String, Object> userDetail : batchUserList) {
BatchUser batchUser = new BatchUser();
batchUser.setBatchId((String) userDetail.get("batchId"));
batchUser.setUserId((String) userDetail.get("userId"));
batchUser.setActive((Boolean) userDetail.get("active"));
batchUsers.add(batchUser);
}
return batchUsers;
} catch (Exception e) {
logger.error(requestContext, "Failed to read BatchUser Table. Exception: ", e);
return null;
Expand Down
dkttarento marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,10 @@ private void updateCourseBatch(Request actorMessage) throws Exception {
if (courseNotificationActive()) {
batchOperationNotifier(actorMessage, courseBatch, participantsMap);
}
if (batchDatesUpdateNotificationActive()) {
batchDatesUpdateNotifier(actorMessage, courseBatch, oldBatch);
}

}

private Map<String, Object> getMentorLists(
Expand Down Expand Up @@ -489,7 +493,7 @@ private void validateBatchStartAndEndDate(
Date startDate = null != requestedStartDate ? requestedStartDate : existingStartDate;
Date endDate = null != requestedEndDate ? requestedEndDate : existingEndDate;

/* if ((existingStartDate.before(todayDate) || existingStartDate.equals(todayDate))
if ((existingStartDate.before(todayDate) || existingStartDate.equals(todayDate))
&& !(existingStartDate.equals(requestedStartDate))) {
throw new ProjectCommonException(
ResponseCode.invalidBatchStartDateError.getErrorCode(),
Expand All @@ -502,7 +506,7 @@ private void validateBatchStartAndEndDate(
ResponseCode.invalidBatchStartDateError.getErrorCode(),
ResponseCode.invalidBatchStartDateError.getErrorMessage(),
ResponseCode.CLIENT_ERROR.getResponseCode());
}*/
}

if (endDate != null && startDate.after(endDate)) {
throw new ProjectCommonException(
Expand Down Expand Up @@ -566,7 +570,7 @@ private void validateBatchEnrollmentEndDate(
Date todayDate) {
Date endDate = requestedEndDate != null ? requestedEndDate : existingEndDate;
if (enrolmentDateValidationEnabled() && requestedEnrollmentEndDate != null
&& (requestedEnrollmentEndDate.before(requestedStartDate))) {
&& (requestedEnrollmentEndDate.after(requestedStartDate))) {
throw new ProjectCommonException(
ResponseCode.enrollmentEndDateStartError.getErrorCode(),
ResponseCode.enrollmentEndDateStartError.getErrorMessage(),
Expand Down Expand Up @@ -729,5 +733,23 @@ private static boolean enrolmentDateValidationEnabled() {
PropertiesCache.getInstance()
.getProperty(JsonKey.COURSE_BATCH_ENROLL_END_DATE_LESS));
}
private boolean batchDatesUpdateNotificationActive() {
return Boolean.parseBoolean(
PropertiesCache.getInstance()
.getProperty(JsonKey.SUNBIRD_BATCH_UPDATE_NOTIFICATIONS_ENABLED));
}

private void batchDatesUpdateNotifier(Request actorMessage, CourseBatch updatedCourseBatch, CourseBatch oldCourseBatch) {
Request batchNotification = new Request(actorMessage.getRequestContext());
batchNotification.getContext().putAll(actorMessage.getContext());
batchNotification.setOperation(ActorOperations.COURSE_BATCH_DATE_NOTIFICATION.getValue());
Map<String, Object> request = new HashMap<>();
request.put(Constants.OLD_COURSE_BATCH, oldCourseBatch);
request.put(Constants.UPDATED_COURSE_BATCH, updatedCourseBatch);
request.put(Constants.REQUEST_CONTEXT, actorMessage.getRequestContext());
request.put(Constants.REQUEST_CONTEXT,actorMessage.getRequest());
batchNotification.setRequest(request);
courseBatchNotificationActorRef.tell(batchNotification, getSelf());
}

}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sendEmailNotificationMailForBatchDatesUpdate shld be Async , req cannot wait till all notifications sent to all the users of the batch

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Update request is handled by CourseBatchManagementActor, and mail is send by CourseBatchNotificationActor, this itself will be async call to CourseBatchNotificationActor this is flow i think correct me if i am wrong.

Original file line number Diff line number Diff line change
@@ -1,39 +1,48 @@
package org.sunbird.learner.actors.coursebatch;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.httpclient.HttpStatus;
import org.sunbird.actor.base.BaseActor;
import org.sunbird.common.Constants;
import org.sunbird.common.exception.ProjectCommonException;
import org.sunbird.common.models.util.ActorOperations;
import org.sunbird.common.models.util.JsonKey;
import org.sunbird.common.models.util.LoggerUtil;
import org.sunbird.common.models.util.PropertiesCache;
import org.sunbird.common.request.Request;
import org.sunbird.common.request.RequestContext;
import org.sunbird.common.responsecode.ResponseCode;
import org.sunbird.common.util.JsonUtil;
import org.sunbird.learner.actors.coursebatch.dao.BatchUserDao;
import org.sunbird.learner.actors.coursebatch.dao.impl.BatchUserDaoImpl;
import org.sunbird.learner.util.ContentUtil;
import org.sunbird.learner.util.CourseBatchSchedulerUtil;
import org.sunbird.models.batch.user.BatchUser;
import org.sunbird.models.course.batch.CourseBatch;
import org.sunbird.userorg.UserOrgService;
import org.sunbird.userorg.UserOrgServiceImpl;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.stream.Collectors;

/**
* Actor responsible to sending email notifications to participants and mentors in open and
* invite-only batches.
*/
public class CourseBatchNotificationActor extends BaseActor {
private static String courseBatchNotificationSignature =
PropertiesCache.getInstance()
.getProperty(JsonKey.SUNBIRD_COURSE_BATCH_NOTIFICATION_SIGNATURE);
PropertiesCache.getInstance()
.getProperty(JsonKey.SUNBIRD_COURSE_BATCH_NOTIFICATION_SIGNATURE);
private static String baseUrl =
PropertiesCache.getInstance().getProperty(JsonKey.SUNBIRD_WEB_URL);
PropertiesCache.getInstance().getProperty(JsonKey.SUNBIRD_WEB_URL);
private static String courseBatchPath =
PropertiesCache.getInstance().getProperty(JsonKey.COURSE_BATCH_PATH);
private UserOrgService userOrgService = UserOrgServiceImpl.getInstance();
private BatchUserDao batchUserDao = new BatchUserDaoImpl();
private ObjectMapper mapper = new ObjectMapper();

@Override
public void onReceive(Request request) throws Throwable {
Expand All @@ -42,6 +51,8 @@ public void onReceive(Request request) throws Throwable {
if (requestedOperation.equals(ActorOperations.COURSE_BATCH_NOTIFICATION.getValue())) {
logger.info(request.getRequestContext(), "CourseBatchNotificationActor:onReceive: operation = " + request.getOperation());
courseBatchNotification(request);
} else if (requestedOperation.equals(ActorOperations.COURSE_BATCH_DATE_NOTIFICATION.getValue())) {
courseBatchDatesUpdateNotification(request);
} else {
logger.error(request.getRequestContext(), "CourseBatchNotificationActor:onReceive: Unsupported operation = "
+ request.getOperation(), null);
Expand Down Expand Up @@ -182,7 +193,80 @@ private void sendMail(RequestContext requestContext, Map<String, Object> request
logger.info(requestContext, "CourseBatchNotificationActor:sendMail: Email sent successfully");
} catch (Exception e) {
logger.error(requestContext, "CourseBatchNotificationActor:sendMail: Exception occurred with error message = "
+ e.getMessage(), e);
+ e.getMessage(), e);
}
}
}

private void courseBatchDatesUpdateNotification(Request request) throws UnirestException {
CourseBatch oldCourseBatch = (CourseBatch) request.getRequest().get("oldCourseBatch");
CourseBatch updatedCourseBatch = (CourseBatch) request.getRequest().get("updatedCourseBatch");
RequestContext context = (RequestContext) request.getRequest().get("requestContext");
Map<String, Object> requestBody = (Map<String, Object>) request.getRequest().get("requestBody");
Map<String, Object> batchAttributes = (Map<String, Object>) requestBody.get("batchAttributes");
List<String> mentorsIds = (List<String>) requestBody.get("mentors");
List<String> reciepientList = new ArrayList<>();
reciepientList.addAll(mentorsIds);
if (null != batchAttributes) {
List<Map<String, Object>> sessionDetails = (List<Map<String, Object>>) batchAttributes.get("sessionDetails_v2");
if (null != sessionDetails) {
for (Map<String, Object> sessionDetail : sessionDetails) {
List<String> facilatorIds = (List<String>) sessionDetail.get("facilatorIDs");
reciepientList.addAll(facilatorIds);
}
}
}
List<BatchUser> batchUsers = batchUserDao.readById(context, updatedCourseBatch.getBatchId());
List<String> batchUserIdList = batchUsers.stream().filter(e -> e.getActive()).map(user -> user.getUserId()).collect(Collectors.toList());
reciepientList.addAll(batchUserIdList);
sendEmailNotificationMailForBatchDatesUpdate(reciepientList, oldCourseBatch, updatedCourseBatch);
}

private void sendEmailNotificationMailForBatchDatesUpdate(List<String> reciepientList, CourseBatch oldBatch, CourseBatch updatedBatch) {
Map<String, Object> request = new HashMap<>();
request.put(Constants.COURSE_NAME, updatedBatch.getName());
request.put(Constants.BATCH_NAME, updatedBatch.getDescription());
request.put(Constants.RECIPIENT_IDS, reciepientList);
request.put(JsonKey.SUBJECT, getBatchUpdateEmailSubject());
request.put(Constants.TRAINING_NAME, updatedBatch.getName());
request.put(JsonKey.REGARDS, Constants.KARMAYOGI_BHARAT);
request.put(JsonKey.EMAIL_TEMPLATE_TYPE, Constants.BATCH_DATE_UPDATE_TEMPLATE);
request.put(Constants.START_DATE, updatedBatch.getStartDate());
request.put(Constants.END_DATE, updatedBatch.getEndDate());
request.put(Constants.ENROLLMENT_END_DATE, updatedBatch.getEnrollmentEndDate());
request.put(JsonKey.BODY, Constants.EMAIL_BODY);
HashMap<String, String> headers = new HashMap<>();
headers.put(Constants.CONTENT_TYPE, Constants.APPLICATION_JSON);
HashMap<String, Object> requestBody = new HashMap<>();
requestBody.put(JsonKey.REQUEST, request);
StringBuilder url = new StringBuilder();
HttpResponse<String> httpResponse = null;
String requeststr = null;
try {
requeststr = mapper.writeValueAsString(requestBody);
url.append(getLearnerHost()).append(getLearnerPath());
httpResponse = Unirest.post(String.valueOf(url)).headers(headers).body(requeststr).asString();
if (httpResponse != null && !ResponseCode.OK.equals(httpResponse.getStatus())) {
throw new RuntimeException("An error occured while sending mail notification");
}
} catch (Exception e) {
if (e instanceof RuntimeException) {
logger.error(null, e.getMessage() + "Headers : " + httpResponse.getHeaders() + "Body : " + httpResponse.getBody(), e);
}
logger.error(null, "Exception occurred with error message = " + e.getMessage(), e);
}
}

private String getLearnerHost() {
return PropertiesCache.getInstance()
.getProperty(JsonKey.LMS_SERVICE_HOST);
}

private String getLearnerPath() {
return PropertiesCache.getInstance()
.getProperty(JsonKey.LMS_SEND_EMAIL_NOTIFICATION_PATH);
}
private String getBatchUpdateEmailSubject() {
return PropertiesCache.getInstance()
.getProperty(JsonKey.SUNBIRD_BATCH_DATE_UPDATE_NOTIFICATIONS_SUBJECT);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -64,4 +64,23 @@ public interface Constants {
public static final String GT = ">";
public static final String ID = "id";
public static final Integer DEFAULT_LIMIT = 250;
public static final String CONTENT_TYPE = "Content-Type";
public static final String APPLICATION_JSON = "application/json";
public static final String OLD_COURSE_BATCH = "oldCourseBatch";
public static final String UPDATED_COURSE_BATCH = "updatedCourseBatch";
public static final String REQUEST_CONTEXT = "requestContext";
public static final String COURSE_NAME = "courseName";
public static final String BATCH_NAME = "batchName";
public static final String RECIPIENT_IDS = "recipientUserIds";
public static final String TRAINING_NAME = "trainingName";
public static final String START_DATE = "startDate";
public static final String END_DATE = "endDate";
public static final String ENROLLMENT_END_DATE = "enrollmentEndDate";
public static final String BATCH_DATE_UPDATE_TEMPLATE = "batchdateupdatetemplate";
public static final String EMAIL_BODY = "emailBody";
public static final String KARMAYOGI_BHARAT = "Karmayogi Bharat";




}
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,8 @@ public enum ActorOperations {
GROUP_ACTIVITY_AGGREGATES("groupActivityAggregates"),
UPDATE_EVENT_SET("updateEventSet"),
DELETE_EVENT_SET("deleteEventSet"),
DELETE_EVENT("deleteEvent");
DELETE_EVENT("deleteEvent"),
COURSE_BATCH_DATE_NOTIFICATION("courseBatchDateNotification");

private String value;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1086,6 +1086,13 @@ public final class JsonKey {
public static final String IS_ADMIN_API = "isAdminAPI";
public static final String RETIRED_COURE_ENABLED = "retiredCoursesEnabled";
public static final String FALSE = "false";

public static final String LMS_SERVICE_HOST = "lms.service.host";
public static final String SUNBIRD_BATCH_UPDATE_NOTIFICATIONS_ENABLED =
"sunbird_batch_update_notification_enabled";

public static final String REGARDS = "regards";
public static final String SUNBIRD_BATCH_DATE_UPDATE_NOTIFICATIONS_SUBJECT = "sunbird_batch_date_update_notifications_subject" ;
public static final String LMS_SEND_EMAIL_NOTIFICATION_PATH = "lms.send.email.notification";

private JsonKey() {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -206,4 +206,7 @@ sunbird_api_mgr_base_url=https://dev.sunbirded.org/api
enrollment_list_size=1000
sunbird_course_batch_path=/app/toc/{courseId}/overview?batchId={batchId}
enrolment_list_include_retired_courses=false
enrol_end_date_allow_lesser_value=false
enrol_end_date_allow_lesser_value=true
lms.service.host=
sunbird_batch_date_update_notifications_subject=Notification for changes in the batch dates
lms.send.email.notification=/v1/notification/email