Skip to content

Commit

Permalink
SAK-46473 Assignments: worklog error handling improvement (sakaiproje…
Browse files Browse the repository at this point in the history
…ct#10293)

* SAK-46473 Assignments: worklog error handling improvement

* SAK-46473: Codacy

* SAK-46473: Codacy 2
  • Loading branch information
jorgecanovas authored Mar 11, 2022
1 parent b47b897 commit 07a6ad8
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 119 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -107,38 +107,6 @@ public class AssignmentEntityProvider extends AbstractEntityProvider implements
private FormattedText formattedText;
private LTIService ltiService;

@Setter
@Getter
public class BuildTimeSheetReturnMessage implements Serializable {

@Setter
@Getter
public class ErrorTimeSheetReturnMessage implements Serializable {
private int code;
private String message;

private ErrorTimeSheetReturnMessage() {}

private ErrorTimeSheetReturnMessage(int codeMsg, String textMsg) {
this.code = codeMsg;
this.message = textMsg;
}
}

private ErrorTimeSheetReturnMessage error;
private boolean success;

public BuildTimeSheetReturnMessage () {}

public BuildTimeSheetReturnMessage (boolean isSuccess, int codeMsg, String textMsg) {
this.success = isSuccess;
if (!isSuccess) {
this.error = new ErrorTimeSheetReturnMessage(codeMsg, textMsg);
}
}
}


// HTML is deliberately not handled here, so that it will be handled by RedirectingAssignmentEntityServlet
public String[] getHandledOutputFormats() {
return new String[] { Formats.XML, Formats.JSON, Formats.FORM };
Expand Down Expand Up @@ -497,35 +465,35 @@ public GraderUser(User sakaiUser) {
}

@EntityCustomAction(action = "addTimeSheet", viewKey = EntityView.VIEW_NEW)
public BuildTimeSheetReturnMessage addTimeSheet(Map<String, Object> params) {
public int addTimeSheet(Map<String, Object> params) {

String userId = sessionManager.getCurrentSessionUserId();

if (StringUtils.isBlank(userId)) {
log.warn("You need to be logged in to add time sheet register");
return new BuildTimeSheetReturnMessage(false, 1, "ts.add.err.userId");
throw new EntityException("You need to be logged in to add time sheet register", "", HttpServletResponse.SC_FORBIDDEN);
}

User user;
try {
user = userDirectoryService.getUser(userId);
} catch (UserNotDefinedException unde) {
log.warn("You need to be logged in to add time sheet register");
return new BuildTimeSheetReturnMessage(false, 1, "ts.add.err.userId");
throw new EntityException("You need to be logged in to add time sheet register", "", HttpServletResponse.SC_FORBIDDEN);
}

String assignmentId = (String) params.get("tsAssignmentId");
if (StringUtils.isBlank(assignmentId)) {
log.warn("You need to supply the assignmentId and ref");
return new BuildTimeSheetReturnMessage(false, 1, "ts.add.err.assignmentId");
throw new EntityException("You need to supply the assignmentId and ref", "", HttpServletResponse.SC_NOT_FOUND);
}

AssignmentSubmission submission;
try {
submission = assignmentService.getSubmission(assignmentId, user);
} catch (PermissionException pe) {
log.warn("You can't modify this sumbitter");
return new BuildTimeSheetReturnMessage(false, 1, "ts.add.err.permission");
throw new EntityException("You can't modify this sumbitter", "", HttpServletResponse.SC_UNAUTHORIZED);
}

if (submission == null) {
Expand All @@ -542,23 +510,23 @@ public BuildTimeSheetReturnMessage addTimeSheet(Map<String, Object> params) {
}
} catch (PermissionException e) {
log.warn("Could not add submission for assignment/submitter: {}/{}, {}", assignmentId, submitterId, e.toString());
return new BuildTimeSheetReturnMessage(false, 1, "ts.add.err.submitter");
throw new EntityException("You can't modify this sumbitter", "", HttpServletResponse.SC_UNAUTHORIZED);
}
}

String duration = (String) params.get("tsDuration");

if (!assignmentService.isValidTimeSheetTime(duration)) {
log.warn("Wrong time format. Must match XXh YYm");
return new BuildTimeSheetReturnMessage(false, 1, "ts.add.err.duration");
throw new EntityException("Wrong time format. Must be XXHXXM","",HttpServletResponse.SC_BAD_REQUEST);
}

String comment = (String) params.get("tsComment");
StringBuilder alertMsg = new StringBuilder();
comment = formattedText.processFormattedText(comment, alertMsg);
if (StringUtils.isBlank(comment) || alertMsg.length() > 0) {
log.warn("Comment field format is not valid");
return new BuildTimeSheetReturnMessage(false, 1, "ts.add.err.comment");
throw new EntityException("Comment field format is not valid", "", HttpServletResponse.SC_BAD_REQUEST);
}

Instant startTime;
Expand All @@ -578,7 +546,7 @@ public BuildTimeSheetReturnMessage addTimeSheet(Map<String, Object> params) {

if (submissionSubmitter == null) {
log.warn("You submitter does not exist");
return new BuildTimeSheetReturnMessage(false, 1, "ts.add.err.submitter");
throw new EntityException("You submitter does not exist", "", HttpServletResponse.SC_NOT_FOUND);
}

TimeSheetEntry timeSheet = new TimeSheetEntry();
Expand All @@ -591,19 +559,19 @@ public BuildTimeSheetReturnMessage addTimeSheet(Map<String, Object> params) {
assignmentService.saveTimeSheetEntry(submissionSubmitter, timeSheet);
} catch (PermissionException e) {
log.warn("You can't modify this sumbitter");
return new BuildTimeSheetReturnMessage(false, 1, "ts.add.err.permission");
throw new EntityException("You can't modify this sumbitter", "", HttpServletResponse.SC_UNAUTHORIZED);
}
return new BuildTimeSheetReturnMessage(true, 0, "");
return HttpServletResponse.SC_OK;
}

@EntityCustomAction(action = "removeTimeSheet", viewKey = EntityView.VIEW_NEW)
public BuildTimeSheetReturnMessage removeTimeSheet(Map<String, Object> params) {
public int removeTimeSheet(Map<String, Object> params) {

String userId = sessionManager.getCurrentSessionUserId();

if (StringUtils.isBlank(userId)) {
log.warn("You need to be logged in to add time sheet register");
return new BuildTimeSheetReturnMessage(false, 1, "ts.rem.err.userId");
throw new EntityException("You need to be logged in to remove time sheet register", "", HttpServletResponse.SC_FORBIDDEN);

}

Expand All @@ -612,21 +580,21 @@ public BuildTimeSheetReturnMessage removeTimeSheet(Map<String, Object> params) {
user = userDirectoryService.getUser(userId);
} catch (UserNotDefinedException unde) {
log.warn("You need to be logged in to add time sheet register");
return new BuildTimeSheetReturnMessage(false, 1, "ts.rem.err.userId");
throw new EntityException("You need to be logged in to remove time sheet register", "", HttpServletResponse.SC_FORBIDDEN);
}

String assignmentId = (String) params.get("tsAssignmentId");
if (StringUtils.isBlank(assignmentId)) {
log.warn("You need to supply the assignmentId and ref");
return new BuildTimeSheetReturnMessage(false, 1, "ts.add.err.assignmentId");
throw new EntityException("You need to supply the assignmentId and ref", "", HttpServletResponse.SC_BAD_REQUEST);
}

AssignmentSubmission submission;
try {
submission = assignmentService.getSubmission(assignmentId, user);
} catch (PermissionException e1) {
log.warn("You can't modify this sumbitter");
return new BuildTimeSheetReturnMessage(false, 1, "ts.add.err.permission");
throw new EntityException("You can't modify this sumbitter", "", HttpServletResponse.SC_UNAUTHORIZED);
}

List<Long> timeSheetIds;
Expand All @@ -638,24 +606,24 @@ public BuildTimeSheetReturnMessage removeTimeSheet(Map<String, Object> params) {
timeSheetIds = Collections.singletonList(Long.parseLong(ts.toString()));
} else {
log.warn("Selected time sheets could not be retrieved from request parameters");
return new BuildTimeSheetReturnMessage(false, 1, "ts.rem.err.empty");
throw new EntityException("Selected time sheet must be provided.", "", HttpServletResponse.SC_BAD_REQUEST);
}

for (Long timeSheetId : timeSheetIds) {
if (null == timeSheetId) {
log.warn("A selected time sheet was null");
return new BuildTimeSheetReturnMessage(false, 1, "ts.rem.err.submitterId");
throw new EntityException("You need to supply the submissionId and ref", "", HttpServletResponse.SC_BAD_REQUEST);
}

try {
assignmentService.deleteTimeSheetEntry(timeSheetId);
} catch (PermissionException e) {
log.warn("Could not delete the selected time sheet");
return new BuildTimeSheetReturnMessage(false, 1, "ts.rem.err.permission");
throw new EntityException("You can't modify this sumbitter", "", HttpServletResponse.SC_UNAUTHORIZED);
}
}

return new BuildTimeSheetReturnMessage(true, 0, "");
return HttpServletResponse.SC_OK;
}

@EntityCustomAction(action = "gradable", viewKey = EntityView.VIEW_LIST)
Expand Down
125 changes: 58 additions & 67 deletions assignment/tool/src/webapp/js/studentViewSubmission.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,24 +37,8 @@ ASN_SVS.undoCancel = function()
};

ASN_TS_API.addTimeSheet = function (button, onSuccess, onError) {
var messages = [];
const endpoint = "/direct/assignment/addTimeSheet.json";
const messages = [];

const tsComment = document.getElementById("comment").value;
if (tsComment == null || tsComment.trim() === '') {
messages.push("ts.add.err.comment");
}

const tsDuration = document.getElementById("duration").value;
if (tsDuration == null || tsDuration.trim() === '') {
messages.push("ts.add.err.duration");
}

if (messages.length !== 0) {
onError(null, messages);
return;
}

const params = {
"tsAssignmentId" : document.getElementById("assignmentId").value,
"tsStartTime" : document.getElementById("startTime").value,
Expand All @@ -63,27 +47,35 @@ ASN_TS_API.addTimeSheet = function (button, onSuccess, onError) {
"new_ts_record_year" : document.getElementById("new_ts_record_year").value,
"new_ts_record_hour" : document.getElementById("new_ts_record_hour").value,
"new_ts_record_minute" : document.getElementById("new_ts_record_minute").value,
tsComment,
tsDuration
"tsComment" : document.getElementById("comment").value,
"tsDuration" : document.getElementById("duration").value,
};

if(!document.getElementById("comment").value){ messages.push("ts.add.err.comment"); }
if(!document.getElementById("duration").value){ messages.push("ts.add.err.duration"); }
button.classList.add("spinButton");
button.disabled = true;

ASN_TS_API._POST(endpoint, params, onSuccess, onError);
if(messages.length === 0){
ASN_TS_API._POST(endpoint, params, onSuccess, onError);
} else {
onError(null, messages);
}
};

ASN_TS_API.removeTimeSheet = function (button, onSuccess, onError) {
var messages = [];
const endpoint = "/direct/assignment/removeTimeSheet.json";
const params = {
"selectedTimeSheets" : [...document.getElementsByName("selectedTimesheet")].filter((el) => el.checked).map((el) => el.value),
"tsAssignmentId" : document.getElementById("assignmentId").value,
};

if(!params.selectedTimeSheets || params.selectedTimeSheets.length === 0){messages.push("ts.rem.err.empty"); }
button.classList.add("spinButton");
button.disabled = true;

ASN_TS_API._POST(endpoint, params, onSuccess, onError);
if(messages.length === 0){
ASN_TS_API._POST(endpoint, params, onSuccess, onError);
} else {
onError(null, messages);
}
};

ASN_TS_API._GET = function (url, data, onSuccess, onError, onComplete) {
Expand Down Expand Up @@ -123,68 +115,67 @@ ASN.switchTimesheetTab = function (source) {
};

ASN.tsHandleAjaxAddSuccess = function (data) {
const alertTsheetAddRecord = document.getElementById("alertTsheetAddRecord");
if (data.error && data.error.message) {
const button = document.getElementById("btnTimesheetAdd");
button.classList.remove("spinButton");
button.disabled = false;
alertTsheetAddRecord.innerHTML = window.i18nWlogTab[data.error.message];
if(alertTsheetAddRecord.classList.contains('hidden')) {
alertTsheetAddRecord.classList.toggle('hidden');
}
} else {
if(!alertTsheetAddRecord.classList.contains('hidden')) {
alertTsheetAddRecord.classList.toggle('hidden');
}
ASN.submitForm('addSubmissionForm', 'view', null, null);
}
ASN.submitForm( 'addSubmissionForm', 'view', null, null );
};

ASN.tsHandleAjaxRemoveSuccess = function (data) {
const alertTsheetDelRecord = document.getElementById("alertTsheetDelRecord");
if (data.error && data.error.message) {
const button = document.getElementById("btnTimesheetDelete");
button.classList.remove("spinButton");
button.disabled = false;
alertTsheetDelRecord.innerHTML = window.i18nWlogTab[data.error.message];
if(alertTsheetDelRecord.classList.contains('hidden')) {
alertTsheetDelRecord.classList.toggle('hidden');
}
} else {
if(!alertTsheetDelRecord.classList.contains('hidden')) {
alertTsheetDelRecord.classList.toggle('hidden');
}
ASN.submitForm('addSubmissionForm', 'view', null, null);
}
ASN.submitForm( 'addSubmissionForm', 'view', null, null );
};

ASN.tsAddHandleAjaxError = function (xhr, messagesParam) {
const messages = typeof(messagesParam) === 'string' ? [] : messagesParam;
if(xhr && xhr.status){
switch(xhr.status){
case 400: messages.push("ts.add.err.duration");
break;
case 401: messages.push("ts.add.err.permission");
break;
case 403: messages.push("ts.add.err.userId");
break;
case 404: messages.push("ts.add.err.assignmentId");
}
}

const button = document.getElementById("btnTimesheetAdd");
const alertTsheetAddRecord = document.getElementById("alertTsheetAddRecord");
button.classList.remove("spinButton");
button.disabled = false;
if(alertTsheetAddRecord.classList.contains('hidden')) {
alertTsheetAddRecord.classList.toggle('hidden');

const alertTsheetAddRecord = document.getElementById("alertTsheetAddRecord");
alertTsheetAddRecord.classList.remove("hidden");
// Object.keys(window.i18nWlogTab).find((key) => key.includes('ts.add.err.permission'))
let messageArray = [];
for (const [index, key] of Object.entries(messages)) {
messageArray.push(window.i18nWlogTab[key]);
}
const messageArray = [];
alertTsheetAddRecord.innerHTML
= Object.entries(messages).reduce((acc, entry) => { acc.push(i18nWlogTab[entry[1]]); return acc; }, []).join("<br>");
const node = document.createElement("br");
alertTsheetAddRecord.appendChild(node);
};

ASN.tsRemoveHandleAjaxError = function (xhr, messagesParam) {
const messages = typeof(messagesParam) === 'string' ? [] : messagesParam;
if(xhr && xhr.status){
switch(xhr.status){
case 400: messages.push("ts.add.err.assignmentId");
break;
case 401: messages.push("ts.add.err.permission");
break;
case 403: messages.push("ts.rem.err.userId");
}
}

var button = document.getElementById("btnTimesheetDelete");
const alertTsheetDelRecord = document.getElementById("alertTsheetDelRecord");
const button = document.getElementById("btnTimesheetDelete");
button.classList.remove("spinButton");
button.disabled = false;
if(alertTsheetDelRecord.classList.contains('hidden')) {
alertTsheetDelRecord.classList.toggle('hidden');

const alertTsheetDelRecord = document.getElementById("alertTsheetDelRecord");
alertTsheetDelRecord.classList.remove("hidden");
// Object.keys(window.i18nWlogTab).find((key) => key.includes('ts.add.err.permission'))
let messageArray = [];
for (const [index, key] of Object.entries(messages)) {
messageArray.push(window.i18nWlogTab[key]);
}
alertTsheetDelRecord.innerHTML
= Object.entries(messages).reduce((acc, entry) => { acc.push(i18nWlogTab[entry[1]]); return acc; }, []).join("<br>");
const node = document.createElement("br");
alertTsheetDelRecord.appendChild(node);
};

ASN.checkTimesheetRecord = function () {
Expand Down

0 comments on commit 07a6ad8

Please sign in to comment.