From 8d6b72dbf65194189ef458d8c9e659143557b616 Mon Sep 17 00:00:00 2001 From: Phuong H Date: Fri, 16 Oct 2015 09:48:38 +0700 Subject: [PATCH 01/80] Make calculateChallengePhases to become a public function so that it can be reused --- src/main/java/com/techlooper/service/ChallengeService.java | 2 ++ .../java/com/techlooper/service/impl/ChallengeServiceImpl.java | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/techlooper/service/ChallengeService.java b/src/main/java/com/techlooper/service/ChallengeService.java index 8a7237d4e..ca187e36c 100644 --- a/src/main/java/com/techlooper/service/ChallengeService.java +++ b/src/main/java/com/techlooper/service/ChallengeService.java @@ -101,4 +101,6 @@ List findChallengeSubmissionWithinPeriod( ChallengeRegistrantDto acceptRegistrant(String ownerEmail, Long registrantId); + void calculateChallengePhases(ChallengeDetailDto challengeDetailDto); + } diff --git a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java index ddcd96da2..6c30b3c9f 100644 --- a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java @@ -874,7 +874,7 @@ public ChallengeDetailDto getChallengeDetail(Long challengeId, String loginEmail return null; } - public static void calculateChallengePhases(ChallengeDetailDto challengeDetailDto) { + public void calculateChallengePhases(ChallengeDetailDto challengeDetailDto) { String now = DateTimeUtils.currentDate(); String timeline[] = { From 75ef1607358160f309f32a07fcefc70d12965cf6 Mon Sep 17 00:00:00 2001 From: johnsonpham Date: Fri, 16 Oct 2015 11:01:32 +0700 Subject: [PATCH 02/80] add choose email template combobox for feedback form --- .../assets/modules/common/feedback/feedback.html | 8 ++++++++ .../modules/common/feedback/feedbackDirective.js | 1 - .../webapp/assets/modules/common/resourcesService.js | 11 ++++++++++- .../assets/modules/contest-detail/contestDetail.html | 3 +++ .../modules/contest-detail/contestDetailController.js | 9 --------- 5 files changed, 21 insertions(+), 11 deletions(-) diff --git a/src/main/webapp/assets/modules/common/feedback/feedback.html b/src/main/webapp/assets/modules/common/feedback/feedback.html index c41067334..285a5e981 100644 --- a/src/main/webapp/assets/modules/common/feedback/feedback.html +++ b/src/main/webapp/assets/modules/common/feedback/feedback.html @@ -8,6 +8,14 @@ +
+ +
+ +
+
diff --git a/src/main/webapp/assets/modules/common/feedback/feedbackDirective.js b/src/main/webapp/assets/modules/common/feedback/feedbackDirective.js index 32a297e4a..67f4f5ea4 100644 --- a/src/main/webapp/assets/modules/common/feedback/feedbackDirective.js +++ b/src/main/webapp/assets/modules/common/feedback/feedbackDirective.js @@ -13,7 +13,6 @@ techlooper.directive("feedbackForm", function (apiService, $timeout) { else { scope.composeEmail.names = scope.composeEmail.registrantFirstName; } - scope.send = function () { if (scope.feedbackContent == undefined || scope.feedbackContent == '') { return; diff --git a/src/main/webapp/assets/modules/common/resourcesService.js b/src/main/webapp/assets/modules/common/resourcesService.js index 084c7794a..e5d9863b6 100644 --- a/src/main/webapp/assets/modules/common/resourcesService.js +++ b/src/main/webapp/assets/modules/common/resourcesService.js @@ -15,6 +15,13 @@ techlooper.factory("resourcesService", function ($translate, $q) { {translate: "theSolutionIsInnovative", id: "theSolutionIsInnovative"} ]; + var emailTemplateOptions = [ + {translate: "welcomeContestant", id: "welcomeContestant"}, + {translate: "askContestantSubmission", id: "askContestantSubmission"}, + {translate: "disqualifyContestant", id: "disqualifyContestant"}, + {translate: "winnerAnnouncement", id: "winnerAnnouncement"} + ]; + var paymentOptions = [ {translate: "hourlyByByHour", reviewTranslate: "hourlyJob", id: "hourly"}, {translate: "fixedPricePayByProject", reviewTranslate: "fixedPrice", id: "fixedPrice"} @@ -79,6 +86,7 @@ techlooper.factory("resourcesService", function ($translate, $q) { paymentConfig: $.extend(true, {}, {options: paymentOptions}, idSelectize("paymentConfig")), estimatedDurationConfig: $.extend(true, {}, {options: estimatedDurationOptions}, idSelectize("estimatedDurationConfig")), estimatedWorkloadConfig: $.extend(true, {}, {options: estimatedWorkloadOptions}, idSelectize("estimatedWorkloadConfig")), + emailTemplateConfig: $.extend(true, {}, {options: emailTemplateOptions}, titleSelectize("emailTemplateConfig")), inOptions: function (title, config) { var index = -1; $.each(config.options, function (i, opt) { @@ -109,7 +117,8 @@ techlooper.factory("resourcesService", function ($translate, $q) { {ins: instance.qualityIdeaConfig, placeholder: "exQualityIdeaConfig"}, {ins: instance.paymentConfig, placeholder: "exPaymentConfig"}, {ins: instance.estimatedDurationConfig, placeholder: "exEstimatedDurationConfig"}, - {ins: instance.estimatedWorkloadConfig, placeholder: "exEstimatedWorkloadConfig"} + {ins: instance.estimatedWorkloadConfig, placeholder: "exEstimatedWorkloadConfig"}, + {ins: instance.emailTemplateConfig, placeholder: "exChooseATemplate"} ]; $.each(translations, function (i, item) { diff --git a/src/main/webapp/assets/modules/contest-detail/contestDetail.html b/src/main/webapp/assets/modules/contest-detail/contestDetail.html index 6ffb3e0e7..b30ccf3c5 100644 --- a/src/main/webapp/assets/modules/contest-detail/contestDetail.html +++ b/src/main/webapp/assets/modules/contest-detail/contestDetail.html @@ -235,6 +235,9 @@

+

diff --git a/src/main/webapp/assets/modules/contest-detail/contestDetailController.js b/src/main/webapp/assets/modules/contest-detail/contestDetailController.js index 60d1cb2c7..f9b9a6576 100644 --- a/src/main/webapp/assets/modules/contest-detail/contestDetailController.js +++ b/src/main/webapp/assets/modules/contest-detail/contestDetailController.js @@ -213,15 +213,6 @@ techlooper.controller('contestDetailController', function ($scope, apiService, l }); } - //$scope.showSubmitForm = function () { - // var subForm = $('.submit-phase-contest'); - // if (subForm.hasClass('show')) { - // subForm.removeClass('show'); - // } - // else { - // subForm.addClass('show'); - // } - //}; $scope.config = { registrantsFilter: resourcesService.registrantsFilterConfig }; From 7000893380e008f302bc9226f958b39a83f20067 Mon Sep 17 00:00:00 2001 From: johnsonpham Date: Fri, 16 Oct 2015 11:01:58 +0700 Subject: [PATCH 03/80] update responsive for feedback form --- src/main/webapp/assets/sass/contest-detail.sass | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/main/webapp/assets/sass/contest-detail.sass b/src/main/webapp/assets/sass/contest-detail.sass index 3bfa3cf70..0d1d9b2ae 100644 --- a/src/main/webapp/assets/sass/contest-detail.sass +++ b/src/main/webapp/assets/sass/contest-detail.sass @@ -536,8 +536,14 @@ display: inline-block border-radius: 3px position: relative + .selectize-control + text-align: left .mail-body border: 0 + .form-group + input + border-radius: 4px + border: 1px solid #cccccc .mail-subject padding: 10px 0 .control-label @@ -549,6 +555,8 @@ .form-group margin: 0 padding: 0 20px + input + border-radius: 4px .note-editor background-color: #fff min-height: 200px From 2e552cace0e4a28edf260dd13e93e25823f6a9b1 Mon Sep 17 00:00:00 2001 From: johnsonpham Date: Fri, 16 Oct 2015 11:03:43 +0700 Subject: [PATCH 04/80] translate for choose email template combobox on the feedback form --- .../webapp/assets/modules/translation/messages_en.json | 8 +++++++- .../webapp/assets/modules/translation/messages_vi.json | 8 +++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/main/webapp/assets/modules/translation/messages_en.json b/src/main/webapp/assets/modules/translation/messages_en.json index cb6d2d6e6..068f362cf 100644 --- a/src/main/webapp/assets/modules/translation/messages_en.json +++ b/src/main/webapp/assets/modules/translation/messages_en.json @@ -774,5 +774,11 @@ "allContestants": "All Contestants", "allSubmission": "All Submission", "404Error": "This URL leads to 404 page. Please check again.", - "cannotSendMail": "You don’t have right to perform this action." + "cannotSendMail": "You don’t have right to perform this action.", + "template": "Template:", + "welcomeContestant": "Welcome new contestant", + "askContestantSubmission": "Ask for submission", + "disqualifyContestant": "Disqualify a contestant", + "winnerAnnouncement": "Winner announcement", + "exChooseATemplate": "Choose a template" } \ No newline at end of file diff --git a/src/main/webapp/assets/modules/translation/messages_vi.json b/src/main/webapp/assets/modules/translation/messages_vi.json index 719585442..2486e988c 100644 --- a/src/main/webapp/assets/modules/translation/messages_vi.json +++ b/src/main/webapp/assets/modules/translation/messages_vi.json @@ -777,6 +777,12 @@ "exRegistrantsFilterConfig": "Tất cả thí sinh", "allSubmission": "Tất cả bài nộp", "404Error": "URL này dẫn đến trang không tồn tại (lỗi 404). Xin vui lòng kiểm tra lại.", - "cannotSendMail": "Bạn không có quyền thực hiện hành động này." + "cannotSendMail": "Bạn không có quyền thực hiện hành động này.", + "template": "Template:", + "welcomeContestant": "Welcome new contestant", + "askContestantSubmission": "Ask for submission", + "disqualifyContestant": "Disqualify a contestant", + "winnerAnnouncement": "Winner announcement", + "exChooseATemplate": "choose a template" } From d55569a9a231ff5f794ac8859e44aa34a373c2a4 Mon Sep 17 00:00:00 2001 From: Phuong H Date: Fri, 16 Oct 2015 13:43:41 +0700 Subject: [PATCH 05/80] Challenge Criteria service --- .../ChallengeCriteriaController.java | 28 ++ .../techlooper/entity/ChallengeCriteria.java | 27 ++ .../techlooper/entity/ChallengeEntity.java | 11 + .../model/ChallengeCriteriaDto.java | 39 ++ .../techlooper/model/ChallengeDetailDto.java | 370 +++++++++--------- .../service/ChallengeCriteriaService.java | 11 + .../techlooper/service/ChallengeService.java | 2 + .../impl/ChallengeCriteriaServiceImpl.java | 39 ++ .../service/impl/ChallengeServiceImpl.java | 8 + .../assets/modules/common/apiService.js | 7 + 10 files changed, 367 insertions(+), 175 deletions(-) create mode 100644 src/main/java/com/techlooper/controller/ChallengeCriteriaController.java create mode 100644 src/main/java/com/techlooper/entity/ChallengeCriteria.java create mode 100644 src/main/java/com/techlooper/model/ChallengeCriteriaDto.java create mode 100644 src/main/java/com/techlooper/service/ChallengeCriteriaService.java create mode 100644 src/main/java/com/techlooper/service/impl/ChallengeCriteriaServiceImpl.java diff --git a/src/main/java/com/techlooper/controller/ChallengeCriteriaController.java b/src/main/java/com/techlooper/controller/ChallengeCriteriaController.java new file mode 100644 index 000000000..74e7ac157 --- /dev/null +++ b/src/main/java/com/techlooper/controller/ChallengeCriteriaController.java @@ -0,0 +1,28 @@ +package com.techlooper.controller; + +import com.techlooper.entity.ChallengeCriteria; +import com.techlooper.model.ChallengeCriteriaDto; +import com.techlooper.service.ChallengeCriteriaService; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; + +/** + * Created by phuonghqh on 10/16/15. + */ +@RestController +public class ChallengeCriteriaController { + + @Resource + private ChallengeCriteriaService challengeCriteriaService; + + @PreAuthorize("hasAuthority('EMPLOYER')") + @RequestMapping(value = "challenge/criteria", method = RequestMethod.POST) + public ChallengeCriteriaDto save(ChallengeCriteriaDto challengeCriteriaDto, HttpServletRequest request) { + return challengeCriteriaService.save(challengeCriteriaDto, request.getRemoteUser()); + } +} diff --git a/src/main/java/com/techlooper/entity/ChallengeCriteria.java b/src/main/java/com/techlooper/entity/ChallengeCriteria.java new file mode 100644 index 000000000..6b41aa578 --- /dev/null +++ b/src/main/java/com/techlooper/entity/ChallengeCriteria.java @@ -0,0 +1,27 @@ +package com.techlooper.entity; + +/** + * Created by phuonghqh on 10/16/15. + */ +public class ChallengeCriteria { + + private String name; + + private Long weight; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Long getWeight() { + return weight; + } + + public void setWeight(Long weight) { + this.weight = weight; + } +} diff --git a/src/main/java/com/techlooper/entity/ChallengeEntity.java b/src/main/java/com/techlooper/entity/ChallengeEntity.java index 3f7d409ed..e5b1ec483 100644 --- a/src/main/java/com/techlooper/entity/ChallengeEntity.java +++ b/src/main/java/com/techlooper/entity/ChallengeEntity.java @@ -22,6 +22,9 @@ public class ChallengeEntity { @Id private Long challengeId; + @Field(type = FieldType.Nested) + private ChallengeCriteria criteria; + @Field(type = String) private String challengeName; @@ -94,6 +97,14 @@ public class ChallengeEntity { @Field(type = Integer) private int lastEmailSentResultCode; + public ChallengeCriteria getCriteria() { + return criteria; + } + + public void setCriteria(ChallengeCriteria criteria) { + this.criteria = criteria; + } + public Boolean getExpired() { return expired; } diff --git a/src/main/java/com/techlooper/model/ChallengeCriteriaDto.java b/src/main/java/com/techlooper/model/ChallengeCriteriaDto.java new file mode 100644 index 000000000..03368e4c5 --- /dev/null +++ b/src/main/java/com/techlooper/model/ChallengeCriteriaDto.java @@ -0,0 +1,39 @@ +package com.techlooper.model; + +import java.io.Serializable; + +/** + * Created by phuonghqh on 10/16/15. + */ +public class ChallengeCriteriaDto implements Serializable { + + private Long challengeId; + + private String name; + + private Long weight; + + public Long getChallengeId() { + return challengeId; + } + + public void setChallengeId(Long challengeId) { + this.challengeId = challengeId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Long getWeight() { + return weight; + } + + public void setWeight(Long weight) { + this.weight = weight; + } +} diff --git a/src/main/java/com/techlooper/model/ChallengeDetailDto.java b/src/main/java/com/techlooper/model/ChallengeDetailDto.java index fd5245c6d..ef8bc0a94 100644 --- a/src/main/java/com/techlooper/model/ChallengeDetailDto.java +++ b/src/main/java/com/techlooper/model/ChallengeDetailDto.java @@ -1,5 +1,7 @@ package com.techlooper.model; +import com.techlooper.entity.ChallengeCriteria; + import java.util.List; /** @@ -7,253 +9,271 @@ */ public class ChallengeDetailDto { - private Long challengeId; + private Long challengeId; + + private String challengeName; + + private String challengeOverview; + + private String businessRequirement; + + private String generalNote; + + private List technologies; - private String challengeName; + private String documents; - private String challengeOverview; + private String deliverables; - private String businessRequirement; + private String reviewStyle; - private String generalNote; + private String startDateTime; - private List technologies; + private String registrationDateTime; - private String documents; + private String ideaSubmissionDateTime; - private String deliverables; + private String uxSubmissionDateTime; - private String reviewStyle; + private String prototypeSubmissionDateTime; - private String startDateTime; + private String submissionDateTime; - private String registrationDateTime; + private Integer firstPlaceReward; - private String ideaSubmissionDateTime; + private Integer secondPlaceReward; - private String uxSubmissionDateTime; + private Integer thirdPlaceReward; - private String prototypeSubmissionDateTime; + private String qualityIdea; - private String submissionDateTime; + private Long numberOfRegistrants; - private Integer firstPlaceReward; + private List receivedEmails; - private Integer secondPlaceReward; + private Boolean expired; - private Integer thirdPlaceReward; + private ChallengePhaseEnum currentPhase; - private String qualityIdea; + private ChallengePhaseEnum nextPhase; - private Long numberOfRegistrants; + private Boolean isAuthor; - private List receivedEmails; + private ChallengeCriteria criteria; - private Boolean expired; + public ChallengeCriteria getCriteria() { + return criteria; + } - private ChallengePhaseEnum currentPhase; + public void setCriteria(ChallengeCriteria criteria) { + this.criteria = criteria; + } - private ChallengePhaseEnum nextPhase; + public Boolean getAuthor() { + return isAuthor; + } - private Boolean isAuthor; + public void setAuthor(Boolean author) { + isAuthor = author; + } - public ChallengePhaseEnum getCurrentPhase() { - return currentPhase; - } + public ChallengePhaseEnum getCurrentPhase() { + return currentPhase; + } - public void setCurrentPhase(ChallengePhaseEnum currentPhase) { - this.currentPhase = currentPhase; - } + public void setCurrentPhase(ChallengePhaseEnum currentPhase) { + this.currentPhase = currentPhase; + } - public ChallengePhaseEnum getNextPhase() { - return nextPhase; - } + public ChallengePhaseEnum getNextPhase() { + return nextPhase; + } - public void setNextPhase(ChallengePhaseEnum nextPhase) { - this.nextPhase = nextPhase; - } + public void setNextPhase(ChallengePhaseEnum nextPhase) { + this.nextPhase = nextPhase; + } - public Boolean getExpired() { - return expired; - } + public Boolean getExpired() { + return expired; + } - public void setExpired(Boolean expired) { - this.expired = expired; - } + public void setExpired(Boolean expired) { + this.expired = expired; + } - public List getReceivedEmails() { - return receivedEmails; - } + public List getReceivedEmails() { + return receivedEmails; + } - public void setReceivedEmails(List receivedEmails) { - this.receivedEmails = receivedEmails; - } + public void setReceivedEmails(List receivedEmails) { + this.receivedEmails = receivedEmails; + } - public Long getChallengeId() { - return challengeId; - } + public Long getChallengeId() { + return challengeId; + } - public void setChallengeId(Long challengeId) { - this.challengeId = challengeId; - } + public void setChallengeId(Long challengeId) { + this.challengeId = challengeId; + } - public String getChallengeName() { - return challengeName; - } + public String getChallengeName() { + return challengeName; + } - public void setChallengeName(String challengeName) { - this.challengeName = challengeName; - } + public void setChallengeName(String challengeName) { + this.challengeName = challengeName; + } - public String getChallengeOverview() { - return challengeOverview; - } + public String getChallengeOverview() { + return challengeOverview; + } - public void setChallengeOverview(String challengeOverview) { - this.challengeOverview = challengeOverview; - } + public void setChallengeOverview(String challengeOverview) { + this.challengeOverview = challengeOverview; + } - public String getBusinessRequirement() { - return businessRequirement; - } + public String getBusinessRequirement() { + return businessRequirement; + } - public void setBusinessRequirement(String businessRequirement) { - this.businessRequirement = businessRequirement; - } + public void setBusinessRequirement(String businessRequirement) { + this.businessRequirement = businessRequirement; + } - public String getGeneralNote() { - return generalNote; - } + public String getGeneralNote() { + return generalNote; + } - public void setGeneralNote(String generalNote) { - this.generalNote = generalNote; - } + public void setGeneralNote(String generalNote) { + this.generalNote = generalNote; + } - public List getTechnologies() { - return technologies; - } + public List getTechnologies() { + return technologies; + } - public void setTechnologies(List technologies) { - this.technologies = technologies; - } + public void setTechnologies(List technologies) { + this.technologies = technologies; + } - public String getDocuments() { - return documents; - } + public String getDocuments() { + return documents; + } - public void setDocuments(String documents) { - this.documents = documents; - } + public void setDocuments(String documents) { + this.documents = documents; + } - public String getDeliverables() { - return deliverables; - } + public String getDeliverables() { + return deliverables; + } - public void setDeliverables(String deliverables) { - this.deliverables = deliverables; - } + public void setDeliverables(String deliverables) { + this.deliverables = deliverables; + } - public String getReviewStyle() { - return reviewStyle; - } + public String getReviewStyle() { + return reviewStyle; + } - public void setReviewStyle(String reviewStyle) { - this.reviewStyle = reviewStyle; - } + public void setReviewStyle(String reviewStyle) { + this.reviewStyle = reviewStyle; + } - public String getStartDateTime() { - return startDateTime; - } + public String getStartDateTime() { + return startDateTime; + } - public void setStartDateTime(String startDateTime) { - this.startDateTime = startDateTime; - } + public void setStartDateTime(String startDateTime) { + this.startDateTime = startDateTime; + } - public String getRegistrationDateTime() { - return registrationDateTime; - } + public String getRegistrationDateTime() { + return registrationDateTime; + } - public void setRegistrationDateTime(String registrationDateTime) { - this.registrationDateTime = registrationDateTime; - } + public void setRegistrationDateTime(String registrationDateTime) { + this.registrationDateTime = registrationDateTime; + } - public String getIdeaSubmissionDateTime() { - return ideaSubmissionDateTime; - } + public String getIdeaSubmissionDateTime() { + return ideaSubmissionDateTime; + } - public void setIdeaSubmissionDateTime(String ideaSubmissionDateTime) { - this.ideaSubmissionDateTime = ideaSubmissionDateTime; - } + public void setIdeaSubmissionDateTime(String ideaSubmissionDateTime) { + this.ideaSubmissionDateTime = ideaSubmissionDateTime; + } - public String getUxSubmissionDateTime() { - return uxSubmissionDateTime; - } + public String getUxSubmissionDateTime() { + return uxSubmissionDateTime; + } - public void setUxSubmissionDateTime(String uxSubmissionDateTime) { - this.uxSubmissionDateTime = uxSubmissionDateTime; - } + public void setUxSubmissionDateTime(String uxSubmissionDateTime) { + this.uxSubmissionDateTime = uxSubmissionDateTime; + } - public String getPrototypeSubmissionDateTime() { - return prototypeSubmissionDateTime; - } + public String getPrototypeSubmissionDateTime() { + return prototypeSubmissionDateTime; + } - public void setPrototypeSubmissionDateTime(String prototypeSubmissionDateTime) { - this.prototypeSubmissionDateTime = prototypeSubmissionDateTime; - } + public void setPrototypeSubmissionDateTime(String prototypeSubmissionDateTime) { + this.prototypeSubmissionDateTime = prototypeSubmissionDateTime; + } - public String getSubmissionDateTime() { - return submissionDateTime; - } + public String getSubmissionDateTime() { + return submissionDateTime; + } - public void setSubmissionDateTime(String submissionDateTime) { - this.submissionDateTime = submissionDateTime; - } + public void setSubmissionDateTime(String submissionDateTime) { + this.submissionDateTime = submissionDateTime; + } - public Integer getFirstPlaceReward() { - return firstPlaceReward; - } + public Integer getFirstPlaceReward() { + return firstPlaceReward; + } - public void setFirstPlaceReward(Integer firstPlaceReward) { - this.firstPlaceReward = firstPlaceReward; - } + public void setFirstPlaceReward(Integer firstPlaceReward) { + this.firstPlaceReward = firstPlaceReward; + } - public Integer getSecondPlaceReward() { - return secondPlaceReward; - } + public Integer getSecondPlaceReward() { + return secondPlaceReward; + } - public void setSecondPlaceReward(Integer secondPlaceReward) { - this.secondPlaceReward = secondPlaceReward; - } + public void setSecondPlaceReward(Integer secondPlaceReward) { + this.secondPlaceReward = secondPlaceReward; + } - public Integer getThirdPlaceReward() { - return thirdPlaceReward; - } + public Integer getThirdPlaceReward() { + return thirdPlaceReward; + } - public void setThirdPlaceReward(Integer thirdPlaceReward) { - this.thirdPlaceReward = thirdPlaceReward; - } + public void setThirdPlaceReward(Integer thirdPlaceReward) { + this.thirdPlaceReward = thirdPlaceReward; + } - public String getQualityIdea() { - return qualityIdea; - } + public String getQualityIdea() { + return qualityIdea; + } - public void setQualityIdea(String qualityIdea) { - this.qualityIdea = qualityIdea; - } + public void setQualityIdea(String qualityIdea) { + this.qualityIdea = qualityIdea; + } - public Long getNumberOfRegistrants() { - return numberOfRegistrants; - } + public Long getNumberOfRegistrants() { + return numberOfRegistrants; + } - public void setNumberOfRegistrants(Long numberOfRegistrants) { - this.numberOfRegistrants = numberOfRegistrants; - } + public void setNumberOfRegistrants(Long numberOfRegistrants) { + this.numberOfRegistrants = numberOfRegistrants; + } - public Boolean getIsAuthor() { - return isAuthor; - } + public Boolean getIsAuthor() { + return isAuthor; + } - public void setIsAuthor(Boolean isAuthor) { - this.isAuthor = isAuthor; - } + public void setIsAuthor(Boolean isAuthor) { + this.isAuthor = isAuthor; + } } diff --git a/src/main/java/com/techlooper/service/ChallengeCriteriaService.java b/src/main/java/com/techlooper/service/ChallengeCriteriaService.java new file mode 100644 index 000000000..9fdb1d806 --- /dev/null +++ b/src/main/java/com/techlooper/service/ChallengeCriteriaService.java @@ -0,0 +1,11 @@ +package com.techlooper.service; + +import com.techlooper.model.ChallengeCriteriaDto; + +/** + * Created by phuonghqh on 10/16/15. + */ +public interface ChallengeCriteriaService { + + ChallengeCriteriaDto save(ChallengeCriteriaDto challengeCriteriaDto, String owner); +} diff --git a/src/main/java/com/techlooper/service/ChallengeService.java b/src/main/java/com/techlooper/service/ChallengeService.java index ca187e36c..a66750563 100644 --- a/src/main/java/com/techlooper/service/ChallengeService.java +++ b/src/main/java/com/techlooper/service/ChallengeService.java @@ -87,6 +87,8 @@ List findChallengeSubmissionWithinPeriod( boolean isOwnerOfChallenge(String ownerEmail, Long challengeId); + ChallengeEntity findChallengeIdAndOwnerEmail(Long challengeId, String ownerEmail); + boolean sendEmailToDailyChallengeRegistrants(String challengeOwner, Long challengeId, Long now, EmailContent emailContent); boolean sendEmailToRegistrant(String challengeOwner, Long challengeId, Long registrantId, EmailContent emailContent); diff --git a/src/main/java/com/techlooper/service/impl/ChallengeCriteriaServiceImpl.java b/src/main/java/com/techlooper/service/impl/ChallengeCriteriaServiceImpl.java new file mode 100644 index 000000000..81d9364b4 --- /dev/null +++ b/src/main/java/com/techlooper/service/impl/ChallengeCriteriaServiceImpl.java @@ -0,0 +1,39 @@ +package com.techlooper.service.impl; + +import com.techlooper.entity.ChallengeCriteria; +import com.techlooper.entity.ChallengeEntity; +import com.techlooper.model.ChallengeCriteriaDto; +import com.techlooper.repository.elasticsearch.ChallengeRepository; +import com.techlooper.service.ChallengeCriteriaService; +import com.techlooper.service.ChallengeService; +import org.dozer.Mapper; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; + +/** + * Created by phuonghqh on 10/16/15. + */ +@Service +public class ChallengeCriteriaServiceImpl implements ChallengeCriteriaService { + + @Resource + private ChallengeRepository challengeRepository; + + @Resource + private ChallengeService challengeService; + + @Resource + private Mapper dozerMapper; + + public ChallengeCriteriaDto save(ChallengeCriteriaDto challengeCriteriaDto, String ownerEmail) { + ChallengeEntity challenge = challengeService.findChallengeIdAndOwnerEmail(challengeCriteriaDto.getChallengeId(), ownerEmail); + if (challenge == null) { + return null; + } + + challenge.setCriteria(dozerMapper.map(challengeCriteriaDto, ChallengeCriteria.class)); + challengeRepository.save(challenge); + return challengeCriteriaDto; + } +} diff --git a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java index 6c30b3c9f..ebf34f4ed 100644 --- a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java @@ -769,6 +769,14 @@ public boolean isOwnerOfChallenge(String ownerEmail, Long challengeId) { return challenge.getAuthorEmail().equalsIgnoreCase(ownerEmail); } + public ChallengeEntity findChallengeIdAndOwnerEmail(Long challengeId, String ownerEmail) { + ChallengeEntity challenge = challengeRepository.findOne(challengeId); + if (challenge.getAuthorEmail().equalsIgnoreCase(ownerEmail)) { + return challenge; + } + return null; + } + public boolean sendEmailToDailyChallengeRegistrants(String challengeOwner, Long challengeId, Long now, EmailContent emailContent) { if (isOwnerOfChallenge(challengeOwner, challengeId)) { List registrants = findChallengeRegistrantWithinPeriod(challengeId, now, TimePeriodEnum.TWENTY_FOUR_HOURS); diff --git a/src/main/webapp/assets/modules/common/apiService.js b/src/main/webapp/assets/modules/common/apiService.js index 3386d0b6e..4bff64ba1 100644 --- a/src/main/webapp/assets/modules/common/apiService.js +++ b/src/main/webapp/assets/modules/common/apiService.js @@ -258,6 +258,13 @@ techlooper.factory("apiService", function ($rootScope, $location, jsonValue, $ht * */ getUrlResponseCode: function (url) { return $http.post("resource/getUrlResponseCode", {url: url}, {transformResponse: function (d, h) {return d;}}); + }, + + /** + * @see com.techlooper.controller.ChallengeCriteriaController.save + * */ + saveChallengeCriteria: function(criteria) { + return $http.post("challenge/criteria", criteria); } }; From d067815ec93509260e9b62a53e3a83f8a645564a Mon Sep 17 00:00:00 2001 From: johnsonpham Date: Fri, 16 Oct 2015 14:38:06 +0700 Subject: [PATCH 06/80] add selection phase type for registrants filter on the challenge details page --- .../webapp/assets/modules/common/resourcesService.js | 10 ++++++++++ .../assets/modules/contest-detail/contestDetail.html | 10 +++++----- .../modules/contest-detail/contestDetailController.js | 5 ++++- 3 files changed, 19 insertions(+), 6 deletions(-) diff --git a/src/main/webapp/assets/modules/common/resourcesService.js b/src/main/webapp/assets/modules/common/resourcesService.js index e5d9863b6..c8711b16b 100644 --- a/src/main/webapp/assets/modules/common/resourcesService.js +++ b/src/main/webapp/assets/modules/common/resourcesService.js @@ -4,6 +4,14 @@ techlooper.factory("resourcesService", function ($translate, $q) { {translate: "allSubmission", id: "challengeSubmission"} ]; + var registrantsPhaseOptions = [ + {translate: "allPhase", id: "allPhase"}, + {translate: "registration", id: "registration"}, + {translate: "idea", id: "idea"}, + {translate: "uiux", id: "uiux"}, + {translate: "prototype", id: "prototype"}, + {translate: "finalApp", id: "finalApp"} + ]; var reviewStyleOptions = [ {translate: "contestOwnerSignOff", id: "contestOwnerSignOff"} ]; @@ -81,6 +89,7 @@ techlooper.factory("resourcesService", function ($translate, $q) { var instance = { registrantsFilterConfig: $.extend(true, {}, {options: registrantsFilterOptions}, idSelectize("registrantsFilterConfig")), + registrantsPhaseConfig: $.extend(true, {}, {options: registrantsPhaseOptions}, idSelectize("registrantsPhaseConfig")), reviewStyleConfig: $.extend(true, {}, {options: reviewStyleOptions}, titleSelectize("reviewStyleConfig")), qualityIdeaConfig: $.extend(true, {}, {options: qualityIdeaOptions}, titleSelectize("qualityIdeaConfig")), paymentConfig: $.extend(true, {}, {options: paymentOptions}, idSelectize("paymentConfig")), @@ -113,6 +122,7 @@ techlooper.factory("resourcesService", function ($translate, $q) { var translations = [ {ins: instance.registrantsFilterConfig, placeholder: "exRegistrantsFilterConfig"}, + {ins: instance.registrantsPhaseConfig, placeholder: "exRegistrantsPhaseConfig"}, {ins: instance.reviewStyleConfig, placeholder: "exContestOwnerSignOff"}, {ins: instance.qualityIdeaConfig, placeholder: "exQualityIdeaConfig"}, {ins: instance.paymentConfig, placeholder: "exPaymentConfig"}, diff --git a/src/main/webapp/assets/modules/contest-detail/contestDetail.html b/src/main/webapp/assets/modules/contest-detail/contestDetail.html index b30ccf3c5..d1fccf647 100644 --- a/src/main/webapp/assets/modules/contest-detail/contestDetail.html +++ b/src/main/webapp/assets/modules/contest-detail/contestDetail.html @@ -235,21 +235,21 @@

- +

- +
- + diff --git a/src/main/webapp/assets/modules/contest-detail/contestDetailController.js b/src/main/webapp/assets/modules/contest-detail/contestDetailController.js index f9b9a6576..b9fca12c8 100644 --- a/src/main/webapp/assets/modules/contest-detail/contestDetailController.js +++ b/src/main/webapp/assets/modules/contest-detail/contestDetailController.js @@ -214,8 +214,11 @@ techlooper.controller('contestDetailController', function ($scope, apiService, l } $scope.config = { - registrantsFilter: resourcesService.registrantsFilterConfig + registrantsFilter: resourcesService.registrantsFilterConfig, + registrantsPhase: resourcesService.registrantsPhaseConfig }; + $scope.dateFrom = moment().add(-1, 'day').format('DD/MM/YYYY'); + $scope.dateTo = moment().format('DD/MM/YYYY'); $('.registrants-date').find('.date').datepicker({ autoclose: true, format: 'dd/mm/yyyy' From f51f5c24c48694ded4945bd168e73d146e240dbf Mon Sep 17 00:00:00 2001 From: johnsonpham Date: Fri, 16 Oct 2015 14:39:15 +0700 Subject: [PATCH 07/80] translate for section phase list of registrants filter on the challenge details page --- src/main/webapp/assets/modules/translation/messages_en.json | 2 ++ src/main/webapp/assets/modules/translation/messages_vi.json | 2 ++ 2 files changed, 4 insertions(+) diff --git a/src/main/webapp/assets/modules/translation/messages_en.json b/src/main/webapp/assets/modules/translation/messages_en.json index 068f362cf..9e02152af 100644 --- a/src/main/webapp/assets/modules/translation/messages_en.json +++ b/src/main/webapp/assets/modules/translation/messages_en.json @@ -731,9 +731,11 @@ "qualifyConfirmation": "Are you sure to qualify this contestant again?", "mileStones": "Milestones:", "pleaseSelectMileStone": "Please select milestones relevant to your contest.", + "allPhase": "All Phase", "prototype": "Prototype", "idea": "Idea", "uiux": "UI/UX", + "exRegistrantsPhaseConfig": "All Phase", "ideaDeadline": "Contestants Have To Submit Idea By: *", "uIDeadline": "Contestants Have To Submit UI/UX By: *", "prototypeDeadline": "Contestants Have To Submit Prototype By: *", diff --git a/src/main/webapp/assets/modules/translation/messages_vi.json b/src/main/webapp/assets/modules/translation/messages_vi.json index 2486e988c..5cb4f3859 100644 --- a/src/main/webapp/assets/modules/translation/messages_vi.json +++ b/src/main/webapp/assets/modules/translation/messages_vi.json @@ -741,9 +741,11 @@ "finalDateGtRegisterDate": "Ngày Hết Hạn Gửi Sán Phẩm phải sau Ngày Hết Hạn Đăng Ký ít nhất 1 ngày.", "mileStones": "Giai Đoạn:", "pleaseSelectMileStone": "Lựa chọn các giai đoạn cho cuộc thi của bạn", + "allPhase": "All Phase", "prototype": "Prototype", "idea": "Ý Tưởng", "uiux": "UI/UX", + "exRegistrantsPhaseConfig": "All Phase", "ideaDeadline": "Thí Sinh Phải Đề Xuất Ý Tưởng Trước Ngày: *", "uIDeadline": "Thí Sinh Phải Nộp UI/UX Trước Ngày: *", "prototypeDeadline": "Thí Sinh Phải Nộp Prototype Trước Ngày: *", From bf3134f91cba2357d0e72e9b75f77b198d83b430 Mon Sep 17 00:00:00 2001 From: johnsonpham Date: Fri, 16 Oct 2015 14:39:33 +0700 Subject: [PATCH 08/80] update responsive for registrants filter on the challenge details page --- src/main/webapp/assets/sass/contest-detail.sass | 9 ++++++--- src/main/webapp/assets/sass/z-responsive-candidate.sass | 7 ++++++- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/main/webapp/assets/sass/contest-detail.sass b/src/main/webapp/assets/sass/contest-detail.sass index 0d1d9b2ae..8c1553667 100644 --- a/src/main/webapp/assets/sass/contest-detail.sass +++ b/src/main/webapp/assets/sass/contest-detail.sass @@ -244,11 +244,14 @@ width: 100% clear: both .registrants-query - width: 20% + width: 40% float: left - padding-right: 5px + .selectize-control + width: 48.6% + float: left + margin-right: 5px .registrants-date - width: 50% + width: 52% float: left .input-group width: 50% diff --git a/src/main/webapp/assets/sass/z-responsive-candidate.sass b/src/main/webapp/assets/sass/z-responsive-candidate.sass index 508046bab..6003c9700 100644 --- a/src/main/webapp/assets/sass/z-responsive-candidate.sass +++ b/src/main/webapp/assets/sass/z-responsive-candidate.sass @@ -1229,7 +1229,11 @@ clear: both .registrants-query width: 100% - padding: 0 0 7px 0 + padding: 0 + .selectize-control + width: 100% + clear: both + margin: 0 0 5px 0 .registrants-date width: 100% padding: 0 @@ -1251,6 +1255,7 @@ button margin: auto padding: 6px 30px + tr background-color: #fff .contest-content-item From 8195094f6c2feb54932379d0679c60e554154fd2 Mon Sep 17 00:00:00 2001 From: khoa-nd Date: Fri, 16 Oct 2015 16:23:21 +0700 Subject: [PATCH 09/80] Remove the email to employer about new registration --- .../service/impl/ChallengeServiceImpl.java | 1503 ++++++++--------- 1 file changed, 744 insertions(+), 759 deletions(-) diff --git a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java index ebf34f4ed..5e5eac1f3 100644 --- a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java @@ -64,276 +64,271 @@ @Service public class ChallengeServiceImpl implements ChallengeService { - private final static Logger LOGGER = LoggerFactory.getLogger(ChallengeServiceImpl.class); + private final static Logger LOGGER = LoggerFactory.getLogger(ChallengeServiceImpl.class); + + private final static ChallengePhaseEnum CHALLENGE_TIMELINE[] = { + ChallengePhaseEnum.FINAL, + ChallengePhaseEnum.PROTOTYPE, + ChallengePhaseEnum.UIUX, + ChallengePhaseEnum.IDEA, + ChallengePhaseEnum.REGISTRATION + }; - private final static ChallengePhaseEnum CHALLENGE_TIMELINE[] = { - ChallengePhaseEnum.FINAL, - ChallengePhaseEnum.PROTOTYPE, - ChallengePhaseEnum.UIUX, - ChallengePhaseEnum.IDEA, - ChallengePhaseEnum.REGISTRATION - }; + @Resource + private ElasticsearchTemplate elasticsearchTemplateUserImport; - @Resource - private ElasticsearchTemplate elasticsearchTemplateUserImport; + @Resource + private MimeMessage postChallengeMailMessage; - @Resource - private MimeMessage postChallengeMailMessage; + @Resource + private Template postChallengeMailTemplateEn; - @Resource - private Template postChallengeMailTemplateEn; + @Resource + private Template postChallengeUpdateMailTemplateEn; - @Resource - private Template postChallengeUpdateMailTemplateEn; + @Resource + private Template postChallengeMailTemplateVi; - @Resource - private Template postChallengeMailTemplateVi; + @Value("${mail.postChallenge.subject.vn}") + private String postChallengeMailSubjectVn; - @Value("${mail.postChallenge.subject.vn}") - private String postChallengeMailSubjectVn; + @Value("${mail.postChallenge.subject.en}") + private String postChallengeMailSubjectEn; - @Value("${mail.postChallenge.subject.en}") - private String postChallengeMailSubjectEn; + @Value("${mail.postChallenge.techloopies.mailSubject}") + private String postChallengeTechloopiesMailSubject; - @Value("${mail.postChallenge.techloopies.mailSubject}") - private String postChallengeTechloopiesMailSubject; + @Value("${mail.postChallenge.techloopies.updateMailSubject}") + private String postChallengeTechloopiesUpdateMailSubject; - @Value("${mail.postChallenge.techloopies.updateMailSubject}") - private String postChallengeTechloopiesUpdateMailSubject; + @Value("${mail.postChallenge.techloopies.mailList}") + private String postChallengeTechloopiesMailList; - @Value("${mail.postChallenge.techloopies.mailList}") - private String postChallengeTechloopiesMailList; + @Value("${web.baseUrl}") + private String webBaseUrl; - @Value("${web.baseUrl}") - private String webBaseUrl; + @Resource + private Template confirmUserJoinChallengeMailTemplateEn; - @Resource - private Template confirmUserJoinChallengeMailTemplateEn; + @Resource + private Template confirmUserJoinChallengeMailTemplateVi; - @Resource - private Template confirmUserJoinChallengeMailTemplateVi; + @Value("${mail.confirmUserJoinChallenge.subject.vn}") + private String confirmUserJoinChallengeMailSubjectVn; - @Value("${mail.confirmUserJoinChallenge.subject.vn}") - private String confirmUserJoinChallengeMailSubjectVn; + @Value("${mail.confirmUserJoinChallenge.subject.en}") + private String confirmUserJoinChallengeMailSubjectEn; - @Value("${mail.confirmUserJoinChallenge.subject.en}") - private String confirmUserJoinChallengeMailSubjectEn; + @Resource + private Template alertEmployerChallengeMailTemplateEn; - @Resource - private Template alertEmployerChallengeMailTemplateEn; + @Resource + private Template alertEmployerChallengeMailTemplateVi; - @Resource - private Template alertEmployerChallengeMailTemplateVi; + @Value("${mail.alertEmployerChallenge.subject.vn}") + private String alertEmployerChallengeMailSubjectVn; - @Value("${mail.alertEmployerChallenge.subject.vn}") - private String alertEmployerChallengeMailSubjectVn; + @Value("${mail.alertEmployerChallenge.subject.en}") + private String alertEmployerChallengeMailSubjectEn; - @Value("${mail.alertEmployerChallenge.subject.en}") - private String alertEmployerChallengeMailSubjectEn; + @Value("${mail.techlooper.reply_to}") + private String mailTechlooperReplyTo; - @Value("${mail.techlooper.reply_to}") - private String mailTechlooperReplyTo; + @Resource + private JavaMailSender mailSender; - @Resource - private JavaMailSender mailSender; + @Resource + private ChallengeRepository challengeRepository; - @Resource - private ChallengeRepository challengeRepository; + @Resource + private ChallengeRegistrantRepository challengeRegistrantRepository; - @Resource - private ChallengeRegistrantRepository challengeRegistrantRepository; + @Resource + private ChallengeSubmissionRepository challengeSubmissionRepository; - @Resource - private ChallengeSubmissionRepository challengeSubmissionRepository; + @Resource + private Mapper dozerMapper; - @Resource - private Mapper dozerMapper; + @Value("${elasticsearch.userimport.index.name}") + private String techlooperIndex; - @Value("${elasticsearch.userimport.index.name}") - private String techlooperIndex; + @Value("${mail.notifyChallengeTimelineRegistration.subject.vn}") + private String notifyChallengeTimelineRegistrationMailSubjectVn; - @Value("${mail.notifyChallengeTimelineRegistration.subject.vn}") - private String notifyChallengeTimelineRegistrationMailSubjectVn; + @Value("${mail.notifyChallengeTimelineRegistration.subject.en}") + private String notifyChallengeTimelineRegistrationMailSubjectEn; - @Value("${mail.notifyChallengeTimelineRegistration.subject.en}") - private String notifyChallengeTimelineRegistrationMailSubjectEn; + @Value("${mail.notifyChallengeTimelineInProgress.subject.vn}") + private String notifyChallengeTimelineInProgressMailSubjectVn; - @Value("${mail.notifyChallengeTimelineInProgress.subject.vn}") - private String notifyChallengeTimelineInProgressMailSubjectVn; + @Value("${mail.notifyChallengeTimelineInProgress.subject.en}") + private String notifyChallengeTimelineInProgressMailSubjectEn; - @Value("${mail.notifyChallengeTimelineInProgress.subject.en}") - private String notifyChallengeTimelineInProgressMailSubjectEn; + @Value("${mail.dailyChallengeSummary.subject.en}") + private String dailyChallengeSummaryMailSubjectEn; - @Value("${mail.dailyChallengeSummary.subject.en}") - private String dailyChallengeSummaryMailSubjectEn; + @Value("${mail.dailyChallengeSummary.subject.vi}") + private String dailyChallengeSummaryMailSubjectVi; - @Value("${mail.dailyChallengeSummary.subject.vi}") - private String dailyChallengeSummaryMailSubjectVi; + @Resource + private Template notifyChallengeTimelineMailTemplateVi; - @Resource - private Template notifyChallengeTimelineMailTemplateVi; + @Resource + private Template notifyChallengeTimelineMailTemplateEn; - @Resource - private Template notifyChallengeTimelineMailTemplateEn; + @Resource + private Template dailyChallengeSummaryMailTemplateVi; - @Resource - private Template dailyChallengeSummaryMailTemplateVi; + @Resource + private Template dailyChallengeSummaryMailTemplateEn; - @Resource - private Template dailyChallengeSummaryMailTemplateEn; + @Resource + private EmailService emailService; - @Resource - private EmailService emailService; + public ChallengeEntity savePostChallenge(ChallengeDto challengeDto) throws Exception { + ChallengeEntity challengeEntity = dozerMapper.map(challengeDto, ChallengeEntity.class); + if (challengeDto.getChallengeId() == null) { + challengeEntity.setChallengeId(new Date().getTime()); + } + return challengeRepository.save(challengeEntity); + } - public ChallengeEntity savePostChallenge(ChallengeDto challengeDto) throws Exception { - ChallengeEntity challengeEntity = dozerMapper.map(challengeDto, ChallengeEntity.class); - if (challengeDto.getChallengeId() == null) { - challengeEntity.setChallengeId(new Date().getTime()); + public void sendPostChallengeEmailToEmployer(ChallengeEntity challengeEntity) + throws MessagingException, IOException, TemplateException { + String mailSubject = challengeEntity.getLang() == Language.vi ? postChallengeMailSubjectVn : postChallengeMailSubjectEn; + Address[] recipientAddresses = getRecipientAddresses(challengeEntity, true); + Template template = challengeEntity.getLang() == Language.vi ? postChallengeMailTemplateVi : postChallengeMailTemplateEn; + sendPostChallengeEmail(challengeEntity, mailSubject, recipientAddresses, template); } - return challengeRepository.save(challengeEntity); - } - - public void sendPostChallengeEmailToEmployer(ChallengeEntity challengeEntity) - throws MessagingException, IOException, TemplateException { - String mailSubject = challengeEntity.getLang() == Language.vi ? postChallengeMailSubjectVn : postChallengeMailSubjectEn; - Address[] recipientAddresses = getRecipientAddresses(challengeEntity, true); - Template template = challengeEntity.getLang() == Language.vi ? postChallengeMailTemplateVi : postChallengeMailTemplateEn; - sendPostChallengeEmail(challengeEntity, mailSubject, recipientAddresses, template); - } - - public void sendPostChallengeEmailToTechloopies(ChallengeEntity challengeEntity, Boolean isNewChallenge) - throws MessagingException, IOException, TemplateException { - String mailSubject = isNewChallenge ? postChallengeTechloopiesMailSubject : - String.format(postChallengeTechloopiesUpdateMailSubject, challengeEntity.getChallengeName()); - Template mailTemplate = isNewChallenge ? postChallengeMailTemplateEn : postChallengeUpdateMailTemplateEn; - Address[] recipientAddresses = InternetAddress.parse(postChallengeTechloopiesMailList); - sendPostChallengeEmail(challengeEntity, mailSubject, recipientAddresses, mailTemplate); - } - - @Override - public void sendEmailNotifyRegistrantAboutChallengeTimeline(ChallengeEntity challengeEntity, - ChallengeRegistrantEntity challengeRegistrantEntity, ChallengePhaseEnum challengePhase) throws Exception { - String mailSubject = getNotifyRegistrantChallengeTimelineSubject(challengeRegistrantEntity, challengePhase); - Address[] recipientAddresses = InternetAddress.parse(challengeRegistrantEntity.getRegistrantEmail()); - Template template = challengeRegistrantEntity.getLang() == Language.vi ? - notifyChallengeTimelineMailTemplateVi : notifyChallengeTimelineMailTemplateEn; - postChallengeMailMessage.setRecipients(Message.RecipientType.TO, recipientAddresses); - postChallengeMailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); - StringWriter stringWriter = new StringWriter(); - - Map templateModel = new HashMap<>(); - templateModel.put("challengeEntity", challengeEntity); - templateModel.put("webBaseUrl", webBaseUrl); - templateModel.put("technologies", StringUtils.join(challengeEntity.getTechnologies(), "
")); - templateModel.put("receivedEmails", StringUtils.join(challengeEntity.getReceivedEmails(), "
")); - templateModel.put("firstPlaceReward", challengeEntity.getFirstPlaceReward() != null ? challengeEntity.getFirstPlaceReward() : 0); - templateModel.put("secondPlaceReward", challengeEntity.getSecondPlaceReward() != null ? challengeEntity.getSecondPlaceReward() : 0); - templateModel.put("thirdPlaceReward", challengeEntity.getThirdPlaceReward() != null ? challengeEntity.getThirdPlaceReward() : 0); - templateModel.put("challengeId", challengeEntity.getChallengeId().toString()); - templateModel.put("challengeNameAlias", challengeEntity.getChallengeName().replaceAll("\\W", "-")); - - int numberOfDays = 0; - if (challengePhase == ChallengePhaseEnum.REGISTRATION) { - numberOfDays = daysBetween(currentDate(), challengeEntity.getRegistrationDateTime()) + 1; + + public void sendPostChallengeEmailToTechloopies(ChallengeEntity challengeEntity, Boolean isNewChallenge) + throws MessagingException, IOException, TemplateException { + String mailSubject = isNewChallenge ? postChallengeTechloopiesMailSubject : + String.format(postChallengeTechloopiesUpdateMailSubject, challengeEntity.getChallengeName()); + Template mailTemplate = isNewChallenge ? postChallengeMailTemplateEn : postChallengeUpdateMailTemplateEn; + Address[] recipientAddresses = InternetAddress.parse(postChallengeTechloopiesMailList); + sendPostChallengeEmail(challengeEntity, mailSubject, recipientAddresses, mailTemplate); } - else if (challengePhase == ChallengePhaseEnum.IN_PROGRESS) { - numberOfDays = daysBetween(currentDate(), challengeEntity.getSubmissionDateTime()) + 1; + + @Override + public void sendEmailNotifyRegistrantAboutChallengeTimeline(ChallengeEntity challengeEntity, + ChallengeRegistrantEntity challengeRegistrantEntity, ChallengePhaseEnum challengePhase) throws Exception { + String mailSubject = getNotifyRegistrantChallengeTimelineSubject(challengeRegistrantEntity, challengePhase); + Address[] recipientAddresses = InternetAddress.parse(challengeRegistrantEntity.getRegistrantEmail()); + Template template = challengeRegistrantEntity.getLang() == Language.vi ? + notifyChallengeTimelineMailTemplateVi : notifyChallengeTimelineMailTemplateEn; + postChallengeMailMessage.setRecipients(Message.RecipientType.TO, recipientAddresses); + postChallengeMailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); + StringWriter stringWriter = new StringWriter(); + + Map templateModel = new HashMap<>(); + templateModel.put("challengeEntity", challengeEntity); + templateModel.put("webBaseUrl", webBaseUrl); + templateModel.put("technologies", StringUtils.join(challengeEntity.getTechnologies(), "
")); + templateModel.put("receivedEmails", StringUtils.join(challengeEntity.getReceivedEmails(), "
")); + templateModel.put("firstPlaceReward", challengeEntity.getFirstPlaceReward() != null ? challengeEntity.getFirstPlaceReward() : 0); + templateModel.put("secondPlaceReward", challengeEntity.getSecondPlaceReward() != null ? challengeEntity.getSecondPlaceReward() : 0); + templateModel.put("thirdPlaceReward", challengeEntity.getThirdPlaceReward() != null ? challengeEntity.getThirdPlaceReward() : 0); + templateModel.put("challengeId", challengeEntity.getChallengeId().toString()); + templateModel.put("challengeNameAlias", challengeEntity.getChallengeName().replaceAll("\\W", "-")); + + int numberOfDays = 0; + if (challengePhase == ChallengePhaseEnum.REGISTRATION) { + numberOfDays = daysBetween(currentDate(), challengeEntity.getRegistrationDateTime()) + 1; + } else if (challengePhase == ChallengePhaseEnum.IN_PROGRESS) { + numberOfDays = daysBetween(currentDate(), challengeEntity.getSubmissionDateTime()) + 1; + } + + templateModel.put("numberOfDays", numberOfDays); + templateModel.put("challengePhase", challengePhase.getValue()); + templateModel.put("challengeRegistrant", challengeRegistrantEntity); + + template.process(templateModel, stringWriter); + mailSubject = String.format(mailSubject, numberOfDays, challengeEntity.getChallengeName()); + postChallengeMailMessage.setSubject(MimeUtility.encodeText(mailSubject, "UTF-8", null)); + postChallengeMailMessage.setText(stringWriter.toString(), "UTF-8", "html"); + + stringWriter.flush(); + postChallengeMailMessage.saveChanges(); + mailSender.send(postChallengeMailMessage); + LOGGER.info(postChallengeMailMessage.getMessageID() + " has been sent to users " + + postChallengeMailMessage.getAllRecipients() + " with challengeId = " + challengeEntity.getChallengeId()); + } + + private String getNotifyRegistrantChallengeTimelineSubject( + ChallengeRegistrantEntity challengeRegistrantEntity, ChallengePhaseEnum challengePhase) { + if (challengeRegistrantEntity.getLang() == Language.vi) { + if (challengePhase == ChallengePhaseEnum.REGISTRATION) { + return notifyChallengeTimelineRegistrationMailSubjectVn; + } else { + return notifyChallengeTimelineInProgressMailSubjectVn; + } + } else { + if (challengePhase == ChallengePhaseEnum.REGISTRATION) { + return notifyChallengeTimelineRegistrationMailSubjectEn; + } else { + return notifyChallengeTimelineInProgressMailSubjectEn; + } + } } - templateModel.put("numberOfDays", numberOfDays); - templateModel.put("challengePhase", challengePhase.getValue()); - templateModel.put("challengeRegistrant", challengeRegistrantEntity); - - template.process(templateModel, stringWriter); - mailSubject = String.format(mailSubject, numberOfDays, challengeEntity.getChallengeName()); - postChallengeMailMessage.setSubject(MimeUtility.encodeText(mailSubject, "UTF-8", null)); - postChallengeMailMessage.setText(stringWriter.toString(), "UTF-8", "html"); - - stringWriter.flush(); - postChallengeMailMessage.saveChanges(); - mailSender.send(postChallengeMailMessage); - LOGGER.info(postChallengeMailMessage.getMessageID() + " has been sent to users " + - postChallengeMailMessage.getAllRecipients() + " with challengeId = " + challengeEntity.getChallengeId()); - } - - private String getNotifyRegistrantChallengeTimelineSubject( - ChallengeRegistrantEntity challengeRegistrantEntity, ChallengePhaseEnum challengePhase) { - if (challengeRegistrantEntity.getLang() == Language.vi) { - if (challengePhase == ChallengePhaseEnum.REGISTRATION) { - return notifyChallengeTimelineRegistrationMailSubjectVn; - } - else { - return notifyChallengeTimelineInProgressMailSubjectVn; - } + public Long getNumberOfRegistrants(Long challengeId) { + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withSearchType(SearchType.COUNT); + searchQueryBuilder.withFilter(FilterBuilders.termFilter("challengeId", challengeId)); + return challengeRegistrantRepository.search(searchQueryBuilder.build()).getTotalElements(); } - else { - if (challengePhase == ChallengePhaseEnum.REGISTRATION) { - return notifyChallengeTimelineRegistrationMailSubjectEn; - } - else { - return notifyChallengeTimelineInProgressMailSubjectEn; - } + + public void sendApplicationEmailToContestant(ChallengeEntity challengeEntity, ChallengeRegistrantEntity challengeRegistrantEntity) throws MessagingException, IOException, TemplateException { + Template template = challengeRegistrantEntity.getLang() == Language.vi ? + confirmUserJoinChallengeMailTemplateVi : confirmUserJoinChallengeMailTemplateEn; + String mailSubject = challengeRegistrantEntity.getLang() == Language.vi ? + confirmUserJoinChallengeMailSubjectVn : confirmUserJoinChallengeMailSubjectEn; + mailSubject = String.format(mailSubject, challengeEntity.getChallengeName()); + Address[] emailAddress = InternetAddress.parse(challengeRegistrantEntity.getRegistrantEmail()); + sendContestApplicationEmail(template, mailSubject, emailAddress, challengeEntity, challengeRegistrantEntity, false); } - } - - public Long getNumberOfRegistrants(Long challengeId) { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withSearchType(SearchType.COUNT); - searchQueryBuilder.withFilter(FilterBuilders.termFilter("challengeId", challengeId)); - return challengeRegistrantRepository.search(searchQueryBuilder.build()).getTotalElements(); - } - - public void sendApplicationEmailToContestant(ChallengeEntity challengeEntity, ChallengeRegistrantEntity challengeRegistrantEntity) throws MessagingException, IOException, TemplateException { - Template template = challengeRegistrantEntity.getLang() == Language.vi ? - confirmUserJoinChallengeMailTemplateVi : confirmUserJoinChallengeMailTemplateEn; - String mailSubject = challengeRegistrantEntity.getLang() == Language.vi ? - confirmUserJoinChallengeMailSubjectVn : confirmUserJoinChallengeMailSubjectEn; - mailSubject = String.format(mailSubject, challengeEntity.getChallengeName()); - Address[] emailAddress = InternetAddress.parse(challengeRegistrantEntity.getRegistrantEmail()); - sendContestApplicationEmail(template, mailSubject, emailAddress, challengeEntity, challengeRegistrantEntity, false); - } - - public void sendApplicationEmailToEmployer(ChallengeEntity challengeEntity, ChallengeRegistrantEntity challengeRegistrantEntity) throws MessagingException, IOException, TemplateException { - Template template = challengeRegistrantEntity.getLang() == Language.vi ? - alertEmployerChallengeMailTemplateVi : alertEmployerChallengeMailTemplateEn; - String mailSubject = challengeRegistrantEntity.getLang() == Language.vi ? - alertEmployerChallengeMailSubjectVn : alertEmployerChallengeMailSubjectEn; - mailSubject = String.format(mailSubject, challengeEntity.getChallengeName()); - Address[] emailAddress = getRecipientAddresses(challengeEntity, false); - sendContestApplicationEmail(template, mailSubject, emailAddress, challengeEntity, challengeRegistrantEntity, true); - } - - public long joinChallenge(ChallengeRegistrantDto challengeRegistrantDto) { - ChallengeRegistrantEntity entity = joinChallengeEntity(challengeRegistrantDto); - if (entity != null) { - return getNumberOfRegistrants(challengeRegistrantDto.getChallengeId()); + + public void sendApplicationEmailToEmployer(ChallengeEntity challengeEntity, ChallengeRegistrantEntity challengeRegistrantEntity) throws MessagingException, IOException, TemplateException { + Template template = challengeRegistrantEntity.getLang() == Language.vi ? + alertEmployerChallengeMailTemplateVi : alertEmployerChallengeMailTemplateEn; + String mailSubject = challengeRegistrantEntity.getLang() == Language.vi ? + alertEmployerChallengeMailSubjectVn : alertEmployerChallengeMailSubjectEn; + mailSubject = String.format(mailSubject, challengeEntity.getChallengeName()); + Address[] emailAddress = getRecipientAddresses(challengeEntity, false); + sendContestApplicationEmail(template, mailSubject, emailAddress, challengeEntity, challengeRegistrantEntity, true); } - return 0; - } - - public ChallengeRegistrantEntity joinChallengeEntity(ChallengeRegistrantDto challengeRegistrantDto) { - Long challengeId = challengeRegistrantDto.getChallengeId(); - boolean isExist = checkIfChallengeRegistrantExist(challengeId, challengeRegistrantDto.getRegistrantEmail()); - - if (!isExist) { - ChallengeRegistrantEntity challengeRegistrantEntity = dozerMapper.map(challengeRegistrantDto, ChallengeRegistrantEntity.class); - ChallengeEntity challengeEntity = challengeRepository.findOne(challengeId); - challengeRegistrantEntity.setRegistrantId(new Date().getTime()); - challengeRegistrantEntity = challengeRegistrantRepository.save(challengeRegistrantEntity); - try { - sendApplicationEmailToContestant(challengeEntity, challengeRegistrantEntity); - sendApplicationEmailToEmployer(challengeEntity, challengeRegistrantEntity); - challengeRegistrantEntity.setMailSent(Boolean.TRUE); - return challengeRegistrantRepository.save(challengeRegistrantEntity); - } - catch (Exception e) { - LOGGER.debug("Can not send email", e); - } + + public long joinChallenge(ChallengeRegistrantDto challengeRegistrantDto) { + ChallengeRegistrantEntity entity = joinChallengeEntity(challengeRegistrantDto); + if (entity != null) { + return getNumberOfRegistrants(challengeRegistrantDto.getChallengeId()); + } + return 0; } - return null; - } + public ChallengeRegistrantEntity joinChallengeEntity(ChallengeRegistrantDto challengeRegistrantDto) { + Long challengeId = challengeRegistrantDto.getChallengeId(); + boolean isExist = checkIfChallengeRegistrantExist(challengeId, challengeRegistrantDto.getRegistrantEmail()); + + if (!isExist) { + ChallengeRegistrantEntity challengeRegistrantEntity = dozerMapper.map(challengeRegistrantDto, ChallengeRegistrantEntity.class); + ChallengeEntity challengeEntity = challengeRepository.findOne(challengeId); + challengeRegistrantEntity.setRegistrantId(new Date().getTime()); + challengeRegistrantEntity = challengeRegistrantRepository.save(challengeRegistrantEntity); + try { + sendApplicationEmailToContestant(challengeEntity, challengeRegistrantEntity); + //sendApplicationEmailToEmployer(challengeEntity, challengeRegistrantEntity); + challengeRegistrantEntity.setMailSent(Boolean.TRUE); + return challengeRegistrantRepository.save(challengeRegistrantEntity); + } catch (Exception e) { + LOGGER.debug("Can not send email", e); + } + } + + return null; + } - public List listChallenges() { + public List listChallenges() { // List challenges = new ArrayList<>(); // Iterator challengeIter = challengeRepository.findAll().iterator(); // while (challengeIter.hasNext()) { @@ -343,173 +338,168 @@ public List listChallenges() { // challenges.add(challengeDetailDto); // } // return sortChallengesByDescendingStartDate(challenges); - TermQueryBuilder notExpiredQuery = termQuery("expired", Boolean.TRUE); - Iterable challengeIterator = challengeRepository.search(boolQuery().mustNot(notExpiredQuery)); - ArrayList challenges = new ArrayList<>(); - challengeIterator.forEach(challengeEntity -> { - ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); - challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeEntity.getChallengeId())); - challenges.add(challengeDetailDto); - }); - return sortChallengesByDescendingStartDate(challenges); - } - - private void sendContestApplicationEmail(Template template, String mailSubject, Address[] recipientAddresses, - ChallengeEntity challengeEntity, ChallengeRegistrantEntity challengeRegistrantEntity, boolean hasReplyTo) - throws MessagingException, IOException, TemplateException { - postChallengeMailMessage.setRecipients(Message.RecipientType.TO, recipientAddresses); - - if (hasReplyTo) { - postChallengeMailMessage.setReplyTo(InternetAddress.parse(challengeRegistrantEntity.getRegistrantEmail())); + TermQueryBuilder notExpiredQuery = termQuery("expired", Boolean.TRUE); + Iterable challengeIterator = challengeRepository.search(boolQuery().mustNot(notExpiredQuery)); + ArrayList challenges = new ArrayList<>(); + challengeIterator.forEach(challengeEntity -> { + ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); + challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeEntity.getChallengeId())); + challenges.add(challengeDetailDto); + }); + return sortChallengesByDescendingStartDate(challenges); } - else { - postChallengeMailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); + + private void sendContestApplicationEmail(Template template, String mailSubject, Address[] recipientAddresses, + ChallengeEntity challengeEntity, ChallengeRegistrantEntity challengeRegistrantEntity, boolean hasReplyTo) + throws MessagingException, IOException, TemplateException { + postChallengeMailMessage.setRecipients(Message.RecipientType.TO, recipientAddresses); + + if (hasReplyTo) { + postChallengeMailMessage.setReplyTo(InternetAddress.parse(challengeRegistrantEntity.getRegistrantEmail())); + } else { + postChallengeMailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); + } + + StringWriter stringWriter = new StringWriter(); + Map templateModel = new HashMap<>(); + templateModel.put("webBaseUrl", webBaseUrl); + templateModel.put("challengeName", challengeEntity.getChallengeName()); + templateModel.put("businessRequirement", challengeEntity.getBusinessRequirement()); + templateModel.put("generalNote", challengeEntity.getGeneralNote()); + templateModel.put("technologies", StringUtils.join(challengeEntity.getTechnologies(), "
")); + templateModel.put("documents", challengeEntity.getDocuments()); + templateModel.put("deliverables", challengeEntity.getDeliverables()); + templateModel.put("receivedEmails", StringUtils.join(challengeEntity.getReceivedEmails(), "
")); + templateModel.put("reviewStyle", challengeEntity.getReviewStyle()); + templateModel.put("startDate", challengeEntity.getStartDateTime()); + templateModel.put("registrationDate", challengeEntity.getRegistrationDateTime()); + templateModel.put("submissionDate", challengeEntity.getSubmissionDateTime()); + templateModel.put("qualityIdea", challengeEntity.getQualityIdea()); + templateModel.put("firstPlaceReward", challengeEntity.getFirstPlaceReward() != null ? challengeEntity.getFirstPlaceReward() : 0); + templateModel.put("secondPlaceReward", challengeEntity.getSecondPlaceReward() != null ? challengeEntity.getSecondPlaceReward() : 0); + templateModel.put("thirdPlaceReward", challengeEntity.getThirdPlaceReward() != null ? challengeEntity.getThirdPlaceReward() : 0); + templateModel.put("challengeId", challengeEntity.getChallengeId().toString()); + templateModel.put("authorEmail", challengeEntity.getAuthorEmail()); + templateModel.put("challengeOverview", challengeEntity.getChallengeOverview()); + templateModel.put("firstName", challengeRegistrantEntity.getRegistrantFirstName()); + templateModel.put("lastName", challengeRegistrantEntity.getRegistrantLastName()); + templateModel.put("registrantEmail", challengeRegistrantEntity.getRegistrantEmail()); + templateModel.put("challengeNameAlias", challengeEntity.getChallengeName().replaceAll("\\W", "-")); + + template.process(templateModel, stringWriter); + postChallengeMailMessage.setSubject(MimeUtility.encodeText(mailSubject, "UTF-8", null)); + postChallengeMailMessage.setText(stringWriter.toString(), "UTF-8", "html"); + + stringWriter.flush(); + postChallengeMailMessage.saveChanges(); + mailSender.send(postChallengeMailMessage); } - StringWriter stringWriter = new StringWriter(); - Map templateModel = new HashMap<>(); - templateModel.put("webBaseUrl", webBaseUrl); - templateModel.put("challengeName", challengeEntity.getChallengeName()); - templateModel.put("businessRequirement", challengeEntity.getBusinessRequirement()); - templateModel.put("generalNote", challengeEntity.getGeneralNote()); - templateModel.put("technologies", StringUtils.join(challengeEntity.getTechnologies(), "
")); - templateModel.put("documents", challengeEntity.getDocuments()); - templateModel.put("deliverables", challengeEntity.getDeliverables()); - templateModel.put("receivedEmails", StringUtils.join(challengeEntity.getReceivedEmails(), "
")); - templateModel.put("reviewStyle", challengeEntity.getReviewStyle()); - templateModel.put("startDate", challengeEntity.getStartDateTime()); - templateModel.put("registrationDate", challengeEntity.getRegistrationDateTime()); - templateModel.put("submissionDate", challengeEntity.getSubmissionDateTime()); - templateModel.put("qualityIdea", challengeEntity.getQualityIdea()); - templateModel.put("firstPlaceReward", challengeEntity.getFirstPlaceReward() != null ? challengeEntity.getFirstPlaceReward() : 0); - templateModel.put("secondPlaceReward", challengeEntity.getSecondPlaceReward() != null ? challengeEntity.getSecondPlaceReward() : 0); - templateModel.put("thirdPlaceReward", challengeEntity.getThirdPlaceReward() != null ? challengeEntity.getThirdPlaceReward() : 0); - templateModel.put("challengeId", challengeEntity.getChallengeId().toString()); - templateModel.put("authorEmail", challengeEntity.getAuthorEmail()); - templateModel.put("challengeOverview", challengeEntity.getChallengeOverview()); - templateModel.put("firstName", challengeRegistrantEntity.getRegistrantFirstName()); - templateModel.put("lastName", challengeRegistrantEntity.getRegistrantLastName()); - templateModel.put("registrantEmail", challengeRegistrantEntity.getRegistrantEmail()); - templateModel.put("challengeNameAlias", challengeEntity.getChallengeName().replaceAll("\\W", "-")); - - template.process(templateModel, stringWriter); - postChallengeMailMessage.setSubject(MimeUtility.encodeText(mailSubject, "UTF-8", null)); - postChallengeMailMessage.setText(stringWriter.toString(), "UTF-8", "html"); - - stringWriter.flush(); - postChallengeMailMessage.saveChanges(); - mailSender.send(postChallengeMailMessage); - } - - private void sendPostChallengeEmail(ChallengeEntity challengeEntity, String mailSubject, - Address[] recipientAddresses, Template template) throws MessagingException, IOException, TemplateException { - postChallengeMailMessage.setRecipients(Message.RecipientType.TO, recipientAddresses); - postChallengeMailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); - StringWriter stringWriter = new StringWriter(); - - Map templateModel = new HashMap<>(); - templateModel.put("webBaseUrl", webBaseUrl); - templateModel.put("challengeName", challengeEntity.getChallengeName()); - templateModel.put("businessRequirement", challengeEntity.getBusinessRequirement()); - templateModel.put("generalNote", challengeEntity.getGeneralNote()); - templateModel.put("technologies", StringUtils.join(challengeEntity.getTechnologies(), "
")); - templateModel.put("documents", challengeEntity.getDocuments()); - templateModel.put("deliverables", challengeEntity.getDeliverables()); - templateModel.put("receivedEmails", StringUtils.join(challengeEntity.getReceivedEmails(), "
")); - templateModel.put("reviewStyle", challengeEntity.getReviewStyle()); - templateModel.put("startDate", challengeEntity.getStartDateTime()); - templateModel.put("registrationDate", challengeEntity.getRegistrationDateTime()); - templateModel.put("submissionDate", challengeEntity.getSubmissionDateTime()); - templateModel.put("qualityIdea", challengeEntity.getQualityIdea()); - templateModel.put("firstPlaceReward", challengeEntity.getFirstPlaceReward() != null ? challengeEntity.getFirstPlaceReward() : 0); - templateModel.put("secondPlaceReward", challengeEntity.getSecondPlaceReward() != null ? challengeEntity.getSecondPlaceReward() : 0); - templateModel.put("thirdPlaceReward", challengeEntity.getThirdPlaceReward() != null ? challengeEntity.getThirdPlaceReward() : 0); - templateModel.put("challengeId", challengeEntity.getChallengeId().toString()); - templateModel.put("authorEmail", challengeEntity.getAuthorEmail()); - templateModel.put("challengeOverview", challengeEntity.getChallengeOverview()); - templateModel.put("challengeNameAlias", challengeEntity.getChallengeName().replaceAll("\\W", "-")); - - template.process(templateModel, stringWriter); - mailSubject = String.format(mailSubject, challengeEntity.getAuthorEmail(), challengeEntity.getChallengeName()); - postChallengeMailMessage.setSubject(MimeUtility.encodeText(mailSubject, "UTF-8", null)); - postChallengeMailMessage.setText(stringWriter.toString(), "UTF-8", "html"); - - stringWriter.flush(); - postChallengeMailMessage.saveChanges(); - mailSender.send(postChallengeMailMessage); - } - - private Address[] getRecipientAddresses(ChallengeEntity challengeEntity, boolean includeAuthor) throws AddressException { - Set emails = new HashSet<>(challengeEntity.getReceivedEmails()); - if (includeAuthor) { - emails.add(challengeEntity.getAuthorEmail()); + private void sendPostChallengeEmail(ChallengeEntity challengeEntity, String mailSubject, + Address[] recipientAddresses, Template template) throws MessagingException, IOException, TemplateException { + postChallengeMailMessage.setRecipients(Message.RecipientType.TO, recipientAddresses); + postChallengeMailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); + StringWriter stringWriter = new StringWriter(); + + Map templateModel = new HashMap<>(); + templateModel.put("webBaseUrl", webBaseUrl); + templateModel.put("challengeName", challengeEntity.getChallengeName()); + templateModel.put("businessRequirement", challengeEntity.getBusinessRequirement()); + templateModel.put("generalNote", challengeEntity.getGeneralNote()); + templateModel.put("technologies", StringUtils.join(challengeEntity.getTechnologies(), "
")); + templateModel.put("documents", challengeEntity.getDocuments()); + templateModel.put("deliverables", challengeEntity.getDeliverables()); + templateModel.put("receivedEmails", StringUtils.join(challengeEntity.getReceivedEmails(), "
")); + templateModel.put("reviewStyle", challengeEntity.getReviewStyle()); + templateModel.put("startDate", challengeEntity.getStartDateTime()); + templateModel.put("registrationDate", challengeEntity.getRegistrationDateTime()); + templateModel.put("submissionDate", challengeEntity.getSubmissionDateTime()); + templateModel.put("qualityIdea", challengeEntity.getQualityIdea()); + templateModel.put("firstPlaceReward", challengeEntity.getFirstPlaceReward() != null ? challengeEntity.getFirstPlaceReward() : 0); + templateModel.put("secondPlaceReward", challengeEntity.getSecondPlaceReward() != null ? challengeEntity.getSecondPlaceReward() : 0); + templateModel.put("thirdPlaceReward", challengeEntity.getThirdPlaceReward() != null ? challengeEntity.getThirdPlaceReward() : 0); + templateModel.put("challengeId", challengeEntity.getChallengeId().toString()); + templateModel.put("authorEmail", challengeEntity.getAuthorEmail()); + templateModel.put("challengeOverview", challengeEntity.getChallengeOverview()); + templateModel.put("challengeNameAlias", challengeEntity.getChallengeName().replaceAll("\\W", "-")); + + template.process(templateModel, stringWriter); + mailSubject = String.format(mailSubject, challengeEntity.getAuthorEmail(), challengeEntity.getChallengeName()); + postChallengeMailMessage.setSubject(MimeUtility.encodeText(mailSubject, "UTF-8", null)); + postChallengeMailMessage.setText(stringWriter.toString(), "UTF-8", "html"); + + stringWriter.flush(); + postChallengeMailMessage.saveChanges(); + mailSender.send(postChallengeMailMessage); } - return InternetAddress.parse(StringUtils.join(emails, ',')); - } - - private List sortChallengesByDescendingStartDate(List challenges) { - SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); - return challenges.stream().sorted((challenge1, challenge2) -> { - try { - if (challenge2.getStartDateTime() == null) { - return -1; - } - else if (challenge1.getStartDateTime() == null) { - return 1; - } - long challenge2StartDate = sdf.parse(challenge2.getStartDateTime()).getTime(); - long challenge1StartDate = sdf.parse(challenge1.getStartDateTime()).getTime(); - if (challenge2StartDate - challenge1StartDate > 0) { - return 1; - } - else if (challenge2StartDate - challenge1StartDate < 0) { - return -1; - } - else { - return 0; + + private Address[] getRecipientAddresses(ChallengeEntity challengeEntity, boolean includeAuthor) throws AddressException { + Set emails = new HashSet<>(challengeEntity.getReceivedEmails()); + if (includeAuthor) { + emails.add(challengeEntity.getAuthorEmail()); } - } - catch (ParseException e) { - return 0; - } - }).collect(toList()); - } - - public boolean checkIfChallengeRegistrantExist(Long challengeId, String email) { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder(); - searchQueryBuilder.withQuery(boolQuery() - .must(matchPhraseQuery("registrantEmail", email)) - .must(termQuery("challengeId", challengeId))); - - long total = challengeRegistrantRepository.search(searchQueryBuilder.build()).getTotalElements(); - return (total > 0); - } - - @Override - public Long getTotalNumberOfChallenges() { - return challengeRepository.count(); - } - - @Override - public Double getTotalAmountOfPrizeValues() { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withSearchType(SearchType.COUNT); - searchQueryBuilder.withQuery(matchAllQuery()); - - SumBuilder sumPrizeBuilder = sum("sumPrize").script("doc['firstPlaceReward'].value + doc['secondPlaceReward'].value + doc['thirdPlaceReward'].value"); - searchQueryBuilder.addAggregation(sumPrizeBuilder); - - Aggregations aggregations = elasticsearchTemplateUserImport.query(searchQueryBuilder.build(), SearchResponse::getAggregations); - Sum sumReponse = aggregations.get("sumPrize"); - return sumReponse != null ? sumReponse.getValue() : 0D; - } - - @Override - public Long getTotalNumberOfRegistrants() { - return challengeRegistrantRepository.count(); - } - - @Override - public ChallengeDetailDto getTheLatestChallenge() { + return InternetAddress.parse(StringUtils.join(emails, ',')); + } + + private List sortChallengesByDescendingStartDate(List challenges) { + SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); + return challenges.stream().sorted((challenge1, challenge2) -> { + try { + if (challenge2.getStartDateTime() == null) { + return -1; + } else if (challenge1.getStartDateTime() == null) { + return 1; + } + long challenge2StartDate = sdf.parse(challenge2.getStartDateTime()).getTime(); + long challenge1StartDate = sdf.parse(challenge1.getStartDateTime()).getTime(); + if (challenge2StartDate - challenge1StartDate > 0) { + return 1; + } else if (challenge2StartDate - challenge1StartDate < 0) { + return -1; + } else { + return 0; + } + } catch (ParseException e) { + return 0; + } + }).collect(toList()); + } + + public boolean checkIfChallengeRegistrantExist(Long challengeId, String email) { + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder(); + searchQueryBuilder.withQuery(boolQuery() + .must(matchPhraseQuery("registrantEmail", email)) + .must(termQuery("challengeId", challengeId))); + + long total = challengeRegistrantRepository.search(searchQueryBuilder.build()).getTotalElements(); + return (total > 0); + } + + @Override + public Long getTotalNumberOfChallenges() { + return challengeRepository.count(); + } + + @Override + public Double getTotalAmountOfPrizeValues() { + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withSearchType(SearchType.COUNT); + searchQueryBuilder.withQuery(matchAllQuery()); + + SumBuilder sumPrizeBuilder = sum("sumPrize").script("doc['firstPlaceReward'].value + doc['secondPlaceReward'].value + doc['thirdPlaceReward'].value"); + searchQueryBuilder.addAggregation(sumPrizeBuilder); + + Aggregations aggregations = elasticsearchTemplateUserImport.query(searchQueryBuilder.build(), SearchResponse::getAggregations); + Sum sumReponse = aggregations.get("sumPrize"); + return sumReponse != null ? sumReponse.getValue() : 0D; + } + + @Override + public Long getTotalNumberOfRegistrants() { + return challengeRegistrantRepository.count(); + } + + @Override + public ChallengeDetailDto getTheLatestChallenge() { // NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder(); // searchQueryBuilder.withQuery(QueryBuilders.matchAllQuery()); // searchQueryBuilder.withSort(SortBuilders.fieldSort("challengeId").order(SortOrder.DESC)); @@ -520,403 +510,398 @@ public ChallengeDetailDto getTheLatestChallenge() { // ChallengeEntity challengeEntity = challengeEntities.get(0); // return dozerMapper.map(challengeEntity, ChallengeDetailDto.class); // } - return listChallenges().get(0); - } - - public Collection findByOwnerAndCondition(String owner, - Predicate condition) { - NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().withIndices(techlooperIndex).withTypes("challenge"); - QueryStringQueryBuilder query = queryStringQuery(owner).defaultField("authorEmail"); - queryBuilder.withFilter(FilterBuilders.queryFilter(query)); - - int pageIndex = 0; - Set challenges = new HashSet<>(); - while (true) { - queryBuilder.withPageable(new PageRequest(pageIndex++, 100)); - FacetedPage page = challengeRepository.search(queryBuilder.build()); - if (!page.hasContent()) { - break; - } - - page.spliterator().forEachRemaining(challenge -> { - if (condition.test(challenge)) { - ChallengeDetailDto challengeDetailDto = dozerMapper.map(challenge, ChallengeDetailDto.class); - challengeDetailDto.setNumberOfRegistrants(countRegistrantsByChallengeId(challenge.getChallengeId())); - challenges.add(challengeDetailDto); + return listChallenges().get(0); + } + + public Collection findByOwnerAndCondition(String owner, + Predicate condition) { + NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().withIndices(techlooperIndex).withTypes("challenge"); + QueryStringQueryBuilder query = queryStringQuery(owner).defaultField("authorEmail"); + queryBuilder.withFilter(FilterBuilders.queryFilter(query)); + + int pageIndex = 0; + Set challenges = new HashSet<>(); + while (true) { + queryBuilder.withPageable(new PageRequest(pageIndex++, 100)); + FacetedPage page = challengeRepository.search(queryBuilder.build()); + if (!page.hasContent()) { + break; + } + + page.spliterator().forEachRemaining(challenge -> { + if (condition.test(challenge)) { + ChallengeDetailDto challengeDetailDto = dozerMapper.map(challenge, ChallengeDetailDto.class); + challengeDetailDto.setNumberOfRegistrants(countRegistrantsByChallengeId(challenge.getChallengeId())); + challenges.add(challengeDetailDto); + } + }); + } + return challenges; + } + + public List listChallenges(String ownerEmail) { + List result = new ArrayList<>(); + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challenge"); + MatchQueryBuilder authorEmailQuery = matchQuery("authorEmail", ownerEmail).minimumShouldMatch("100%"); + TermQueryBuilder notExpiredQuery = termQuery("expired", Boolean.TRUE); + + searchQueryBuilder.withQuery(boolQuery().must(authorEmailQuery).mustNot(notExpiredQuery)); + List challengeEntities = DataUtils.getAllEntities(challengeRepository, searchQueryBuilder); + + for (ChallengeEntity challengeEntity : challengeEntities) { + ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); + challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeDetailDto.getChallengeId())); + result.add(challengeDetailDto); } - }); + return result; } - return challenges; - } - - public List listChallenges(String ownerEmail) { - List result = new ArrayList<>(); - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challenge"); - MatchQueryBuilder authorEmailQuery = matchQuery("authorEmail", ownerEmail).minimumShouldMatch("100%"); - TermQueryBuilder notExpiredQuery = termQuery("expired", Boolean.TRUE); - - searchQueryBuilder.withQuery(boolQuery().must(authorEmailQuery).mustNot(notExpiredQuery)); - List challengeEntities = DataUtils.getAllEntities(challengeRepository, searchQueryBuilder); - - for (ChallengeEntity challengeEntity : challengeEntities) { - ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); - challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeDetailDto.getChallengeId())); - result.add(challengeDetailDto); + + public Collection findInProgressChallenges(String owner) { + DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("dd/MM/yyyy"); + return findByOwnerAndCondition(owner, challengeEntity -> { + DateTime startDate = dateTimeFormatter.parseDateTime(challengeEntity.getStartDateTime()); + DateTime submissionDate = dateTimeFormatter.parseDateTime(challengeEntity.getSubmissionDateTime()); + DateTime now = DateTime.now(); + boolean inRange = now.isAfter(startDate) && now.isBefore(submissionDate); + boolean atBoundary = now.isEqual(startDate) || now.isEqual(submissionDate); + return inRange || atBoundary; + }); } - return result; - } - - public Collection findInProgressChallenges(String owner) { - DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("dd/MM/yyyy"); - return findByOwnerAndCondition(owner, challengeEntity -> { - DateTime startDate = dateTimeFormatter.parseDateTime(challengeEntity.getStartDateTime()); - DateTime submissionDate = dateTimeFormatter.parseDateTime(challengeEntity.getSubmissionDateTime()); - DateTime now = DateTime.now(); - boolean inRange = now.isAfter(startDate) && now.isBefore(submissionDate); - boolean atBoundary = now.isEqual(startDate) || now.isEqual(submissionDate); - return inRange || atBoundary; - }); - } - - public Long countRegistrantsByChallengeId(Long challengeId) { - NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().withIndices(techlooperIndex).withTypes("challengeRegistrant"); - queryBuilder.withFilter(FilterBuilders.queryFilter(termQuery("challengeId", challengeId))) - .withSearchType(SearchType.COUNT); - return challengeRegistrantRepository.search(queryBuilder.build()).getTotalElements(); - } - - public boolean delete(Long id, String ownerEmail) { - ChallengeEntity challenge = challengeRepository.findOne(id); - if (challenge.getAuthorEmail().equalsIgnoreCase(ownerEmail)) { - challenge.setExpired(Boolean.TRUE); - challengeRepository.save(challenge); - return true; + + public Long countRegistrantsByChallengeId(Long challengeId) { + NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().withIndices(techlooperIndex).withTypes("challengeRegistrant"); + queryBuilder.withFilter(FilterBuilders.queryFilter(termQuery("challengeId", challengeId))) + .withSearchType(SearchType.COUNT); + return challengeRegistrantRepository.search(queryBuilder.build()).getTotalElements(); } - return false; - } - - public ChallengeDto findChallengeById(Long id) { - return dozerMapper.map(challengeRepository.findOne(id), ChallengeDto.class); - } - - public Set findRegistrantsByOwner(RegistrantFilterCondition condition) throws ParseException { - Set result = new HashSet<>(); - Long challengeId = condition.getChallengeId(); - ChallengeEntity challengeEntity = challengeRepository.findOne(challengeId); - - if (challengeEntity != null && challengeEntity.getAuthorEmail().equals(condition.getAuthorEmail())) { - List registrants = filterChallengeRegistrantByDate(condition); - for (ChallengeRegistrantEntity registrant : registrants) { - ChallengeRegistrantDto registrantDto = dozerMapper.map(registrant, ChallengeRegistrantDto.class); - registrantDto.setSubmissions(findChallengeSubmissionByRegistrant(challengeId, registrant.getRegistrantId())); - result.add(registrantDto); - } + + public boolean delete(Long id, String ownerEmail) { + ChallengeEntity challenge = challengeRepository.findOne(id); + if (challenge.getAuthorEmail().equalsIgnoreCase(ownerEmail)) { + challenge.setExpired(Boolean.TRUE); + challengeRepository.save(challenge); + return true; + } + return false; } - return result; - } - - public ChallengeRegistrantDto saveRegistrant(String ownerEmail, ChallengeRegistrantDto challengeRegistrantDto) { - ChallengeEntity challenge = challengeRepository.findOne(challengeRegistrantDto.getChallengeId()); - if (ownerEmail.equalsIgnoreCase(challenge.getAuthorEmail())) { - ChallengeRegistrantEntity registrant = challengeRegistrantRepository.findOne(challengeRegistrantDto.getRegistrantId()); - challengeRegistrantDto.setRegistrantEmail(registrant.getRegistrantEmail()); - dozerMapper.map(challengeRegistrantDto, registrant); - registrant = challengeRegistrantRepository.save(registrant); - challengeRegistrantDto = dozerMapper.map(registrant, ChallengeRegistrantDto.class); -// challengeRegistrantDto.setRegistrantEmail(null); + public ChallengeDto findChallengeById(Long id) { + return dozerMapper.map(challengeRepository.findOne(id), ChallengeDto.class); } - return challengeRegistrantDto; - } - - @Override - public List findChallengeRegistrantWithinPeriod( - Long challengeId, Long currentDateTime, TimePeriodEnum period) { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeRegistrant"); - - BoolQueryBuilder boolQueryBuilder = boolQuery(); - boolQueryBuilder.must(termQuery("challengeId", challengeId)); - - Long pastTime = currentDateTime - period.getMiliseconds() > 0 ? currentDateTime - period.getMiliseconds() : 0; - boolQueryBuilder.must(rangeQuery("registrantId").from(pastTime)); - searchQueryBuilder.withQuery(boolQueryBuilder); - searchQueryBuilder.withSort(fieldSort("registrantId").order(SortOrder.DESC)); - return DataUtils.getAllEntities(challengeRegistrantRepository, searchQueryBuilder); - } - - @Override - public List filterChallengeRegistrantByDate(RegistrantFilterCondition condition) throws ParseException { - List result = new ArrayList<>(); - - if (ChallengeRegistrantFilterTypeEnum.BY_SUBMISSION.getValue().equals(condition.getFilterType())) { - Set registrantIds = findRegistrantByChallengeSubmissionDate( - condition.getChallengeId(), condition.getFromDate(), condition.getToDate()); - for (Long registrantId : registrantIds) { - ChallengeRegistrantEntity registrantEntity = challengeRegistrantRepository.findOne(registrantId); - if (registrantEntity != null) { - result.add(registrantEntity); + + public Set findRegistrantsByOwner(RegistrantFilterCondition condition) throws ParseException { + Set result = new HashSet<>(); + Long challengeId = condition.getChallengeId(); + ChallengeEntity challengeEntity = challengeRepository.findOne(challengeId); + + if (challengeEntity != null && challengeEntity.getAuthorEmail().equals(condition.getAuthorEmail())) { + List registrants = filterChallengeRegistrantByDate(condition); + for (ChallengeRegistrantEntity registrant : registrants) { + ChallengeRegistrantDto registrantDto = dozerMapper.map(registrant, ChallengeRegistrantDto.class); + registrantDto.setSubmissions(findChallengeSubmissionByRegistrant(challengeId, registrant.getRegistrantId())); + result.add(registrantDto); + } } - } + + return result; + } + + public ChallengeRegistrantDto saveRegistrant(String ownerEmail, ChallengeRegistrantDto challengeRegistrantDto) { + ChallengeEntity challenge = challengeRepository.findOne(challengeRegistrantDto.getChallengeId()); + if (ownerEmail.equalsIgnoreCase(challenge.getAuthorEmail())) { + ChallengeRegistrantEntity registrant = challengeRegistrantRepository.findOne(challengeRegistrantDto.getRegistrantId()); + challengeRegistrantDto.setRegistrantEmail(registrant.getRegistrantEmail()); + dozerMapper.map(challengeRegistrantDto, registrant); + registrant = challengeRegistrantRepository.save(registrant); + challengeRegistrantDto = dozerMapper.map(registrant, ChallengeRegistrantDto.class); +// challengeRegistrantDto.setRegistrantEmail(null); + } + return challengeRegistrantDto; } - else { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeRegistrant"); - BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); - if (condition.getChallengeId() != null) { - boolQueryBuilder.must(termQuery("challengeId", condition.getChallengeId())); - } + @Override + public List findChallengeRegistrantWithinPeriod( + Long challengeId, Long currentDateTime, TimePeriodEnum period) { + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeRegistrant"); + + BoolQueryBuilder boolQueryBuilder = boolQuery(); + boolQueryBuilder.must(termQuery("challengeId", challengeId)); - if (StringUtils.isNotEmpty(condition.getFilterType()) && - (StringUtils.isNotEmpty(condition.getFromDate()) || StringUtils.isNotEmpty(condition.getToDate()))) { - RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(condition.getFilterType()); + Long pastTime = currentDateTime - period.getMiliseconds() > 0 ? currentDateTime - period.getMiliseconds() : 0; + boolQueryBuilder.must(rangeQuery("registrantId").from(pastTime)); + searchQueryBuilder.withQuery(boolQueryBuilder); + searchQueryBuilder.withSort(fieldSort("registrantId").order(SortOrder.DESC)); + return DataUtils.getAllEntities(challengeRegistrantRepository, searchQueryBuilder); + } - if (StringUtils.isNotEmpty(condition.getFromDate())) { - Long from = string2Date(condition.getFromDate(), BASIC_DATE_PATTERN).getTime(); - rangeQueryBuilder.from(from); + @Override + public List filterChallengeRegistrantByDate(RegistrantFilterCondition condition) throws ParseException { + List result = new ArrayList<>(); + + if (ChallengeRegistrantFilterTypeEnum.BY_SUBMISSION.getValue().equals(condition.getFilterType())) { + Set registrantIds = findRegistrantByChallengeSubmissionDate( + condition.getChallengeId(), condition.getFromDate(), condition.getToDate()); + for (Long registrantId : registrantIds) { + ChallengeRegistrantEntity registrantEntity = challengeRegistrantRepository.findOne(registrantId); + if (registrantEntity != null) { + result.add(registrantEntity); + } + } + } else { + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeRegistrant"); + BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); + + if (condition.getChallengeId() != null) { + boolQueryBuilder.must(termQuery("challengeId", condition.getChallengeId())); + } + + if (StringUtils.isNotEmpty(condition.getFilterType()) && + (StringUtils.isNotEmpty(condition.getFromDate()) || StringUtils.isNotEmpty(condition.getToDate()))) { + RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(condition.getFilterType()); + + if (StringUtils.isNotEmpty(condition.getFromDate())) { + Long from = string2Date(condition.getFromDate(), BASIC_DATE_PATTERN).getTime(); + rangeQueryBuilder.from(from); + } + if (StringUtils.isNotEmpty(condition.getToDate())) { + Long to = string2Date(condition.getToDate(), BASIC_DATE_PATTERN).getTime() + + TimePeriodEnum.TWENTY_FOUR_HOURS.getMiliseconds(); + rangeQueryBuilder.to(to); + } + + boolQueryBuilder.must(rangeQueryBuilder); + } + + searchQueryBuilder.withQuery(boolQueryBuilder); + result.addAll(DataUtils.getAllEntities(challengeRegistrantRepository, searchQueryBuilder)); } - if (StringUtils.isNotEmpty(condition.getToDate())) { - Long to = string2Date(condition.getToDate(), BASIC_DATE_PATTERN).getTime() + - TimePeriodEnum.TWENTY_FOUR_HOURS.getMiliseconds(); - rangeQueryBuilder.to(to); + + return result; + } + + @Override + public List findChallengeSubmissionWithinPeriod( + Long challengeId, Long currentDateTime, TimePeriodEnum period) { + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeSubmission"); + + BoolQueryBuilder boolQueryBuilder = boolQuery(); + boolQueryBuilder.must(termQuery("challengeId", challengeId)); + + boolQueryBuilder.must(rangeQuery("submissionDateTime").from(yesterdayDate())); + searchQueryBuilder.withQuery(boolQueryBuilder); + searchQueryBuilder.withSort(fieldSort("challengeSubmissionId").order(SortOrder.DESC)); + + return DataUtils.getAllEntities(challengeSubmissionRepository, searchQueryBuilder); + } + + @Override + public List listChallengesByPhase(ChallengePhaseEnum challengePhase) { + List challengeEntities = new ArrayList<>(); + // from <= NOW < to + RangeFilterBuilder fromFilter = rangeFilter(challengePhase.getFromDateTimeField()).lt("now/d"); + RangeFilterBuilder toFilter = rangeFilter(challengePhase.getToDateTimeField()).gte("now/d"); + TermFilterBuilder expiredChallengeFilter = termFilter("expired", Boolean.TRUE); + BoolFilterBuilder dateTimeRangeFilter = boolFilter().must(fromFilter).must(toFilter).mustNot(expiredChallengeFilter); + + Iterator challengeIterator = + challengeRepository.search(filteredQuery(matchAllQuery(), dateTimeRangeFilter)).iterator(); + while (challengeIterator.hasNext()) { + challengeEntities.add(challengeIterator.next()); } - boolQueryBuilder.must(rangeQueryBuilder); - } + return challengeEntities; + } - searchQueryBuilder.withQuery(boolQueryBuilder); - result.addAll(DataUtils.getAllEntities(challengeRegistrantRepository, searchQueryBuilder)); + @Override + public void sendDailySummaryEmailToChallengeOwner(ChallengeEntity challengeEntity) throws Exception { + String mailSubject = challengeEntity.getLang() == Language.vi ? dailyChallengeSummaryMailSubjectVi : + dailyChallengeSummaryMailSubjectEn; + Address[] recipientAddresses = getRecipientAddresses(challengeEntity, true); + Template template = challengeEntity.getLang() == Language.vi ? + dailyChallengeSummaryMailTemplateVi : dailyChallengeSummaryMailTemplateEn; + postChallengeMailMessage.setRecipients(Message.RecipientType.TO, recipientAddresses); + Address[] replyToAddresses = InternetAddress.parse(postChallengeTechloopiesMailList); + postChallengeMailMessage.setReplyTo(replyToAddresses); + StringWriter stringWriter = new StringWriter(); + + Map templateModel = new HashMap<>(); + templateModel.put("webBaseUrl", webBaseUrl); + templateModel.put("challengeName", challengeEntity.getChallengeName()); + templateModel.put("challengeId", challengeEntity.getChallengeId().toString()); + templateModel.put("challengeNameAlias", challengeEntity.getChallengeName().replaceAll("\\W", "-")); + templateModel.put("currentDateTime", String.valueOf(new Date().getTime())); + templateModel.put("yesterdayDateTime", DateTimeUtils.yesterdayDate()); + + Long currentDateTime = new Date().getTime(); + List latestRegistrants = findChallengeRegistrantWithinPeriod( + challengeEntity.getChallengeId(), currentDateTime, TimePeriodEnum.TWENTY_FOUR_HOURS); + templateModel.put("numberOfRegistrants", latestRegistrants.size()); + templateModel.put("latestRegistrants", latestRegistrants); + + List latestSubmissions = findChallengeSubmissionWithinPeriod( + challengeEntity.getChallengeId(), currentDateTime, TimePeriodEnum.TWENTY_FOUR_HOURS); + templateModel.put("numberOfSubmissions", latestSubmissions.size()); + templateModel.put("latestSubmissions", latestSubmissions); + + template.process(templateModel, stringWriter); + mailSubject = String.format(mailSubject, challengeEntity.getChallengeName()); + postChallengeMailMessage.setSubject(MimeUtility.encodeText(mailSubject, "UTF-8", null)); + postChallengeMailMessage.setText(stringWriter.toString(), "UTF-8", "html"); + + stringWriter.flush(); + postChallengeMailMessage.saveChanges(); + mailSender.send(postChallengeMailMessage); } - return result; - } - - @Override - public List findChallengeSubmissionWithinPeriod( - Long challengeId, Long currentDateTime, TimePeriodEnum period) { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeSubmission"); - - BoolQueryBuilder boolQueryBuilder = boolQuery(); - boolQueryBuilder.must(termQuery("challengeId", challengeId)); - - boolQueryBuilder.must(rangeQuery("submissionDateTime").from(yesterdayDate())); - searchQueryBuilder.withQuery(boolQueryBuilder); - searchQueryBuilder.withSort(fieldSort("challengeSubmissionId").order(SortOrder.DESC)); - - return DataUtils.getAllEntities(challengeSubmissionRepository, searchQueryBuilder); - } - - @Override - public List listChallengesByPhase(ChallengePhaseEnum challengePhase) { - List challengeEntities = new ArrayList<>(); - // from <= NOW < to - RangeFilterBuilder fromFilter = rangeFilter(challengePhase.getFromDateTimeField()).lt("now/d"); - RangeFilterBuilder toFilter = rangeFilter(challengePhase.getToDateTimeField()).gte("now/d"); - TermFilterBuilder expiredChallengeFilter = termFilter("expired", Boolean.TRUE); - BoolFilterBuilder dateTimeRangeFilter = boolFilter().must(fromFilter).must(toFilter).mustNot(expiredChallengeFilter); - - Iterator challengeIterator = - challengeRepository.search(filteredQuery(matchAllQuery(), dateTimeRangeFilter)).iterator(); - while (challengeIterator.hasNext()) { - challengeEntities.add(challengeIterator.next()); + public boolean isOwnerOfChallenge(String ownerEmail, Long challengeId) { + ChallengeEntity challenge = challengeRepository.findOne(challengeId); + return challenge.getAuthorEmail().equalsIgnoreCase(ownerEmail); } - return challengeEntities; - } - - @Override - public void sendDailySummaryEmailToChallengeOwner(ChallengeEntity challengeEntity) throws Exception { - String mailSubject = challengeEntity.getLang() == Language.vi ? dailyChallengeSummaryMailSubjectVi : - dailyChallengeSummaryMailSubjectEn; - Address[] recipientAddresses = getRecipientAddresses(challengeEntity, true); - Template template = challengeEntity.getLang() == Language.vi ? - dailyChallengeSummaryMailTemplateVi : dailyChallengeSummaryMailTemplateEn; - postChallengeMailMessage.setRecipients(Message.RecipientType.TO, recipientAddresses); - Address[] replyToAddresses = InternetAddress.parse(postChallengeTechloopiesMailList); - postChallengeMailMessage.setReplyTo(replyToAddresses); - StringWriter stringWriter = new StringWriter(); - - Map templateModel = new HashMap<>(); - templateModel.put("webBaseUrl", webBaseUrl); - templateModel.put("challengeName", challengeEntity.getChallengeName()); - templateModel.put("challengeId", challengeEntity.getChallengeId().toString()); - templateModel.put("challengeNameAlias", challengeEntity.getChallengeName().replaceAll("\\W", "-")); - templateModel.put("currentDateTime", String.valueOf(new Date().getTime())); - templateModel.put("yesterdayDateTime", DateTimeUtils.yesterdayDate()); - - Long currentDateTime = new Date().getTime(); - List latestRegistrants = findChallengeRegistrantWithinPeriod( - challengeEntity.getChallengeId(), currentDateTime, TimePeriodEnum.TWENTY_FOUR_HOURS); - templateModel.put("numberOfRegistrants", latestRegistrants.size()); - templateModel.put("latestRegistrants", latestRegistrants); - - List latestSubmissions = findChallengeSubmissionWithinPeriod( - challengeEntity.getChallengeId(), currentDateTime, TimePeriodEnum.TWENTY_FOUR_HOURS); - templateModel.put("numberOfSubmissions", latestSubmissions.size()); - templateModel.put("latestSubmissions", latestSubmissions); - - template.process(templateModel, stringWriter); - mailSubject = String.format(mailSubject, challengeEntity.getChallengeName()); - postChallengeMailMessage.setSubject(MimeUtility.encodeText(mailSubject, "UTF-8", null)); - postChallengeMailMessage.setText(stringWriter.toString(), "UTF-8", "html"); - - stringWriter.flush(); - postChallengeMailMessage.saveChanges(); - mailSender.send(postChallengeMailMessage); - } - - public boolean isOwnerOfChallenge(String ownerEmail, Long challengeId) { - ChallengeEntity challenge = challengeRepository.findOne(challengeId); - return challenge.getAuthorEmail().equalsIgnoreCase(ownerEmail); - } - - public ChallengeEntity findChallengeIdAndOwnerEmail(Long challengeId, String ownerEmail) { - ChallengeEntity challenge = challengeRepository.findOne(challengeId); - if (challenge.getAuthorEmail().equalsIgnoreCase(ownerEmail)) { - return challenge; + public ChallengeEntity findChallengeIdAndOwnerEmail(Long challengeId, String ownerEmail) { + ChallengeEntity challenge = challengeRepository.findOne(challengeId); + if (challenge.getAuthorEmail().equalsIgnoreCase(ownerEmail)) { + return challenge; + } + return null; } - return null; - } - - public boolean sendEmailToDailyChallengeRegistrants(String challengeOwner, Long challengeId, Long now, EmailContent emailContent) { - if (isOwnerOfChallenge(challengeOwner, challengeId)) { - List registrants = findChallengeRegistrantWithinPeriod(challengeId, now, TimePeriodEnum.TWENTY_FOUR_HOURS); - String csvEmails = registrants.stream().map(ChallengeRegistrantEntity::getRegistrantEmail).distinct().collect(joining(",")); - try { - emailContent.setRecipients(InternetAddress.parse(csvEmails)); - } - catch (AddressException e) { - LOGGER.debug("Can not parse email address", e); - return false; - } + + public boolean sendEmailToDailyChallengeRegistrants(String challengeOwner, Long challengeId, Long now, EmailContent emailContent) { + if (isOwnerOfChallenge(challengeOwner, challengeId)) { + List registrants = findChallengeRegistrantWithinPeriod(challengeId, now, TimePeriodEnum.TWENTY_FOUR_HOURS); + String csvEmails = registrants.stream().map(ChallengeRegistrantEntity::getRegistrantEmail).distinct().collect(joining(",")); + try { + emailContent.setRecipients(InternetAddress.parse(csvEmails)); + } catch (AddressException e) { + LOGGER.debug("Can not parse email address", e); + return false; + } + } + return emailService.sendEmail(emailContent); } - return emailService.sendEmail(emailContent); - } - - public boolean sendEmailToRegistrant(String challengeOwner, Long challengeId, Long registrantId, EmailContent emailContent) { - if (isOwnerOfChallenge(challengeOwner, challengeId)) { - ChallengeRegistrantEntity registrant = challengeRegistrantRepository.findOne(registrantId); - String csvEmails = registrant.getRegistrantEmail(); - try { - emailContent.setRecipients(InternetAddress.parse(csvEmails)); - } - catch (AddressException e) { - LOGGER.debug("Can not parse email address", e); - return false; - } + + public boolean sendEmailToRegistrant(String challengeOwner, Long challengeId, Long registrantId, EmailContent emailContent) { + if (isOwnerOfChallenge(challengeOwner, challengeId)) { + ChallengeRegistrantEntity registrant = challengeRegistrantRepository.findOne(registrantId); + String csvEmails = registrant.getRegistrantEmail(); + try { + emailContent.setRecipients(InternetAddress.parse(csvEmails)); + } catch (AddressException e) { + LOGGER.debug("Can not parse email address", e); + return false; + } + } + return emailService.sendEmail(emailContent); } - return emailService.sendEmail(emailContent); - } - - @Override - public List findChallengeSubmissionByRegistrant(Long challengeId, Long registrantId) { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeSubmission"); - BoolFilterBuilder boolFilterBuilder = new BoolFilterBuilder(); - boolFilterBuilder.must(termFilter("challengeId", challengeId)); - boolFilterBuilder.must(termFilter("registrantId", registrantId)); - - searchQueryBuilder.withQuery(filteredQuery(matchAllQuery(), boolFilterBuilder)); - List submissions = DataUtils.getAllEntities(challengeSubmissionRepository, searchQueryBuilder); - return submissions.stream().map(submission -> dozerMapper.map(submission, ChallengeSubmissionDto.class)).collect(toList()); - } - - @Override - public void updateSendEmailToContestantResultCode(ChallengeRegistrantEntity challengeRegistrantEntity, EmailSentResultEnum code) { - if (challengeRegistrantEntity != null) { - challengeRegistrantEntity.setLastEmailSentDateTime(currentDate(BASIC_DATE_TIME_PATTERN)); - challengeRegistrantEntity.setLastEmailSentResultCode(code.getValue()); - challengeRegistrantRepository.save(challengeRegistrantEntity); + + @Override + public List findChallengeSubmissionByRegistrant(Long challengeId, Long registrantId) { + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeSubmission"); + BoolFilterBuilder boolFilterBuilder = new BoolFilterBuilder(); + boolFilterBuilder.must(termFilter("challengeId", challengeId)); + boolFilterBuilder.must(termFilter("registrantId", registrantId)); + + searchQueryBuilder.withQuery(filteredQuery(matchAllQuery(), boolFilterBuilder)); + List submissions = DataUtils.getAllEntities(challengeSubmissionRepository, searchQueryBuilder); + return submissions.stream().map(submission -> dozerMapper.map(submission, ChallengeSubmissionDto.class)).collect(toList()); } - } - public void updateSendEmailToChallengeOwnerResultCode(ChallengeEntity challengeEntity, EmailSentResultEnum code) { - if (challengeEntity != null) { - challengeEntity.setLastEmailSentDateTime(currentDate(BASIC_DATE_TIME_PATTERN)); - challengeEntity.setLastEmailSentResultCode(code.getValue()); - challengeRepository.save(challengeEntity); + @Override + public void updateSendEmailToContestantResultCode(ChallengeRegistrantEntity challengeRegistrantEntity, EmailSentResultEnum code) { + if (challengeRegistrantEntity != null) { + challengeRegistrantEntity.setLastEmailSentDateTime(currentDate(BASIC_DATE_TIME_PATTERN)); + challengeRegistrantEntity.setLastEmailSentResultCode(code.getValue()); + challengeRegistrantRepository.save(challengeRegistrantEntity); + } } - } - public Set findRegistrantByChallengeSubmissionDate(Long challengeId, String fromDate, String toDate) { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeSubmission"); - BoolQueryBuilder boolQueryBuilder = boolQuery(); - boolQueryBuilder.must(termQuery("challengeId", challengeId)); + public void updateSendEmailToChallengeOwnerResultCode(ChallengeEntity challengeEntity, EmailSentResultEnum code) { + if (challengeEntity != null) { + challengeEntity.setLastEmailSentDateTime(currentDate(BASIC_DATE_TIME_PATTERN)); + challengeEntity.setLastEmailSentResultCode(code.getValue()); + challengeRepository.save(challengeEntity); + } + } + + public Set findRegistrantByChallengeSubmissionDate(Long challengeId, String fromDate, String toDate) { + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeSubmission"); + BoolQueryBuilder boolQueryBuilder = boolQuery(); + boolQueryBuilder.must(termQuery("challengeId", challengeId)); - RangeQueryBuilder submissionDateQuery = QueryBuilders.rangeQuery("submissionDateTime"); - if (StringUtils.isNotEmpty(fromDate) || StringUtils.isNotEmpty(toDate)) { - if (StringUtils.isNotEmpty(fromDate)) { - submissionDateQuery.from(fromDate); - } + RangeQueryBuilder submissionDateQuery = QueryBuilders.rangeQuery("submissionDateTime"); + if (StringUtils.isNotEmpty(fromDate) || StringUtils.isNotEmpty(toDate)) { + if (StringUtils.isNotEmpty(fromDate)) { + submissionDateQuery.from(fromDate); + } - if (StringUtils.isNotEmpty(toDate)) { - submissionDateQuery.to(toDate); - } + if (StringUtils.isNotEmpty(toDate)) { + submissionDateQuery.to(toDate); + } - boolQueryBuilder.must(submissionDateQuery); + boolQueryBuilder.must(submissionDateQuery); + } + + searchQueryBuilder.withQuery(boolQueryBuilder); + List submissions = DataUtils.getAllEntities(challengeSubmissionRepository, searchQueryBuilder); + return submissions.stream().map(submission -> submission.getRegistrantId()).collect(toSet()); } - searchQueryBuilder.withQuery(boolQueryBuilder); - List submissions = DataUtils.getAllEntities(challengeSubmissionRepository, searchQueryBuilder); - return submissions.stream().map(submission -> submission.getRegistrantId()).collect(toSet()); - } - - public ChallengeDetailDto getChallengeDetail(Long challengeId, String loginEmail) { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challenge"); - TermQueryBuilder challengeIdQuery = termQuery("challengeId", challengeId); - //MatchQueryBuilder authorEmailQuery = matchQuery("authorEmail", loginEmail).minimumShouldMatch("100%"); - TermQueryBuilder expiredChallengeQuery = termQuery("expired", Boolean.TRUE); - - searchQueryBuilder.withQuery(boolQuery().must(challengeIdQuery).mustNot(expiredChallengeQuery)); - List challengeEntities = DataUtils.getAllEntities(challengeRepository, searchQueryBuilder); - - if (!challengeEntities.isEmpty()) { - ChallengeEntity challengeEntity = challengeEntities.get(0); - ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); - challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeId)); - calculateChallengePhases(challengeDetailDto); + public ChallengeDetailDto getChallengeDetail(Long challengeId, String loginEmail) { + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challenge"); + TermQueryBuilder challengeIdQuery = termQuery("challengeId", challengeId); + //MatchQueryBuilder authorEmailQuery = matchQuery("authorEmail", loginEmail).minimumShouldMatch("100%"); + TermQueryBuilder expiredChallengeQuery = termQuery("expired", Boolean.TRUE); + + searchQueryBuilder.withQuery(boolQuery().must(challengeIdQuery).mustNot(expiredChallengeQuery)); + List challengeEntities = DataUtils.getAllEntities(challengeRepository, searchQueryBuilder); + + if (!challengeEntities.isEmpty()) { + ChallengeEntity challengeEntity = challengeEntities.get(0); + ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); + challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeId)); + calculateChallengePhases(challengeDetailDto); // challengeDetailDto.setCurrentPhase(getChallengeCurrentPhase(challengeEntity)); // challengeDetailDto.setNextPhase(getChallengeNextPhase(challengeEntity)); - calculateChallengePhases(challengeDetailDto); - challengeDetailDto.setIsAuthor(challengeEntity.getAuthorEmail().equals(loginEmail)); - return challengeDetailDto; + calculateChallengePhases(challengeDetailDto); + challengeDetailDto.setIsAuthor(challengeEntity.getAuthorEmail().equals(loginEmail)); + return challengeDetailDto; + } + return null; } - return null; - } - - public void calculateChallengePhases(ChallengeDetailDto challengeDetailDto) { - String now = DateTimeUtils.currentDate(); - - String timeline[] = { - challengeDetailDto.getSubmissionDateTime(), - challengeDetailDto.getPrototypeSubmissionDateTime(), - challengeDetailDto.getUxSubmissionDateTime(), - challengeDetailDto.getIdeaSubmissionDateTime(), - challengeDetailDto.getRegistrationDateTime() - }; - int currentIndex = -1; - int nextIndex = -1; - for (int i = 0; i < timeline.length; ++i) { - try { - String milestone = timeline[i]; - if (DateTimeUtils.daysBetween(now, milestone) >= 0) { - nextIndex = currentIndex; - currentIndex = i; + public void calculateChallengePhases(ChallengeDetailDto challengeDetailDto) { + String now = DateTimeUtils.currentDate(); + + String timeline[] = { + challengeDetailDto.getSubmissionDateTime(), + challengeDetailDto.getPrototypeSubmissionDateTime(), + challengeDetailDto.getUxSubmissionDateTime(), + challengeDetailDto.getIdeaSubmissionDateTime(), + challengeDetailDto.getRegistrationDateTime() + }; + + int currentIndex = -1; + int nextIndex = -1; + for (int i = 0; i < timeline.length; ++i) { + try { + String milestone = timeline[i]; + if (DateTimeUtils.daysBetween(now, milestone) >= 0) { + nextIndex = currentIndex; + currentIndex = i; + } + } catch (Exception e) { + continue; + } } - } - catch (Exception e) { - continue; - } - } - if (currentIndex == -1) {//FINAL - challengeDetailDto.setCurrentPhase(ChallengePhaseEnum.FINAL); - challengeDetailDto.setNextPhase(ChallengePhaseEnum.FINAL); - } - else { - challengeDetailDto.setCurrentPhase(CHALLENGE_TIMELINE[currentIndex]); - challengeDetailDto.setNextPhase(CHALLENGE_TIMELINE[nextIndex > -1 ? nextIndex : currentIndex]); + if (currentIndex == -1) {//FINAL + challengeDetailDto.setCurrentPhase(ChallengePhaseEnum.FINAL); + challengeDetailDto.setNextPhase(ChallengePhaseEnum.FINAL); + } else { + challengeDetailDto.setCurrentPhase(CHALLENGE_TIMELINE[currentIndex]); + challengeDetailDto.setNextPhase(CHALLENGE_TIMELINE[nextIndex > -1 ? nextIndex : currentIndex]); + } } - } // public static void main(String[] args) { // ChallengeDetailDto challengeDetailDto = new ChallengeDetailDto(); @@ -958,27 +943,27 @@ public void calculateChallengePhases(ChallengeDetailDto challengeDetailDto) { //// System.out.println(challengeDetailDto.getNextPhase()); // } - public ChallengeRegistrantDto acceptRegistrant(String ownerEmail, Long registrantId) { - ChallengeRegistrantEntity registrant = challengeRegistrantRepository.findOne(registrantId); - if (registrant == null) { - return null; - } + public ChallengeRegistrantDto acceptRegistrant(String ownerEmail, Long registrantId) { + ChallengeRegistrantEntity registrant = challengeRegistrantRepository.findOne(registrantId); + if (registrant == null) { + return null; + } - ChallengeEntity challenge = challengeRepository.findOne(registrant.getChallengeId()); - if (!ownerEmail.equalsIgnoreCase(challenge.getAuthorEmail())) { - return null; - } + ChallengeEntity challenge = challengeRepository.findOne(registrant.getChallengeId()); + if (!ownerEmail.equalsIgnoreCase(challenge.getAuthorEmail())) { + return null; + } - ChallengeDetailDto challengeDetailDto = dozerMapper.map(challenge, ChallengeDetailDto.class); - calculateChallengePhases(challengeDetailDto); - ChallengePhaseEnum activePhase = challengeDetailDto.getNextPhase(); - if (activePhase != registrant.getActivePhase()) { - registrant.setActivePhase(activePhase); - registrant = challengeRegistrantRepository.save(registrant); - } + ChallengeDetailDto challengeDetailDto = dozerMapper.map(challenge, ChallengeDetailDto.class); + calculateChallengePhases(challengeDetailDto); + ChallengePhaseEnum activePhase = challengeDetailDto.getNextPhase(); + if (activePhase != registrant.getActivePhase()) { + registrant.setActivePhase(activePhase); + registrant = challengeRegistrantRepository.save(registrant); + } - return dozerMapper.map(registrant, ChallengeRegistrantDto.class); - } + return dozerMapper.map(registrant, ChallengeRegistrantDto.class); + } // private ChallengePhaseEnum getChallengeNextPhase(ChallengeEntity challengeEntity) { // int nextMilestoneIndex = getChallengeCurrentPhaseIndex(challengeEntity); From 93a0e4a7e198cf06276e13d35ec272db638c72f5 Mon Sep 17 00:00:00 2001 From: Phuong H Date: Fri, 16 Oct 2015 16:38:52 +0700 Subject: [PATCH 10/80] Add challenge criteria entity --- .../ChallengeCriteriaController.java | 6 +- .../techlooper/entity/ChallengeCriteria.java | 4 +- .../techlooper/entity/ChallengeEntity.java | 417 +++++++++--------- .../model/ChallengeCriteriaDto.java | 23 +- .../techlooper/model/ChallengeDetailDto.java | 11 +- .../service/ChallengeCriteriaService.java | 3 +- .../impl/ChallengeCriteriaServiceImpl.java | 11 +- .../assets/modules/common/apiService.js | 10 +- 8 files changed, 241 insertions(+), 244 deletions(-) diff --git a/src/main/java/com/techlooper/controller/ChallengeCriteriaController.java b/src/main/java/com/techlooper/controller/ChallengeCriteriaController.java index 74e7ac157..03e4884e7 100644 --- a/src/main/java/com/techlooper/controller/ChallengeCriteriaController.java +++ b/src/main/java/com/techlooper/controller/ChallengeCriteriaController.java @@ -1,6 +1,6 @@ package com.techlooper.controller; -import com.techlooper.entity.ChallengeCriteria; +import com.techlooper.entity.ChallengeEntity; import com.techlooper.model.ChallengeCriteriaDto; import com.techlooper.service.ChallengeCriteriaService; import org.springframework.security.access.prepost.PreAuthorize; @@ -22,7 +22,7 @@ public class ChallengeCriteriaController { @PreAuthorize("hasAuthority('EMPLOYER')") @RequestMapping(value = "challenge/criteria", method = RequestMethod.POST) - public ChallengeCriteriaDto save(ChallengeCriteriaDto challengeCriteriaDto, HttpServletRequest request) { - return challengeCriteriaService.save(challengeCriteriaDto, request.getRemoteUser()); + public ChallengeEntity save(ChallengeCriteriaDto challengeCriteriaDto, HttpServletRequest request) { + return challengeCriteriaService.saveChallengeCriterias(challengeCriteriaDto, request.getRemoteUser()); } } diff --git a/src/main/java/com/techlooper/entity/ChallengeCriteria.java b/src/main/java/com/techlooper/entity/ChallengeCriteria.java index 6b41aa578..2c211ede7 100644 --- a/src/main/java/com/techlooper/entity/ChallengeCriteria.java +++ b/src/main/java/com/techlooper/entity/ChallengeCriteria.java @@ -1,9 +1,11 @@ package com.techlooper.entity; +import java.io.Serializable; + /** * Created by phuonghqh on 10/16/15. */ -public class ChallengeCriteria { +public class ChallengeCriteria implements Serializable { private String name; diff --git a/src/main/java/com/techlooper/entity/ChallengeEntity.java b/src/main/java/com/techlooper/entity/ChallengeEntity.java index e5b1ec483..a45b0fdb9 100644 --- a/src/main/java/com/techlooper/entity/ChallengeEntity.java +++ b/src/main/java/com/techlooper/entity/ChallengeEntity.java @@ -8,6 +8,7 @@ import org.springframework.data.elasticsearch.annotations.FieldType; import java.util.List; +import java.util.Set; import static org.springframework.data.elasticsearch.annotations.FieldType.Boolean; import static org.springframework.data.elasticsearch.annotations.FieldType.Integer; @@ -19,289 +20,289 @@ @Document(indexName = "techlooper", type = "challenge") public class ChallengeEntity { - @Id - private Long challengeId; + @Id + private Long challengeId; - @Field(type = FieldType.Nested) - private ChallengeCriteria criteria; + @Field(type = FieldType.Nested) + private Set challengeCriterias; - @Field(type = String) - private String challengeName; + @Field(type = String) + private String challengeName; - @Field(type = String) - private String challengeOverview; + @Field(type = String) + private String challengeOverview; - @Field(type = String) - private String businessRequirement; + @Field(type = String) + private String businessRequirement; - @Field(type = String) - private String generalNote; + @Field(type = String) + private String generalNote; - @Field(type = String) - private List technologies; + @Field(type = String) + private List technologies; - @Field(type = String) - private String documents; + @Field(type = String) + private String documents; - @Field(type = String) - private String deliverables; + @Field(type = String) + private String deliverables; - @Field(type = String) - private List receivedEmails; + @Field(type = String) + private List receivedEmails; - @Field(type = String) - private String reviewStyle; + @Field(type = String) + private String reviewStyle; - @Field(type = FieldType.Date, format = DateFormat.custom, pattern = "dd/MM/yyyy") - private String startDateTime; + @Field(type = FieldType.Date, format = DateFormat.custom, pattern = "dd/MM/yyyy") + private String startDateTime; - @Field(type = FieldType.Date, format = DateFormat.custom, pattern = "dd/MM/yyyy") - private String registrationDateTime; + @Field(type = FieldType.Date, format = DateFormat.custom, pattern = "dd/MM/yyyy") + private String registrationDateTime; - @Field(type = FieldType.Date, format = DateFormat.custom, pattern = "dd/MM/yyyy") - private String ideaSubmissionDateTime; + @Field(type = FieldType.Date, format = DateFormat.custom, pattern = "dd/MM/yyyy") + private String ideaSubmissionDateTime; - @Field(type = FieldType.Date, format = DateFormat.custom, pattern = "dd/MM/yyyy") - private String uxSubmissionDateTime; + @Field(type = FieldType.Date, format = DateFormat.custom, pattern = "dd/MM/yyyy") + private String uxSubmissionDateTime; - @Field(type = FieldType.Date, format = DateFormat.custom, pattern = "dd/MM/yyyy") - private String prototypeSubmissionDateTime; + @Field(type = FieldType.Date, format = DateFormat.custom, pattern = "dd/MM/yyyy") + private String prototypeSubmissionDateTime; - @Field(type = FieldType.Date, format = DateFormat.custom, pattern = "dd/MM/yyyy") - private String submissionDateTime; + @Field(type = FieldType.Date, format = DateFormat.custom, pattern = "dd/MM/yyyy") + private String submissionDateTime; - @Field(type = FieldType.Integer) - private Integer firstPlaceReward; + @Field(type = FieldType.Integer) + private Integer firstPlaceReward; - @Field(type = FieldType.Integer) - private Integer secondPlaceReward; + @Field(type = FieldType.Integer) + private Integer secondPlaceReward; - @Field(type = FieldType.Integer) - private Integer thirdPlaceReward; + @Field(type = FieldType.Integer) + private Integer thirdPlaceReward; - @Field(type = String) - private String qualityIdea; + @Field(type = String) + private String qualityIdea; - @Field(type = String) - private String authorEmail; + @Field(type = String) + private String authorEmail; - @Field(type = String) - private Language lang; + @Field(type = String) + private Language lang; - @Field(type = Boolean) - private Boolean expired; + @Field(type = Boolean) + private Boolean expired; - @Field(type = FieldType.Date, format = DateFormat.custom, pattern = "dd/MM/yyyy HH:mm") - private String lastEmailSentDateTime; + @Field(type = FieldType.Date, format = DateFormat.custom, pattern = "dd/MM/yyyy HH:mm") + private String lastEmailSentDateTime; - @Field(type = Integer) - private int lastEmailSentResultCode; + @Field(type = Integer) + private int lastEmailSentResultCode; - public ChallengeCriteria getCriteria() { - return criteria; - } + public Set getChallengeCriterias() { + return challengeCriterias; + } - public void setCriteria(ChallengeCriteria criteria) { - this.criteria = criteria; - } + public void setChallengeCriterias(Set challengeCriterias) { + this.challengeCriterias = challengeCriterias; + } - public Boolean getExpired() { - return expired; - } + public Boolean getExpired() { + return expired; + } - public void setExpired(Boolean expired) { - this.expired = expired; - } + public void setExpired(Boolean expired) { + this.expired = expired; + } - public Long getChallengeId() { - return challengeId; - } + public Long getChallengeId() { + return challengeId; + } - public void setChallengeId(Long challengeId) { - this.challengeId = challengeId; - } + public void setChallengeId(Long challengeId) { + this.challengeId = challengeId; + } - public String getChallengeName() { - return challengeName; - } + public String getChallengeName() { + return challengeName; + } - public void setChallengeName(String challengeName) { - this.challengeName = challengeName; - } + public void setChallengeName(String challengeName) { + this.challengeName = challengeName; + } - public String getBusinessRequirement() { - return businessRequirement; - } + public String getBusinessRequirement() { + return businessRequirement; + } - public void setBusinessRequirement(String businessRequirement) { - this.businessRequirement = businessRequirement; - } + public void setBusinessRequirement(String businessRequirement) { + this.businessRequirement = businessRequirement; + } - public String getGeneralNote() { - return generalNote; - } + public String getGeneralNote() { + return generalNote; + } - public void setGeneralNote(String generalNote) { - this.generalNote = generalNote; - } + public void setGeneralNote(String generalNote) { + this.generalNote = generalNote; + } - public List getTechnologies() { - return technologies; - } + public List getTechnologies() { + return technologies; + } - public void setTechnologies(List technologies) { - this.technologies = technologies; - } + public void setTechnologies(List technologies) { + this.technologies = technologies; + } - public String getDocuments() { - return documents; - } + public String getDocuments() { + return documents; + } - public void setDocuments(String documents) { - this.documents = documents; - } + public void setDocuments(String documents) { + this.documents = documents; + } - public String getDeliverables() { - return deliverables; - } + public String getDeliverables() { + return deliverables; + } - public void setDeliverables(String deliverables) { - this.deliverables = deliverables; - } + public void setDeliverables(String deliverables) { + this.deliverables = deliverables; + } - public List getReceivedEmails() { - return receivedEmails; - } + public List getReceivedEmails() { + return receivedEmails; + } - public void setReceivedEmails(List receivedEmails) { - this.receivedEmails = receivedEmails; - } + public void setReceivedEmails(List receivedEmails) { + this.receivedEmails = receivedEmails; + } - public String getReviewStyle() { - return reviewStyle; - } + public String getReviewStyle() { + return reviewStyle; + } - public void setReviewStyle(String reviewStyle) { - this.reviewStyle = reviewStyle; - } + public void setReviewStyle(String reviewStyle) { + this.reviewStyle = reviewStyle; + } - public String getStartDateTime() { - return startDateTime; - } + public String getStartDateTime() { + return startDateTime; + } - public void setStartDateTime(String startDateTime) { - this.startDateTime = startDateTime; - } + public void setStartDateTime(String startDateTime) { + this.startDateTime = startDateTime; + } - public String getRegistrationDateTime() { - return registrationDateTime; - } + public String getRegistrationDateTime() { + return registrationDateTime; + } - public void setRegistrationDateTime(String registrationDateTime) { - this.registrationDateTime = registrationDateTime; - } + public void setRegistrationDateTime(String registrationDateTime) { + this.registrationDateTime = registrationDateTime; + } - public String getIdeaSubmissionDateTime() { - return ideaSubmissionDateTime; - } + public String getIdeaSubmissionDateTime() { + return ideaSubmissionDateTime; + } - public void setIdeaSubmissionDateTime(String ideaSubmissionDateTime) { - this.ideaSubmissionDateTime = ideaSubmissionDateTime; - } + public void setIdeaSubmissionDateTime(String ideaSubmissionDateTime) { + this.ideaSubmissionDateTime = ideaSubmissionDateTime; + } - public String getUxSubmissionDateTime() { - return uxSubmissionDateTime; - } + public String getUxSubmissionDateTime() { + return uxSubmissionDateTime; + } - public void setUxSubmissionDateTime(String uxSubmissionDateTime) { - this.uxSubmissionDateTime = uxSubmissionDateTime; - } + public void setUxSubmissionDateTime(String uxSubmissionDateTime) { + this.uxSubmissionDateTime = uxSubmissionDateTime; + } - public String getPrototypeSubmissionDateTime() { - return prototypeSubmissionDateTime; - } + public String getPrototypeSubmissionDateTime() { + return prototypeSubmissionDateTime; + } - public void setPrototypeSubmissionDateTime(String prototypeSubmissionDateTime) { - this.prototypeSubmissionDateTime = prototypeSubmissionDateTime; - } + public void setPrototypeSubmissionDateTime(String prototypeSubmissionDateTime) { + this.prototypeSubmissionDateTime = prototypeSubmissionDateTime; + } - public String getSubmissionDateTime() { - return submissionDateTime; - } + public String getSubmissionDateTime() { + return submissionDateTime; + } - public void setSubmissionDateTime(String submissionDateTime) { - this.submissionDateTime = submissionDateTime; - } + public void setSubmissionDateTime(String submissionDateTime) { + this.submissionDateTime = submissionDateTime; + } - public Integer getFirstPlaceReward() { - return firstPlaceReward; - } + public Integer getFirstPlaceReward() { + return firstPlaceReward; + } - public void setFirstPlaceReward(Integer firstPlaceReward) { - this.firstPlaceReward = firstPlaceReward; - } + public void setFirstPlaceReward(Integer firstPlaceReward) { + this.firstPlaceReward = firstPlaceReward; + } - public Integer getSecondPlaceReward() { - return secondPlaceReward; - } + public Integer getSecondPlaceReward() { + return secondPlaceReward; + } - public void setSecondPlaceReward(Integer secondPlaceReward) { - this.secondPlaceReward = secondPlaceReward; - } + public void setSecondPlaceReward(Integer secondPlaceReward) { + this.secondPlaceReward = secondPlaceReward; + } - public Integer getThirdPlaceReward() { - return thirdPlaceReward; - } + public Integer getThirdPlaceReward() { + return thirdPlaceReward; + } - public void setThirdPlaceReward(Integer thirdPlaceReward) { - this.thirdPlaceReward = thirdPlaceReward; - } + public void setThirdPlaceReward(Integer thirdPlaceReward) { + this.thirdPlaceReward = thirdPlaceReward; + } - public String getQualityIdea() { - return qualityIdea; - } + public String getQualityIdea() { + return qualityIdea; + } - public void setQualityIdea(String qualityIdea) { - this.qualityIdea = qualityIdea; - } + public void setQualityIdea(String qualityIdea) { + this.qualityIdea = qualityIdea; + } - public String getAuthorEmail() { - return authorEmail; - } + public String getAuthorEmail() { + return authorEmail; + } - public void setAuthorEmail(String authorEmail) { - this.authorEmail = authorEmail; - } + public void setAuthorEmail(String authorEmail) { + this.authorEmail = authorEmail; + } - public Language getLang() { - return lang; - } + public Language getLang() { + return lang; + } - public void setLang(Language lang) { - this.lang = lang; - } + public void setLang(Language lang) { + this.lang = lang; + } - public String getChallengeOverview() { - return challengeOverview; - } + public String getChallengeOverview() { + return challengeOverview; + } - public void setChallengeOverview(String challengeOverview) { - this.challengeOverview = challengeOverview; - } + public void setChallengeOverview(String challengeOverview) { + this.challengeOverview = challengeOverview; + } - public String getLastEmailSentDateTime() { - return lastEmailSentDateTime; - } + public String getLastEmailSentDateTime() { + return lastEmailSentDateTime; + } - public void setLastEmailSentDateTime(String lastEmailSentDateTime) { - this.lastEmailSentDateTime = lastEmailSentDateTime; - } + public void setLastEmailSentDateTime(String lastEmailSentDateTime) { + this.lastEmailSentDateTime = lastEmailSentDateTime; + } - public int getLastEmailSentResultCode() { - return lastEmailSentResultCode; - } + public int getLastEmailSentResultCode() { + return lastEmailSentResultCode; + } - public void setLastEmailSentResultCode(int lastEmailSentResultCode) { - this.lastEmailSentResultCode = lastEmailSentResultCode; - } + public void setLastEmailSentResultCode(int lastEmailSentResultCode) { + this.lastEmailSentResultCode = lastEmailSentResultCode; + } } diff --git a/src/main/java/com/techlooper/model/ChallengeCriteriaDto.java b/src/main/java/com/techlooper/model/ChallengeCriteriaDto.java index 03368e4c5..c40b796ff 100644 --- a/src/main/java/com/techlooper/model/ChallengeCriteriaDto.java +++ b/src/main/java/com/techlooper/model/ChallengeCriteriaDto.java @@ -1,6 +1,9 @@ package com.techlooper.model; +import com.techlooper.entity.ChallengeCriteria; + import java.io.Serializable; +import java.util.Set; /** * Created by phuonghqh on 10/16/15. @@ -9,9 +12,7 @@ public class ChallengeCriteriaDto implements Serializable { private Long challengeId; - private String name; - - private Long weight; + private Set challengeCriterias; public Long getChallengeId() { return challengeId; @@ -21,19 +22,11 @@ public void setChallengeId(Long challengeId) { this.challengeId = challengeId; } - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Long getWeight() { - return weight; + public Set getChallengeCriterias() { + return challengeCriterias; } - public void setWeight(Long weight) { - this.weight = weight; + public void setChallengeCriterias(Set challengeCriterias) { + this.challengeCriterias = challengeCriterias; } } diff --git a/src/main/java/com/techlooper/model/ChallengeDetailDto.java b/src/main/java/com/techlooper/model/ChallengeDetailDto.java index ef8bc0a94..759274e15 100644 --- a/src/main/java/com/techlooper/model/ChallengeDetailDto.java +++ b/src/main/java/com/techlooper/model/ChallengeDetailDto.java @@ -3,6 +3,7 @@ import com.techlooper.entity.ChallengeCriteria; import java.util.List; +import java.util.Set; /** * Created by NguyenDangKhoa on 7/3/15. @@ -59,14 +60,14 @@ public class ChallengeDetailDto { private Boolean isAuthor; - private ChallengeCriteria criteria; + private Set challengeCriterias; - public ChallengeCriteria getCriteria() { - return criteria; + public Set getChallengeCriterias() { + return challengeCriterias; } - public void setCriteria(ChallengeCriteria criteria) { - this.criteria = criteria; + public void setChallengeCriterias(Set challengeCriterias) { + this.challengeCriterias = challengeCriterias; } public Boolean getAuthor() { diff --git a/src/main/java/com/techlooper/service/ChallengeCriteriaService.java b/src/main/java/com/techlooper/service/ChallengeCriteriaService.java index 9fdb1d806..dd1cee116 100644 --- a/src/main/java/com/techlooper/service/ChallengeCriteriaService.java +++ b/src/main/java/com/techlooper/service/ChallengeCriteriaService.java @@ -1,5 +1,6 @@ package com.techlooper.service; +import com.techlooper.entity.ChallengeEntity; import com.techlooper.model.ChallengeCriteriaDto; /** @@ -7,5 +8,5 @@ */ public interface ChallengeCriteriaService { - ChallengeCriteriaDto save(ChallengeCriteriaDto challengeCriteriaDto, String owner); + ChallengeEntity saveChallengeCriterias(ChallengeCriteriaDto challengeCriteriaDto, String owner); } diff --git a/src/main/java/com/techlooper/service/impl/ChallengeCriteriaServiceImpl.java b/src/main/java/com/techlooper/service/impl/ChallengeCriteriaServiceImpl.java index 81d9364b4..2d8e13b8c 100644 --- a/src/main/java/com/techlooper/service/impl/ChallengeCriteriaServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/ChallengeCriteriaServiceImpl.java @@ -10,6 +10,8 @@ import org.springframework.stereotype.Service; import javax.annotation.Resource; +import java.util.HashSet; +import java.util.Set; /** * Created by phuonghqh on 10/16/15. @@ -26,14 +28,15 @@ public class ChallengeCriteriaServiceImpl implements ChallengeCriteriaService { @Resource private Mapper dozerMapper; - public ChallengeCriteriaDto save(ChallengeCriteriaDto challengeCriteriaDto, String ownerEmail) { + public ChallengeEntity saveChallengeCriterias(ChallengeCriteriaDto challengeCriteriaDto, String ownerEmail) { ChallengeEntity challenge = challengeService.findChallengeIdAndOwnerEmail(challengeCriteriaDto.getChallengeId(), ownerEmail); if (challenge == null) { return null; } - challenge.setCriteria(dozerMapper.map(challengeCriteriaDto, ChallengeCriteria.class)); - challengeRepository.save(challenge); - return challengeCriteriaDto; + Set criterias = new HashSet<>(); + challengeCriteriaDto.getChallengeCriterias().forEach(criterias::add); + challenge.setChallengeCriterias(criterias); + return challengeRepository.save(challenge); } } diff --git a/src/main/webapp/assets/modules/common/apiService.js b/src/main/webapp/assets/modules/common/apiService.js index 4bff64ba1..dd8bac7db 100644 --- a/src/main/webapp/assets/modules/common/apiService.js +++ b/src/main/webapp/assets/modules/common/apiService.js @@ -258,14 +258,10 @@ techlooper.factory("apiService", function ($rootScope, $location, jsonValue, $ht * */ getUrlResponseCode: function (url) { return $http.post("resource/getUrlResponseCode", {url: url}, {transformResponse: function (d, h) {return d;}}); - }, - - /** - * @see com.techlooper.controller.ChallengeCriteriaController.save - * */ - saveChallengeCriteria: function(criteria) { - return $http.post("challenge/criteria", criteria); } + + + }; return instance; From 83246881a3aa207d254b489a9d0b80f3eaa8ef4d Mon Sep 17 00:00:00 2001 From: johnsonpham Date: Fri, 16 Oct 2015 17:00:11 +0700 Subject: [PATCH 11/80] Implement input score creteria form --- .../modules/contest-detail/contestDetail.html | 8 ++- .../contest-detail/contestDetailAction.html | 1 + .../contest-detail/contestDetailDirective.js | 23 +++++++- .../contest-detail/contestDetailScore.html | 56 +++++++++++++++++++ 4 files changed, 84 insertions(+), 4 deletions(-) create mode 100644 src/main/webapp/assets/modules/contest-detail/contestDetailScore.html diff --git a/src/main/webapp/assets/modules/contest-detail/contestDetail.html b/src/main/webapp/assets/modules/contest-detail/contestDetail.html index d1fccf647..32505782a 100644 --- a/src/main/webapp/assets/modules/contest-detail/contestDetail.html +++ b/src/main/webapp/assets/modules/contest-detail/contestDetail.html @@ -310,9 +310,7 @@

- - + {{user.score}}
@@ -327,6 +325,8 @@

{{'qualify' | translate}} +
  • + {{'score' | translate}}
  • {{'review' | translate}}
  • @@ -349,6 +349,8 @@

  • {{'qualify' | translate}}
  • +
  • + {{'score' | translate}}
  • {{'review' | translate}}
  • {{'feedback' | translate}}
  • {{'accept' | translate}}
  • diff --git a/src/main/webapp/assets/modules/contest-detail/contestDetailAction.html b/src/main/webapp/assets/modules/contest-detail/contestDetailAction.html index 4a531f0cd..2a1d1a439 100644 --- a/src/main/webapp/assets/modules/contest-detail/contestDetailAction.html +++ b/src/main/webapp/assets/modules/contest-detail/contestDetailAction.html @@ -1,6 +1,7 @@
    + diff --git a/src/main/webapp/assets/modules/contest-detail/contestDetailDirective.js b/src/main/webapp/assets/modules/contest-detail/contestDetailDirective.js index 5057cc948..3be1dcbfa 100644 --- a/src/main/webapp/assets/modules/contest-detail/contestDetailDirective.js +++ b/src/main/webapp/assets/modules/contest-detail/contestDetailDirective.js @@ -27,6 +27,10 @@ techlooper showView("qualification"); } + scope.registrant.showScore = function () { + showView("score"); + } + scope.registrant.showReviewSubmission = function () { showView("reviewSubmission"); } @@ -60,6 +64,14 @@ techlooper delete scope.registrant.visible; }; + scope.registrant.score = function() { + //apiService.acceptChallengeRegistrant(scope.registrant.registrantId) + // .success(function(registrant) { + // scope.registrant.activePhase = registrant.activePhase; + // }); + delete scope.registrant.visible; + }; + scope.registrant.hide = function() { if (!scope.registrant.visible) return; delete scope.registrant.visible; @@ -121,10 +133,19 @@ techlooper }; }) .directive('acceptance', function () { + return { + restrict: "E", + replace: true, + templateUrl: "modules/contest-detail/contestDetailAcceptance.html", + link: function (scope, element, attr, ctrl) { + } + }; + }) +.directive('contestDetailScore', function () { return { restrict: "E", replace: true, - templateUrl: "modules/contest-detail/contestDetailAcceptance.html", + templateUrl: "modules/contest-detail/contestDetailScore.html", link: function (scope, element, attr, ctrl) { } }; diff --git a/src/main/webapp/assets/modules/contest-detail/contestDetailScore.html b/src/main/webapp/assets/modules/contest-detail/contestDetailScore.html new file mode 100644 index 000000000..631381619 --- /dev/null +++ b/src/main/webapp/assets/modules/contest-detail/contestDetailScore.html @@ -0,0 +1,56 @@ +
    +
    +
    +
      +
    • +
      + Lorem Ipsum is simply dummy text of the printing: +
      +
      + +
      +
      + +
      +
    • +
    • +
      + Lorem Ipsum is simply dummy text of the printing: +
      +
      + +
      +
      + +
      +
    • +
    • +
      + Lorem Ipsum is simply dummy text of the printing: +
      +
      + +
      +
      + +
      +
    • +
    • +
      + {{'totalPoints' | translate}} +
      +
      + +
      +
      + +
      +
    • +
    • + + +
    • +
    +
    +
    +
    \ No newline at end of file From 95f398b6e4ea088fabf550d0cf9693c795d86b77 Mon Sep 17 00:00:00 2001 From: johnsonpham Date: Fri, 16 Oct 2015 17:00:46 +0700 Subject: [PATCH 12/80] english translate for input score criteria form --- .../webapp/assets/modules/translation/messages_en.json | 7 +++++-- .../webapp/assets/modules/translation/messages_vi.json | 5 ++++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/main/webapp/assets/modules/translation/messages_en.json b/src/main/webapp/assets/modules/translation/messages_en.json index 9e02152af..59446d847 100644 --- a/src/main/webapp/assets/modules/translation/messages_en.json +++ b/src/main/webapp/assets/modules/translation/messages_en.json @@ -774,7 +774,7 @@ "acceptDescription": "Are you sure you want to select this contestant from {{current}} phase to {{next}} phase?", "exRegistrantsFilterConfig": "All Contestants", "allContestants": "All Contestants", - "allSubmission": "All Submission", + "allSubmission": "All Submissions", "404Error": "This URL leads to 404 page. Please check again.", "cannotSendMail": "You don’t have right to perform this action.", "template": "Template:", @@ -782,5 +782,8 @@ "askContestantSubmission": "Ask for submission", "disqualifyContestant": "Disqualify a contestant", "winnerAnnouncement": "Winner announcement", - "exChooseATemplate": "Choose a template" + "exChooseATemplate": "Choose a template", + "points": "Points", + "comment": "Comment", + "totalPoints": "Total Points" } \ No newline at end of file diff --git a/src/main/webapp/assets/modules/translation/messages_vi.json b/src/main/webapp/assets/modules/translation/messages_vi.json index 5cb4f3859..18b45eea1 100644 --- a/src/main/webapp/assets/modules/translation/messages_vi.json +++ b/src/main/webapp/assets/modules/translation/messages_vi.json @@ -785,6 +785,9 @@ "askContestantSubmission": "Ask for submission", "disqualifyContestant": "Disqualify a contestant", "winnerAnnouncement": "Winner announcement", - "exChooseATemplate": "choose a template" + "exChooseATemplate": "choose a template", + "points": "Points", + "comment": "Comment", + "totalPoints": "Total Points" } From e9a50c31c05f51726650231cc2da6a0d3d28286f Mon Sep 17 00:00:00 2001 From: johnsonpham Date: Fri, 16 Oct 2015 17:01:09 +0700 Subject: [PATCH 13/80] make responsive for input score criteria --- .../webapp/assets/sass/contest-detail.sass | 46 ++++++++++++++++++- .../assets/sass/z-responsive-candidate.sass | 14 ++++++ 2 files changed, 59 insertions(+), 1 deletion(-) diff --git a/src/main/webapp/assets/sass/contest-detail.sass b/src/main/webapp/assets/sass/contest-detail.sass index 8c1553667..4de66e0b3 100644 --- a/src/main/webapp/assets/sass/contest-detail.sass +++ b/src/main/webapp/assets/sass/contest-detail.sass @@ -586,7 +586,51 @@ padding: 6px 20px color: #fff display: inline-block - + .registrant-score + width: 100% + clear: both + display: inline-block + padding: 10px 0 + .score-form + background-color: #f6f6f6 + border: 1px solid white + border-radius: 3px + clear: both + display: inline-block + padding: 10px + width: 100% + ul + margin: 0 + padding: 0 + li + width: 100% + clear: both + padding: 3px 0 10px 0 + border-bottom: 1px solid #fff + text-align: left + display: inline-block + .points-name + width: 40% + float: left + display: inline-block + .points-input + width: 8% + float: left + display: inline-block + padding: 0 5px + .points-comment + width: 52% + float: left + display: inline-block + li:last-child + padding-bottom: 0 + text-align: right + border-bottom: 0 + a + margin: auto + display: inline-block + color: #fff + padding: 8px 35px 4px 35px .submit-phase-contest.show height: 280px background-color: #f1f2f7 diff --git a/src/main/webapp/assets/sass/z-responsive-candidate.sass b/src/main/webapp/assets/sass/z-responsive-candidate.sass index 6003c9700..95da0e8f9 100644 --- a/src/main/webapp/assets/sass/z-responsive-candidate.sass +++ b/src/main/webapp/assets/sass/z-responsive-candidate.sass @@ -1405,6 +1405,20 @@ label width: 100% text-align: left !important + .registrant-score + .score-form ul li + .points-name + clear: both + display: block + padding-bottom: 5px + width: 100% + .points-input + width: 22% + padding-left: 0 + .points-comment + width: 78% + .score-form ul li:last-child + text-align: center .contest-detail-action p text-align: left !important From 79be68265c0a4cc009561c0aa3a526ad9d5f34fc Mon Sep 17 00:00:00 2001 From: khoa-nd Date: Fri, 16 Oct 2015 17:31:13 +0700 Subject: [PATCH 14/80] Filter contestants by phase --- .../techlooper/model/RegistrantFilterCondition.java | 10 ++++++++++ .../service/impl/ChallengeServiceImpl.java | 9 +++++++++ .../assets/modules/common/resourcesService.js | 13 +++++++------ .../modules/contest-detail/contestDetail.html | 2 +- .../contest-detail/contestDetailController.js | 9 +++++++++ 5 files changed, 36 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/techlooper/model/RegistrantFilterCondition.java b/src/main/java/com/techlooper/model/RegistrantFilterCondition.java index 52786de63..b41d3865a 100644 --- a/src/main/java/com/techlooper/model/RegistrantFilterCondition.java +++ b/src/main/java/com/techlooper/model/RegistrantFilterCondition.java @@ -11,6 +11,8 @@ public class RegistrantFilterCondition { private String filterType; + private String phase; + private String fromDate; private String toDate; @@ -39,6 +41,14 @@ public void setFilterType(String filterType) { this.filterType = filterType; } + public String getPhase() { + return phase; + } + + public void setPhase(String phase) { + this.phase = phase; + } + public String getFromDate() { return fromDate; } diff --git a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java index 5e5eac1f3..9b8af69ed 100644 --- a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java @@ -647,6 +647,11 @@ public List filterChallengeRegistrantByDate(Registran result.add(registrantEntity); } } + + if (StringUtils.isNotEmpty(condition.getPhase())) { + result = result.stream().filter(registrantEntity -> + condition.getPhase().equals(registrantEntity.getActivePhase().getValue())).collect(toList()); + } } else { NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeRegistrant"); BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); @@ -655,6 +660,10 @@ public List filterChallengeRegistrantByDate(Registran boolQueryBuilder.must(termQuery("challengeId", condition.getChallengeId())); } + if (StringUtils.isNotEmpty(condition.getPhase())) { + boolQueryBuilder.must(matchPhraseQuery("activePhase", condition.getPhase())); + } + if (StringUtils.isNotEmpty(condition.getFilterType()) && (StringUtils.isNotEmpty(condition.getFromDate()) || StringUtils.isNotEmpty(condition.getToDate()))) { RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(condition.getFilterType()); diff --git a/src/main/webapp/assets/modules/common/resourcesService.js b/src/main/webapp/assets/modules/common/resourcesService.js index c8711b16b..bcfc3e560 100644 --- a/src/main/webapp/assets/modules/common/resourcesService.js +++ b/src/main/webapp/assets/modules/common/resourcesService.js @@ -5,12 +5,13 @@ techlooper.factory("resourcesService", function ($translate, $q) { ]; var registrantsPhaseOptions = [ - {translate: "allPhase", id: "allPhase"}, - {translate: "registration", id: "registration"}, - {translate: "idea", id: "idea"}, - {translate: "uiux", id: "uiux"}, - {translate: "prototype", id: "prototype"}, - {translate: "finalApp", id: "finalApp"} + {translate: "allPhase", id: ""}, + {translate: "registration", id: "REGISTRATION"}, + {translate: "inProgress", id: "IN_PROGRESS"}, + {translate: "idea", id: "IDEA"}, + {translate: "uiux", id: "UIUX"}, + {translate: "prototype", id: "PROTOTYPE"}, + {translate: "finalApp", id: "FINAL"} ]; var reviewStyleOptions = [ {translate: "contestOwnerSignOff", id: "contestOwnerSignOff"} diff --git a/src/main/webapp/assets/modules/contest-detail/contestDetail.html b/src/main/webapp/assets/modules/contest-detail/contestDetail.html index d1fccf647..c3aae8b53 100644 --- a/src/main/webapp/assets/modules/contest-detail/contestDetail.html +++ b/src/main/webapp/assets/modules/contest-detail/contestDetail.html @@ -235,7 +235,7 @@

    -

    diff --git a/src/main/webapp/assets/modules/contest-detail/contestDetailController.js b/src/main/webapp/assets/modules/contest-detail/contestDetailController.js index b9fca12c8..ef6fcdc1f 100644 --- a/src/main/webapp/assets/modules/contest-detail/contestDetailController.js +++ b/src/main/webapp/assets/modules/contest-detail/contestDetailController.js @@ -156,6 +156,15 @@ techlooper.controller('contestDetailController', function ($scope, apiService, l registrantFilterCondition.filterType = "registrantId"; } + if ($scope.phase) { + registrantFilterCondition.phase = $scope.phase; + } else if (param.phase) { + registrantFilterCondition.phase = param.phase; + $scope.phase = param.phase; + } else { + registrantFilterCondition.phase = ""; + } + if ($scope.fromDate) { registrantFilterCondition.fromDate = $scope.fromDate; } else { From 8659f3bdb9ff5f89e94929fbc2c4fed0e187e340 Mon Sep 17 00:00:00 2001 From: johnsonpham Date: Fri, 16 Oct 2015 18:10:52 +0700 Subject: [PATCH 15/80] show Current Phase for challenge on the Challenge name --- .../modules/contest-detail/contestDetail.html | 12 ++++++++++-- .../contest-detail/contestDetailController.js | 1 + .../webapp/assets/sass/contest-detail.sass | 18 ++++++++++++++++++ 3 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/main/webapp/assets/modules/contest-detail/contestDetail.html b/src/main/webapp/assets/modules/contest-detail/contestDetail.html index 32505782a..1857b973f 100644 --- a/src/main/webapp/assets/modules/contest-detail/contestDetail.html +++ b/src/main/webapp/assets/modules/contest-detail/contestDetail.html @@ -1,7 +1,10 @@
    -

    {{contestDetail.challengeName}}

    +

    {{contestDetail.challengeName}} + + {{contestDetail.currentPhase | progress: 'challengePhaseTitle'}} +

    @@ -45,7 +48,12 @@

    {{contestDetail.challengeName}}

    -

    +

    + {{contestDetail.progress.translate | translate}} + + ({{contestDetail.currentPhase | progress: 'challengePhaseTitle'}}) + +

    diff --git a/src/main/webapp/assets/modules/contest-detail/contestDetailController.js b/src/main/webapp/assets/modules/contest-detail/contestDetailController.js index b9fca12c8..17dc64b7b 100644 --- a/src/main/webapp/assets/modules/contest-detail/contestDetailController.js +++ b/src/main/webapp/assets/modules/contest-detail/contestDetailController.js @@ -124,6 +124,7 @@ techlooper.controller('contestDetailController', function ($scope, apiService, l else { $scope.contestDetail.timeline = 5; } + console.log($scope.contestDetail); }) .error(function () {$location.url("404");}); diff --git a/src/main/webapp/assets/sass/contest-detail.sass b/src/main/webapp/assets/sass/contest-detail.sass index 4de66e0b3..788904031 100644 --- a/src/main/webapp/assets/sass/contest-detail.sass +++ b/src/main/webapp/assets/sass/contest-detail.sass @@ -34,6 +34,24 @@ font-size: 18px font-weight: 400 text-transform: capitalize + .header-page + h2 + span + border-radius: 4px + padding: 0 4px + color: #fff + font-size: 14px + font-style: italic + span.registration + background-color: #1ea185 + span.idea + background-color: #9bba5c + span.uiux + background-color: #f29b27 + span.prototype + background-color: #bd392f + span.final + background-color: #257abb .contest-name width: 100% display: inline-block From 47b75ebf67ea41415aa15354ffb51e50cf455c45 Mon Sep 17 00:00:00 2001 From: johnsonpham Date: Mon, 19 Oct 2015 11:19:31 +0700 Subject: [PATCH 16/80] translate for selectbox email template --- .../assets/modules/common/resourcesService.js | 3 +-- .../assets/modules/translation/messages_vi.json | 16 ++++++++-------- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/src/main/webapp/assets/modules/common/resourcesService.js b/src/main/webapp/assets/modules/common/resourcesService.js index bcfc3e560..616ea68a5 100644 --- a/src/main/webapp/assets/modules/common/resourcesService.js +++ b/src/main/webapp/assets/modules/common/resourcesService.js @@ -27,8 +27,7 @@ techlooper.factory("resourcesService", function ($translate, $q) { var emailTemplateOptions = [ {translate: "welcomeContestant", id: "welcomeContestant"}, {translate: "askContestantSubmission", id: "askContestantSubmission"}, - {translate: "disqualifyContestant", id: "disqualifyContestant"}, - {translate: "winnerAnnouncement", id: "winnerAnnouncement"} + {translate: "disqualifyContestant", id: "disqualifyContestant"} ]; var paymentOptions = [ diff --git a/src/main/webapp/assets/modules/translation/messages_vi.json b/src/main/webapp/assets/modules/translation/messages_vi.json index 18b45eea1..eb2970389 100644 --- a/src/main/webapp/assets/modules/translation/messages_vi.json +++ b/src/main/webapp/assets/modules/translation/messages_vi.json @@ -780,14 +780,14 @@ "allSubmission": "Tất cả bài nộp", "404Error": "URL này dẫn đến trang không tồn tại (lỗi 404). Xin vui lòng kiểm tra lại.", "cannotSendMail": "Bạn không có quyền thực hiện hành động này.", - "template": "Template:", - "welcomeContestant": "Welcome new contestant", - "askContestantSubmission": "Ask for submission", - "disqualifyContestant": "Disqualify a contestant", + "template": "Mẫu Email:", + "welcomeContestant": "Chào mừng thí sinh mới", + "askContestantSubmission": "Yêu cầu về bài gửi", + "disqualifyContestant": "Loại bỏ thí sinh", "winnerAnnouncement": "Winner announcement", - "exChooseATemplate": "choose a template", - "points": "Points", - "comment": "Comment", - "totalPoints": "Total Points" + "exChooseATemplate": "Lựa chọn mẫu Email", + "points": "Điểm", + "comment": "Nhận xét", + "totalPoints": "Tổng Điểm" } From cadd0d6c764e74929f8cf45a6ab9a6e7551798bb Mon Sep 17 00:00:00 2001 From: khoa-nd Date: Mon, 19 Oct 2015 11:51:33 +0700 Subject: [PATCH 17/80] Filter for "Registration" phase in the registrant list --- .../com/techlooper/service/impl/ChallengeServiceImpl.java | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java index 9b8af69ed..6ac78f0ea 100644 --- a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java @@ -655,12 +655,13 @@ public List filterChallengeRegistrantByDate(Registran } else { NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeRegistrant"); BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); + final String registrationPhase = ChallengePhaseEnum.REGISTRATION.getValue(); if (condition.getChallengeId() != null) { boolQueryBuilder.must(termQuery("challengeId", condition.getChallengeId())); } - if (StringUtils.isNotEmpty(condition.getPhase())) { + if (StringUtils.isNotEmpty(condition.getPhase()) && !registrationPhase.equals(condition.getPhase())) { boolQueryBuilder.must(matchPhraseQuery("activePhase", condition.getPhase())); } @@ -683,6 +684,11 @@ public List filterChallengeRegistrantByDate(Registran searchQueryBuilder.withQuery(boolQueryBuilder); result.addAll(DataUtils.getAllEntities(challengeRegistrantRepository, searchQueryBuilder)); + + if (registrationPhase.equals(condition.getPhase())) { + result = result.stream().filter(registrantEntity -> registrantEntity.getActivePhase() == null + || registrationPhase.equals(registrantEntity.getActivePhase().getValue())).collect(toList()); + } } return result; From 106c53f9744bd535fe5b0e2733b3e1bad22b7996 Mon Sep 17 00:00:00 2001 From: Phuong H Date: Mon, 19 Oct 2015 15:07:40 +0700 Subject: [PATCH 18/80] Add challenge criteria service --- .../techlooper/entity/ChallengeCriteria.java | 26 +++++++ .../model/ChallengeCriteriaDto.java | 26 +++++++ .../impl/ChallengeCriteriaServiceImpl.java | 18 ++++- .../resources/google-auth/StoredCredential | Bin 82 -> 0 bytes .../ChallengeServiceConfigurationTest.java | 28 -------- .../ChallengeCriteriaServiceImplTest.java | 64 ++++++++++++++++++ .../impl/ChallengeServiceImplTest.java | 4 +- 7 files changed, 134 insertions(+), 32 deletions(-) delete mode 100644 src/main/test/resources/google-auth/StoredCredential delete mode 100644 src/test/java/com/techlooper/config/ChallengeServiceConfigurationTest.java create mode 100644 src/test/java/com/techlooper/service/impl/ChallengeCriteriaServiceImplTest.java diff --git a/src/main/java/com/techlooper/entity/ChallengeCriteria.java b/src/main/java/com/techlooper/entity/ChallengeCriteria.java index 2c211ede7..2aaa18da7 100644 --- a/src/main/java/com/techlooper/entity/ChallengeCriteria.java +++ b/src/main/java/com/techlooper/entity/ChallengeCriteria.java @@ -26,4 +26,30 @@ public Long getWeight() { public void setWeight(Long weight) { this.weight = weight; } + + public static class ChallengeCriteriaBuilder { + private ChallengeCriteria challengeCriteria; + + private ChallengeCriteriaBuilder() { + challengeCriteria = new ChallengeCriteria(); + } + + public ChallengeCriteriaBuilder withName(String name) { + challengeCriteria.name = name; + return this; + } + + public ChallengeCriteriaBuilder withWeight(Long weight) { + challengeCriteria.weight = weight; + return this; + } + + public static ChallengeCriteriaBuilder challengeCriteria() { + return new ChallengeCriteriaBuilder(); + } + + public ChallengeCriteria build() { + return challengeCriteria; + } + } } diff --git a/src/main/java/com/techlooper/model/ChallengeCriteriaDto.java b/src/main/java/com/techlooper/model/ChallengeCriteriaDto.java index c40b796ff..feaaffb51 100644 --- a/src/main/java/com/techlooper/model/ChallengeCriteriaDto.java +++ b/src/main/java/com/techlooper/model/ChallengeCriteriaDto.java @@ -29,4 +29,30 @@ public Set getChallengeCriterias() { public void setChallengeCriterias(Set challengeCriterias) { this.challengeCriterias = challengeCriterias; } + + public static class ChallengeCriteriaDtoBuilder { + private ChallengeCriteriaDto challengeCriteriaDto; + + private ChallengeCriteriaDtoBuilder() { + challengeCriteriaDto = new ChallengeCriteriaDto(); + } + + public ChallengeCriteriaDtoBuilder withChallengeId(Long challengeId) { + challengeCriteriaDto.challengeId = challengeId; + return this; + } + + public ChallengeCriteriaDtoBuilder withChallengeCriterias(Set challengeCriterias) { + challengeCriteriaDto.challengeCriterias = challengeCriterias; + return this; + } + + public static ChallengeCriteriaDtoBuilder challengeCriteriaDto() { + return new ChallengeCriteriaDtoBuilder(); + } + + public ChallengeCriteriaDto build() { + return challengeCriteriaDto; + } + } } diff --git a/src/main/java/com/techlooper/service/impl/ChallengeCriteriaServiceImpl.java b/src/main/java/com/techlooper/service/impl/ChallengeCriteriaServiceImpl.java index 2d8e13b8c..6781396e2 100644 --- a/src/main/java/com/techlooper/service/impl/ChallengeCriteriaServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/ChallengeCriteriaServiceImpl.java @@ -2,11 +2,16 @@ import com.techlooper.entity.ChallengeCriteria; import com.techlooper.entity.ChallengeEntity; +import com.techlooper.entity.ChallengeRegistrantEntity; import com.techlooper.model.ChallengeCriteriaDto; +import com.techlooper.repository.elasticsearch.ChallengeRegistrantRepository; import com.techlooper.repository.elasticsearch.ChallengeRepository; import com.techlooper.service.ChallengeCriteriaService; import com.techlooper.service.ChallengeService; -import org.dozer.Mapper; +import org.apache.lucene.queryparser.xml.QueryBuilder; +import org.apache.lucene.queryparser.xml.builders.TermQueryBuilder; +import org.apache.lucene.search.TermQuery; +import org.elasticsearch.index.query.QueryBuilders; import org.springframework.stereotype.Service; import javax.annotation.Resource; @@ -26,7 +31,7 @@ public class ChallengeCriteriaServiceImpl implements ChallengeCriteriaService { private ChallengeService challengeService; @Resource - private Mapper dozerMapper; + private ChallengeRegistrantRepository challengeRegistrantRepository; public ChallengeEntity saveChallengeCriterias(ChallengeCriteriaDto challengeCriteriaDto, String ownerEmail) { ChallengeEntity challenge = challengeService.findChallengeIdAndOwnerEmail(challengeCriteriaDto.getChallengeId(), ownerEmail); @@ -37,6 +42,15 @@ public ChallengeEntity saveChallengeCriterias(ChallengeCriteriaDto challengeCrit Set criterias = new HashSet<>(); challengeCriteriaDto.getChallengeCriterias().forEach(criterias::add); challenge.setChallengeCriterias(criterias); + + //TODO update to all registrants + challengeRegistrantRepository.search(QueryBuilders.termQuery("challengeId", challengeCriteriaDto.getChallengeId())) + .forEach(challengeRegistrantEntity -> { + challengeRegistrantEntity + }); + + + return challengeRepository.save(challenge); } } diff --git a/src/main/test/resources/google-auth/StoredCredential b/src/main/test/resources/google-auth/StoredCredential deleted file mode 100644 index c5975123e324fcbdfc5624e1442489e4e62468d6..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 82 zcmZ4UmVvdnh(Rzbu`E%qv?Mb}&m*xo!#A;jmHpPi!(s^+nHiYe7`Srs6I0w0lS}f8 eJQ+AkGKx}*GxBp%Dhli!7{H*M14s#gm=yqSWEX`1 diff --git a/src/test/java/com/techlooper/config/ChallengeServiceConfigurationTest.java b/src/test/java/com/techlooper/config/ChallengeServiceConfigurationTest.java deleted file mode 100644 index 366f567a8..000000000 --- a/src/test/java/com/techlooper/config/ChallengeServiceConfigurationTest.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.techlooper.config; - -import com.techlooper.converter.LocaleConverter; -import com.techlooper.service.ProjectService; -import com.techlooper.service.impl.ProjectServiceImpl; -import org.dozer.DozerBeanMapper; -import org.dozer.Mapper; -import org.dozer.loader.api.BeanMappingBuilder; -import org.dozer.loader.api.FieldsMappingOptions; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.context.annotation.PropertySources; -import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; -import org.springframework.social.facebook.api.FacebookProfile; - -/** - * Created by NguyenDangKhoa on 7/13/15. - */ -@Configuration -@PropertySources({@PropertySource("classpath:techlooper.properties")}) -public class ChallengeServiceConfigurationTest { - - @Bean - public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { - return new PropertySourcesPlaceholderConfigurer(); - } -} diff --git a/src/test/java/com/techlooper/service/impl/ChallengeCriteriaServiceImplTest.java b/src/test/java/com/techlooper/service/impl/ChallengeCriteriaServiceImplTest.java new file mode 100644 index 000000000..3ae489e11 --- /dev/null +++ b/src/test/java/com/techlooper/service/impl/ChallengeCriteriaServiceImplTest.java @@ -0,0 +1,64 @@ +package com.techlooper.service.impl; + +import com.techlooper.config.BaseConfigurationTest; +import com.techlooper.config.ElasticsearchConfiguration; +import com.techlooper.entity.ChallengeCriteria; +import com.techlooper.entity.ChallengeEntity; +import com.techlooper.model.ChallengeCriteriaDto; +import com.techlooper.repository.elasticsearch.ChallengeRepository; +import com.techlooper.service.ChallengeCriteriaService; +import com.techlooper.service.ChallengeService; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.util.ReflectionTestUtils; + +import javax.annotation.Resource; +import java.util.HashSet; +import java.util.Set; + +/** + * Created by phuonghqh on 10/19/15. + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {BaseConfigurationTest.class, ElasticsearchConfiguration.class}) +public class ChallengeCriteriaServiceImplTest { + + private ChallengeCriteriaService challengeCriteriaService; + + private ChallengeService challengeService; + + @Resource + private ChallengeRepository challengeRepository; + + @Before + public void before() { + challengeService = new ChallengeServiceImpl(); + ReflectionTestUtils.setField(challengeService, "challengeRepository", challengeRepository); + + challengeCriteriaService = new ChallengeCriteriaServiceImpl(); + ReflectionTestUtils.setField(challengeCriteriaService, "challengeService", challengeService); + ReflectionTestUtils.setField(challengeCriteriaService, "challengeRepository", challengeRepository); + } + + @Test + public void testSaveChallengeCriterias() { + Long id = 1444017901257L; + String owner = "thu.hoang@navigosgroup.com"; + + Set challengeCriterias = new HashSet<>(); + for (int i = 0; i < 5; i++) { + challengeCriterias.add(ChallengeCriteria.ChallengeCriteriaBuilder.challengeCriteria() + .withName("name 1").withWeight(Long.valueOf(i + 10)).build()); + } + + ChallengeCriteriaDto challengeCriteriaDto = ChallengeCriteriaDto.ChallengeCriteriaDtoBuilder.challengeCriteriaDto() + .withChallengeId(id).withChallengeCriterias(challengeCriterias).build(); + + ChallengeEntity challenge = challengeCriteriaService.saveChallengeCriterias(challengeCriteriaDto, owner); + Assert.assertTrue(challenge.getChallengeCriterias().size() >= 5); + } +} diff --git a/src/test/java/com/techlooper/service/impl/ChallengeServiceImplTest.java b/src/test/java/com/techlooper/service/impl/ChallengeServiceImplTest.java index a23151c2a..791df477d 100644 --- a/src/test/java/com/techlooper/service/impl/ChallengeServiceImplTest.java +++ b/src/test/java/com/techlooper/service/impl/ChallengeServiceImplTest.java @@ -1,6 +1,6 @@ package com.techlooper.service.impl; -import com.techlooper.config.ChallengeServiceConfigurationTest; +import com.techlooper.config.BaseConfigurationTest; import com.techlooper.config.ElasticsearchConfiguration; import com.techlooper.entity.ChallengeRegistrantEntity; import com.techlooper.model.Language; @@ -16,7 +16,7 @@ import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {ElasticsearchConfiguration.class, ChallengeServiceConfigurationTest.class}) +@ContextConfiguration(classes = {ElasticsearchConfiguration.class, BaseConfigurationTest.class}) public class ChallengeServiceImplTest { private static final int NUMBER_OF_ITEMS = 50; From c9466f5c357295995465fa5753f2c9e5d7eef40e Mon Sep 17 00:00:00 2001 From: Phuong H Date: Mon, 19 Oct 2015 15:08:25 +0700 Subject: [PATCH 19/80] Fix build fail --- .../techlooper/service/impl/ChallengeCriteriaServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/techlooper/service/impl/ChallengeCriteriaServiceImpl.java b/src/main/java/com/techlooper/service/impl/ChallengeCriteriaServiceImpl.java index 6781396e2..08be9d708 100644 --- a/src/main/java/com/techlooper/service/impl/ChallengeCriteriaServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/ChallengeCriteriaServiceImpl.java @@ -46,7 +46,7 @@ public ChallengeEntity saveChallengeCriterias(ChallengeCriteriaDto challengeCrit //TODO update to all registrants challengeRegistrantRepository.search(QueryBuilders.termQuery("challengeId", challengeCriteriaDto.getChallengeId())) .forEach(challengeRegistrantEntity -> { - challengeRegistrantEntity +// challengeRegistrantEntity }); From 64fed0463a962edace7135f18bf4d81f2fd4cabe Mon Sep 17 00:00:00 2001 From: Phuong H Date: Mon, 19 Oct 2015 15:41:10 +0700 Subject: [PATCH 20/80] Add default criterias to challenge-publish function --- .../service/impl/ChallengeServiceImpl.java | 1551 +++++++++-------- 1 file changed, 788 insertions(+), 763 deletions(-) diff --git a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java index 6ac78f0ea..d65d05525 100644 --- a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java @@ -1,9 +1,6 @@ package com.techlooper.service.impl; -import com.techlooper.entity.ChallengeEntity; -import com.techlooper.entity.ChallengeRegistrantDto; -import com.techlooper.entity.ChallengeRegistrantEntity; -import com.techlooper.entity.ChallengeSubmissionEntity; +import com.techlooper.entity.*; import com.techlooper.model.*; import com.techlooper.repository.elasticsearch.ChallengeRegistrantRepository; import com.techlooper.repository.elasticsearch.ChallengeRepository; @@ -64,271 +61,289 @@ @Service public class ChallengeServiceImpl implements ChallengeService { - private final static Logger LOGGER = LoggerFactory.getLogger(ChallengeServiceImpl.class); + private final static Logger LOGGER = LoggerFactory.getLogger(ChallengeServiceImpl.class); - private final static ChallengePhaseEnum CHALLENGE_TIMELINE[] = { - ChallengePhaseEnum.FINAL, - ChallengePhaseEnum.PROTOTYPE, - ChallengePhaseEnum.UIUX, - ChallengePhaseEnum.IDEA, - ChallengePhaseEnum.REGISTRATION - }; + private final static ChallengePhaseEnum CHALLENGE_TIMELINE[] = { + ChallengePhaseEnum.FINAL, + ChallengePhaseEnum.PROTOTYPE, + ChallengePhaseEnum.UIUX, + ChallengePhaseEnum.IDEA, + ChallengePhaseEnum.REGISTRATION + }; - @Resource - private ElasticsearchTemplate elasticsearchTemplateUserImport; + @Resource + private ElasticsearchTemplate elasticsearchTemplateUserImport; - @Resource - private MimeMessage postChallengeMailMessage; + @Resource + private MimeMessage postChallengeMailMessage; - @Resource - private Template postChallengeMailTemplateEn; + @Resource + private Template postChallengeMailTemplateEn; - @Resource - private Template postChallengeUpdateMailTemplateEn; + @Resource + private Template postChallengeUpdateMailTemplateEn; - @Resource - private Template postChallengeMailTemplateVi; + @Resource + private Template postChallengeMailTemplateVi; - @Value("${mail.postChallenge.subject.vn}") - private String postChallengeMailSubjectVn; + @Value("${mail.postChallenge.subject.vn}") + private String postChallengeMailSubjectVn; - @Value("${mail.postChallenge.subject.en}") - private String postChallengeMailSubjectEn; + @Value("${mail.postChallenge.subject.en}") + private String postChallengeMailSubjectEn; - @Value("${mail.postChallenge.techloopies.mailSubject}") - private String postChallengeTechloopiesMailSubject; + @Value("${mail.postChallenge.techloopies.mailSubject}") + private String postChallengeTechloopiesMailSubject; - @Value("${mail.postChallenge.techloopies.updateMailSubject}") - private String postChallengeTechloopiesUpdateMailSubject; + @Value("${mail.postChallenge.techloopies.updateMailSubject}") + private String postChallengeTechloopiesUpdateMailSubject; - @Value("${mail.postChallenge.techloopies.mailList}") - private String postChallengeTechloopiesMailList; + @Value("${mail.postChallenge.techloopies.mailList}") + private String postChallengeTechloopiesMailList; - @Value("${web.baseUrl}") - private String webBaseUrl; + @Value("${web.baseUrl}") + private String webBaseUrl; - @Resource - private Template confirmUserJoinChallengeMailTemplateEn; + @Resource + private Template confirmUserJoinChallengeMailTemplateEn; - @Resource - private Template confirmUserJoinChallengeMailTemplateVi; + @Resource + private Template confirmUserJoinChallengeMailTemplateVi; - @Value("${mail.confirmUserJoinChallenge.subject.vn}") - private String confirmUserJoinChallengeMailSubjectVn; + @Value("${mail.confirmUserJoinChallenge.subject.vn}") + private String confirmUserJoinChallengeMailSubjectVn; - @Value("${mail.confirmUserJoinChallenge.subject.en}") - private String confirmUserJoinChallengeMailSubjectEn; + @Value("${mail.confirmUserJoinChallenge.subject.en}") + private String confirmUserJoinChallengeMailSubjectEn; - @Resource - private Template alertEmployerChallengeMailTemplateEn; + @Resource + private Template alertEmployerChallengeMailTemplateEn; - @Resource - private Template alertEmployerChallengeMailTemplateVi; + @Resource + private Template alertEmployerChallengeMailTemplateVi; - @Value("${mail.alertEmployerChallenge.subject.vn}") - private String alertEmployerChallengeMailSubjectVn; + @Value("${mail.alertEmployerChallenge.subject.vn}") + private String alertEmployerChallengeMailSubjectVn; - @Value("${mail.alertEmployerChallenge.subject.en}") - private String alertEmployerChallengeMailSubjectEn; + @Value("${mail.alertEmployerChallenge.subject.en}") + private String alertEmployerChallengeMailSubjectEn; - @Value("${mail.techlooper.reply_to}") - private String mailTechlooperReplyTo; + @Value("${mail.techlooper.reply_to}") + private String mailTechlooperReplyTo; - @Resource - private JavaMailSender mailSender; + @Resource + private JavaMailSender mailSender; - @Resource - private ChallengeRepository challengeRepository; + @Resource + private ChallengeRepository challengeRepository; - @Resource - private ChallengeRegistrantRepository challengeRegistrantRepository; + @Resource + private ChallengeRegistrantRepository challengeRegistrantRepository; - @Resource - private ChallengeSubmissionRepository challengeSubmissionRepository; + @Resource + private ChallengeSubmissionRepository challengeSubmissionRepository; - @Resource - private Mapper dozerMapper; + @Resource + private Mapper dozerMapper; - @Value("${elasticsearch.userimport.index.name}") - private String techlooperIndex; + @Value("${elasticsearch.userimport.index.name}") + private String techlooperIndex; - @Value("${mail.notifyChallengeTimelineRegistration.subject.vn}") - private String notifyChallengeTimelineRegistrationMailSubjectVn; + @Value("${mail.notifyChallengeTimelineRegistration.subject.vn}") + private String notifyChallengeTimelineRegistrationMailSubjectVn; - @Value("${mail.notifyChallengeTimelineRegistration.subject.en}") - private String notifyChallengeTimelineRegistrationMailSubjectEn; + @Value("${mail.notifyChallengeTimelineRegistration.subject.en}") + private String notifyChallengeTimelineRegistrationMailSubjectEn; - @Value("${mail.notifyChallengeTimelineInProgress.subject.vn}") - private String notifyChallengeTimelineInProgressMailSubjectVn; + @Value("${mail.notifyChallengeTimelineInProgress.subject.vn}") + private String notifyChallengeTimelineInProgressMailSubjectVn; - @Value("${mail.notifyChallengeTimelineInProgress.subject.en}") - private String notifyChallengeTimelineInProgressMailSubjectEn; + @Value("${mail.notifyChallengeTimelineInProgress.subject.en}") + private String notifyChallengeTimelineInProgressMailSubjectEn; - @Value("${mail.dailyChallengeSummary.subject.en}") - private String dailyChallengeSummaryMailSubjectEn; + @Value("${mail.dailyChallengeSummary.subject.en}") + private String dailyChallengeSummaryMailSubjectEn; - @Value("${mail.dailyChallengeSummary.subject.vi}") - private String dailyChallengeSummaryMailSubjectVi; + @Value("${mail.dailyChallengeSummary.subject.vi}") + private String dailyChallengeSummaryMailSubjectVi; - @Resource - private Template notifyChallengeTimelineMailTemplateVi; + @Resource + private Template notifyChallengeTimelineMailTemplateVi; - @Resource - private Template notifyChallengeTimelineMailTemplateEn; + @Resource + private Template notifyChallengeTimelineMailTemplateEn; - @Resource - private Template dailyChallengeSummaryMailTemplateVi; + @Resource + private Template dailyChallengeSummaryMailTemplateVi; - @Resource - private Template dailyChallengeSummaryMailTemplateEn; + @Resource + private Template dailyChallengeSummaryMailTemplateEn; - @Resource - private EmailService emailService; + @Resource + private EmailService emailService; - public ChallengeEntity savePostChallenge(ChallengeDto challengeDto) throws Exception { - ChallengeEntity challengeEntity = dozerMapper.map(challengeDto, ChallengeEntity.class); - if (challengeDto.getChallengeId() == null) { - challengeEntity.setChallengeId(new Date().getTime()); - } - return challengeRepository.save(challengeEntity); + public ChallengeEntity savePostChallenge(ChallengeDto challengeDto) throws Exception { + ChallengeEntity challengeEntity = dozerMapper.map(challengeDto, ChallengeEntity.class); + if (challengeDto.getChallengeId() == null) { + challengeEntity.setChallengeId(new Date().getTime()); } - public void sendPostChallengeEmailToEmployer(ChallengeEntity challengeEntity) - throws MessagingException, IOException, TemplateException { - String mailSubject = challengeEntity.getLang() == Language.vi ? postChallengeMailSubjectVn : postChallengeMailSubjectEn; - Address[] recipientAddresses = getRecipientAddresses(challengeEntity, true); - Template template = challengeEntity.getLang() == Language.vi ? postChallengeMailTemplateVi : postChallengeMailTemplateEn; - sendPostChallengeEmail(challengeEntity, mailSubject, recipientAddresses, template); + Set defaultCriterias = new HashSet<>(); + defaultCriterias.add(ChallengeCriteria.ChallengeCriteriaBuilder.challengeCriteria() + .withName("UI/UX implemented solution").withWeight(25L).build()); + defaultCriterias.add(ChallengeCriteria.ChallengeCriteriaBuilder.challengeCriteria() + .withName("Creativity on the proposed solution").withWeight(25L).build()); + defaultCriterias.add(ChallengeCriteria.ChallengeCriteriaBuilder.challengeCriteria() + .withName("Source code quality").withWeight(25L).build()); + defaultCriterias.add(ChallengeCriteria.ChallengeCriteriaBuilder.challengeCriteria() + .withName("Usage of top edge technology").withWeight(25L).build()); + defaultCriterias.add(ChallengeCriteria.ChallengeCriteriaBuilder.challengeCriteria() + .withName("Application functionality").withWeight(25L).build()); + + return challengeRepository.save(challengeEntity); + } + + public void sendPostChallengeEmailToEmployer(ChallengeEntity challengeEntity) + throws MessagingException, IOException, TemplateException { + String mailSubject = challengeEntity.getLang() == Language.vi ? postChallengeMailSubjectVn : postChallengeMailSubjectEn; + Address[] recipientAddresses = getRecipientAddresses(challengeEntity, true); + Template template = challengeEntity.getLang() == Language.vi ? postChallengeMailTemplateVi : postChallengeMailTemplateEn; + sendPostChallengeEmail(challengeEntity, mailSubject, recipientAddresses, template); + } + + public void sendPostChallengeEmailToTechloopies(ChallengeEntity challengeEntity, Boolean isNewChallenge) + throws MessagingException, IOException, TemplateException { + String mailSubject = isNewChallenge ? postChallengeTechloopiesMailSubject : + String.format(postChallengeTechloopiesUpdateMailSubject, challengeEntity.getChallengeName()); + Template mailTemplate = isNewChallenge ? postChallengeMailTemplateEn : postChallengeUpdateMailTemplateEn; + Address[] recipientAddresses = InternetAddress.parse(postChallengeTechloopiesMailList); + sendPostChallengeEmail(challengeEntity, mailSubject, recipientAddresses, mailTemplate); + } + + @Override + public void sendEmailNotifyRegistrantAboutChallengeTimeline(ChallengeEntity challengeEntity, + ChallengeRegistrantEntity challengeRegistrantEntity, ChallengePhaseEnum challengePhase) throws Exception { + String mailSubject = getNotifyRegistrantChallengeTimelineSubject(challengeRegistrantEntity, challengePhase); + Address[] recipientAddresses = InternetAddress.parse(challengeRegistrantEntity.getRegistrantEmail()); + Template template = challengeRegistrantEntity.getLang() == Language.vi ? + notifyChallengeTimelineMailTemplateVi : notifyChallengeTimelineMailTemplateEn; + postChallengeMailMessage.setRecipients(Message.RecipientType.TO, recipientAddresses); + postChallengeMailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); + StringWriter stringWriter = new StringWriter(); + + Map templateModel = new HashMap<>(); + templateModel.put("challengeEntity", challengeEntity); + templateModel.put("webBaseUrl", webBaseUrl); + templateModel.put("technologies", StringUtils.join(challengeEntity.getTechnologies(), "
    ")); + templateModel.put("receivedEmails", StringUtils.join(challengeEntity.getReceivedEmails(), "
    ")); + templateModel.put("firstPlaceReward", challengeEntity.getFirstPlaceReward() != null ? challengeEntity.getFirstPlaceReward() : 0); + templateModel.put("secondPlaceReward", challengeEntity.getSecondPlaceReward() != null ? challengeEntity.getSecondPlaceReward() : 0); + templateModel.put("thirdPlaceReward", challengeEntity.getThirdPlaceReward() != null ? challengeEntity.getThirdPlaceReward() : 0); + templateModel.put("challengeId", challengeEntity.getChallengeId().toString()); + templateModel.put("challengeNameAlias", challengeEntity.getChallengeName().replaceAll("\\W", "-")); + + int numberOfDays = 0; + if (challengePhase == ChallengePhaseEnum.REGISTRATION) { + numberOfDays = daysBetween(currentDate(), challengeEntity.getRegistrationDateTime()) + 1; } - - public void sendPostChallengeEmailToTechloopies(ChallengeEntity challengeEntity, Boolean isNewChallenge) - throws MessagingException, IOException, TemplateException { - String mailSubject = isNewChallenge ? postChallengeTechloopiesMailSubject : - String.format(postChallengeTechloopiesUpdateMailSubject, challengeEntity.getChallengeName()); - Template mailTemplate = isNewChallenge ? postChallengeMailTemplateEn : postChallengeUpdateMailTemplateEn; - Address[] recipientAddresses = InternetAddress.parse(postChallengeTechloopiesMailList); - sendPostChallengeEmail(challengeEntity, mailSubject, recipientAddresses, mailTemplate); + else if (challengePhase == ChallengePhaseEnum.IN_PROGRESS) { + numberOfDays = daysBetween(currentDate(), challengeEntity.getSubmissionDateTime()) + 1; } - @Override - public void sendEmailNotifyRegistrantAboutChallengeTimeline(ChallengeEntity challengeEntity, - ChallengeRegistrantEntity challengeRegistrantEntity, ChallengePhaseEnum challengePhase) throws Exception { - String mailSubject = getNotifyRegistrantChallengeTimelineSubject(challengeRegistrantEntity, challengePhase); - Address[] recipientAddresses = InternetAddress.parse(challengeRegistrantEntity.getRegistrantEmail()); - Template template = challengeRegistrantEntity.getLang() == Language.vi ? - notifyChallengeTimelineMailTemplateVi : notifyChallengeTimelineMailTemplateEn; - postChallengeMailMessage.setRecipients(Message.RecipientType.TO, recipientAddresses); - postChallengeMailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); - StringWriter stringWriter = new StringWriter(); - - Map templateModel = new HashMap<>(); - templateModel.put("challengeEntity", challengeEntity); - templateModel.put("webBaseUrl", webBaseUrl); - templateModel.put("technologies", StringUtils.join(challengeEntity.getTechnologies(), "
    ")); - templateModel.put("receivedEmails", StringUtils.join(challengeEntity.getReceivedEmails(), "
    ")); - templateModel.put("firstPlaceReward", challengeEntity.getFirstPlaceReward() != null ? challengeEntity.getFirstPlaceReward() : 0); - templateModel.put("secondPlaceReward", challengeEntity.getSecondPlaceReward() != null ? challengeEntity.getSecondPlaceReward() : 0); - templateModel.put("thirdPlaceReward", challengeEntity.getThirdPlaceReward() != null ? challengeEntity.getThirdPlaceReward() : 0); - templateModel.put("challengeId", challengeEntity.getChallengeId().toString()); - templateModel.put("challengeNameAlias", challengeEntity.getChallengeName().replaceAll("\\W", "-")); - - int numberOfDays = 0; - if (challengePhase == ChallengePhaseEnum.REGISTRATION) { - numberOfDays = daysBetween(currentDate(), challengeEntity.getRegistrationDateTime()) + 1; - } else if (challengePhase == ChallengePhaseEnum.IN_PROGRESS) { - numberOfDays = daysBetween(currentDate(), challengeEntity.getSubmissionDateTime()) + 1; - } - - templateModel.put("numberOfDays", numberOfDays); - templateModel.put("challengePhase", challengePhase.getValue()); - templateModel.put("challengeRegistrant", challengeRegistrantEntity); - - template.process(templateModel, stringWriter); - mailSubject = String.format(mailSubject, numberOfDays, challengeEntity.getChallengeName()); - postChallengeMailMessage.setSubject(MimeUtility.encodeText(mailSubject, "UTF-8", null)); - postChallengeMailMessage.setText(stringWriter.toString(), "UTF-8", "html"); - - stringWriter.flush(); - postChallengeMailMessage.saveChanges(); - mailSender.send(postChallengeMailMessage); - LOGGER.info(postChallengeMailMessage.getMessageID() + " has been sent to users " + - postChallengeMailMessage.getAllRecipients() + " with challengeId = " + challengeEntity.getChallengeId()); + templateModel.put("numberOfDays", numberOfDays); + templateModel.put("challengePhase", challengePhase.getValue()); + templateModel.put("challengeRegistrant", challengeRegistrantEntity); + + template.process(templateModel, stringWriter); + mailSubject = String.format(mailSubject, numberOfDays, challengeEntity.getChallengeName()); + postChallengeMailMessage.setSubject(MimeUtility.encodeText(mailSubject, "UTF-8", null)); + postChallengeMailMessage.setText(stringWriter.toString(), "UTF-8", "html"); + + stringWriter.flush(); + postChallengeMailMessage.saveChanges(); + mailSender.send(postChallengeMailMessage); + LOGGER.info(postChallengeMailMessage.getMessageID() + " has been sent to users " + + postChallengeMailMessage.getAllRecipients() + " with challengeId = " + challengeEntity.getChallengeId()); + } + + private String getNotifyRegistrantChallengeTimelineSubject( + ChallengeRegistrantEntity challengeRegistrantEntity, ChallengePhaseEnum challengePhase) { + if (challengeRegistrantEntity.getLang() == Language.vi) { + if (challengePhase == ChallengePhaseEnum.REGISTRATION) { + return notifyChallengeTimelineRegistrationMailSubjectVn; + } + else { + return notifyChallengeTimelineInProgressMailSubjectVn; + } } - - private String getNotifyRegistrantChallengeTimelineSubject( - ChallengeRegistrantEntity challengeRegistrantEntity, ChallengePhaseEnum challengePhase) { - if (challengeRegistrantEntity.getLang() == Language.vi) { - if (challengePhase == ChallengePhaseEnum.REGISTRATION) { - return notifyChallengeTimelineRegistrationMailSubjectVn; - } else { - return notifyChallengeTimelineInProgressMailSubjectVn; - } - } else { - if (challengePhase == ChallengePhaseEnum.REGISTRATION) { - return notifyChallengeTimelineRegistrationMailSubjectEn; - } else { - return notifyChallengeTimelineInProgressMailSubjectEn; - } - } + else { + if (challengePhase == ChallengePhaseEnum.REGISTRATION) { + return notifyChallengeTimelineRegistrationMailSubjectEn; + } + else { + return notifyChallengeTimelineInProgressMailSubjectEn; + } } - - public Long getNumberOfRegistrants(Long challengeId) { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withSearchType(SearchType.COUNT); - searchQueryBuilder.withFilter(FilterBuilders.termFilter("challengeId", challengeId)); - return challengeRegistrantRepository.search(searchQueryBuilder.build()).getTotalElements(); + } + + public Long getNumberOfRegistrants(Long challengeId) { + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withSearchType(SearchType.COUNT); + searchQueryBuilder.withFilter(FilterBuilders.termFilter("challengeId", challengeId)); + return challengeRegistrantRepository.search(searchQueryBuilder.build()).getTotalElements(); + } + + public void sendApplicationEmailToContestant(ChallengeEntity challengeEntity, ChallengeRegistrantEntity challengeRegistrantEntity) throws MessagingException, IOException, TemplateException { + Template template = challengeRegistrantEntity.getLang() == Language.vi ? + confirmUserJoinChallengeMailTemplateVi : confirmUserJoinChallengeMailTemplateEn; + String mailSubject = challengeRegistrantEntity.getLang() == Language.vi ? + confirmUserJoinChallengeMailSubjectVn : confirmUserJoinChallengeMailSubjectEn; + mailSubject = String.format(mailSubject, challengeEntity.getChallengeName()); + Address[] emailAddress = InternetAddress.parse(challengeRegistrantEntity.getRegistrantEmail()); + sendContestApplicationEmail(template, mailSubject, emailAddress, challengeEntity, challengeRegistrantEntity, false); + } + + public void sendApplicationEmailToEmployer(ChallengeEntity challengeEntity, ChallengeRegistrantEntity challengeRegistrantEntity) throws MessagingException, IOException, TemplateException { + Template template = challengeRegistrantEntity.getLang() == Language.vi ? + alertEmployerChallengeMailTemplateVi : alertEmployerChallengeMailTemplateEn; + String mailSubject = challengeRegistrantEntity.getLang() == Language.vi ? + alertEmployerChallengeMailSubjectVn : alertEmployerChallengeMailSubjectEn; + mailSubject = String.format(mailSubject, challengeEntity.getChallengeName()); + Address[] emailAddress = getRecipientAddresses(challengeEntity, false); + sendContestApplicationEmail(template, mailSubject, emailAddress, challengeEntity, challengeRegistrantEntity, true); + } + + public long joinChallenge(ChallengeRegistrantDto challengeRegistrantDto) { + ChallengeRegistrantEntity entity = joinChallengeEntity(challengeRegistrantDto); + if (entity != null) { + return getNumberOfRegistrants(challengeRegistrantDto.getChallengeId()); } - - public void sendApplicationEmailToContestant(ChallengeEntity challengeEntity, ChallengeRegistrantEntity challengeRegistrantEntity) throws MessagingException, IOException, TemplateException { - Template template = challengeRegistrantEntity.getLang() == Language.vi ? - confirmUserJoinChallengeMailTemplateVi : confirmUserJoinChallengeMailTemplateEn; - String mailSubject = challengeRegistrantEntity.getLang() == Language.vi ? - confirmUserJoinChallengeMailSubjectVn : confirmUserJoinChallengeMailSubjectEn; - mailSubject = String.format(mailSubject, challengeEntity.getChallengeName()); - Address[] emailAddress = InternetAddress.parse(challengeRegistrantEntity.getRegistrantEmail()); - sendContestApplicationEmail(template, mailSubject, emailAddress, challengeEntity, challengeRegistrantEntity, false); + return 0; + } + + public ChallengeRegistrantEntity joinChallengeEntity(ChallengeRegistrantDto challengeRegistrantDto) { + Long challengeId = challengeRegistrantDto.getChallengeId(); + boolean isExist = checkIfChallengeRegistrantExist(challengeId, challengeRegistrantDto.getRegistrantEmail()); + + if (!isExist) { + ChallengeRegistrantEntity challengeRegistrantEntity = dozerMapper.map(challengeRegistrantDto, ChallengeRegistrantEntity.class); + ChallengeEntity challengeEntity = challengeRepository.findOne(challengeId); + challengeRegistrantEntity.setRegistrantId(new Date().getTime()); + challengeRegistrantEntity = challengeRegistrantRepository.save(challengeRegistrantEntity); + try { + sendApplicationEmailToContestant(challengeEntity, challengeRegistrantEntity); + //sendApplicationEmailToEmployer(challengeEntity, challengeRegistrantEntity); + challengeRegistrantEntity.setMailSent(Boolean.TRUE); + return challengeRegistrantRepository.save(challengeRegistrantEntity); + } + catch (Exception e) { + LOGGER.debug("Can not send email", e); + } } - public void sendApplicationEmailToEmployer(ChallengeEntity challengeEntity, ChallengeRegistrantEntity challengeRegistrantEntity) throws MessagingException, IOException, TemplateException { - Template template = challengeRegistrantEntity.getLang() == Language.vi ? - alertEmployerChallengeMailTemplateVi : alertEmployerChallengeMailTemplateEn; - String mailSubject = challengeRegistrantEntity.getLang() == Language.vi ? - alertEmployerChallengeMailSubjectVn : alertEmployerChallengeMailSubjectEn; - mailSubject = String.format(mailSubject, challengeEntity.getChallengeName()); - Address[] emailAddress = getRecipientAddresses(challengeEntity, false); - sendContestApplicationEmail(template, mailSubject, emailAddress, challengeEntity, challengeRegistrantEntity, true); - } + return null; + } - public long joinChallenge(ChallengeRegistrantDto challengeRegistrantDto) { - ChallengeRegistrantEntity entity = joinChallengeEntity(challengeRegistrantDto); - if (entity != null) { - return getNumberOfRegistrants(challengeRegistrantDto.getChallengeId()); - } - return 0; - } - - public ChallengeRegistrantEntity joinChallengeEntity(ChallengeRegistrantDto challengeRegistrantDto) { - Long challengeId = challengeRegistrantDto.getChallengeId(); - boolean isExist = checkIfChallengeRegistrantExist(challengeId, challengeRegistrantDto.getRegistrantEmail()); - - if (!isExist) { - ChallengeRegistrantEntity challengeRegistrantEntity = dozerMapper.map(challengeRegistrantDto, ChallengeRegistrantEntity.class); - ChallengeEntity challengeEntity = challengeRepository.findOne(challengeId); - challengeRegistrantEntity.setRegistrantId(new Date().getTime()); - challengeRegistrantEntity = challengeRegistrantRepository.save(challengeRegistrantEntity); - try { - sendApplicationEmailToContestant(challengeEntity, challengeRegistrantEntity); - //sendApplicationEmailToEmployer(challengeEntity, challengeRegistrantEntity); - challengeRegistrantEntity.setMailSent(Boolean.TRUE); - return challengeRegistrantRepository.save(challengeRegistrantEntity); - } catch (Exception e) { - LOGGER.debug("Can not send email", e); - } - } - - return null; - } - - public List listChallenges() { + public List listChallenges() { // List challenges = new ArrayList<>(); // Iterator challengeIter = challengeRepository.findAll().iterator(); // while (challengeIter.hasNext()) { @@ -338,168 +353,173 @@ public List listChallenges() { // challenges.add(challengeDetailDto); // } // return sortChallengesByDescendingStartDate(challenges); - TermQueryBuilder notExpiredQuery = termQuery("expired", Boolean.TRUE); - Iterable challengeIterator = challengeRepository.search(boolQuery().mustNot(notExpiredQuery)); - ArrayList challenges = new ArrayList<>(); - challengeIterator.forEach(challengeEntity -> { - ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); - challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeEntity.getChallengeId())); - challenges.add(challengeDetailDto); - }); - return sortChallengesByDescendingStartDate(challenges); + TermQueryBuilder notExpiredQuery = termQuery("expired", Boolean.TRUE); + Iterable challengeIterator = challengeRepository.search(boolQuery().mustNot(notExpiredQuery)); + ArrayList challenges = new ArrayList<>(); + challengeIterator.forEach(challengeEntity -> { + ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); + challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeEntity.getChallengeId())); + challenges.add(challengeDetailDto); + }); + return sortChallengesByDescendingStartDate(challenges); + } + + private void sendContestApplicationEmail(Template template, String mailSubject, Address[] recipientAddresses, + ChallengeEntity challengeEntity, ChallengeRegistrantEntity challengeRegistrantEntity, boolean hasReplyTo) + throws MessagingException, IOException, TemplateException { + postChallengeMailMessage.setRecipients(Message.RecipientType.TO, recipientAddresses); + + if (hasReplyTo) { + postChallengeMailMessage.setReplyTo(InternetAddress.parse(challengeRegistrantEntity.getRegistrantEmail())); } - - private void sendContestApplicationEmail(Template template, String mailSubject, Address[] recipientAddresses, - ChallengeEntity challengeEntity, ChallengeRegistrantEntity challengeRegistrantEntity, boolean hasReplyTo) - throws MessagingException, IOException, TemplateException { - postChallengeMailMessage.setRecipients(Message.RecipientType.TO, recipientAddresses); - - if (hasReplyTo) { - postChallengeMailMessage.setReplyTo(InternetAddress.parse(challengeRegistrantEntity.getRegistrantEmail())); - } else { - postChallengeMailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); - } - - StringWriter stringWriter = new StringWriter(); - Map templateModel = new HashMap<>(); - templateModel.put("webBaseUrl", webBaseUrl); - templateModel.put("challengeName", challengeEntity.getChallengeName()); - templateModel.put("businessRequirement", challengeEntity.getBusinessRequirement()); - templateModel.put("generalNote", challengeEntity.getGeneralNote()); - templateModel.put("technologies", StringUtils.join(challengeEntity.getTechnologies(), "
    ")); - templateModel.put("documents", challengeEntity.getDocuments()); - templateModel.put("deliverables", challengeEntity.getDeliverables()); - templateModel.put("receivedEmails", StringUtils.join(challengeEntity.getReceivedEmails(), "
    ")); - templateModel.put("reviewStyle", challengeEntity.getReviewStyle()); - templateModel.put("startDate", challengeEntity.getStartDateTime()); - templateModel.put("registrationDate", challengeEntity.getRegistrationDateTime()); - templateModel.put("submissionDate", challengeEntity.getSubmissionDateTime()); - templateModel.put("qualityIdea", challengeEntity.getQualityIdea()); - templateModel.put("firstPlaceReward", challengeEntity.getFirstPlaceReward() != null ? challengeEntity.getFirstPlaceReward() : 0); - templateModel.put("secondPlaceReward", challengeEntity.getSecondPlaceReward() != null ? challengeEntity.getSecondPlaceReward() : 0); - templateModel.put("thirdPlaceReward", challengeEntity.getThirdPlaceReward() != null ? challengeEntity.getThirdPlaceReward() : 0); - templateModel.put("challengeId", challengeEntity.getChallengeId().toString()); - templateModel.put("authorEmail", challengeEntity.getAuthorEmail()); - templateModel.put("challengeOverview", challengeEntity.getChallengeOverview()); - templateModel.put("firstName", challengeRegistrantEntity.getRegistrantFirstName()); - templateModel.put("lastName", challengeRegistrantEntity.getRegistrantLastName()); - templateModel.put("registrantEmail", challengeRegistrantEntity.getRegistrantEmail()); - templateModel.put("challengeNameAlias", challengeEntity.getChallengeName().replaceAll("\\W", "-")); - - template.process(templateModel, stringWriter); - postChallengeMailMessage.setSubject(MimeUtility.encodeText(mailSubject, "UTF-8", null)); - postChallengeMailMessage.setText(stringWriter.toString(), "UTF-8", "html"); - - stringWriter.flush(); - postChallengeMailMessage.saveChanges(); - mailSender.send(postChallengeMailMessage); + else { + postChallengeMailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); } - private void sendPostChallengeEmail(ChallengeEntity challengeEntity, String mailSubject, - Address[] recipientAddresses, Template template) throws MessagingException, IOException, TemplateException { - postChallengeMailMessage.setRecipients(Message.RecipientType.TO, recipientAddresses); - postChallengeMailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); - StringWriter stringWriter = new StringWriter(); - - Map templateModel = new HashMap<>(); - templateModel.put("webBaseUrl", webBaseUrl); - templateModel.put("challengeName", challengeEntity.getChallengeName()); - templateModel.put("businessRequirement", challengeEntity.getBusinessRequirement()); - templateModel.put("generalNote", challengeEntity.getGeneralNote()); - templateModel.put("technologies", StringUtils.join(challengeEntity.getTechnologies(), "
    ")); - templateModel.put("documents", challengeEntity.getDocuments()); - templateModel.put("deliverables", challengeEntity.getDeliverables()); - templateModel.put("receivedEmails", StringUtils.join(challengeEntity.getReceivedEmails(), "
    ")); - templateModel.put("reviewStyle", challengeEntity.getReviewStyle()); - templateModel.put("startDate", challengeEntity.getStartDateTime()); - templateModel.put("registrationDate", challengeEntity.getRegistrationDateTime()); - templateModel.put("submissionDate", challengeEntity.getSubmissionDateTime()); - templateModel.put("qualityIdea", challengeEntity.getQualityIdea()); - templateModel.put("firstPlaceReward", challengeEntity.getFirstPlaceReward() != null ? challengeEntity.getFirstPlaceReward() : 0); - templateModel.put("secondPlaceReward", challengeEntity.getSecondPlaceReward() != null ? challengeEntity.getSecondPlaceReward() : 0); - templateModel.put("thirdPlaceReward", challengeEntity.getThirdPlaceReward() != null ? challengeEntity.getThirdPlaceReward() : 0); - templateModel.put("challengeId", challengeEntity.getChallengeId().toString()); - templateModel.put("authorEmail", challengeEntity.getAuthorEmail()); - templateModel.put("challengeOverview", challengeEntity.getChallengeOverview()); - templateModel.put("challengeNameAlias", challengeEntity.getChallengeName().replaceAll("\\W", "-")); - - template.process(templateModel, stringWriter); - mailSubject = String.format(mailSubject, challengeEntity.getAuthorEmail(), challengeEntity.getChallengeName()); - postChallengeMailMessage.setSubject(MimeUtility.encodeText(mailSubject, "UTF-8", null)); - postChallengeMailMessage.setText(stringWriter.toString(), "UTF-8", "html"); - - stringWriter.flush(); - postChallengeMailMessage.saveChanges(); - mailSender.send(postChallengeMailMessage); + StringWriter stringWriter = new StringWriter(); + Map templateModel = new HashMap<>(); + templateModel.put("webBaseUrl", webBaseUrl); + templateModel.put("challengeName", challengeEntity.getChallengeName()); + templateModel.put("businessRequirement", challengeEntity.getBusinessRequirement()); + templateModel.put("generalNote", challengeEntity.getGeneralNote()); + templateModel.put("technologies", StringUtils.join(challengeEntity.getTechnologies(), "
    ")); + templateModel.put("documents", challengeEntity.getDocuments()); + templateModel.put("deliverables", challengeEntity.getDeliverables()); + templateModel.put("receivedEmails", StringUtils.join(challengeEntity.getReceivedEmails(), "
    ")); + templateModel.put("reviewStyle", challengeEntity.getReviewStyle()); + templateModel.put("startDate", challengeEntity.getStartDateTime()); + templateModel.put("registrationDate", challengeEntity.getRegistrationDateTime()); + templateModel.put("submissionDate", challengeEntity.getSubmissionDateTime()); + templateModel.put("qualityIdea", challengeEntity.getQualityIdea()); + templateModel.put("firstPlaceReward", challengeEntity.getFirstPlaceReward() != null ? challengeEntity.getFirstPlaceReward() : 0); + templateModel.put("secondPlaceReward", challengeEntity.getSecondPlaceReward() != null ? challengeEntity.getSecondPlaceReward() : 0); + templateModel.put("thirdPlaceReward", challengeEntity.getThirdPlaceReward() != null ? challengeEntity.getThirdPlaceReward() : 0); + templateModel.put("challengeId", challengeEntity.getChallengeId().toString()); + templateModel.put("authorEmail", challengeEntity.getAuthorEmail()); + templateModel.put("challengeOverview", challengeEntity.getChallengeOverview()); + templateModel.put("firstName", challengeRegistrantEntity.getRegistrantFirstName()); + templateModel.put("lastName", challengeRegistrantEntity.getRegistrantLastName()); + templateModel.put("registrantEmail", challengeRegistrantEntity.getRegistrantEmail()); + templateModel.put("challengeNameAlias", challengeEntity.getChallengeName().replaceAll("\\W", "-")); + + template.process(templateModel, stringWriter); + postChallengeMailMessage.setSubject(MimeUtility.encodeText(mailSubject, "UTF-8", null)); + postChallengeMailMessage.setText(stringWriter.toString(), "UTF-8", "html"); + + stringWriter.flush(); + postChallengeMailMessage.saveChanges(); + mailSender.send(postChallengeMailMessage); + } + + private void sendPostChallengeEmail(ChallengeEntity challengeEntity, String mailSubject, + Address[] recipientAddresses, Template template) throws MessagingException, IOException, TemplateException { + postChallengeMailMessage.setRecipients(Message.RecipientType.TO, recipientAddresses); + postChallengeMailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); + StringWriter stringWriter = new StringWriter(); + + Map templateModel = new HashMap<>(); + templateModel.put("webBaseUrl", webBaseUrl); + templateModel.put("challengeName", challengeEntity.getChallengeName()); + templateModel.put("businessRequirement", challengeEntity.getBusinessRequirement()); + templateModel.put("generalNote", challengeEntity.getGeneralNote()); + templateModel.put("technologies", StringUtils.join(challengeEntity.getTechnologies(), "
    ")); + templateModel.put("documents", challengeEntity.getDocuments()); + templateModel.put("deliverables", challengeEntity.getDeliverables()); + templateModel.put("receivedEmails", StringUtils.join(challengeEntity.getReceivedEmails(), "
    ")); + templateModel.put("reviewStyle", challengeEntity.getReviewStyle()); + templateModel.put("startDate", challengeEntity.getStartDateTime()); + templateModel.put("registrationDate", challengeEntity.getRegistrationDateTime()); + templateModel.put("submissionDate", challengeEntity.getSubmissionDateTime()); + templateModel.put("qualityIdea", challengeEntity.getQualityIdea()); + templateModel.put("firstPlaceReward", challengeEntity.getFirstPlaceReward() != null ? challengeEntity.getFirstPlaceReward() : 0); + templateModel.put("secondPlaceReward", challengeEntity.getSecondPlaceReward() != null ? challengeEntity.getSecondPlaceReward() : 0); + templateModel.put("thirdPlaceReward", challengeEntity.getThirdPlaceReward() != null ? challengeEntity.getThirdPlaceReward() : 0); + templateModel.put("challengeId", challengeEntity.getChallengeId().toString()); + templateModel.put("authorEmail", challengeEntity.getAuthorEmail()); + templateModel.put("challengeOverview", challengeEntity.getChallengeOverview()); + templateModel.put("challengeNameAlias", challengeEntity.getChallengeName().replaceAll("\\W", "-")); + + template.process(templateModel, stringWriter); + mailSubject = String.format(mailSubject, challengeEntity.getAuthorEmail(), challengeEntity.getChallengeName()); + postChallengeMailMessage.setSubject(MimeUtility.encodeText(mailSubject, "UTF-8", null)); + postChallengeMailMessage.setText(stringWriter.toString(), "UTF-8", "html"); + + stringWriter.flush(); + postChallengeMailMessage.saveChanges(); + mailSender.send(postChallengeMailMessage); + } + + private Address[] getRecipientAddresses(ChallengeEntity challengeEntity, boolean includeAuthor) throws AddressException { + Set emails = new HashSet<>(challengeEntity.getReceivedEmails()); + if (includeAuthor) { + emails.add(challengeEntity.getAuthorEmail()); } - - private Address[] getRecipientAddresses(ChallengeEntity challengeEntity, boolean includeAuthor) throws AddressException { - Set emails = new HashSet<>(challengeEntity.getReceivedEmails()); - if (includeAuthor) { - emails.add(challengeEntity.getAuthorEmail()); + return InternetAddress.parse(StringUtils.join(emails, ',')); + } + + private List sortChallengesByDescendingStartDate(List challenges) { + SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); + return challenges.stream().sorted((challenge1, challenge2) -> { + try { + if (challenge2.getStartDateTime() == null) { + return -1; } - return InternetAddress.parse(StringUtils.join(emails, ',')); - } - - private List sortChallengesByDescendingStartDate(List challenges) { - SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); - return challenges.stream().sorted((challenge1, challenge2) -> { - try { - if (challenge2.getStartDateTime() == null) { - return -1; - } else if (challenge1.getStartDateTime() == null) { - return 1; - } - long challenge2StartDate = sdf.parse(challenge2.getStartDateTime()).getTime(); - long challenge1StartDate = sdf.parse(challenge1.getStartDateTime()).getTime(); - if (challenge2StartDate - challenge1StartDate > 0) { - return 1; - } else if (challenge2StartDate - challenge1StartDate < 0) { - return -1; - } else { - return 0; - } - } catch (ParseException e) { - return 0; - } - }).collect(toList()); - } - - public boolean checkIfChallengeRegistrantExist(Long challengeId, String email) { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder(); - searchQueryBuilder.withQuery(boolQuery() - .must(matchPhraseQuery("registrantEmail", email)) - .must(termQuery("challengeId", challengeId))); - - long total = challengeRegistrantRepository.search(searchQueryBuilder.build()).getTotalElements(); - return (total > 0); - } - - @Override - public Long getTotalNumberOfChallenges() { - return challengeRepository.count(); - } - - @Override - public Double getTotalAmountOfPrizeValues() { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withSearchType(SearchType.COUNT); - searchQueryBuilder.withQuery(matchAllQuery()); - - SumBuilder sumPrizeBuilder = sum("sumPrize").script("doc['firstPlaceReward'].value + doc['secondPlaceReward'].value + doc['thirdPlaceReward'].value"); - searchQueryBuilder.addAggregation(sumPrizeBuilder); - - Aggregations aggregations = elasticsearchTemplateUserImport.query(searchQueryBuilder.build(), SearchResponse::getAggregations); - Sum sumReponse = aggregations.get("sumPrize"); - return sumReponse != null ? sumReponse.getValue() : 0D; - } - - @Override - public Long getTotalNumberOfRegistrants() { - return challengeRegistrantRepository.count(); - } - - @Override - public ChallengeDetailDto getTheLatestChallenge() { + else if (challenge1.getStartDateTime() == null) { + return 1; + } + long challenge2StartDate = sdf.parse(challenge2.getStartDateTime()).getTime(); + long challenge1StartDate = sdf.parse(challenge1.getStartDateTime()).getTime(); + if (challenge2StartDate - challenge1StartDate > 0) { + return 1; + } + else if (challenge2StartDate - challenge1StartDate < 0) { + return -1; + } + else { + return 0; + } + } + catch (ParseException e) { + return 0; + } + }).collect(toList()); + } + + public boolean checkIfChallengeRegistrantExist(Long challengeId, String email) { + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder(); + searchQueryBuilder.withQuery(boolQuery() + .must(matchPhraseQuery("registrantEmail", email)) + .must(termQuery("challengeId", challengeId))); + + long total = challengeRegistrantRepository.search(searchQueryBuilder.build()).getTotalElements(); + return (total > 0); + } + + @Override + public Long getTotalNumberOfChallenges() { + return challengeRepository.count(); + } + + @Override + public Double getTotalAmountOfPrizeValues() { + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withSearchType(SearchType.COUNT); + searchQueryBuilder.withQuery(matchAllQuery()); + + SumBuilder sumPrizeBuilder = sum("sumPrize").script("doc['firstPlaceReward'].value + doc['secondPlaceReward'].value + doc['thirdPlaceReward'].value"); + searchQueryBuilder.addAggregation(sumPrizeBuilder); + + Aggregations aggregations = elasticsearchTemplateUserImport.query(searchQueryBuilder.build(), SearchResponse::getAggregations); + Sum sumReponse = aggregations.get("sumPrize"); + return sumReponse != null ? sumReponse.getValue() : 0D; + } + + @Override + public Long getTotalNumberOfRegistrants() { + return challengeRegistrantRepository.count(); + } + + @Override + public ChallengeDetailDto getTheLatestChallenge() { // NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder(); // searchQueryBuilder.withQuery(QueryBuilders.matchAllQuery()); // searchQueryBuilder.withSort(SortBuilders.fieldSort("challengeId").order(SortOrder.DESC)); @@ -510,413 +530,418 @@ public ChallengeDetailDto getTheLatestChallenge() { // ChallengeEntity challengeEntity = challengeEntities.get(0); // return dozerMapper.map(challengeEntity, ChallengeDetailDto.class); // } - return listChallenges().get(0); - } - - public Collection findByOwnerAndCondition(String owner, - Predicate condition) { - NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().withIndices(techlooperIndex).withTypes("challenge"); - QueryStringQueryBuilder query = queryStringQuery(owner).defaultField("authorEmail"); - queryBuilder.withFilter(FilterBuilders.queryFilter(query)); - - int pageIndex = 0; - Set challenges = new HashSet<>(); - while (true) { - queryBuilder.withPageable(new PageRequest(pageIndex++, 100)); - FacetedPage page = challengeRepository.search(queryBuilder.build()); - if (!page.hasContent()) { - break; - } - - page.spliterator().forEachRemaining(challenge -> { - if (condition.test(challenge)) { - ChallengeDetailDto challengeDetailDto = dozerMapper.map(challenge, ChallengeDetailDto.class); - challengeDetailDto.setNumberOfRegistrants(countRegistrantsByChallengeId(challenge.getChallengeId())); - challenges.add(challengeDetailDto); - } - }); + return listChallenges().get(0); + } + + public Collection findByOwnerAndCondition(String owner, + Predicate condition) { + NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().withIndices(techlooperIndex).withTypes("challenge"); + QueryStringQueryBuilder query = queryStringQuery(owner).defaultField("authorEmail"); + queryBuilder.withFilter(FilterBuilders.queryFilter(query)); + + int pageIndex = 0; + Set challenges = new HashSet<>(); + while (true) { + queryBuilder.withPageable(new PageRequest(pageIndex++, 100)); + FacetedPage page = challengeRepository.search(queryBuilder.build()); + if (!page.hasContent()) { + break; + } + + page.spliterator().forEachRemaining(challenge -> { + if (condition.test(challenge)) { + ChallengeDetailDto challengeDetailDto = dozerMapper.map(challenge, ChallengeDetailDto.class); + challengeDetailDto.setNumberOfRegistrants(countRegistrantsByChallengeId(challenge.getChallengeId())); + challenges.add(challengeDetailDto); } - return challenges; + }); } - - public List listChallenges(String ownerEmail) { - List result = new ArrayList<>(); - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challenge"); - MatchQueryBuilder authorEmailQuery = matchQuery("authorEmail", ownerEmail).minimumShouldMatch("100%"); - TermQueryBuilder notExpiredQuery = termQuery("expired", Boolean.TRUE); - - searchQueryBuilder.withQuery(boolQuery().must(authorEmailQuery).mustNot(notExpiredQuery)); - List challengeEntities = DataUtils.getAllEntities(challengeRepository, searchQueryBuilder); - - for (ChallengeEntity challengeEntity : challengeEntities) { - ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); - challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeDetailDto.getChallengeId())); - result.add(challengeDetailDto); - } - return result; + return challenges; + } + + public List listChallenges(String ownerEmail) { + List result = new ArrayList<>(); + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challenge"); + MatchQueryBuilder authorEmailQuery = matchQuery("authorEmail", ownerEmail).minimumShouldMatch("100%"); + TermQueryBuilder notExpiredQuery = termQuery("expired", Boolean.TRUE); + + searchQueryBuilder.withQuery(boolQuery().must(authorEmailQuery).mustNot(notExpiredQuery)); + List challengeEntities = DataUtils.getAllEntities(challengeRepository, searchQueryBuilder); + + for (ChallengeEntity challengeEntity : challengeEntities) { + ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); + challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeDetailDto.getChallengeId())); + result.add(challengeDetailDto); } - - public Collection findInProgressChallenges(String owner) { - DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("dd/MM/yyyy"); - return findByOwnerAndCondition(owner, challengeEntity -> { - DateTime startDate = dateTimeFormatter.parseDateTime(challengeEntity.getStartDateTime()); - DateTime submissionDate = dateTimeFormatter.parseDateTime(challengeEntity.getSubmissionDateTime()); - DateTime now = DateTime.now(); - boolean inRange = now.isAfter(startDate) && now.isBefore(submissionDate); - boolean atBoundary = now.isEqual(startDate) || now.isEqual(submissionDate); - return inRange || atBoundary; - }); + return result; + } + + public Collection findInProgressChallenges(String owner) { + DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("dd/MM/yyyy"); + return findByOwnerAndCondition(owner, challengeEntity -> { + DateTime startDate = dateTimeFormatter.parseDateTime(challengeEntity.getStartDateTime()); + DateTime submissionDate = dateTimeFormatter.parseDateTime(challengeEntity.getSubmissionDateTime()); + DateTime now = DateTime.now(); + boolean inRange = now.isAfter(startDate) && now.isBefore(submissionDate); + boolean atBoundary = now.isEqual(startDate) || now.isEqual(submissionDate); + return inRange || atBoundary; + }); + } + + public Long countRegistrantsByChallengeId(Long challengeId) { + NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().withIndices(techlooperIndex).withTypes("challengeRegistrant"); + queryBuilder.withFilter(FilterBuilders.queryFilter(termQuery("challengeId", challengeId))) + .withSearchType(SearchType.COUNT); + return challengeRegistrantRepository.search(queryBuilder.build()).getTotalElements(); + } + + public boolean delete(Long id, String ownerEmail) { + ChallengeEntity challenge = challengeRepository.findOne(id); + if (challenge.getAuthorEmail().equalsIgnoreCase(ownerEmail)) { + challenge.setExpired(Boolean.TRUE); + challengeRepository.save(challenge); + return true; } - - public Long countRegistrantsByChallengeId(Long challengeId) { - NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().withIndices(techlooperIndex).withTypes("challengeRegistrant"); - queryBuilder.withFilter(FilterBuilders.queryFilter(termQuery("challengeId", challengeId))) - .withSearchType(SearchType.COUNT); - return challengeRegistrantRepository.search(queryBuilder.build()).getTotalElements(); + return false; + } + + public ChallengeDto findChallengeById(Long id) { + return dozerMapper.map(challengeRepository.findOne(id), ChallengeDto.class); + } + + public Set findRegistrantsByOwner(RegistrantFilterCondition condition) throws ParseException { + Set result = new HashSet<>(); + Long challengeId = condition.getChallengeId(); + ChallengeEntity challengeEntity = challengeRepository.findOne(challengeId); + + if (challengeEntity != null && challengeEntity.getAuthorEmail().equals(condition.getAuthorEmail())) { + List registrants = filterChallengeRegistrantByDate(condition); + for (ChallengeRegistrantEntity registrant : registrants) { + ChallengeRegistrantDto registrantDto = dozerMapper.map(registrant, ChallengeRegistrantDto.class); + registrantDto.setSubmissions(findChallengeSubmissionByRegistrant(challengeId, registrant.getRegistrantId())); + result.add(registrantDto); + } } - public boolean delete(Long id, String ownerEmail) { - ChallengeEntity challenge = challengeRepository.findOne(id); - if (challenge.getAuthorEmail().equalsIgnoreCase(ownerEmail)) { - challenge.setExpired(Boolean.TRUE); - challengeRepository.save(challenge); - return true; - } - return false; - } - - public ChallengeDto findChallengeById(Long id) { - return dozerMapper.map(challengeRepository.findOne(id), ChallengeDto.class); - } - - public Set findRegistrantsByOwner(RegistrantFilterCondition condition) throws ParseException { - Set result = new HashSet<>(); - Long challengeId = condition.getChallengeId(); - ChallengeEntity challengeEntity = challengeRepository.findOne(challengeId); - - if (challengeEntity != null && challengeEntity.getAuthorEmail().equals(condition.getAuthorEmail())) { - List registrants = filterChallengeRegistrantByDate(condition); - for (ChallengeRegistrantEntity registrant : registrants) { - ChallengeRegistrantDto registrantDto = dozerMapper.map(registrant, ChallengeRegistrantDto.class); - registrantDto.setSubmissions(findChallengeSubmissionByRegistrant(challengeId, registrant.getRegistrantId())); - result.add(registrantDto); - } - } - - return result; - } - - public ChallengeRegistrantDto saveRegistrant(String ownerEmail, ChallengeRegistrantDto challengeRegistrantDto) { - ChallengeEntity challenge = challengeRepository.findOne(challengeRegistrantDto.getChallengeId()); - if (ownerEmail.equalsIgnoreCase(challenge.getAuthorEmail())) { - ChallengeRegistrantEntity registrant = challengeRegistrantRepository.findOne(challengeRegistrantDto.getRegistrantId()); - challengeRegistrantDto.setRegistrantEmail(registrant.getRegistrantEmail()); - dozerMapper.map(challengeRegistrantDto, registrant); - registrant = challengeRegistrantRepository.save(registrant); - challengeRegistrantDto = dozerMapper.map(registrant, ChallengeRegistrantDto.class); + return result; + } + + public ChallengeRegistrantDto saveRegistrant(String ownerEmail, ChallengeRegistrantDto challengeRegistrantDto) { + ChallengeEntity challenge = challengeRepository.findOne(challengeRegistrantDto.getChallengeId()); + if (ownerEmail.equalsIgnoreCase(challenge.getAuthorEmail())) { + ChallengeRegistrantEntity registrant = challengeRegistrantRepository.findOne(challengeRegistrantDto.getRegistrantId()); + challengeRegistrantDto.setRegistrantEmail(registrant.getRegistrantEmail()); + dozerMapper.map(challengeRegistrantDto, registrant); + registrant = challengeRegistrantRepository.save(registrant); + challengeRegistrantDto = dozerMapper.map(registrant, ChallengeRegistrantDto.class); // challengeRegistrantDto.setRegistrantEmail(null); - } - return challengeRegistrantDto; - } - - @Override - public List findChallengeRegistrantWithinPeriod( - Long challengeId, Long currentDateTime, TimePeriodEnum period) { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeRegistrant"); - - BoolQueryBuilder boolQueryBuilder = boolQuery(); - boolQueryBuilder.must(termQuery("challengeId", challengeId)); - - Long pastTime = currentDateTime - period.getMiliseconds() > 0 ? currentDateTime - period.getMiliseconds() : 0; - boolQueryBuilder.must(rangeQuery("registrantId").from(pastTime)); - searchQueryBuilder.withQuery(boolQueryBuilder); - searchQueryBuilder.withSort(fieldSort("registrantId").order(SortOrder.DESC)); - return DataUtils.getAllEntities(challengeRegistrantRepository, searchQueryBuilder); } - - @Override - public List filterChallengeRegistrantByDate(RegistrantFilterCondition condition) throws ParseException { - List result = new ArrayList<>(); - - if (ChallengeRegistrantFilterTypeEnum.BY_SUBMISSION.getValue().equals(condition.getFilterType())) { - Set registrantIds = findRegistrantByChallengeSubmissionDate( - condition.getChallengeId(), condition.getFromDate(), condition.getToDate()); - for (Long registrantId : registrantIds) { - ChallengeRegistrantEntity registrantEntity = challengeRegistrantRepository.findOne(registrantId); - if (registrantEntity != null) { - result.add(registrantEntity); - } - } - - if (StringUtils.isNotEmpty(condition.getPhase())) { - result = result.stream().filter(registrantEntity -> - condition.getPhase().equals(registrantEntity.getActivePhase().getValue())).collect(toList()); - } - } else { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeRegistrant"); - BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); - final String registrationPhase = ChallengePhaseEnum.REGISTRATION.getValue(); - - if (condition.getChallengeId() != null) { - boolQueryBuilder.must(termQuery("challengeId", condition.getChallengeId())); - } - - if (StringUtils.isNotEmpty(condition.getPhase()) && !registrationPhase.equals(condition.getPhase())) { - boolQueryBuilder.must(matchPhraseQuery("activePhase", condition.getPhase())); - } - - if (StringUtils.isNotEmpty(condition.getFilterType()) && - (StringUtils.isNotEmpty(condition.getFromDate()) || StringUtils.isNotEmpty(condition.getToDate()))) { - RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(condition.getFilterType()); - - if (StringUtils.isNotEmpty(condition.getFromDate())) { - Long from = string2Date(condition.getFromDate(), BASIC_DATE_PATTERN).getTime(); - rangeQueryBuilder.from(from); - } - if (StringUtils.isNotEmpty(condition.getToDate())) { - Long to = string2Date(condition.getToDate(), BASIC_DATE_PATTERN).getTime() + - TimePeriodEnum.TWENTY_FOUR_HOURS.getMiliseconds(); - rangeQueryBuilder.to(to); - } - - boolQueryBuilder.must(rangeQueryBuilder); - } - - searchQueryBuilder.withQuery(boolQueryBuilder); - result.addAll(DataUtils.getAllEntities(challengeRegistrantRepository, searchQueryBuilder)); - - if (registrationPhase.equals(condition.getPhase())) { - result = result.stream().filter(registrantEntity -> registrantEntity.getActivePhase() == null - || registrationPhase.equals(registrantEntity.getActivePhase().getValue())).collect(toList()); - } + return challengeRegistrantDto; + } + + @Override + public List findChallengeRegistrantWithinPeriod( + Long challengeId, Long currentDateTime, TimePeriodEnum period) { + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeRegistrant"); + + BoolQueryBuilder boolQueryBuilder = boolQuery(); + boolQueryBuilder.must(termQuery("challengeId", challengeId)); + + Long pastTime = currentDateTime - period.getMiliseconds() > 0 ? currentDateTime - period.getMiliseconds() : 0; + boolQueryBuilder.must(rangeQuery("registrantId").from(pastTime)); + searchQueryBuilder.withQuery(boolQueryBuilder); + searchQueryBuilder.withSort(fieldSort("registrantId").order(SortOrder.DESC)); + return DataUtils.getAllEntities(challengeRegistrantRepository, searchQueryBuilder); + } + + @Override + public List filterChallengeRegistrantByDate(RegistrantFilterCondition condition) throws ParseException { + List result = new ArrayList<>(); + + if (ChallengeRegistrantFilterTypeEnum.BY_SUBMISSION.getValue().equals(condition.getFilterType())) { + Set registrantIds = findRegistrantByChallengeSubmissionDate( + condition.getChallengeId(), condition.getFromDate(), condition.getToDate()); + for (Long registrantId : registrantIds) { + ChallengeRegistrantEntity registrantEntity = challengeRegistrantRepository.findOne(registrantId); + if (registrantEntity != null) { + result.add(registrantEntity); } + } - return result; + if (StringUtils.isNotEmpty(condition.getPhase())) { + result = result.stream().filter(registrantEntity -> + condition.getPhase().equals(registrantEntity.getActivePhase().getValue())).collect(toList()); + } } - - @Override - public List findChallengeSubmissionWithinPeriod( - Long challengeId, Long currentDateTime, TimePeriodEnum period) { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeSubmission"); - - BoolQueryBuilder boolQueryBuilder = boolQuery(); - boolQueryBuilder.must(termQuery("challengeId", challengeId)); - - boolQueryBuilder.must(rangeQuery("submissionDateTime").from(yesterdayDate())); - searchQueryBuilder.withQuery(boolQueryBuilder); - searchQueryBuilder.withSort(fieldSort("challengeSubmissionId").order(SortOrder.DESC)); - - return DataUtils.getAllEntities(challengeSubmissionRepository, searchQueryBuilder); - } - - @Override - public List listChallengesByPhase(ChallengePhaseEnum challengePhase) { - List challengeEntities = new ArrayList<>(); - // from <= NOW < to - RangeFilterBuilder fromFilter = rangeFilter(challengePhase.getFromDateTimeField()).lt("now/d"); - RangeFilterBuilder toFilter = rangeFilter(challengePhase.getToDateTimeField()).gte("now/d"); - TermFilterBuilder expiredChallengeFilter = termFilter("expired", Boolean.TRUE); - BoolFilterBuilder dateTimeRangeFilter = boolFilter().must(fromFilter).must(toFilter).mustNot(expiredChallengeFilter); - - Iterator challengeIterator = - challengeRepository.search(filteredQuery(matchAllQuery(), dateTimeRangeFilter)).iterator(); - while (challengeIterator.hasNext()) { - challengeEntities.add(challengeIterator.next()); + else { + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeRegistrant"); + BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); + final String registrationPhase = ChallengePhaseEnum.REGISTRATION.getValue(); + + if (condition.getChallengeId() != null) { + boolQueryBuilder.must(termQuery("challengeId", condition.getChallengeId())); + } + + if (StringUtils.isNotEmpty(condition.getPhase()) && !registrationPhase.equals(condition.getPhase())) { + boolQueryBuilder.must(matchPhraseQuery("activePhase", condition.getPhase())); + } + + if (StringUtils.isNotEmpty(condition.getFilterType()) && + (StringUtils.isNotEmpty(condition.getFromDate()) || StringUtils.isNotEmpty(condition.getToDate()))) { + RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(condition.getFilterType()); + + if (StringUtils.isNotEmpty(condition.getFromDate())) { + Long from = string2Date(condition.getFromDate(), BASIC_DATE_PATTERN).getTime(); + rangeQueryBuilder.from(from); + } + if (StringUtils.isNotEmpty(condition.getToDate())) { + Long to = string2Date(condition.getToDate(), BASIC_DATE_PATTERN).getTime() + + TimePeriodEnum.TWENTY_FOUR_HOURS.getMiliseconds(); + rangeQueryBuilder.to(to); } - return challengeEntities; - } + boolQueryBuilder.must(rangeQueryBuilder); + } - @Override - public void sendDailySummaryEmailToChallengeOwner(ChallengeEntity challengeEntity) throws Exception { - String mailSubject = challengeEntity.getLang() == Language.vi ? dailyChallengeSummaryMailSubjectVi : - dailyChallengeSummaryMailSubjectEn; - Address[] recipientAddresses = getRecipientAddresses(challengeEntity, true); - Template template = challengeEntity.getLang() == Language.vi ? - dailyChallengeSummaryMailTemplateVi : dailyChallengeSummaryMailTemplateEn; - postChallengeMailMessage.setRecipients(Message.RecipientType.TO, recipientAddresses); - Address[] replyToAddresses = InternetAddress.parse(postChallengeTechloopiesMailList); - postChallengeMailMessage.setReplyTo(replyToAddresses); - StringWriter stringWriter = new StringWriter(); - - Map templateModel = new HashMap<>(); - templateModel.put("webBaseUrl", webBaseUrl); - templateModel.put("challengeName", challengeEntity.getChallengeName()); - templateModel.put("challengeId", challengeEntity.getChallengeId().toString()); - templateModel.put("challengeNameAlias", challengeEntity.getChallengeName().replaceAll("\\W", "-")); - templateModel.put("currentDateTime", String.valueOf(new Date().getTime())); - templateModel.put("yesterdayDateTime", DateTimeUtils.yesterdayDate()); - - Long currentDateTime = new Date().getTime(); - List latestRegistrants = findChallengeRegistrantWithinPeriod( - challengeEntity.getChallengeId(), currentDateTime, TimePeriodEnum.TWENTY_FOUR_HOURS); - templateModel.put("numberOfRegistrants", latestRegistrants.size()); - templateModel.put("latestRegistrants", latestRegistrants); - - List latestSubmissions = findChallengeSubmissionWithinPeriod( - challengeEntity.getChallengeId(), currentDateTime, TimePeriodEnum.TWENTY_FOUR_HOURS); - templateModel.put("numberOfSubmissions", latestSubmissions.size()); - templateModel.put("latestSubmissions", latestSubmissions); - - template.process(templateModel, stringWriter); - mailSubject = String.format(mailSubject, challengeEntity.getChallengeName()); - postChallengeMailMessage.setSubject(MimeUtility.encodeText(mailSubject, "UTF-8", null)); - postChallengeMailMessage.setText(stringWriter.toString(), "UTF-8", "html"); - - stringWriter.flush(); - postChallengeMailMessage.saveChanges(); - mailSender.send(postChallengeMailMessage); - } + searchQueryBuilder.withQuery(boolQueryBuilder); + result.addAll(DataUtils.getAllEntities(challengeRegistrantRepository, searchQueryBuilder)); - public boolean isOwnerOfChallenge(String ownerEmail, Long challengeId) { - ChallengeEntity challenge = challengeRepository.findOne(challengeId); - return challenge.getAuthorEmail().equalsIgnoreCase(ownerEmail); + if (registrationPhase.equals(condition.getPhase())) { + result = result.stream().filter(registrantEntity -> registrantEntity.getActivePhase() == null + || registrationPhase.equals(registrantEntity.getActivePhase().getValue())).collect(toList()); + } } - public ChallengeEntity findChallengeIdAndOwnerEmail(Long challengeId, String ownerEmail) { - ChallengeEntity challenge = challengeRepository.findOne(challengeId); - if (challenge.getAuthorEmail().equalsIgnoreCase(ownerEmail)) { - return challenge; - } - return null; + return result; + } + + @Override + public List findChallengeSubmissionWithinPeriod( + Long challengeId, Long currentDateTime, TimePeriodEnum period) { + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeSubmission"); + + BoolQueryBuilder boolQueryBuilder = boolQuery(); + boolQueryBuilder.must(termQuery("challengeId", challengeId)); + + boolQueryBuilder.must(rangeQuery("submissionDateTime").from(yesterdayDate())); + searchQueryBuilder.withQuery(boolQueryBuilder); + searchQueryBuilder.withSort(fieldSort("challengeSubmissionId").order(SortOrder.DESC)); + + return DataUtils.getAllEntities(challengeSubmissionRepository, searchQueryBuilder); + } + + @Override + public List listChallengesByPhase(ChallengePhaseEnum challengePhase) { + List challengeEntities = new ArrayList<>(); + // from <= NOW < to + RangeFilterBuilder fromFilter = rangeFilter(challengePhase.getFromDateTimeField()).lt("now/d"); + RangeFilterBuilder toFilter = rangeFilter(challengePhase.getToDateTimeField()).gte("now/d"); + TermFilterBuilder expiredChallengeFilter = termFilter("expired", Boolean.TRUE); + BoolFilterBuilder dateTimeRangeFilter = boolFilter().must(fromFilter).must(toFilter).mustNot(expiredChallengeFilter); + + Iterator challengeIterator = + challengeRepository.search(filteredQuery(matchAllQuery(), dateTimeRangeFilter)).iterator(); + while (challengeIterator.hasNext()) { + challengeEntities.add(challengeIterator.next()); } - public boolean sendEmailToDailyChallengeRegistrants(String challengeOwner, Long challengeId, Long now, EmailContent emailContent) { - if (isOwnerOfChallenge(challengeOwner, challengeId)) { - List registrants = findChallengeRegistrantWithinPeriod(challengeId, now, TimePeriodEnum.TWENTY_FOUR_HOURS); - String csvEmails = registrants.stream().map(ChallengeRegistrantEntity::getRegistrantEmail).distinct().collect(joining(",")); - try { - emailContent.setRecipients(InternetAddress.parse(csvEmails)); - } catch (AddressException e) { - LOGGER.debug("Can not parse email address", e); - return false; - } - } - return emailService.sendEmail(emailContent); + return challengeEntities; + } + + @Override + public void sendDailySummaryEmailToChallengeOwner(ChallengeEntity challengeEntity) throws Exception { + String mailSubject = challengeEntity.getLang() == Language.vi ? dailyChallengeSummaryMailSubjectVi : + dailyChallengeSummaryMailSubjectEn; + Address[] recipientAddresses = getRecipientAddresses(challengeEntity, true); + Template template = challengeEntity.getLang() == Language.vi ? + dailyChallengeSummaryMailTemplateVi : dailyChallengeSummaryMailTemplateEn; + postChallengeMailMessage.setRecipients(Message.RecipientType.TO, recipientAddresses); + Address[] replyToAddresses = InternetAddress.parse(postChallengeTechloopiesMailList); + postChallengeMailMessage.setReplyTo(replyToAddresses); + StringWriter stringWriter = new StringWriter(); + + Map templateModel = new HashMap<>(); + templateModel.put("webBaseUrl", webBaseUrl); + templateModel.put("challengeName", challengeEntity.getChallengeName()); + templateModel.put("challengeId", challengeEntity.getChallengeId().toString()); + templateModel.put("challengeNameAlias", challengeEntity.getChallengeName().replaceAll("\\W", "-")); + templateModel.put("currentDateTime", String.valueOf(new Date().getTime())); + templateModel.put("yesterdayDateTime", DateTimeUtils.yesterdayDate()); + + Long currentDateTime = new Date().getTime(); + List latestRegistrants = findChallengeRegistrantWithinPeriod( + challengeEntity.getChallengeId(), currentDateTime, TimePeriodEnum.TWENTY_FOUR_HOURS); + templateModel.put("numberOfRegistrants", latestRegistrants.size()); + templateModel.put("latestRegistrants", latestRegistrants); + + List latestSubmissions = findChallengeSubmissionWithinPeriod( + challengeEntity.getChallengeId(), currentDateTime, TimePeriodEnum.TWENTY_FOUR_HOURS); + templateModel.put("numberOfSubmissions", latestSubmissions.size()); + templateModel.put("latestSubmissions", latestSubmissions); + + template.process(templateModel, stringWriter); + mailSubject = String.format(mailSubject, challengeEntity.getChallengeName()); + postChallengeMailMessage.setSubject(MimeUtility.encodeText(mailSubject, "UTF-8", null)); + postChallengeMailMessage.setText(stringWriter.toString(), "UTF-8", "html"); + + stringWriter.flush(); + postChallengeMailMessage.saveChanges(); + mailSender.send(postChallengeMailMessage); + } + + public boolean isOwnerOfChallenge(String ownerEmail, Long challengeId) { + ChallengeEntity challenge = challengeRepository.findOne(challengeId); + return challenge.getAuthorEmail().equalsIgnoreCase(ownerEmail); + } + + public ChallengeEntity findChallengeIdAndOwnerEmail(Long challengeId, String ownerEmail) { + ChallengeEntity challenge = challengeRepository.findOne(challengeId); + if (challenge.getAuthorEmail().equalsIgnoreCase(ownerEmail)) { + return challenge; } - - public boolean sendEmailToRegistrant(String challengeOwner, Long challengeId, Long registrantId, EmailContent emailContent) { - if (isOwnerOfChallenge(challengeOwner, challengeId)) { - ChallengeRegistrantEntity registrant = challengeRegistrantRepository.findOne(registrantId); - String csvEmails = registrant.getRegistrantEmail(); - try { - emailContent.setRecipients(InternetAddress.parse(csvEmails)); - } catch (AddressException e) { - LOGGER.debug("Can not parse email address", e); - return false; - } - } - return emailService.sendEmail(emailContent); + return null; + } + + public boolean sendEmailToDailyChallengeRegistrants(String challengeOwner, Long challengeId, Long now, EmailContent emailContent) { + if (isOwnerOfChallenge(challengeOwner, challengeId)) { + List registrants = findChallengeRegistrantWithinPeriod(challengeId, now, TimePeriodEnum.TWENTY_FOUR_HOURS); + String csvEmails = registrants.stream().map(ChallengeRegistrantEntity::getRegistrantEmail).distinct().collect(joining(",")); + try { + emailContent.setRecipients(InternetAddress.parse(csvEmails)); + } + catch (AddressException e) { + LOGGER.debug("Can not parse email address", e); + return false; + } } - - @Override - public List findChallengeSubmissionByRegistrant(Long challengeId, Long registrantId) { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeSubmission"); - BoolFilterBuilder boolFilterBuilder = new BoolFilterBuilder(); - boolFilterBuilder.must(termFilter("challengeId", challengeId)); - boolFilterBuilder.must(termFilter("registrantId", registrantId)); - - searchQueryBuilder.withQuery(filteredQuery(matchAllQuery(), boolFilterBuilder)); - List submissions = DataUtils.getAllEntities(challengeSubmissionRepository, searchQueryBuilder); - return submissions.stream().map(submission -> dozerMapper.map(submission, ChallengeSubmissionDto.class)).collect(toList()); + return emailService.sendEmail(emailContent); + } + + public boolean sendEmailToRegistrant(String challengeOwner, Long challengeId, Long registrantId, EmailContent emailContent) { + if (isOwnerOfChallenge(challengeOwner, challengeId)) { + ChallengeRegistrantEntity registrant = challengeRegistrantRepository.findOne(registrantId); + String csvEmails = registrant.getRegistrantEmail(); + try { + emailContent.setRecipients(InternetAddress.parse(csvEmails)); + } + catch (AddressException e) { + LOGGER.debug("Can not parse email address", e); + return false; + } } - - @Override - public void updateSendEmailToContestantResultCode(ChallengeRegistrantEntity challengeRegistrantEntity, EmailSentResultEnum code) { - if (challengeRegistrantEntity != null) { - challengeRegistrantEntity.setLastEmailSentDateTime(currentDate(BASIC_DATE_TIME_PATTERN)); - challengeRegistrantEntity.setLastEmailSentResultCode(code.getValue()); - challengeRegistrantRepository.save(challengeRegistrantEntity); - } + return emailService.sendEmail(emailContent); + } + + @Override + public List findChallengeSubmissionByRegistrant(Long challengeId, Long registrantId) { + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeSubmission"); + BoolFilterBuilder boolFilterBuilder = new BoolFilterBuilder(); + boolFilterBuilder.must(termFilter("challengeId", challengeId)); + boolFilterBuilder.must(termFilter("registrantId", registrantId)); + + searchQueryBuilder.withQuery(filteredQuery(matchAllQuery(), boolFilterBuilder)); + List submissions = DataUtils.getAllEntities(challengeSubmissionRepository, searchQueryBuilder); + return submissions.stream().map(submission -> dozerMapper.map(submission, ChallengeSubmissionDto.class)).collect(toList()); + } + + @Override + public void updateSendEmailToContestantResultCode(ChallengeRegistrantEntity challengeRegistrantEntity, EmailSentResultEnum code) { + if (challengeRegistrantEntity != null) { + challengeRegistrantEntity.setLastEmailSentDateTime(currentDate(BASIC_DATE_TIME_PATTERN)); + challengeRegistrantEntity.setLastEmailSentResultCode(code.getValue()); + challengeRegistrantRepository.save(challengeRegistrantEntity); } + } - public void updateSendEmailToChallengeOwnerResultCode(ChallengeEntity challengeEntity, EmailSentResultEnum code) { - if (challengeEntity != null) { - challengeEntity.setLastEmailSentDateTime(currentDate(BASIC_DATE_TIME_PATTERN)); - challengeEntity.setLastEmailSentResultCode(code.getValue()); - challengeRepository.save(challengeEntity); - } + public void updateSendEmailToChallengeOwnerResultCode(ChallengeEntity challengeEntity, EmailSentResultEnum code) { + if (challengeEntity != null) { + challengeEntity.setLastEmailSentDateTime(currentDate(BASIC_DATE_TIME_PATTERN)); + challengeEntity.setLastEmailSentResultCode(code.getValue()); + challengeRepository.save(challengeEntity); } + } - public Set findRegistrantByChallengeSubmissionDate(Long challengeId, String fromDate, String toDate) { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeSubmission"); - BoolQueryBuilder boolQueryBuilder = boolQuery(); - boolQueryBuilder.must(termQuery("challengeId", challengeId)); + public Set findRegistrantByChallengeSubmissionDate(Long challengeId, String fromDate, String toDate) { + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeSubmission"); + BoolQueryBuilder boolQueryBuilder = boolQuery(); + boolQueryBuilder.must(termQuery("challengeId", challengeId)); - RangeQueryBuilder submissionDateQuery = QueryBuilders.rangeQuery("submissionDateTime"); - if (StringUtils.isNotEmpty(fromDate) || StringUtils.isNotEmpty(toDate)) { - if (StringUtils.isNotEmpty(fromDate)) { - submissionDateQuery.from(fromDate); - } + RangeQueryBuilder submissionDateQuery = QueryBuilders.rangeQuery("submissionDateTime"); + if (StringUtils.isNotEmpty(fromDate) || StringUtils.isNotEmpty(toDate)) { + if (StringUtils.isNotEmpty(fromDate)) { + submissionDateQuery.from(fromDate); + } - if (StringUtils.isNotEmpty(toDate)) { - submissionDateQuery.to(toDate); - } + if (StringUtils.isNotEmpty(toDate)) { + submissionDateQuery.to(toDate); + } - boolQueryBuilder.must(submissionDateQuery); - } - - searchQueryBuilder.withQuery(boolQueryBuilder); - List submissions = DataUtils.getAllEntities(challengeSubmissionRepository, searchQueryBuilder); - return submissions.stream().map(submission -> submission.getRegistrantId()).collect(toSet()); + boolQueryBuilder.must(submissionDateQuery); } - public ChallengeDetailDto getChallengeDetail(Long challengeId, String loginEmail) { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challenge"); - TermQueryBuilder challengeIdQuery = termQuery("challengeId", challengeId); - //MatchQueryBuilder authorEmailQuery = matchQuery("authorEmail", loginEmail).minimumShouldMatch("100%"); - TermQueryBuilder expiredChallengeQuery = termQuery("expired", Boolean.TRUE); - - searchQueryBuilder.withQuery(boolQuery().must(challengeIdQuery).mustNot(expiredChallengeQuery)); - List challengeEntities = DataUtils.getAllEntities(challengeRepository, searchQueryBuilder); - - if (!challengeEntities.isEmpty()) { - ChallengeEntity challengeEntity = challengeEntities.get(0); - ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); - challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeId)); - calculateChallengePhases(challengeDetailDto); + searchQueryBuilder.withQuery(boolQueryBuilder); + List submissions = DataUtils.getAllEntities(challengeSubmissionRepository, searchQueryBuilder); + return submissions.stream().map(submission -> submission.getRegistrantId()).collect(toSet()); + } + + public ChallengeDetailDto getChallengeDetail(Long challengeId, String loginEmail) { + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challenge"); + TermQueryBuilder challengeIdQuery = termQuery("challengeId", challengeId); + //MatchQueryBuilder authorEmailQuery = matchQuery("authorEmail", loginEmail).minimumShouldMatch("100%"); + TermQueryBuilder expiredChallengeQuery = termQuery("expired", Boolean.TRUE); + + searchQueryBuilder.withQuery(boolQuery().must(challengeIdQuery).mustNot(expiredChallengeQuery)); + List challengeEntities = DataUtils.getAllEntities(challengeRepository, searchQueryBuilder); + + if (!challengeEntities.isEmpty()) { + ChallengeEntity challengeEntity = challengeEntities.get(0); + ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); + challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeId)); + calculateChallengePhases(challengeDetailDto); // challengeDetailDto.setCurrentPhase(getChallengeCurrentPhase(challengeEntity)); // challengeDetailDto.setNextPhase(getChallengeNextPhase(challengeEntity)); - calculateChallengePhases(challengeDetailDto); - challengeDetailDto.setIsAuthor(challengeEntity.getAuthorEmail().equals(loginEmail)); - return challengeDetailDto; - } - return null; + calculateChallengePhases(challengeDetailDto); + challengeDetailDto.setIsAuthor(challengeEntity.getAuthorEmail().equals(loginEmail)); + return challengeDetailDto; } + return null; + } + + public void calculateChallengePhases(ChallengeDetailDto challengeDetailDto) { + String now = DateTimeUtils.currentDate(); + + String timeline[] = { + challengeDetailDto.getSubmissionDateTime(), + challengeDetailDto.getPrototypeSubmissionDateTime(), + challengeDetailDto.getUxSubmissionDateTime(), + challengeDetailDto.getIdeaSubmissionDateTime(), + challengeDetailDto.getRegistrationDateTime() + }; - public void calculateChallengePhases(ChallengeDetailDto challengeDetailDto) { - String now = DateTimeUtils.currentDate(); - - String timeline[] = { - challengeDetailDto.getSubmissionDateTime(), - challengeDetailDto.getPrototypeSubmissionDateTime(), - challengeDetailDto.getUxSubmissionDateTime(), - challengeDetailDto.getIdeaSubmissionDateTime(), - challengeDetailDto.getRegistrationDateTime() - }; - - int currentIndex = -1; - int nextIndex = -1; - for (int i = 0; i < timeline.length; ++i) { - try { - String milestone = timeline[i]; - if (DateTimeUtils.daysBetween(now, milestone) >= 0) { - nextIndex = currentIndex; - currentIndex = i; - } - } catch (Exception e) { - continue; - } + int currentIndex = -1; + int nextIndex = -1; + for (int i = 0; i < timeline.length; ++i) { + try { + String milestone = timeline[i]; + if (DateTimeUtils.daysBetween(now, milestone) >= 0) { + nextIndex = currentIndex; + currentIndex = i; } + } + catch (Exception e) { + continue; + } + } - if (currentIndex == -1) {//FINAL - challengeDetailDto.setCurrentPhase(ChallengePhaseEnum.FINAL); - challengeDetailDto.setNextPhase(ChallengePhaseEnum.FINAL); - } else { - challengeDetailDto.setCurrentPhase(CHALLENGE_TIMELINE[currentIndex]); - challengeDetailDto.setNextPhase(CHALLENGE_TIMELINE[nextIndex > -1 ? nextIndex : currentIndex]); - } + if (currentIndex == -1) {//FINAL + challengeDetailDto.setCurrentPhase(ChallengePhaseEnum.FINAL); + challengeDetailDto.setNextPhase(ChallengePhaseEnum.FINAL); + } + else { + challengeDetailDto.setCurrentPhase(CHALLENGE_TIMELINE[currentIndex]); + challengeDetailDto.setNextPhase(CHALLENGE_TIMELINE[nextIndex > -1 ? nextIndex : currentIndex]); } + } // public static void main(String[] args) { // ChallengeDetailDto challengeDetailDto = new ChallengeDetailDto(); @@ -958,28 +983,28 @@ public void calculateChallengePhases(ChallengeDetailDto challengeDetailDto) { //// System.out.println(challengeDetailDto.getNextPhase()); // } - public ChallengeRegistrantDto acceptRegistrant(String ownerEmail, Long registrantId) { - ChallengeRegistrantEntity registrant = challengeRegistrantRepository.findOne(registrantId); - if (registrant == null) { - return null; - } - - ChallengeEntity challenge = challengeRepository.findOne(registrant.getChallengeId()); - if (!ownerEmail.equalsIgnoreCase(challenge.getAuthorEmail())) { - return null; - } + public ChallengeRegistrantDto acceptRegistrant(String ownerEmail, Long registrantId) { + ChallengeRegistrantEntity registrant = challengeRegistrantRepository.findOne(registrantId); + if (registrant == null) { + return null; + } - ChallengeDetailDto challengeDetailDto = dozerMapper.map(challenge, ChallengeDetailDto.class); - calculateChallengePhases(challengeDetailDto); - ChallengePhaseEnum activePhase = challengeDetailDto.getNextPhase(); - if (activePhase != registrant.getActivePhase()) { - registrant.setActivePhase(activePhase); - registrant = challengeRegistrantRepository.save(registrant); - } + ChallengeEntity challenge = challengeRepository.findOne(registrant.getChallengeId()); + if (!ownerEmail.equalsIgnoreCase(challenge.getAuthorEmail())) { + return null; + } - return dozerMapper.map(registrant, ChallengeRegistrantDto.class); + ChallengeDetailDto challengeDetailDto = dozerMapper.map(challenge, ChallengeDetailDto.class); + calculateChallengePhases(challengeDetailDto); + ChallengePhaseEnum activePhase = challengeDetailDto.getNextPhase(); + if (activePhase != registrant.getActivePhase()) { + registrant.setActivePhase(activePhase); + registrant = challengeRegistrantRepository.save(registrant); } + return dozerMapper.map(registrant, ChallengeRegistrantDto.class); + } + // private ChallengePhaseEnum getChallengeNextPhase(ChallengeEntity challengeEntity) { // int nextMilestoneIndex = getChallengeCurrentPhaseIndex(challengeEntity); // if (nextMilestoneIndex == -1) { From 727690146b4ec8e5184bece7d98b2cb1905d320c Mon Sep 17 00:00:00 2001 From: Phuong H Date: Mon, 19 Oct 2015 16:05:35 +0700 Subject: [PATCH 21/80] Able to load default challenge criterias into challenge registrant --- .../entity/ChallengeRegistrantDto.java | 13 ++++++ .../entity/ChallengeRegistrantEntity.java | 13 ++++++ .../service/impl/ChallengeServiceImpl.java | 14 +------ .../java/com/techlooper/util/DataUtils.java | 42 +++++++++++++------ 4 files changed, 58 insertions(+), 24 deletions(-) diff --git a/src/main/java/com/techlooper/entity/ChallengeRegistrantDto.java b/src/main/java/com/techlooper/entity/ChallengeRegistrantDto.java index 7845ccc81..debf9fc25 100644 --- a/src/main/java/com/techlooper/entity/ChallengeRegistrantDto.java +++ b/src/main/java/com/techlooper/entity/ChallengeRegistrantDto.java @@ -3,8 +3,11 @@ import com.techlooper.model.ChallengePhaseEnum; import com.techlooper.model.ChallengeSubmissionDto; import com.techlooper.model.Language; +import org.springframework.data.elasticsearch.annotations.Field; +import org.springframework.data.elasticsearch.annotations.FieldType; import java.util.List; +import java.util.Set; /** * Created by NguyenDangKhoa on 7/6/15. @@ -35,6 +38,16 @@ public class ChallengeRegistrantDto { private ChallengePhaseEnum activePhase; + private Set challengeCriterias; + + public Set getChallengeCriterias() { + return challengeCriterias; + } + + public void setChallengeCriterias(Set challengeCriterias) { + this.challengeCriterias = challengeCriterias; + } + public ChallengePhaseEnum getActivePhase() { return activePhase; } diff --git a/src/main/java/com/techlooper/entity/ChallengeRegistrantEntity.java b/src/main/java/com/techlooper/entity/ChallengeRegistrantEntity.java index e17b478a9..fcccf32dc 100644 --- a/src/main/java/com/techlooper/entity/ChallengeRegistrantEntity.java +++ b/src/main/java/com/techlooper/entity/ChallengeRegistrantEntity.java @@ -5,6 +5,8 @@ import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.*; +import java.util.Set; + import static org.springframework.data.elasticsearch.annotations.FieldType.Boolean; import static org.springframework.data.elasticsearch.annotations.FieldType.Double; import static org.springframework.data.elasticsearch.annotations.FieldType.Integer; @@ -56,6 +58,9 @@ public class ChallengeRegistrantEntity { @Field(type = String, index = FieldIndex.not_analyzed) private ChallengePhaseEnum activePhase; + @Field(type = FieldType.Nested) + private Set challengeCriterias; + public ChallengeRegistrantEntity() { } @@ -66,6 +71,14 @@ public ChallengeRegistrantEntity(Long registrantId, java.lang.String registrantE this.registrantFirstName = registrantFirstName; } + public Set getChallengeCriterias() { + return challengeCriterias; + } + + public void setChallengeCriterias(Set challengeCriterias) { + this.challengeCriterias = challengeCriterias; + } + public java.lang.String getDisqualifiedReason() { return disqualifiedReason; } diff --git a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java index d65d05525..8d943082e 100644 --- a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java @@ -188,18 +188,7 @@ public ChallengeEntity savePostChallenge(ChallengeDto challengeDto) throws Excep challengeEntity.setChallengeId(new Date().getTime()); } - Set defaultCriterias = new HashSet<>(); - defaultCriterias.add(ChallengeCriteria.ChallengeCriteriaBuilder.challengeCriteria() - .withName("UI/UX implemented solution").withWeight(25L).build()); - defaultCriterias.add(ChallengeCriteria.ChallengeCriteriaBuilder.challengeCriteria() - .withName("Creativity on the proposed solution").withWeight(25L).build()); - defaultCriterias.add(ChallengeCriteria.ChallengeCriteriaBuilder.challengeCriteria() - .withName("Source code quality").withWeight(25L).build()); - defaultCriterias.add(ChallengeCriteria.ChallengeCriteriaBuilder.challengeCriteria() - .withName("Usage of top edge technology").withWeight(25L).build()); - defaultCriterias.add(ChallengeCriteria.ChallengeCriteriaBuilder.challengeCriteria() - .withName("Application functionality").withWeight(25L).build()); - + challengeEntity.setChallengeCriterias(DataUtils.defaultChallengeCriterias()); return challengeRepository.save(challengeEntity); } @@ -328,6 +317,7 @@ public ChallengeRegistrantEntity joinChallengeEntity(ChallengeRegistrantDto chal ChallengeRegistrantEntity challengeRegistrantEntity = dozerMapper.map(challengeRegistrantDto, ChallengeRegistrantEntity.class); ChallengeEntity challengeEntity = challengeRepository.findOne(challengeId); challengeRegistrantEntity.setRegistrantId(new Date().getTime()); + challengeRegistrantEntity.setChallengeCriterias(challengeEntity.getChallengeCriterias()); challengeRegistrantEntity = challengeRegistrantRepository.save(challengeRegistrantEntity); try { sendApplicationEmailToContestant(challengeEntity, challengeRegistrantEntity); diff --git a/src/main/java/com/techlooper/util/DataUtils.java b/src/main/java/com/techlooper/util/DataUtils.java index 6e95cc172..411ac6b85 100644 --- a/src/main/java/com/techlooper/util/DataUtils.java +++ b/src/main/java/com/techlooper/util/DataUtils.java @@ -1,31 +1,49 @@ package com.techlooper.util; +import com.techlooper.entity.ChallengeCriteria; import org.springframework.data.domain.PageRequest; import org.springframework.data.elasticsearch.core.FacetedPage; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; +import java.util.Set; /** * Created by NguyenDangKhoa on 10/9/15. */ public class DataUtils { - public static List getAllEntities(ElasticsearchRepository repository, NativeSearchQueryBuilder searchQueryBuilder) { - List result = new ArrayList<>(); + public static List getAllEntities(ElasticsearchRepository repository, NativeSearchQueryBuilder searchQueryBuilder) { + List result = new ArrayList<>(); - FacetedPage facetedPage = repository.search(searchQueryBuilder.build()); - int totalPages = facetedPage.getTotalPages(); - int pageIndex = 0; + FacetedPage facetedPage = repository.search(searchQueryBuilder.build()); + int totalPages = facetedPage.getTotalPages(); + int pageIndex = 0; - while (pageIndex < totalPages) { - searchQueryBuilder.withPageable(new PageRequest(pageIndex, 50)); - result.addAll(repository.search(searchQueryBuilder.build()).getContent()); - pageIndex++; - } - - return result; + while (pageIndex < totalPages) { + searchQueryBuilder.withPageable(new PageRequest(pageIndex, 50)); + result.addAll(repository.search(searchQueryBuilder.build()).getContent()); + pageIndex++; } + + return result; + } + + public static Set defaultChallengeCriterias() { + Set defaultCriterias = new HashSet<>(); + defaultCriterias.add(ChallengeCriteria.ChallengeCriteriaBuilder.challengeCriteria() + .withName("UI/UX implemented solution").withWeight(25L).build()); + defaultCriterias.add(ChallengeCriteria.ChallengeCriteriaBuilder.challengeCriteria() + .withName("Creativity on the proposed solution").withWeight(25L).build()); + defaultCriterias.add(ChallengeCriteria.ChallengeCriteriaBuilder.challengeCriteria() + .withName("Source code quality").withWeight(25L).build()); + defaultCriterias.add(ChallengeCriteria.ChallengeCriteriaBuilder.challengeCriteria() + .withName("Usage of top edge technology").withWeight(25L).build()); + defaultCriterias.add(ChallengeCriteria.ChallengeCriteriaBuilder.challengeCriteria() + .withName("Application functionality").withWeight(25L).build()); + return defaultCriterias; + } } From ec97fa338937876258ce2136a1be854edb86ffb8 Mon Sep 17 00:00:00 2001 From: khoa-nd Date: Mon, 19 Oct 2015 16:18:32 +0700 Subject: [PATCH 22/80] Implement service to save email settings for specific employer --- .../techlooper/controller/UserController.java | 560 +++++++++--------- .../com/techlooper/dto/EmailSettingDto.java | 34 ++ .../techlooper/entity/EmailSettingEntity.java | 45 ++ .../elasticsearch/EmailSettingRepository.java | 9 + .../techlooper/service/EmployerService.java | 2 + .../service/impl/EmployerServiceImpl.java | 17 + 6 files changed, 386 insertions(+), 281 deletions(-) create mode 100644 src/main/java/com/techlooper/dto/EmailSettingDto.java create mode 100644 src/main/java/com/techlooper/entity/EmailSettingEntity.java create mode 100644 src/main/java/com/techlooper/repository/elasticsearch/EmailSettingRepository.java diff --git a/src/main/java/com/techlooper/controller/UserController.java b/src/main/java/com/techlooper/controller/UserController.java index 527111c6d..3244dd8a5 100644 --- a/src/main/java/com/techlooper/controller/UserController.java +++ b/src/main/java/com/techlooper/controller/UserController.java @@ -1,6 +1,7 @@ package com.techlooper.controller; import com.techlooper.dto.DashBoardInfo; +import com.techlooper.dto.EmailSettingDto; import com.techlooper.dto.JoinBySocialDto; import com.techlooper.dto.WebinarInfoDto; import com.techlooper.entity.*; @@ -42,85 +43,84 @@ @RestController public class UserController { - private final int MAX_NUMBER_OF_ITEMS_DISPLAY = 3; + private final int MAX_NUMBER_OF_ITEMS_DISPLAY = 3; - @Resource - private ApplicationContext applicationContext; + @Resource + private ApplicationContext applicationContext; - @Resource - private UserService userService; + @Resource + private UserService userService; - @Resource - private TextEncryptor textEncryptor; + @Resource + private TextEncryptor textEncryptor; - @Resource - private UserEvaluationService userEvaluationService; + @Resource + private UserEvaluationService userEvaluationService; - @Resource - private PromotionService promotionService; + @Resource + private PromotionService promotionService; - @Resource - private CurrencyService currencyService; + @Resource + private CurrencyService currencyService; - @Resource - private Mapper dozerMapper; + @Resource + private Mapper dozerMapper; - @Resource - private SalaryReviewService salaryReviewService; + @Resource + private SalaryReviewService salaryReviewService; - @Resource - private JobStatisticService jobStatisticService; + @Resource + private JobStatisticService jobStatisticService; - @Resource - private ChallengeService challengeService; + @Resource + private ChallengeService challengeService; - @Value("${mail.citibank.title.vn}") - private String citibankTitleVn; + @Value("${mail.citibank.title.vn}") + private String citibankTitleVn; - @Value("${mail.citibank.title.en}") - private String citibankTitleEn; + @Value("${mail.citibank.title.en}") + private String citibankTitleEn; - @Value("classpath:braille.txt") - private org.springframework.core.io.Resource brailleTextFile; + @Value("classpath:braille.txt") + private org.springframework.core.io.Resource brailleTextFile; - @Resource - private EmployerService employerService; + @Resource + private EmployerService employerService; - @Resource - private WebinarService webinarService; + @Resource + private WebinarService webinarService; - @Resource - private ProjectService projectService; + @Resource + private ProjectService projectService; - @Resource - private JobAggregatorService jobAggregatorService; + @Resource + private JobAggregatorService jobAggregatorService; - private final static Logger LOGGER = LoggerFactory.getLogger(UserController.class); + private final static Logger LOGGER = LoggerFactory.getLogger(UserController.class); - @RequestMapping(value = "/api/users/add", method = RequestMethod.POST) - public void save(@RequestBody UserImportData userImportData, HttpServletResponse httpServletResponse) { - SocialProvider provider = userImportData.getCrawlerSource(); - UserImportDataProcessor dataProcessor = applicationContext.getBean(provider + "UserImportDataProcessor", UserImportDataProcessor.class); - // process raw user data before import into ElasticSearch - List userImportEntities = dataProcessor.process(Arrays.asList(userImportData)); - httpServletResponse.setStatus(userService.addCrawledUser(userImportEntities.get(0), provider) ? - HttpServletResponse.SC_NO_CONTENT : HttpServletResponse.SC_NOT_ACCEPTABLE); - } - - @RequestMapping(value = "/api/users/addAll", method = RequestMethod.POST) - public void saveAll(@RequestBody List users, HttpServletResponse httpServletResponse) { - if (!users.isEmpty()) { - SocialProvider provider = users.get(0).getCrawlerSource(); - UserImportDataProcessor dataProcessor = applicationContext.getBean(provider + "UserImportDataProcessor", UserImportDataProcessor.class); - // process raw user data before import into ElasticSearch - List userImportEntities = dataProcessor.process(users); - httpServletResponse.setStatus(userService.addCrawledUserAll(userImportEntities, provider, UpdateModeEnum.MERGE) == users.size() ? - HttpServletResponse.SC_NO_CONTENT : HttpServletResponse.SC_NOT_ACCEPTABLE); + @RequestMapping(value = "/api/users/add", method = RequestMethod.POST) + public void save(@RequestBody UserImportData userImportData, HttpServletResponse httpServletResponse) { + SocialProvider provider = userImportData.getCrawlerSource(); + UserImportDataProcessor dataProcessor = applicationContext.getBean(provider + "UserImportDataProcessor", UserImportDataProcessor.class); + // process raw user data before import into ElasticSearch + List userImportEntities = dataProcessor.process(Arrays.asList(userImportData)); + httpServletResponse.setStatus(userService.addCrawledUser(userImportEntities.get(0), provider) ? + HttpServletResponse.SC_NO_CONTENT : HttpServletResponse.SC_NOT_ACCEPTABLE); } - else { - httpServletResponse.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE); + + @RequestMapping(value = "/api/users/addAll", method = RequestMethod.POST) + public void saveAll(@RequestBody List users, HttpServletResponse httpServletResponse) { + if (!users.isEmpty()) { + SocialProvider provider = users.get(0).getCrawlerSource(); + UserImportDataProcessor dataProcessor = applicationContext.getBean(provider + "UserImportDataProcessor", UserImportDataProcessor.class); + // process raw user data before import into ElasticSearch + List userImportEntities = dataProcessor.process(users); + httpServletResponse.setStatus(userService.addCrawledUserAll(userImportEntities, provider, UpdateModeEnum.MERGE) == users.size() ? + HttpServletResponse.SC_NO_CONTENT : HttpServletResponse.SC_NOT_ACCEPTABLE); + } else { + httpServletResponse.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE); + } } - } // @RequestMapping(value = "/user/save", method = RequestMethod.POST) // public List save(@RequestBody @Valid UserInfo userInfo, BindingResult result, HttpServletResponse httpServletResponse) { @@ -133,10 +133,10 @@ public void saveAll(@RequestBody List users, HttpServletResponse // return result.getFieldErrors(); // } - @RequestMapping(value = "/api/user/findTalent", method = RequestMethod.POST) - public TalentSearchResponse findTalent(@RequestBody(required = false) TalentSearchRequest param, HttpServletResponse httpServletResponse) { - return userService.findTalent(param); - } + @RequestMapping(value = "/api/user/findTalent", method = RequestMethod.POST) + public TalentSearchResponse findTalent(@RequestBody(required = false) TalentSearchRequest param, HttpServletResponse httpServletResponse) { + return userService.findTalent(param); + } // @RequestMapping(value = "/api/user/register", method = RequestMethod.POST) // public List registerUser(@RequestBody @Valid UserInfo userInfo, BindingResult result, HttpServletResponse httpServletResponse) { @@ -157,257 +157,255 @@ public TalentSearchResponse findTalent(@RequestBody(required = false) TalentSear // return userInfo; // } - @RequestMapping(value = "/user/verifyUserLogin", method = RequestMethod.POST) - public void verifyUserLogin(@RequestBody SocialRequest searchRequest, @CookieValue("techlooper.key") String techlooperKey, HttpServletResponse httpServletResponse) { - if (!textEncryptor.encrypt(searchRequest.getEmailAddress()).equals(techlooperKey)) { - httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN); + @RequestMapping(value = "/user/verifyUserLogin", method = RequestMethod.POST) + public void verifyUserLogin(@RequestBody SocialRequest searchRequest, @CookieValue("techlooper.key") String techlooperKey, HttpServletResponse httpServletResponse) { + if (!textEncryptor.encrypt(searchRequest.getEmailAddress()).equals(techlooperKey)) { + httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN); + } } - } - @RequestMapping(value = "/salaryReview", method = RequestMethod.POST) - public SalaryReviewDto reviewSalary(@RequestBody SalaryReviewEntity salaryReviewEntity) { - userEvaluationService.reviewSalary(salaryReviewEntity); - SalaryReviewDto salaryReviewDto = dozerMapper.map(salaryReviewEntity, SalaryReviewDto.class); - salaryReviewDto.setUsdToVndRate(currencyService.usdToVndRate()); + @RequestMapping(value = "/salaryReview", method = RequestMethod.POST) + public SalaryReviewDto reviewSalary(@RequestBody SalaryReviewEntity salaryReviewEntity) { + userEvaluationService.reviewSalary(salaryReviewEntity); + SalaryReviewDto salaryReviewDto = dozerMapper.map(salaryReviewEntity, SalaryReviewDto.class); + salaryReviewDto.setUsdToVndRate(currencyService.usdToVndRate()); // get top 3 similar salary reviews - SimilarSalaryReviewRequest request = dozerMapper.map(salaryReviewDto, SimilarSalaryReviewRequest.class); - List similarSalaryReviews = salaryReviewService.getSimilarSalaryReview(request); - salaryReviewDto.setSimilarSalaryReviews(similarSalaryReviews); - return salaryReviewDto; - } - - @RequestMapping(value = "/salaryReview/{id}", method = RequestMethod.GET) - public SalaryReviewDto getReviewSalary(@PathVariable("id") String id) { - return userService.findSalaryReviewById(id); - } - - @RequestMapping(value = "/saveSalaryReviewSurvey", method = RequestMethod.POST) - public void saveSurvey(@RequestBody SalaryReviewSurvey salaryReviewSurvey, HttpServletResponse httpServletResponse) { - boolean isSaved = userEvaluationService.saveSalaryReviewSurvey(salaryReviewSurvey); - if (isSaved) { - httpServletResponse.setStatus(HttpServletResponse.SC_OK); + SimilarSalaryReviewRequest request = dozerMapper.map(salaryReviewDto, SimilarSalaryReviewRequest.class); + List similarSalaryReviews = salaryReviewService.getSimilarSalaryReview(request); + salaryReviewDto.setSimilarSalaryReviews(similarSalaryReviews); + return salaryReviewDto; } - else { - httpServletResponse.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); + + @RequestMapping(value = "/salaryReview/{id}", method = RequestMethod.GET) + public SalaryReviewDto getReviewSalary(@PathVariable("id") String id) { + return userService.findSalaryReviewById(id); } - } - - @RequestMapping(value = "/priceJob", method = RequestMethod.POST) - public PriceJobEntity priceJob(@RequestBody PriceJobEntity priceJobEntity) { - userEvaluationService.priceJob(priceJobEntity); - return priceJobEntity; - } - - @RequestMapping(value = "/savePriceJobSurvey", method = RequestMethod.POST) - public void savePriceJobSurvey(@RequestBody PriceJobSurvey priceJobSurvey, HttpServletResponse httpServletResponse) { - boolean isSaved = userEvaluationService.savePriceJobSurvey(priceJobSurvey); - if (isSaved) { - httpServletResponse.setStatus(HttpServletResponse.SC_OK); + + @RequestMapping(value = "/saveSalaryReviewSurvey", method = RequestMethod.POST) + public void saveSurvey(@RequestBody SalaryReviewSurvey salaryReviewSurvey, HttpServletResponse httpServletResponse) { + boolean isSaved = userEvaluationService.saveSalaryReviewSurvey(salaryReviewSurvey); + if (isSaved) { + httpServletResponse.setStatus(HttpServletResponse.SC_OK); + } else { + httpServletResponse.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); + } } - else { - httpServletResponse.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); + + @RequestMapping(value = "/priceJob", method = RequestMethod.POST) + public PriceJobEntity priceJob(@RequestBody PriceJobEntity priceJobEntity) { + userEvaluationService.priceJob(priceJobEntity); + return priceJobEntity; } - } - - @RequestMapping("promotion/citibank/creditCard") - public void placeCitibankCreditCardPromotion(@Valid @RequestBody CitibankCreditCardPromotion citibankCreditCardPromotion) throws IOException, TemplateException { - promotionService.placePromotion(citibankCreditCardPromotion); - } - - @RequestMapping(value = "salaryReview/placeSalaryReviewReport", method = RequestMethod.POST) - public void placeSalaryReviewReport(@Valid @RequestBody EmailRequest emailRequest) throws TemplateException, IOException, MessagingException { - salaryReviewService.sendSalaryReviewReportEmail(emailRequest); - } - - @MessageMapping("/jobs/createJobAlert") - public void createJobAlert(VnwJobAlertRequest vnwJobAlertRequest) { - salaryReviewService.createVnwJobAlert(vnwJobAlertRequest); - } - - @RequestMapping(value = "/promotion/citibank/title/{lang}", method = RequestMethod.GET) - public String getCitiBankPromotionTitle(@PathVariable String lang) { - return "vn".equalsIgnoreCase(lang) ? citibankTitleVn : citibankTitleEn; - } - - @RequestMapping(value = "/getPromoted/email", method = RequestMethod.POST) - public long sendTopDemandedSkillsEmail(@Valid @RequestBody GetPromotedEmailRequest emailRequest) throws MessagingException, IOException, TemplateException { - long getPromotedId = salaryReviewService.saveGetPromotedInformation(emailRequest); - - if (getPromotedId != -1L && emailRequest.getHasResult()) { - salaryReviewService.sendTopDemandedSkillsEmail(getPromotedId, emailRequest); + + @RequestMapping(value = "/savePriceJobSurvey", method = RequestMethod.POST) + public void savePriceJobSurvey(@RequestBody PriceJobSurvey priceJobSurvey, HttpServletResponse httpServletResponse) { + boolean isSaved = userEvaluationService.savePriceJobSurvey(priceJobSurvey); + if (isSaved) { + httpServletResponse.setStatus(HttpServletResponse.SC_OK); + } else { + httpServletResponse.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); + } } - return getPromotedId; - } - - @RequestMapping(value = "/getPromoted/survey", method = RequestMethod.POST) - public long saveGetPromotedSurvey(@RequestBody GetPromotedSurveyRequest getPromotedSurveyRequest, HttpServletResponse httpServletResponse) { - return salaryReviewService.saveGetPromotedSurvey(getPromotedSurveyRequest); - } - - @RequestMapping(value = "/getPromotedResult/{id}", method = RequestMethod.GET) - public GetPromotedEntity getPromotedResult(@PathVariable Long id) { - return salaryReviewService.getPromotedEntity(id); - } - - @RequestMapping(value = "/download/braille", method = RequestMethod.GET) - public void getFile(HttpServletResponse response) throws IOException { - try { - response.setContentType("text/plain"); - response.setHeader("Content-Disposition", "attachment;filename=braille.txt"); - IOUtils.copy(brailleTextFile.getInputStream(), response.getOutputStream()); - response.flushBuffer(); + @RequestMapping("promotion/citibank/creditCard") + public void placeCitibankCreditCardPromotion(@Valid @RequestBody CitibankCreditCardPromotion citibankCreditCardPromotion) throws IOException, TemplateException { + promotionService.placePromotion(citibankCreditCardPromotion); } - catch (IOException ex) { - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - throw ex; + + @RequestMapping(value = "salaryReview/placeSalaryReviewReport", method = RequestMethod.POST) + public void placeSalaryReviewReport(@Valid @RequestBody EmailRequest emailRequest) throws TemplateException, IOException, MessagingException { + salaryReviewService.sendSalaryReviewReportEmail(emailRequest); } - } - - @PreAuthorize("hasAnyAuthority('EMPLOYER')") - @RequestMapping(value = "user/vnw-current", method = RequestMethod.GET) - public VnwUserDto getVnwCurrentUser(HttpServletRequest servletRequest) { - return userService.findVnwUserByUsername(servletRequest.getRemoteUser()); - } - - @RequestMapping(value = "/personalHomepage", method = RequestMethod.GET) - public PersonalHomepageDto getPersonalHomepageDto() { - PersonalHomepageDto personalHomepage = new PersonalHomepageDto(); - - TermStatisticRequest termStatisticRequest = new TermStatisticRequest(); - try { - termStatisticRequest.setTerm(jobStatisticService.getTechnicalTermHasTheMostJob().getKey()); - TermStatisticResponse termStatisticResponse = - jobStatisticService.generateTermStatistic(termStatisticRequest, HistogramEnum.ONE_YEAR); - personalHomepage.setTermStatistic(termStatisticResponse); + + @MessageMapping("/jobs/createJobAlert") + public void createJobAlert(VnwJobAlertRequest vnwJobAlertRequest) { + salaryReviewService.createVnwJobAlert(vnwJobAlertRequest); } - catch (Exception ex) { - LOGGER.error(ex.getMessage(), ex); + + @RequestMapping(value = "/promotion/citibank/title/{lang}", method = RequestMethod.GET) + public String getCitiBankPromotionTitle(@PathVariable String lang) { + return "vn".equalsIgnoreCase(lang) ? citibankTitleVn : citibankTitleEn; } - try { - ChallengeDetailDto latestChallenge = challengeService.getTheLatestChallenge(); - latestChallenge.setNumberOfRegistrants(challengeService.getNumberOfRegistrants(latestChallenge.getChallengeId())); - personalHomepage.setLatestChallenge(latestChallenge); + @RequestMapping(value = "/getPromoted/email", method = RequestMethod.POST) + public long sendTopDemandedSkillsEmail(@Valid @RequestBody GetPromotedEmailRequest emailRequest) throws MessagingException, IOException, TemplateException { + long getPromotedId = salaryReviewService.saveGetPromotedInformation(emailRequest); + + if (getPromotedId != -1L && emailRequest.getHasResult()) { + salaryReviewService.sendTopDemandedSkillsEmail(getPromotedId, emailRequest); + } + + return getPromotedId; } - catch (Exception ex) { - LOGGER.error(ex.getMessage(), ex); + + @RequestMapping(value = "/getPromoted/survey", method = RequestMethod.POST) + public long saveGetPromotedSurvey(@RequestBody GetPromotedSurveyRequest getPromotedSurveyRequest, HttpServletResponse httpServletResponse) { + return salaryReviewService.saveGetPromotedSurvey(getPromotedSurveyRequest); } - try { - personalHomepage.setLatestEvents(webinarService.listUpcomingWebinar()); + @RequestMapping(value = "/getPromotedResult/{id}", method = RequestMethod.GET) + public GetPromotedEntity getPromotedResult(@PathVariable Long id) { + return salaryReviewService.getPromotedEntity(id); } - catch (Exception ex) { - LOGGER.error(ex.getMessage(), ex); + + @RequestMapping(value = "/download/braille", method = RequestMethod.GET) + public void getFile(HttpServletResponse response) throws IOException { + try { + response.setContentType("text/plain"); + response.setHeader("Content-Disposition", "attachment;filename=braille.txt"); + IOUtils.copy(brailleTextFile.getInputStream(), response.getOutputStream()); + response.flushBuffer(); + } catch (IOException ex) { + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + throw ex; + } + } + + @PreAuthorize("hasAnyAuthority('EMPLOYER')") + @RequestMapping(value = "user/vnw-current", method = RequestMethod.GET) + public VnwUserDto getVnwCurrentUser(HttpServletRequest servletRequest) { + return userService.findVnwUserByUsername(servletRequest.getRemoteUser()); } - try { - List latestProjects = projectService.listProject().stream().limit(MAX_NUMBER_OF_ITEMS_DISPLAY).collect(toList()); - personalHomepage.setLatestProjects(latestProjects); + @RequestMapping(value = "/personalHomepage", method = RequestMethod.GET) + public PersonalHomepageDto getPersonalHomepageDto() { + PersonalHomepageDto personalHomepage = new PersonalHomepageDto(); + + TermStatisticRequest termStatisticRequest = new TermStatisticRequest(); + try { + termStatisticRequest.setTerm(jobStatisticService.getTechnicalTermHasTheMostJob().getKey()); + TermStatisticResponse termStatisticResponse = + jobStatisticService.generateTermStatistic(termStatisticRequest, HistogramEnum.ONE_YEAR); + personalHomepage.setTermStatistic(termStatisticResponse); + } catch (Exception ex) { + LOGGER.error(ex.getMessage(), ex); + } + + try { + ChallengeDetailDto latestChallenge = challengeService.getTheLatestChallenge(); + latestChallenge.setNumberOfRegistrants(challengeService.getNumberOfRegistrants(latestChallenge.getChallengeId())); + personalHomepage.setLatestChallenge(latestChallenge); + } catch (Exception ex) { + LOGGER.error(ex.getMessage(), ex); + } + + try { + personalHomepage.setLatestEvents(webinarService.listUpcomingWebinar()); + } catch (Exception ex) { + LOGGER.error(ex.getMessage(), ex); + } + + try { + List latestProjects = projectService.listProject().stream().limit(MAX_NUMBER_OF_ITEMS_DISPLAY).collect(toList()); + personalHomepage.setLatestProjects(latestProjects); + } catch (Exception ex) { + LOGGER.error(ex.getMessage(), ex); + } + + JobSearchCriteria criteria = new JobSearchCriteria(); + try { + JobSearchResponse allJobSearchResponse = jobAggregatorService.findJob(criteria); + personalHomepage.setTotalLatestJob(allJobSearchResponse.getTotalJob()); + } catch (Exception ex) { + LOGGER.error(ex.getMessage(), ex); + } + + criteria.setTopPriority(Boolean.FALSE); + try { + JobSearchResponse latestJobSearchResponse = jobAggregatorService.findJob(criteria); + personalHomepage.setLatestJobs(latestJobSearchResponse.getJobs().stream().limit(MAX_NUMBER_OF_ITEMS_DISPLAY).collect(toSet())); + } catch (Exception ex) { + LOGGER.error(ex.getMessage(), ex); + } + + return personalHomepage; } - catch (Exception ex) { - LOGGER.error(ex.getMessage(), ex); + + @PreAuthorize("hasAnyAuthority('JOB_SEEKER', 'EMPLOYER')") + @RequestMapping(value = "/user/current", method = RequestMethod.GET) + public UserProfileDto getUserProfile(HttpServletRequest request) { + LOGGER.debug("Reading current user profile info"); + Principal userPrincipal = request.getUserPrincipal(); + Object principal = ((UsernamePasswordAuthenticationToken) userPrincipal).getPrincipal(); + if (!(principal instanceof UserProfileDto)) { + return dozerMapper.map(userService.findVnwUserByUsername(request.getRemoteUser()), UserProfileDto.class); + } + return (UserProfileDto) principal; + } + + @PreAuthorize("hasAnyAuthority('EMPLOYER')") + @RequestMapping(value = "/user/employer/dashboard-info", method = RequestMethod.GET) + public DashBoardInfo getEmployerDashboardInfo(HttpServletRequest request) { + return employerService.getDashboardInfo(request.getRemoteUser()); } - JobSearchCriteria criteria = new JobSearchCriteria(); - try { - JobSearchResponse allJobSearchResponse = jobAggregatorService.findJob(criteria); - personalHomepage.setTotalLatestJob(allJobSearchResponse.getTotalJob()); + @PreAuthorize("hasAnyAuthority('EMPLOYER', 'JOB_SEEKER')") + @RequestMapping(value = "/user/employer/webinar", method = RequestMethod.POST) + public WebinarInfoDto createWebinar(@RequestBody WebinarInfoDto webinarInfoDto, HttpServletRequest request) throws IOException { + Principal userPrincipal = request.getUserPrincipal(); + Object principal = ((UsernamePasswordAuthenticationToken) userPrincipal).getPrincipal(); + UserProfileDto organiser = (principal instanceof UserProfileDto) ? ((UserProfileDto) principal) : + dozerMapper.map(getVnwCurrentUser(request), UserProfileDto.class); + return webinarService.createWebinarInfo(webinarInfoDto, organiser); } - catch (Exception ex) { - LOGGER.error(ex.getMessage(), ex); + + @RequestMapping(value = "user/webinars", method = RequestMethod.GET) + public Collection findAvailableWebinars() { + return webinarService.findAllWebinars(); } - criteria.setTopPriority(Boolean.FALSE); - try { - JobSearchResponse latestJobSearchResponse = jobAggregatorService.findJob(criteria); - personalHomepage.setLatestJobs(latestJobSearchResponse.getJobs().stream().limit(MAX_NUMBER_OF_ITEMS_DISPLAY).collect(toSet())); + @RequestMapping(value = "user/webinar/{id}", method = RequestMethod.GET) + public WebinarInfoDto findWebinarById(@PathVariable Long id) { + return webinarService.findWebinarById(id); } - catch (Exception ex) { - LOGGER.error(ex.getMessage(), ex); + + @RequestMapping(value = "user/webinar/join", method = RequestMethod.POST) + public WebinarInfoDto joinWebinar(@RequestBody JoinBySocialDto joinBySocialDto) throws Exception { + return webinarService.joinWebinar(joinBySocialDto); } - return personalHomepage; - } - - @PreAuthorize("hasAnyAuthority('JOB_SEEKER', 'EMPLOYER')") - @RequestMapping(value = "/user/current", method = RequestMethod.GET) - public UserProfileDto getUserProfile(HttpServletRequest request) { - LOGGER.debug("Reading current user profile info"); - Principal userPrincipal = request.getUserPrincipal(); - Object principal = ((UsernamePasswordAuthenticationToken) userPrincipal).getPrincipal(); - if (!(principal instanceof UserProfileDto)) { - return dozerMapper.map(userService.findVnwUserByUsername(request.getRemoteUser()), UserProfileDto.class); + @PreAuthorize("hasAuthority('EMPLOYER')") + @RequestMapping(value = "user/challengeRegistrantNames/{challengeId}/{now}", method = RequestMethod.GET) + public List getDailyChallengeRegistrantNames(HttpServletRequest request, HttpServletResponse response, + @PathVariable Long challengeId, @PathVariable Long now) { + if (challengeService.isOwnerOfChallenge(request.getRemoteUser(), challengeId)) { + List registrants = challengeService.findChallengeRegistrantWithinPeriod(challengeId, now, TimePeriodEnum.TWENTY_FOUR_HOURS); + return registrants.stream() + .map(registrant -> registrant.getRegistrantFirstName() + " " + registrant.getRegistrantLastName()) + .collect(Collectors.toList()); + } + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + return null; } - return (UserProfileDto) principal; - } - - @PreAuthorize("hasAnyAuthority('EMPLOYER')") - @RequestMapping(value = "/user/employer/dashboard-info", method = RequestMethod.GET) - public DashBoardInfo getEmployerDashboardInfo(HttpServletRequest request) { - return employerService.getDashboardInfo(request.getRemoteUser()); - } - - @PreAuthorize("hasAnyAuthority('EMPLOYER', 'JOB_SEEKER')") - @RequestMapping(value = "/user/employer/webinar", method = RequestMethod.POST) - public WebinarInfoDto createWebinar(@RequestBody WebinarInfoDto webinarInfoDto, HttpServletRequest request) throws IOException { - Principal userPrincipal = request.getUserPrincipal(); - Object principal = ((UsernamePasswordAuthenticationToken) userPrincipal).getPrincipal(); - UserProfileDto organiser = (principal instanceof UserProfileDto) ? ((UserProfileDto) principal) : - dozerMapper.map(getVnwCurrentUser(request), UserProfileDto.class); - return webinarService.createWebinarInfo(webinarInfoDto, organiser); - } - - @RequestMapping(value = "user/webinars", method = RequestMethod.GET) - public Collection findAvailableWebinars() { - return webinarService.findAllWebinars(); - } - - @RequestMapping(value = "user/webinar/{id}", method = RequestMethod.GET) - public WebinarInfoDto findWebinarById(@PathVariable Long id) { - return webinarService.findWebinarById(id); - } - - @RequestMapping(value = "user/webinar/join", method = RequestMethod.POST) - public WebinarInfoDto joinWebinar(@RequestBody JoinBySocialDto joinBySocialDto) throws Exception { - return webinarService.joinWebinar(joinBySocialDto); - } - - @PreAuthorize("hasAuthority('EMPLOYER')") - @RequestMapping(value = "user/challengeRegistrantNames/{challengeId}/{now}", method = RequestMethod.GET) - public List getDailyChallengeRegistrantNames(HttpServletRequest request, HttpServletResponse response, - @PathVariable Long challengeId, @PathVariable Long now) { - if (challengeService.isOwnerOfChallenge(request.getRemoteUser(), challengeId)) { - List registrants = challengeService.findChallengeRegistrantWithinPeriod(challengeId, now, TimePeriodEnum.TWENTY_FOUR_HOURS); - return registrants.stream() - .map(registrant -> registrant.getRegistrantFirstName() + " " + registrant.getRegistrantLastName()) - .collect(Collectors.toList()); + + @PreAuthorize("hasAuthority('EMPLOYER')") + @RequestMapping(value = "user/challenge/sendMailToDaily/{challengeId}/{now}", method = RequestMethod.POST) + public void sendEmailToDailyChallengeRegistrants(HttpServletRequest request, HttpServletResponse response, + @PathVariable Long challengeId, @PathVariable Long now, @RequestBody EmailContent emailContent) { + if (!challengeService.sendEmailToDailyChallengeRegistrants(request.getRemoteUser(), challengeId, now, emailContent)) { + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + } } - response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - return null; - } - - @PreAuthorize("hasAuthority('EMPLOYER')") - @RequestMapping(value = "user/challenge/sendMailToDaily/{challengeId}/{now}", method = RequestMethod.POST) - public void sendEmailToDailyChallengeRegistrants(HttpServletRequest request, HttpServletResponse response, - @PathVariable Long challengeId, @PathVariable Long now, @RequestBody EmailContent emailContent) { - if (!challengeService.sendEmailToDailyChallengeRegistrants(request.getRemoteUser(), challengeId, now, emailContent)) { - response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + + @PreAuthorize("hasAuthority('EMPLOYER')") + @RequestMapping(value = "user/challenge/feedback/{challengeId}/{registrantId}", method = RequestMethod.POST) + public void sendFeedbackToRegistrant(HttpServletRequest request, HttpServletResponse response, + @PathVariable Long challengeId, @PathVariable Long registrantId, @RequestBody EmailContent emailContent) { + if (!challengeService.sendEmailToRegistrant(request.getRemoteUser(), challengeId, registrantId, emailContent)) { + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + } } - } - - @PreAuthorize("hasAuthority('EMPLOYER')") - @RequestMapping(value = "user/challenge/feedback/{challengeId}/{registrantId}", method = RequestMethod.POST) - public void sendFeedbackToRegistrant(HttpServletRequest request, HttpServletResponse response, - @PathVariable Long challengeId, @PathVariable Long registrantId, @RequestBody EmailContent emailContent) { - if (!challengeService.sendEmailToRegistrant(request.getRemoteUser(), challengeId, registrantId, emailContent)) { - response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + + @PreAuthorize("hasAuthority('EMPLOYER')") + @RequestMapping(value = "user/challenge/accept/{registrantId}", method = RequestMethod.GET) + public ChallengeRegistrantDto acceptChallengeRegistrant(HttpServletRequest request, @PathVariable Long registrantId) { + return challengeService.acceptRegistrant(request.getRemoteUser(), registrantId); } - } - @PreAuthorize("hasAuthority('EMPLOYER')") - @RequestMapping(value = "user/challenge/accept/{registrantId}", method = RequestMethod.GET) - public ChallengeRegistrantDto acceptChallengeRegistrant(HttpServletRequest request, @PathVariable Long registrantId) { - return challengeService.acceptRegistrant(request.getRemoteUser(), registrantId); - } + @PreAuthorize("hasAnyAuthority('EMPLOYER')") + @RequestMapping(value = "/user/employer/saveEmailSetting", method = RequestMethod.POST) + public EmailSettingDto saveEmployerEmailSetting(HttpServletRequest request, @RequestBody EmailSettingDto emailSettingDto) { + emailSettingDto.setEmployerEmail(request.getRemoteUser()); + return employerService.saveEmployerEmailSetting(emailSettingDto); + } } diff --git a/src/main/java/com/techlooper/dto/EmailSettingDto.java b/src/main/java/com/techlooper/dto/EmailSettingDto.java new file mode 100644 index 000000000..94ae3d13b --- /dev/null +++ b/src/main/java/com/techlooper/dto/EmailSettingDto.java @@ -0,0 +1,34 @@ +package com.techlooper.dto; + +public class EmailSettingDto { + + private String employerEmail; + + private String replyEmail; + + private String emailSignature; + + public String getEmployerEmail() { + return employerEmail; + } + + public void setEmployerEmail(String employerEmail) { + this.employerEmail = employerEmail; + } + + public String getReplyEmail() { + return replyEmail; + } + + public void setReplyEmail(String replyEmail) { + this.replyEmail = replyEmail; + } + + public String getEmailSignature() { + return emailSignature; + } + + public void setEmailSignature(String emailSignature) { + this.emailSignature = emailSignature; + } +} diff --git a/src/main/java/com/techlooper/entity/EmailSettingEntity.java b/src/main/java/com/techlooper/entity/EmailSettingEntity.java new file mode 100644 index 000000000..cbf1a1ced --- /dev/null +++ b/src/main/java/com/techlooper/entity/EmailSettingEntity.java @@ -0,0 +1,45 @@ +package com.techlooper.entity; + +import org.springframework.data.annotation.Id; +import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.annotations.Field; +import org.springframework.data.elasticsearch.annotations.FieldIndex; + +import static org.springframework.data.elasticsearch.annotations.FieldType.String; + +@Document(indexName = "techlooper", type = "emailSetting") +public class EmailSettingEntity { + + @Id + private String employerEmail; + + @Field(type = String, index = FieldIndex.not_analyzed) + private String replyEmail; + + @Field(type = String) + private String emailSignature; + + public String getEmployerEmail() { + return employerEmail; + } + + public void setEmployerEmail(String employerEmail) { + this.employerEmail = employerEmail; + } + + public String getReplyEmail() { + return replyEmail; + } + + public void setReplyEmail(String replyEmail) { + this.replyEmail = replyEmail; + } + + public String getEmailSignature() { + return emailSignature; + } + + public void setEmailSignature(String emailSignature) { + this.emailSignature = emailSignature; + } +} diff --git a/src/main/java/com/techlooper/repository/elasticsearch/EmailSettingRepository.java b/src/main/java/com/techlooper/repository/elasticsearch/EmailSettingRepository.java new file mode 100644 index 000000000..cb7d1aad3 --- /dev/null +++ b/src/main/java/com/techlooper/repository/elasticsearch/EmailSettingRepository.java @@ -0,0 +1,9 @@ +package com.techlooper.repository.elasticsearch; + +import com.techlooper.entity.EmailSettingEntity; +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface EmailSettingRepository extends ElasticsearchRepository { +} diff --git a/src/main/java/com/techlooper/service/EmployerService.java b/src/main/java/com/techlooper/service/EmployerService.java index 94d90c13b..66db74db2 100644 --- a/src/main/java/com/techlooper/service/EmployerService.java +++ b/src/main/java/com/techlooper/service/EmployerService.java @@ -1,6 +1,7 @@ package com.techlooper.service; import com.techlooper.dto.DashBoardInfo; +import com.techlooper.dto.EmailSettingDto; import com.techlooper.entity.vnw.VnwCompany; import com.techlooper.entity.vnw.VnwUser; @@ -15,4 +16,5 @@ public interface EmployerService { VnwUser findEmployerByUsername(String employerUsername); + EmailSettingDto saveEmployerEmailSetting(EmailSettingDto emailSettingDto); } diff --git a/src/main/java/com/techlooper/service/impl/EmployerServiceImpl.java b/src/main/java/com/techlooper/service/impl/EmployerServiceImpl.java index 93622834b..d4864d34b 100644 --- a/src/main/java/com/techlooper/service/impl/EmployerServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/EmployerServiceImpl.java @@ -1,14 +1,18 @@ package com.techlooper.service.impl; import com.techlooper.dto.DashBoardInfo; +import com.techlooper.dto.EmailSettingDto; +import com.techlooper.entity.EmailSettingEntity; import com.techlooper.entity.vnw.VnwCompany; import com.techlooper.entity.vnw.VnwUser; import com.techlooper.repository.elasticsearch.ChallengeRegistrantRepository; +import com.techlooper.repository.elasticsearch.EmailSettingRepository; import com.techlooper.repository.vnw.VnwCompanyRepo; import com.techlooper.repository.vnw.VnwUserRepo; import com.techlooper.service.ChallengeService; import com.techlooper.service.EmployerService; import com.techlooper.service.ProjectService; +import org.dozer.Mapper; import org.springframework.stereotype.Service; import javax.annotation.Resource; @@ -34,6 +38,12 @@ public class EmployerServiceImpl implements EmployerService { @Resource private ChallengeRegistrantRepository challengeRegistrantRepository; + @Resource + private EmailSettingRepository emailSettingRepository; + + @Resource + private Mapper dozerMapper; + public DashBoardInfo getDashboardInfo(String owner) { VnwUser user = vnwUserRepo.findByUsernameIgnoreCase(owner); String email = user.getEmail(); @@ -53,4 +63,11 @@ public VnwCompany findCompanyById(Long companyId) { public VnwUser findEmployerByUsername(String employerUsername) { return vnwUserRepo.findByUsernameIgnoreCase(employerUsername); } + + @Override + public EmailSettingDto saveEmployerEmailSetting(EmailSettingDto emailSettingDto) { + EmailSettingEntity emailSettingEntity = dozerMapper.map(emailSettingDto, EmailSettingEntity.class); + emailSettingRepository.save(emailSettingEntity); + return emailSettingDto; + } } From 79028f92d629b646ac27c88685f0c8bae85f85f7 Mon Sep 17 00:00:00 2001 From: johnsonpham Date: Mon, 19 Oct 2015 16:29:19 +0700 Subject: [PATCH 23/80] add email setting page --- src/main/webapp/assets/modules/_app.js | 5 ++++ .../webapp/assets/modules/common/json.val.js | 6 +++-- .../modules/email-setting/email-setting.html | 27 +++++++++++++++++++ .../modules/email-setting/emailSetting.js | 3 +++ 4 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 src/main/webapp/assets/modules/email-setting/email-setting.html create mode 100644 src/main/webapp/assets/modules/email-setting/emailSetting.js diff --git a/src/main/webapp/assets/modules/_app.js b/src/main/webapp/assets/modules/_app.js index 570e77021..934265da1 100644 --- a/src/main/webapp/assets/modules/_app.js +++ b/src/main/webapp/assets/modules/_app.js @@ -204,6 +204,11 @@ techlooper.config(["$routeProvider", "$translateProvider", "$authProvider", "loc .when("/404", { templateUrl: "modules/404/404.html" }) + .when("/email-setting", { + templateUrl: "modules/email-setting/email-setting.html", + controller: "emailSetting" + + }) .otherwise({ redirectTo: function (err, path, params) { if (!$.isEmptyObject(params)) { diff --git a/src/main/webapp/assets/modules/common/json.val.js b/src/main/webapp/assets/modules/common/json.val.js index afae4d3e3..1322b8a40 100644 --- a/src/main/webapp/assets/modules/common/json.val.js +++ b/src/main/webapp/assets/modules/common/json.val.js @@ -183,7 +183,8 @@ techlooper.factory("jsonValue", function () { freelancerPostProject: "/freelancer/post-project", freelancerProjectDetail: "/freelancer/project-detail", freelancerProjects: "/freelancer/projects", - whyFreelancer: "/freelancer/whyFreelancer" + whyFreelancer: "/freelancer/whyFreelancer", + emailSetting: "/email-setting" }, views: { @@ -225,7 +226,8 @@ techlooper.factory("jsonValue", function () { events: "events", eventDetails: "eventDetails", topics: "topics", - notFound: "notFound" + notFound: "notFound", + emailSetting: "emailSetting" }, uiViews: [ diff --git a/src/main/webapp/assets/modules/email-setting/email-setting.html b/src/main/webapp/assets/modules/email-setting/email-setting.html new file mode 100644 index 000000000..d53914716 --- /dev/null +++ b/src/main/webapp/assets/modules/email-setting/email-setting.html @@ -0,0 +1,27 @@ + diff --git a/src/main/webapp/assets/modules/email-setting/emailSetting.js b/src/main/webapp/assets/modules/email-setting/emailSetting.js new file mode 100644 index 000000000..322e92abe --- /dev/null +++ b/src/main/webapp/assets/modules/email-setting/emailSetting.js @@ -0,0 +1,3 @@ +techlooper.controller("emailSetting", function ($scope) { + +}); \ No newline at end of file From fd23f604e9cde7b0ba5a9c77edd821fd774465d7 Mon Sep 17 00:00:00 2001 From: johnsonpham Date: Mon, 19 Oct 2015 17:43:56 +0700 Subject: [PATCH 24/80] style for email setting page --- src/main/webapp/assets/sass/main.sass | 38 ++++++++++++++++++++++++--- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/src/main/webapp/assets/sass/main.sass b/src/main/webapp/assets/sass/main.sass index c2f56be34..ec78e4427 100644 --- a/src/main/webapp/assets/sass/main.sass +++ b/src/main/webapp/assets/sass/main.sass @@ -71,9 +71,8 @@ textarea.change-color .gray background-color: #dfdede .green - transition: border 0.5s ease + transition: border, color 0.5s ease border: 1px solid #008000 !important - transition: color 0.5s ease color: #008000 !important .btn padding: 7px 12px 3px 12px @@ -2276,4 +2275,37 @@ a.salary-report-share:hover padding-top: 30px img width: 200px - margin: auto \ No newline at end of file + margin: auto +.email-setting-page + margin: auto + text-align: center + .email-setting-form + width: 80% + clear: both + display: inline-block + padding: 20px + margin: auto + .note-editor + min-height: inherit + label + clear: both + display: inline-block + width: 100% + text-align: left + padding: 0 + .form-group + width: 100% + clear: both + display: inline-block + label + width: 100% + clear: both + input + width: 100% + margin: 0 + .mail-text + border: 0 + text-align: left + .mail-body + border: 0 + padding: 0 From 6204b6324fb14ac3c86cd0f60a03d45bcbb598a4 Mon Sep 17 00:00:00 2001 From: johnsonpham Date: Mon, 19 Oct 2015 17:46:26 +0700 Subject: [PATCH 25/80] make responsive for Email Setting page --- src/main/webapp/assets/sass/z-responsive-candidate.sass | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/webapp/assets/sass/z-responsive-candidate.sass b/src/main/webapp/assets/sass/z-responsive-candidate.sass index 95da0e8f9..22ab5bef4 100644 --- a/src/main/webapp/assets/sass/z-responsive-candidate.sass +++ b/src/main/webapp/assets/sass/z-responsive-candidate.sass @@ -2131,7 +2131,10 @@ width: 100% clear: both padding-top: 10px - + .email-setting-page + .email-setting-form + width: 100% + padding: 20px 10px @media (max-width: 460px) .rwd-table margin: auto From fb4970b693a7fa5a47a01738c1a8a7212b13b897 Mon Sep 17 00:00:00 2001 From: Phuong H Date: Mon, 19 Oct 2015 17:55:06 +0700 Subject: [PATCH 26/80] Add challenge registrant criteria to registrant entity --- .../entity/ChallengeRegistrantCriteria.java | 29 +++++++++++++++++++ .../entity/ChallengeRegistrantDto.java | 8 ++--- .../entity/ChallengeRegistrantEntity.java | 6 ++-- .../service/impl/ChallengeServiceImpl.java | 10 ++++++- 4 files changed, 44 insertions(+), 9 deletions(-) create mode 100644 src/main/java/com/techlooper/entity/ChallengeRegistrantCriteria.java diff --git a/src/main/java/com/techlooper/entity/ChallengeRegistrantCriteria.java b/src/main/java/com/techlooper/entity/ChallengeRegistrantCriteria.java new file mode 100644 index 000000000..63b7f936a --- /dev/null +++ b/src/main/java/com/techlooper/entity/ChallengeRegistrantCriteria.java @@ -0,0 +1,29 @@ +package com.techlooper.entity; + +import java.io.Serializable; + +/** + * Created by phuonghqh on 10/19/15. + */ +public class ChallengeRegistrantCriteria implements Serializable { + + private String name; + + private Long score; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Long getScore() { + return score; + } + + public void setScore(Long score) { + this.score = score; + } +} diff --git a/src/main/java/com/techlooper/entity/ChallengeRegistrantDto.java b/src/main/java/com/techlooper/entity/ChallengeRegistrantDto.java index debf9fc25..3c54f8012 100644 --- a/src/main/java/com/techlooper/entity/ChallengeRegistrantDto.java +++ b/src/main/java/com/techlooper/entity/ChallengeRegistrantDto.java @@ -3,8 +3,6 @@ import com.techlooper.model.ChallengePhaseEnum; import com.techlooper.model.ChallengeSubmissionDto; import com.techlooper.model.Language; -import org.springframework.data.elasticsearch.annotations.Field; -import org.springframework.data.elasticsearch.annotations.FieldType; import java.util.List; import java.util.Set; @@ -38,13 +36,13 @@ public class ChallengeRegistrantDto { private ChallengePhaseEnum activePhase; - private Set challengeCriterias; + private Set challengeCriterias; - public Set getChallengeCriterias() { + public Set getChallengeCriterias() { return challengeCriterias; } - public void setChallengeCriterias(Set challengeCriterias) { + public void setChallengeCriterias(Set challengeCriterias) { this.challengeCriterias = challengeCriterias; } diff --git a/src/main/java/com/techlooper/entity/ChallengeRegistrantEntity.java b/src/main/java/com/techlooper/entity/ChallengeRegistrantEntity.java index fcccf32dc..536898309 100644 --- a/src/main/java/com/techlooper/entity/ChallengeRegistrantEntity.java +++ b/src/main/java/com/techlooper/entity/ChallengeRegistrantEntity.java @@ -59,7 +59,7 @@ public class ChallengeRegistrantEntity { private ChallengePhaseEnum activePhase; @Field(type = FieldType.Nested) - private Set challengeCriterias; + private Set challengeCriterias; public ChallengeRegistrantEntity() { } @@ -71,11 +71,11 @@ public ChallengeRegistrantEntity(Long registrantId, java.lang.String registrantE this.registrantFirstName = registrantFirstName; } - public Set getChallengeCriterias() { + public Set getChallengeCriterias() { return challengeCriterias; } - public void setChallengeCriterias(Set challengeCriterias) { + public void setChallengeCriterias(Set challengeCriterias) { this.challengeCriterias = challengeCriterias; } diff --git a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java index 8d943082e..1169e1301 100644 --- a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java @@ -317,8 +317,16 @@ public ChallengeRegistrantEntity joinChallengeEntity(ChallengeRegistrantDto chal ChallengeRegistrantEntity challengeRegistrantEntity = dozerMapper.map(challengeRegistrantDto, ChallengeRegistrantEntity.class); ChallengeEntity challengeEntity = challengeRepository.findOne(challengeId); challengeRegistrantEntity.setRegistrantId(new Date().getTime()); - challengeRegistrantEntity.setChallengeCriterias(challengeEntity.getChallengeCriterias()); +// challengeRegistrantEntity.setChallengeCriterias(challengeEntity.getChallengeCriterias()); + if (challengeEntity.getChallengeCriterias() != null) { + final Set criterias = new HashSet<>(); + challengeEntity.getChallengeCriterias().forEach(criteria -> { + criterias.add(dozerMapper.map(criteria, ChallengeRegistrantCriteria.class)); + }); + challengeRegistrantEntity.setChallengeCriterias(criterias); + } challengeRegistrantEntity = challengeRegistrantRepository.save(challengeRegistrantEntity); + try { sendApplicationEmailToContestant(challengeEntity, challengeRegistrantEntity); //sendApplicationEmailToEmployer(challengeEntity, challengeRegistrantEntity); From 1366990cce76edf0ef3b9265b58d21be69f4c89b Mon Sep 17 00:00:00 2001 From: johnsonpham Date: Mon, 19 Oct 2015 18:06:46 +0700 Subject: [PATCH 27/80] add Evaluation Criteria Form for Challenge details page --- .../webapp/assets/modules/common/json.val.js | 5 +- .../modules/contest-detail/contestDetail.html | 7 ++ .../contest-detail/contestDetailDirective.js | 8 ++ .../contest-detail/evaluationCriteria.html | 79 +++++++++++++++++++ .../modules/email-setting/email-setting.html | 7 +- .../webapp/assets/sass/contest-detail.sass | 71 ++++++++++++++++- 6 files changed, 166 insertions(+), 11 deletions(-) create mode 100644 src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html diff --git a/src/main/webapp/assets/modules/common/json.val.js b/src/main/webapp/assets/modules/common/json.val.js index 1322b8a40..66ad2618e 100644 --- a/src/main/webapp/assets/modules/common/json.val.js +++ b/src/main/webapp/assets/modules/common/json.val.js @@ -1045,16 +1045,15 @@ techlooper.factory("jsonValue", function () { summerNoteConfig: { height: 150, toolbar: [ - ['headline', ['style']], ['fontface', ['fontname']], ['textsize', ['fontsize']], - ['style', ['bold', 'italic', 'underline', 'superscript', 'subscript', 'strikethrough', 'clear']], + ['style', ['bold', 'italic', 'underline', 'strikethrough']], ['fontclr', ['color']], ['alignment', ['ul', 'ol', 'paragraph', 'lineheight']], ['height', ['height']], ['table', ['table']], ['insert', ['link', 'hr']], - ['view', ['fullscreen', 'codeview']] + ['view', ['fullscreen']] ] } } diff --git a/src/main/webapp/assets/modules/contest-detail/contestDetail.html b/src/main/webapp/assets/modules/contest-detail/contestDetail.html index 8d298ff76..4de2af2b0 100644 --- a/src/main/webapp/assets/modules/contest-detail/contestDetail.html +++ b/src/main/webapp/assets/modules/contest-detail/contestDetail.html @@ -12,6 +12,9 @@

    {{contestDetail.challengeName}}
  • {{'registrants' | translate}} ({{contestDetail.numberOfRegistrants}})
  • +
  • + +
  • @@ -373,6 +376,7 @@

    +

    +
    + +

    diff --git a/src/main/webapp/assets/modules/contest-detail/contestDetailDirective.js b/src/main/webapp/assets/modules/contest-detail/contestDetailDirective.js index 3be1dcbfa..b0ce1bc11 100644 --- a/src/main/webapp/assets/modules/contest-detail/contestDetailDirective.js +++ b/src/main/webapp/assets/modules/contest-detail/contestDetailDirective.js @@ -149,4 +149,12 @@ techlooper link: function (scope, element, attr, ctrl) { } }; +}).directive('evaluationCriteria', function () { + return { + restrict: "E", + replace: true, + templateUrl: "modules/contest-detail/evaluationCriteria.html", + link: function (scope, element, attr, ctrl) { + } + }; }); \ No newline at end of file diff --git a/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html b/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html new file mode 100644 index 000000000..26690065c --- /dev/null +++ b/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html @@ -0,0 +1,79 @@ +
    +
    +
    +
    +

    +
    +
    +

    +
    +
    +
    +
    +
    + +
    +
    + + +
    +
    +
    +
    + +
    +
    + + +
    +
    +
    +
    + +
    +
    + + +
    +
    +
    +
    + +
    +
    + + +
    +
    +
    +
    + +
    +
    + + +
    +
    +
    +
    +
    +
    +
    +

    +
    +
    +

    +
    +
    +
    +
    +
    + +
    +
    + / 100 +
    +
    +
    +
    +
    \ No newline at end of file diff --git a/src/main/webapp/assets/modules/email-setting/email-setting.html b/src/main/webapp/assets/modules/email-setting/email-setting.html index d53914716..5fee0ec04 100644 --- a/src/main/webapp/assets/modules/email-setting/email-setting.html +++ b/src/main/webapp/assets/modules/email-setting/email-setting.html @@ -6,12 +6,11 @@

  • + Lorem Ipsum is simply dummy text of the printing
    + 25 x
    + =
    + 0
    @@ -37,17 +41,21 @@
  • + Lorem Ipsum is simply dummy text of the printing
    + 25 x
    + =
    + 0
    @@ -56,17 +64,21 @@
  • + Lorem Ipsum is simply dummy text of the printing
    + 25 x
    + =
    + 0
    @@ -75,17 +87,21 @@
  • - Lorem Ipsum is simply + + Lorem Ipsum is simply dummy text of the printing
    + 25 x
    + =
    + 0
    @@ -94,17 +110,21 @@
  • - Lorem Ipsum is simply dummy text + + Lorem Ipsum is simply dummy text of the printing
    + 25 x
    + =
    + 0
    diff --git a/src/main/webapp/assets/sass/contest-detail.sass b/src/main/webapp/assets/sass/contest-detail.sass index f8a3688cd..a49ed5560 100644 --- a/src/main/webapp/assets/sass/contest-detail.sass +++ b/src/main/webapp/assets/sass/contest-detail.sass @@ -630,6 +630,8 @@ border-bottom: 1px solid #fff text-align: left display: inline-block + .label-col + display: none p margin: 0 padding: 0 diff --git a/src/main/webapp/assets/sass/z-responsive-candidate.sass b/src/main/webapp/assets/sass/z-responsive-candidate.sass index 692bbf4f9..ea19c1bde 100644 --- a/src/main/webapp/assets/sass/z-responsive-candidate.sass +++ b/src/main/webapp/assets/sass/z-responsive-candidate.sass @@ -1407,18 +1407,46 @@ text-align: left !important .registrant-score .score-form ul li + .label-col + display: inline-block + clear: both + width: 100% + text-align: left + font-weight: 500 .points-name clear: both display: block padding-bottom: 5px width: 100% + .weight-input + width: 35% .points-input - width: 22% + width: 35% padding-left: 0 + .all-points + width: 30% .points-comment - width: 78% + width: 100% + display: inline-block + clear: both + padding: 10px 0 0 0 .score-form ul li:last-child text-align: center + .score-form ul li.header + display: none + .score-form ul li.total + .points-comment + width: 100% + display: inline-block + clear: both + padding: 10px 0 0 0 + .score + width: 20% + span.math + display: none + p + width: 80% + padding-top: 0 .contest-detail-action p text-align: left !important From 62c52458efd094400ed9457905dab47f9e9bb072 Mon Sep 17 00:00:00 2001 From: johnsonpham Date: Tue, 20 Oct 2015 18:07:05 +0700 Subject: [PATCH 51/80] validation email and show successfully and fail messages for setting email page --- .../modules/email-setting/email-setting.html | 9 +++++- .../modules/email-setting/emailSetting.js | 32 +++++++++++++++---- .../modules/translation/messages_en.json | 6 ++-- src/main/webapp/assets/sass/main.sass | 6 ++++ 4 files changed, 44 insertions(+), 9 deletions(-) diff --git a/src/main/webapp/assets/modules/email-setting/email-setting.html b/src/main/webapp/assets/modules/email-setting/email-setting.html index 1d590842a..1d623cd68 100644 --- a/src/main/webapp/assets/modules/email-setting/email-setting.html +++ b/src/main/webapp/assets/modules/email-setting/email-setting.html @@ -4,10 +4,17 @@

    - {{user.score}} + 45
    diff --git a/src/main/webapp/assets/sass/contest-detail.sass b/src/main/webapp/assets/sass/contest-detail.sass index a49ed5560..1508a782a 100644 --- a/src/main/webapp/assets/sass/contest-detail.sass +++ b/src/main/webapp/assets/sass/contest-detail.sass @@ -392,6 +392,9 @@ text-align: center border-radius: 3px border: 1px solid #d4d7d8 + a + color: #2e6da4 + font-weight: 500 .registration-action width: 10% float: left @@ -665,6 +668,7 @@ input width: 75% float: left + text-align: center span height: 34px line-height: 34px From 15d7aa04d0edadbda28f148a5fb12246f8d21ef6 Mon Sep 17 00:00:00 2001 From: johnsonpham Date: Wed, 21 Oct 2015 11:10:45 +0700 Subject: [PATCH 54/80] update html --- .../contest-detail/contestDetailScore.html | 94 +------------------ 1 file changed, 1 insertion(+), 93 deletions(-) diff --git a/src/main/webapp/assets/modules/contest-detail/contestDetailScore.html b/src/main/webapp/assets/modules/contest-detail/contestDetailScore.html index cd45562c4..5fffa994c 100644 --- a/src/main/webapp/assets/modules/contest-detail/contestDetailScore.html +++ b/src/main/webapp/assets/modules/contest-detail/contestDetailScore.html @@ -28,99 +28,7 @@
    - - = -
    -
    - - 0 -
    -
    - -
    -
  • -
  • -
    - - Lorem Ipsum is simply dummy text of the printing -
    -
    - - 25 - x -
    -
    - - - = -
    -
    - - 0 -
    -
    - -
    -
  • -
  • -
    - - Lorem Ipsum is simply dummy text of the printing -
    -
    - - 25 - x -
    -
    - - - = -
    -
    - - 0 -
    -
    - -
    -
  • -
  • -
    - - Lorem Ipsum is simply dummy text of the printing -
    -
    - - 25 - x -
    -
    - - - = -
    -
    - - 0 -
    -
    - -
    -
  • -
  • -
    - - Lorem Ipsum is simply dummy text of the printing -
    -
    - - 25 - x -
    -
    - - + =
    From 737ba0482039537f912d7cc8afcbea67353b7197 Mon Sep 17 00:00:00 2001 From: khoa-nd Date: Wed, 21 Oct 2015 11:33:21 +0700 Subject: [PATCH 55/80] Load list of email templates dynamically --- .../techlooper/controller/UserController.java | 13 ++- .../com/techlooper/dto/EmailTemplateDto.java | 24 +++++ .../entity/EmailTemplateEntity.java | 91 +++++++++++++++++++ .../EmailTemplateRepository.java | 9 ++ .../com/techlooper/service/EmailService.java | 7 +- .../service/impl/EmailServiceImpl.java | 28 ++++++ .../assets/modules/common/apiService.js | 4 + .../assets/modules/common/resourcesService.js | 23 +++-- .../modules/translation/messages_en.json | 1 + .../modules/translation/messages_vi.json | 1 + 10 files changed, 189 insertions(+), 12 deletions(-) create mode 100644 src/main/java/com/techlooper/dto/EmailTemplateDto.java create mode 100644 src/main/java/com/techlooper/entity/EmailTemplateEntity.java create mode 100644 src/main/java/com/techlooper/repository/elasticsearch/EmailTemplateRepository.java diff --git a/src/main/java/com/techlooper/controller/UserController.java b/src/main/java/com/techlooper/controller/UserController.java index f1fcfb9b7..424e3d0e5 100644 --- a/src/main/java/com/techlooper/controller/UserController.java +++ b/src/main/java/com/techlooper/controller/UserController.java @@ -1,9 +1,6 @@ package com.techlooper.controller; -import com.techlooper.dto.DashBoardInfo; -import com.techlooper.dto.EmailSettingDto; -import com.techlooper.dto.JoinBySocialDto; -import com.techlooper.dto.WebinarInfoDto; +import com.techlooper.dto.*; import com.techlooper.entity.*; import com.techlooper.entity.userimport.UserImportEntity; import com.techlooper.entity.vnw.dto.VnwUserDto; @@ -96,6 +93,9 @@ public class UserController { @Resource private JobAggregatorService jobAggregatorService; + @Resource + private EmailService emailService; + private final static Logger LOGGER = LoggerFactory.getLogger(UserController.class); @RequestMapping(value = "/api/users/add", method = RequestMethod.POST) @@ -414,4 +414,9 @@ public EmailSettingDto saveEmployerEmailSetting(HttpServletRequest request, @Req public EmailSettingDto findEmployerEmailSetting(HttpServletRequest request) { return employerService.findEmployerEmailSetting(request.getRemoteUser()); } + + @RequestMapping(value = "/emailTemplates", method = RequestMethod.GET) + public List getAvailableEmailTemplates() { + return emailService.getAvailableEmailTemplates(); + } } diff --git a/src/main/java/com/techlooper/dto/EmailTemplateDto.java b/src/main/java/com/techlooper/dto/EmailTemplateDto.java new file mode 100644 index 000000000..054605bf6 --- /dev/null +++ b/src/main/java/com/techlooper/dto/EmailTemplateDto.java @@ -0,0 +1,24 @@ +package com.techlooper.dto; + +public class EmailTemplateDto { + + private Long templateId; + + private String templateName; + + public Long getTemplateId() { + return templateId; + } + + public void setTemplateId(Long templateId) { + this.templateId = templateId; + } + + public String getTemplateName() { + return templateName; + } + + public void setTemplateName(String templateName) { + this.templateName = templateName; + } +} diff --git a/src/main/java/com/techlooper/entity/EmailTemplateEntity.java b/src/main/java/com/techlooper/entity/EmailTemplateEntity.java new file mode 100644 index 000000000..dce50f28c --- /dev/null +++ b/src/main/java/com/techlooper/entity/EmailTemplateEntity.java @@ -0,0 +1,91 @@ +package com.techlooper.entity; + +import org.springframework.data.annotation.Id; +import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.annotations.Field; + +import java.util.List; + +import static org.springframework.data.elasticsearch.annotations.FieldType.Boolean; +import static org.springframework.data.elasticsearch.annotations.FieldType.String; + +@Document(indexName = "techlooper", type = "emailTemplate") +public class EmailTemplateEntity { + + @Id + private Long templateId; + + @Field(type = String) + private String templateName; + + @Field(type = String) + private String subject; + + @Field(type = String) + private List subjectVariables; + + @Field(type = String) + private String body; + + @Field(type = String) + private List bodyVariables; + + @Field(type = Boolean) + private Boolean isEnable; + + public Long getTemplateId() { + return templateId; + } + + public void setTemplateId(Long templateId) { + this.templateId = templateId; + } + + public String getTemplateName() { + return templateName; + } + + public void setTemplateName(String templateName) { + this.templateName = templateName; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public List getSubjectVariables() { + return subjectVariables; + } + + public void setSubjectVariables(List subjectVariables) { + this.subjectVariables = subjectVariables; + } + + public String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } + + public List getBodyVariables() { + return bodyVariables; + } + + public void setBodyVariables(List bodyVariables) { + this.bodyVariables = bodyVariables; + } + + public Boolean getIsEnable() { + return isEnable; + } + + public void setIsEnable(Boolean isEnable) { + this.isEnable = isEnable; + } +} diff --git a/src/main/java/com/techlooper/repository/elasticsearch/EmailTemplateRepository.java b/src/main/java/com/techlooper/repository/elasticsearch/EmailTemplateRepository.java new file mode 100644 index 000000000..8ed05b663 --- /dev/null +++ b/src/main/java/com/techlooper/repository/elasticsearch/EmailTemplateRepository.java @@ -0,0 +1,9 @@ +package com.techlooper.repository.elasticsearch; + +import com.techlooper.entity.EmailTemplateEntity; +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface EmailTemplateRepository extends ElasticsearchRepository { +} diff --git a/src/main/java/com/techlooper/service/EmailService.java b/src/main/java/com/techlooper/service/EmailService.java index 181b55bdb..a62bcb2ea 100644 --- a/src/main/java/com/techlooper/service/EmailService.java +++ b/src/main/java/com/techlooper/service/EmailService.java @@ -1,11 +1,16 @@ package com.techlooper.service; +import com.techlooper.dto.EmailTemplateDto; import com.techlooper.model.EmailContent; +import java.util.List; + /** * Created by phuonghqh on 10/1/15. */ public interface EmailService { - boolean sendEmail(EmailContent emailContent); + boolean sendEmail(EmailContent emailContent); + + List getAvailableEmailTemplates(); } diff --git a/src/main/java/com/techlooper/service/impl/EmailServiceImpl.java b/src/main/java/com/techlooper/service/impl/EmailServiceImpl.java index 0e82dd19d..19c442105 100644 --- a/src/main/java/com/techlooper/service/impl/EmailServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/EmailServiceImpl.java @@ -1,13 +1,20 @@ package com.techlooper.service.impl; +import com.techlooper.dto.EmailTemplateDto; +import com.techlooper.entity.EmailTemplateEntity; import com.techlooper.model.EmailContent; import com.techlooper.model.Language; +import com.techlooper.repository.elasticsearch.EmailTemplateRepository; import com.techlooper.service.EmailService; +import com.techlooper.util.DataUtils; import freemarker.template.Template; import org.apache.commons.lang3.StringUtils; +import org.dozer.Mapper; +import org.elasticsearch.index.query.QueryBuilders; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Service; @@ -16,7 +23,9 @@ import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeUtility; import java.io.StringWriter; +import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Map; /** @@ -42,6 +51,12 @@ public class EmailServiceImpl implements EmailService { @Value("${web.baseUrl}") private String webBaseUrl; + @Resource + private EmailTemplateRepository emailTemplateRepository; + + @Resource + private Mapper dozerMapper; + public boolean sendEmail(EmailContent emailContent) { try { String subject = StringUtils.isNotEmpty(emailContent.getSubject()) ? emailContent.getSubject() : "[No Subject]"; @@ -66,4 +81,17 @@ public boolean sendEmail(EmailContent emailContent) { } return true; } + + @Override + public List getAvailableEmailTemplates() { + List emailTemplateDtoList = new ArrayList<>(); + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("emailTemplate"); + searchQueryBuilder.withQuery(QueryBuilders.termQuery("isEnable", Boolean.TRUE)); + List templateEntities = DataUtils.getAllEntities(emailTemplateRepository, searchQueryBuilder); + + for (EmailTemplateEntity emailTemplateEntity : templateEntities) { + emailTemplateDtoList.add(dozerMapper.map(emailTemplateEntity, EmailTemplateDto.class)); + } + return emailTemplateDtoList; + } } diff --git a/src/main/webapp/assets/modules/common/apiService.js b/src/main/webapp/assets/modules/common/apiService.js index 8a2b3a4f8..3acd29c1a 100644 --- a/src/main/webapp/assets/modules/common/apiService.js +++ b/src/main/webapp/assets/modules/common/apiService.js @@ -266,6 +266,10 @@ techlooper.factory("apiService", function ($rootScope, $location, jsonValue, $ht loadEmailSetting: function () { return $http.get("user/employer/emailSetting"); + }, + + getAvailableEmailTemplates : function () { + return $http.get("emailTemplates"); } }; diff --git a/src/main/webapp/assets/modules/common/resourcesService.js b/src/main/webapp/assets/modules/common/resourcesService.js index 616ea68a5..37eb08919 100644 --- a/src/main/webapp/assets/modules/common/resourcesService.js +++ b/src/main/webapp/assets/modules/common/resourcesService.js @@ -1,4 +1,4 @@ -techlooper.factory("resourcesService", function ($translate, $q) { +techlooper.factory("resourcesService", function ($translate, $q, apiService) { var registrantsFilterOptions = [ {translate: "allContestants", id: "registrantId"}, {translate: "allSubmission", id: "challengeSubmission"} @@ -24,11 +24,20 @@ techlooper.factory("resourcesService", function ($translate, $q) { {translate: "theSolutionIsInnovative", id: "theSolutionIsInnovative"} ]; - var emailTemplateOptions = [ - {translate: "welcomeContestant", id: "welcomeContestant"}, - {translate: "askContestantSubmission", id: "askContestantSubmission"}, - {translate: "disqualifyContestant", id: "disqualifyContestant"} - ]; + var emailTemplateOptions = []; + + apiService.getAvailableEmailTemplates() + .success(function (data) { + $.each(data, function (i, template) { + var templateOption = { + translate: template.templateId, + id: template.templateName + }; + emailTemplateOptions.push(templateOption); + }); + }) + + console.log(emailTemplateOptions); var paymentOptions = [ {translate: "hourlyByByHour", reviewTranslate: "hourlyJob", id: "hourly"}, @@ -95,7 +104,7 @@ techlooper.factory("resourcesService", function ($translate, $q) { paymentConfig: $.extend(true, {}, {options: paymentOptions}, idSelectize("paymentConfig")), estimatedDurationConfig: $.extend(true, {}, {options: estimatedDurationOptions}, idSelectize("estimatedDurationConfig")), estimatedWorkloadConfig: $.extend(true, {}, {options: estimatedWorkloadOptions}, idSelectize("estimatedWorkloadConfig")), - emailTemplateConfig: $.extend(true, {}, {options: emailTemplateOptions}, titleSelectize("emailTemplateConfig")), + emailTemplateConfig: $.extend(true, {}, {options: emailTemplateOptions}, idSelectize("emailTemplateConfig")), inOptions: function (title, config) { var index = -1; $.each(config.options, function (i, opt) { diff --git a/src/main/webapp/assets/modules/translation/messages_en.json b/src/main/webapp/assets/modules/translation/messages_en.json index 412d0c726..ee6f89124 100644 --- a/src/main/webapp/assets/modules/translation/messages_en.json +++ b/src/main/webapp/assets/modules/translation/messages_en.json @@ -778,6 +778,7 @@ "404Error": "This URL leads to 404 page. Please check again.", "cannotSendMail": "You don’t have right to perform this action.", "template": "Template:", + "chooseATemplate": "Choose a template", "welcomeContestant": "Welcome new contestant", "askContestantSubmission": "Ask for submission", "disqualifyContestant": "Disqualify a contestant", diff --git a/src/main/webapp/assets/modules/translation/messages_vi.json b/src/main/webapp/assets/modules/translation/messages_vi.json index 9e8fcd66f..95034a1d0 100644 --- a/src/main/webapp/assets/modules/translation/messages_vi.json +++ b/src/main/webapp/assets/modules/translation/messages_vi.json @@ -781,6 +781,7 @@ "404Error": "URL này dẫn đến trang không tồn tại (lỗi 404). Xin vui lòng kiểm tra lại.", "cannotSendMail": "Bạn không có quyền thực hiện hành động này.", "template": "Mẫu Email:", + "chooseATemplate": "Chọn một mẫu email", "welcomeContestant": "Chào mừng thí sinh mới", "askContestantSubmission": "Yêu cầu về bài gửi", "disqualifyContestant": "Loại bỏ thí sinh", From ef385cfcd6d3a3e7deb6fbf23e2afe0517107b69 Mon Sep 17 00:00:00 2001 From: Phuong H Date: Wed, 21 Oct 2015 11:52:22 +0700 Subject: [PATCH 56/80] Able to save registrant score --- bower.json | 3 +- .../ChallengeCriteriaController.java | 25 ++++++++-- .../entity/ChallengeRegistrantDto.java | 10 ++-- .../techlooper/model/ChallengeDetailDto.java | 10 ++-- .../service/ChallengeCriteriaService.java | 4 +- .../impl/ChallengeCriteriaServiceImpl.java | 42 ++++++++++++++--- .../service/impl/ChallengeServiceImpl.java | 12 +++-- .../assets/modules/common/apiService.js | 27 +++++++++-- .../modules/common/model/challengeDetail.js | 21 +++++++++ .../common/model/challengeRegistrant.js | 27 +++++++++++ .../assets/modules/common/securityService.js | 2 +- .../modules/contest-detail/contestDetail.html | 4 +- .../contest-detail/contestDetailController.js | 1 - .../contest-detail/evaluationCriteria.html | 46 +++---------------- .../ChallengeCriteriaServiceImplTest.java | 16 ++++--- 15 files changed, 170 insertions(+), 80 deletions(-) create mode 100644 src/main/webapp/assets/modules/common/model/challengeDetail.js create mode 100644 src/main/webapp/assets/modules/common/model/challengeRegistrant.js diff --git a/bower.json b/bower.json index 12eee0c96..a055e5bff 100644 --- a/bower.json +++ b/bower.json @@ -45,7 +45,8 @@ "moment": "latest", "angular-strap": "latest", "datetimepicker": "latest", - "angular-summernote": "latest" + "angular-summernote": "latest", + "underscore": "latest" }, "overrides": { "jquery": { diff --git a/src/main/java/com/techlooper/controller/ChallengeCriteriaController.java b/src/main/java/com/techlooper/controller/ChallengeCriteriaController.java index 7bd540c18..f848b413b 100644 --- a/src/main/java/com/techlooper/controller/ChallengeCriteriaController.java +++ b/src/main/java/com/techlooper/controller/ChallengeCriteriaController.java @@ -1,15 +1,17 @@ package com.techlooper.controller; -import com.techlooper.entity.ChallengeEntity; import com.techlooper.model.ChallengeCriteriaDto; +import com.techlooper.model.ChallengeRegistrantCriteriaDto; import com.techlooper.service.ChallengeCriteriaService; import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; /** * Created by phuonghqh on 10/16/15. @@ -22,7 +24,24 @@ public class ChallengeCriteriaController { @PreAuthorize("hasAuthority('EMPLOYER')") @RequestMapping(value = "challenge/criteria", method = RequestMethod.POST) - public ChallengeCriteriaDto save(ChallengeCriteriaDto challengeCriteriaDto, HttpServletRequest request) { - return challengeCriteriaService.saveChallengeCriteria(challengeCriteriaDto, request.getRemoteUser()); + public ChallengeCriteriaDto saveChallengeCriteria(@RequestBody ChallengeCriteriaDto challengeCriteriaDto, HttpServletRequest request, HttpServletResponse response) { + ChallengeCriteriaDto result = challengeCriteriaService.saveChallengeCriteria(challengeCriteriaDto, request.getRemoteUser()); + if (result == null) { + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + } + return result; } + + @PreAuthorize("hasAuthority('EMPLOYER')") + @RequestMapping(value = "challengeRegistrant/criteria", method = RequestMethod.POST) + public ChallengeRegistrantCriteriaDto saveChallengeRegistrantCriteria(@RequestBody ChallengeRegistrantCriteriaDto registrantCriteriaDto, + HttpServletRequest request, HttpServletResponse response) { + ChallengeRegistrantCriteriaDto result = challengeCriteriaService.saveScoreChallengeRegistrantCriteria(registrantCriteriaDto, request.getRemoteUser()); + if (result == null) { + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + } + return result; + } + + } diff --git a/src/main/java/com/techlooper/entity/ChallengeRegistrantDto.java b/src/main/java/com/techlooper/entity/ChallengeRegistrantDto.java index 3c54f8012..e0d6612e2 100644 --- a/src/main/java/com/techlooper/entity/ChallengeRegistrantDto.java +++ b/src/main/java/com/techlooper/entity/ChallengeRegistrantDto.java @@ -36,14 +36,14 @@ public class ChallengeRegistrantDto { private ChallengePhaseEnum activePhase; - private Set challengeCriterias; + private Set criteria; - public Set getChallengeCriterias() { - return challengeCriterias; + public Set getCriteria() { + return criteria; } - public void setChallengeCriterias(Set challengeCriterias) { - this.challengeCriterias = challengeCriterias; + public void setCriteria(Set criteria) { + this.criteria = criteria; } public ChallengePhaseEnum getActivePhase() { diff --git a/src/main/java/com/techlooper/model/ChallengeDetailDto.java b/src/main/java/com/techlooper/model/ChallengeDetailDto.java index 759274e15..5d139db95 100644 --- a/src/main/java/com/techlooper/model/ChallengeDetailDto.java +++ b/src/main/java/com/techlooper/model/ChallengeDetailDto.java @@ -60,14 +60,14 @@ public class ChallengeDetailDto { private Boolean isAuthor; - private Set challengeCriterias; + private Set criteria; - public Set getChallengeCriterias() { - return challengeCriterias; + public Set getCriteria() { + return criteria; } - public void setChallengeCriterias(Set challengeCriterias) { - this.challengeCriterias = challengeCriterias; + public void setCriteria(Set criteria) { + this.criteria = criteria; } public Boolean getAuthor() { diff --git a/src/main/java/com/techlooper/service/ChallengeCriteriaService.java b/src/main/java/com/techlooper/service/ChallengeCriteriaService.java index a63017d0a..f5fde522c 100644 --- a/src/main/java/com/techlooper/service/ChallengeCriteriaService.java +++ b/src/main/java/com/techlooper/service/ChallengeCriteriaService.java @@ -1,7 +1,7 @@ package com.techlooper.service; -import com.techlooper.entity.ChallengeEntity; import com.techlooper.model.ChallengeCriteriaDto; +import com.techlooper.model.ChallengeRegistrantCriteriaDto; /** * Created by phuonghqh on 10/16/15. @@ -9,4 +9,6 @@ public interface ChallengeCriteriaService { ChallengeCriteriaDto saveChallengeCriteria(ChallengeCriteriaDto challengeCriteriaDto, String owner); + + ChallengeRegistrantCriteriaDto saveScoreChallengeRegistrantCriteria(ChallengeRegistrantCriteriaDto registrantCriteriaDto, String ownerEmail); } diff --git a/src/main/java/com/techlooper/service/impl/ChallengeCriteriaServiceImpl.java b/src/main/java/com/techlooper/service/impl/ChallengeCriteriaServiceImpl.java index 36cef3bbb..b76060544 100644 --- a/src/main/java/com/techlooper/service/impl/ChallengeCriteriaServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/ChallengeCriteriaServiceImpl.java @@ -6,6 +6,7 @@ import com.techlooper.entity.ChallengeRegistrantEntity; import com.techlooper.model.ChallengeCriteriaDto; import com.techlooper.model.ChallengeRegistrantCriteriaDto; +import com.techlooper.model.ChallengeRegistrantCriteriaDto.ChallengeRegistrantCriteriaDtoBuilder; import com.techlooper.repository.elasticsearch.ChallengeRegistrantRepository; import com.techlooper.repository.elasticsearch.ChallengeRepository; import com.techlooper.service.ChallengeCriteriaService; @@ -41,7 +42,7 @@ public class ChallengeCriteriaServiceImpl implements ChallengeCriteriaService { public ChallengeCriteriaDto saveChallengeCriteria(ChallengeCriteriaDto challengeCriteriaDto, String ownerEmail) { ChallengeEntity challenge = challengeService.findChallengeIdAndOwnerEmail(challengeCriteriaDto.getChallengeId(), ownerEmail); if (challenge == null) { - return challengeCriteriaDto; + return null; } Set criteria = new HashSet<>(); @@ -58,9 +59,6 @@ public ChallengeCriteriaDto saveChallengeCriteria(ChallengeCriteriaDto challenge final ChallengeRegistrantEntity registrantEntity = challengeIterator.next(); final Set registrantCriteria = new HashSet<>(); - if (registrantEntity.getRegistrantId() == 27L) { - System.out.println(27); - } criteria.forEach(challengeCri -> { ChallengeRegistrantCriteria registrantCri = registrantEntity.getCriteria().stream() .filter(cri -> challengeCri.getCriteriaId().equals(cri.getCriteriaId())) @@ -71,12 +69,42 @@ public ChallengeCriteriaDto saveChallengeCriteria(ChallengeCriteriaDto challenge }); registrantEntity.setCriteria(registrantCriteria); challengeRegistrantEntities.add(registrantEntity); - challengeCriteriaDto.getRegistrantCriteria().add(dozerMapper.map(registrantEntity, ChallengeRegistrantCriteriaDto.class)); } challenge.setCriteria(criteria); - challengeRegistrantRepository.save(challengeRegistrantEntities); - challengeRepository.save(challenge); + if (challengeRegistrantEntities.size() > 0) { + Set registrantCriteria = new HashSet<>(); + challengeRegistrantRepository.save(challengeRegistrantEntities) + .forEach(registrant -> registrantCriteria.add(toChallengeRegistrantCriteriaDto(registrant))); + } + + challenge = challengeRepository.save(challenge); + challengeCriteriaDto.setChallengeId(challenge.getChallengeId()); + challengeCriteriaDto.setChallengeCriteria(challenge.getCriteria()); return challengeCriteriaDto; } + + public ChallengeRegistrantCriteriaDto saveScoreChallengeRegistrantCriteria(ChallengeRegistrantCriteriaDto registrantCriteriaDto, String ownerEmail) { + ChallengeRegistrantEntity registrant = challengeRegistrantRepository.findOne(registrantCriteriaDto.getRegistrantId()); + ChallengeEntity challenge = challengeService.findChallengeIdAndOwnerEmail(registrant.getChallengeId(), ownerEmail); + if (challenge == null) { + return null; + } + + registrant.getCriteria().forEach(cri -> { + ChallengeRegistrantCriteria criteriaDto = registrantCriteriaDto.getCriteria().stream() + .filter(criDto -> criDto.getCriteriaId().equals(cri.getCriteriaId())).findFirst().get(); + cri.setScore(criteriaDto.getScore()); + registrantCriteriaDto.getCriteria().remove(criteriaDto); + }); + + registrant = challengeRegistrantRepository.save(registrant); + return toChallengeRegistrantCriteriaDto(registrant); + } + + private ChallengeRegistrantCriteriaDto toChallengeRegistrantCriteriaDto(ChallengeRegistrantEntity registrantEntity) { + return ChallengeRegistrantCriteriaDtoBuilder.challengeRegistrantCriteriaDto() + .withRegistrantId(registrantEntity.getRegistrantId()) + .withCriteria(registrantEntity.getCriteria()).build(); + } } diff --git a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java index b47c260f8..5cc924466 100644 --- a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java @@ -781,10 +781,10 @@ public boolean isOwnerOfChallenge(String ownerEmail, Long challengeId) { public ChallengeEntity findChallengeIdAndOwnerEmail(Long challengeId, String ownerEmail) { ChallengeEntity challenge = challengeRepository.findOne(challengeId); - if (challenge.getAuthorEmail().equalsIgnoreCase(ownerEmail)) { - return challenge; + if (challenge == null || !challenge.getAuthorEmail().equalsIgnoreCase(ownerEmail)) { + return null; } - return null; + return challenge; } public boolean sendEmailToDailyChallengeRegistrants(String challengeOwner, Long challengeId, Long now, EmailContent emailContent) { @@ -886,7 +886,11 @@ public ChallengeDetailDto getChallengeDetail(Long challengeId, String loginEmail // challengeDetailDto.setCurrentPhase(getChallengeCurrentPhase(challengeEntity)); // challengeDetailDto.setNextPhase(getChallengeNextPhase(challengeEntity)); calculateChallengePhases(challengeDetailDto); - challengeDetailDto.setIsAuthor(challengeEntity.getAuthorEmail().equals(loginEmail)); + boolean isAuthor = challengeEntity.getAuthorEmail().equals(loginEmail); + challengeDetailDto.setIsAuthor(isAuthor); + if (!isAuthor) { + challengeDetailDto.setCriteria(null); + } return challengeDetailDto; } return null; diff --git a/src/main/webapp/assets/modules/common/apiService.js b/src/main/webapp/assets/modules/common/apiService.js index 8a2b3a4f8..bff949025 100644 --- a/src/main/webapp/assets/modules/common/apiService.js +++ b/src/main/webapp/assets/modules/common/apiService.js @@ -34,7 +34,10 @@ techlooper.factory("apiService", function ($rootScope, $location, jsonValue, $ht }, getContestDetail: function (id) { - return $http.get("challenge/" + id); + return $http.get("challenge/" + id) + .success(function(data) { + $filter("challengeDetail")(data); + }); }, joinContest: function (contestId, firstName, lastName, registrantEmail, lang) { @@ -199,7 +202,12 @@ techlooper.factory("apiService", function ($rootScope, $location, jsonValue, $ht * @see com.techlooper.controller.ChallengeController.getRegistrantsById * */ getChallengeRegistrants: function (registrantFilterCondition) { - return $http.post("challenges/" + registrantFilterCondition.challengeId + "/registrants", registrantFilterCondition); + return $http.post("challenges/" + registrantFilterCondition.challengeId + "/registrants", registrantFilterCondition) + .success(function(registrants) { + $.each(registrants, function(i, registrant) { + $filter("challengeRegistrant")(registrant); + }); + }); }, /** @@ -266,8 +274,21 @@ techlooper.factory("apiService", function ($rootScope, $location, jsonValue, $ht loadEmailSetting: function () { return $http.get("user/employer/emailSetting"); - } + }, + /** + * @see com.techlooper.controller.ChallengeCriteriaController.saveChallengeCriteria + * */ + saveChallengeCriteria: function(criteria) { + return $http.post("challenge/criteria", criteria); + }, + + /** + * @see com.techlooper.controller.ChallengeCriteriaController.saveChallengeRegistrantCriteria + * */ + saveChallengeRegistrantCriteria: function(criteria) { + return $http.post("challengeRegistrant/criteria", criteria); + } }; return instance; diff --git a/src/main/webapp/assets/modules/common/model/challengeDetail.js b/src/main/webapp/assets/modules/common/model/challengeDetail.js new file mode 100644 index 000000000..c5c68cc8a --- /dev/null +++ b/src/main/webapp/assets/modules/common/model/challengeDetail.js @@ -0,0 +1,21 @@ +techlooper.filter("challengeDetail", function (apiService) { + return function (input, type) { + if (!input || input.$isRich) return input; + + var challengeDetail = input; + + challengeDetail.saveCriteria = function() { + var criteria = { + challengeId: challengeDetail.challengeId, + challengeCriteria: challengeDetail.criteria + } + apiService.saveChallengeCriteria(criteria) + .success(function(data) { + console.log(data); + }); + } + + challengeDetail.$isRich = true; + return challengeDetail; + } +}); \ No newline at end of file diff --git a/src/main/webapp/assets/modules/common/model/challengeRegistrant.js b/src/main/webapp/assets/modules/common/model/challengeRegistrant.js new file mode 100644 index 000000000..87e627d31 --- /dev/null +++ b/src/main/webapp/assets/modules/common/model/challengeRegistrant.js @@ -0,0 +1,27 @@ +techlooper.filter("challengeRegistrant", function (apiService) { + return function (input, type) { + if (!input || input.$isRich) return input; + + var registrant = input; + + registrant.saveCriteria = function() { + var criteria = { + registrantId: registrant.registrantId, + criteria: registrant.criteria + } + apiService.saveChallengeRegistrantCriteria(criteria) + .success(function(criteria) { + console.log(criteria); + //$.each(criteria, function(i, cri) { + // var registrantCri = _.findWhere(registrant.criteria, {criteriaId: cri.criteriaId}); + // if (registrantCri) { + // registrantCri.score = cri.score; + // } + //}); + }); + } + + registrant.$isRich = true; + return registrant; + } +}); \ No newline at end of file diff --git a/src/main/webapp/assets/modules/common/securityService.js b/src/main/webapp/assets/modules/common/securityService.js index 3922ec3e2..827f086c3 100644 --- a/src/main/webapp/assets/modules/common/securityService.js +++ b/src/main/webapp/assets/modules/common/securityService.js @@ -14,7 +14,7 @@ techlooper.factory("securityService", function (apiService, $route, $rootScope, } else { $location.search({}); - //$route.reload(); + $route.reload(); } }); }, diff --git a/src/main/webapp/assets/modules/contest-detail/contestDetail.html b/src/main/webapp/assets/modules/contest-detail/contestDetail.html index 4de2af2b0..f79bc7088 100644 --- a/src/main/webapp/assets/modules/contest-detail/contestDetail.html +++ b/src/main/webapp/assets/modules/contest-detail/contestDetail.html @@ -12,7 +12,7 @@

    {{contestDetail.challengeName}}
  • {{'registrants' | translate}} ({{contestDetail.numberOfRegistrants}})
  • -
  • +
  • @@ -384,7 +384,7 @@

  • -
    +
    diff --git a/src/main/webapp/assets/modules/contest-detail/contestDetailController.js b/src/main/webapp/assets/modules/contest-detail/contestDetailController.js index fe6e76c39..ef6fcdc1f 100644 --- a/src/main/webapp/assets/modules/contest-detail/contestDetailController.js +++ b/src/main/webapp/assets/modules/contest-detail/contestDetailController.js @@ -124,7 +124,6 @@ techlooper.controller('contestDetailController', function ($scope, apiService, l else { $scope.contestDetail.timeline = 5; } - console.log($scope.contestDetail); }) .error(function () {$location.url("404");}); diff --git a/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html b/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html index 870c6a28b..ecbbb54bf 100644 --- a/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html +++ b/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html @@ -9,51 +9,17 @@
    -
    + +
    - +
    - - -
    -
    -
    -
    - -
    -
    - - -
    -
    -
    -
    - -
    -
    - - -
    -
    -
    -
    - -
    -
    - - -
    -
    -
    -
    - -
    -
    - +
    +
    @@ -65,7 +31,7 @@

    - +
    diff --git a/src/test/java/com/techlooper/service/impl/ChallengeCriteriaServiceImplTest.java b/src/test/java/com/techlooper/service/impl/ChallengeCriteriaServiceImplTest.java index 7915f017e..ac9cfe2b3 100644 --- a/src/test/java/com/techlooper/service/impl/ChallengeCriteriaServiceImplTest.java +++ b/src/test/java/com/techlooper/service/impl/ChallengeCriteriaServiceImplTest.java @@ -12,9 +12,7 @@ import com.techlooper.repository.elasticsearch.ChallengeRepository; import com.techlooper.service.ChallengeCriteriaService; import com.techlooper.service.ChallengeService; -import com.techlooper.util.DataUtils; import org.dozer.Mapper; -import org.elasticsearch.index.query.QueryBuilders; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -60,6 +58,9 @@ public void before() { } @Test + public void testEmpty() { + } + public void testSaveChallengeCriteria() { Long id = 1436339203843L; String owner = "thu.hoang@navigosgroup.com"; @@ -99,14 +100,14 @@ public void testSaveChallengeCriteria() { } } - @Test public void testEditChallengeCriteria() { Long id = 1436339203843L; String owner = "thu.hoang@navigosgroup.com"; ChallengeEntity challenge = challengeRepository.findOne(id); Set challengeCriteria = challenge.getCriteria(); - ChallengeCriteria sampleCriteria = ChallengeCriteria.ChallengeCriteriaBuilder.challengeCriteria().withCriteriaId("sample").withName("sample name").build(); + ChallengeCriteria sampleCriteria = ChallengeCriteria.ChallengeCriteriaBuilder.challengeCriteria() + .withCriteriaId("sample").withName("sample name").withWeight(100L).build(); challengeCriteria.add(sampleCriteria); challenge = challengeRepository.save(challenge); @@ -117,15 +118,16 @@ public void testEditChallengeCriteria() { Long registrantId = 27L; ChallengeRegistrantEntity registrant = challengeRegistrantRepository.findOne(registrantId); if (registrant != null) { - registrant.getCriteria().stream().filter(cri -> cri.getCriteriaId().equals("sample")).findFirst().get().setScore(100L); + registrant.getCriteria().stream().filter(cri -> cri.getCriteriaId().equals(sampleCriteria.getCriteriaId())).findFirst().get().setScore(100L); registrant = challengeRegistrantRepository.save(registrant); sampleCriteria.setName("sample name changed"); challengeCriteriaService.saveChallengeCriteria(challengeCriteriaDto, owner); registrant = challengeRegistrantRepository.findOne(registrantId); - ChallengeRegistrantCriteria registrantCriteria = registrant.getCriteria().stream().filter(cri -> cri.getCriteriaId().equals("sample")).findFirst().get(); - Assert.assertEquals(registrantCriteria.getName(), sampleCriteria.getName()); + ChallengeRegistrantCriteria registrantCriteria = registrant.getCriteria().stream() + .filter(cri -> cri.getName().equals(sampleCriteria.getName())).findFirst().get(); + Assert.assertNotNull(registrantCriteria); } } } From ee14d26541650005035547850dcc638ced51a28e Mon Sep 17 00:00:00 2001 From: Phuong H Date: Wed, 21 Oct 2015 13:32:03 +0700 Subject: [PATCH 57/80] Able to load registrant criteria --- .../entity/ChallengeRegistrantCriteria.java | 10 ++++++++++ .../impl/ChallengeCriteriaServiceImpl.java | 3 +++ .../modules/common/model/challengeDetail.js | 1 + .../common/model/challengeRegistrant.js | 19 +++++++++++-------- .../contest-detail/contestDetailScore.html | 12 ++++++------ 5 files changed, 31 insertions(+), 14 deletions(-) diff --git a/src/main/java/com/techlooper/entity/ChallengeRegistrantCriteria.java b/src/main/java/com/techlooper/entity/ChallengeRegistrantCriteria.java index 97dc475ca..ca2f3357f 100644 --- a/src/main/java/com/techlooper/entity/ChallengeRegistrantCriteria.java +++ b/src/main/java/com/techlooper/entity/ChallengeRegistrantCriteria.java @@ -23,6 +23,16 @@ public class ChallengeRegistrantCriteria implements Serializable { private Long score; + private String comment; + + public java.lang.String getComment() { + return comment; + } + + public void setComment(java.lang.String comment) { + this.comment = comment; + } + public java.lang.String getCriteriaId() { return criteriaId; } diff --git a/src/main/java/com/techlooper/service/impl/ChallengeCriteriaServiceImpl.java b/src/main/java/com/techlooper/service/impl/ChallengeCriteriaServiceImpl.java index b76060544..81726e5b8 100644 --- a/src/main/java/com/techlooper/service/impl/ChallengeCriteriaServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/ChallengeCriteriaServiceImpl.java @@ -94,7 +94,10 @@ public ChallengeRegistrantCriteriaDto saveScoreChallengeRegistrantCriteria(Chall registrant.getCriteria().forEach(cri -> { ChallengeRegistrantCriteria criteriaDto = registrantCriteriaDto.getCriteria().stream() .filter(criDto -> criDto.getCriteriaId().equals(cri.getCriteriaId())).findFirst().get(); + + // only save score and comment cri.setScore(criteriaDto.getScore()); + cri.setComment(criteriaDto.getComment()); registrantCriteriaDto.getCriteria().remove(criteriaDto); }); diff --git a/src/main/webapp/assets/modules/common/model/challengeDetail.js b/src/main/webapp/assets/modules/common/model/challengeDetail.js index c5c68cc8a..9f7dc939d 100644 --- a/src/main/webapp/assets/modules/common/model/challengeDetail.js +++ b/src/main/webapp/assets/modules/common/model/challengeDetail.js @@ -9,6 +9,7 @@ techlooper.filter("challengeDetail", function (apiService) { challengeId: challengeDetail.challengeId, challengeCriteria: challengeDetail.criteria } + apiService.saveChallengeCriteria(criteria) .success(function(data) { console.log(data); diff --git a/src/main/webapp/assets/modules/common/model/challengeRegistrant.js b/src/main/webapp/assets/modules/common/model/challengeRegistrant.js index 87e627d31..1004fc97c 100644 --- a/src/main/webapp/assets/modules/common/model/challengeRegistrant.js +++ b/src/main/webapp/assets/modules/common/model/challengeRegistrant.js @@ -10,14 +10,17 @@ techlooper.filter("challengeRegistrant", function (apiService) { criteria: registrant.criteria } apiService.saveChallengeRegistrantCriteria(criteria) - .success(function(criteria) { - console.log(criteria); - //$.each(criteria, function(i, cri) { - // var registrantCri = _.findWhere(registrant.criteria, {criteriaId: cri.criteriaId}); - // if (registrantCri) { - // registrantCri.score = cri.score; - // } - //}); + .success(function(data) { + $.each(data.criteria, function(i, cri) { + var registrantCri = _.findWhere(registrant.criteria, {criteriaId: cri.criteriaId}); + if (registrantCri) { + registrantCri.score = cri.score; + registrantCri.comment = cri.comment; + } + else { + registrant.criteria.push(cri); + } + }); }); } diff --git a/src/main/webapp/assets/modules/contest-detail/contestDetailScore.html b/src/main/webapp/assets/modules/contest-detail/contestDetailScore.html index 5fffa994c..c95772901 100644 --- a/src/main/webapp/assets/modules/contest-detail/contestDetailScore.html +++ b/src/main/webapp/assets/modules/contest-detail/contestDetailScore.html @@ -16,19 +16,19 @@

    -
  • +
  • - Lorem Ipsum is simply dummy text of the printing + {{cri.name}}
    - 25 + {{cri.weight}} x
    - + =
    @@ -36,7 +36,7 @@ 0
    - +
  • @@ -49,7 +49,7 @@
  • - +
    From 5f3fe7369f509852275e598dd966a9528ff5c6bb Mon Sep 17 00:00:00 2001 From: Phuong H Date: Wed, 21 Oct 2015 13:34:25 +0700 Subject: [PATCH 58/80] Load registrant criteria --- .../techlooper/service/impl/ChallengeCriteriaServiceImpl.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/com/techlooper/service/impl/ChallengeCriteriaServiceImpl.java b/src/main/java/com/techlooper/service/impl/ChallengeCriteriaServiceImpl.java index 81726e5b8..19484806f 100644 --- a/src/main/java/com/techlooper/service/impl/ChallengeCriteriaServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/ChallengeCriteriaServiceImpl.java @@ -76,6 +76,7 @@ public ChallengeCriteriaDto saveChallengeCriteria(ChallengeCriteriaDto challenge Set registrantCriteria = new HashSet<>(); challengeRegistrantRepository.save(challengeRegistrantEntities) .forEach(registrant -> registrantCriteria.add(toChallengeRegistrantCriteriaDto(registrant))); + challengeCriteriaDto.setRegistrantCriteria(registrantCriteria); } challenge = challengeRepository.save(challenge); From 00c17572283abd7b38f8b80f007be5d7cdbae287 Mon Sep 17 00:00:00 2001 From: Phuong H Date: Wed, 21 Oct 2015 13:55:32 +0700 Subject: [PATCH 59/80] Able to reload registrant criteria from challenge saved --- .../assets/modules/common/model/challengeDetail.js | 9 +++++++-- .../modules/common/model/challengeRegistrant.js | 12 +++++++++++- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/src/main/webapp/assets/modules/common/model/challengeDetail.js b/src/main/webapp/assets/modules/common/model/challengeDetail.js index 9f7dc939d..89ec6b06e 100644 --- a/src/main/webapp/assets/modules/common/model/challengeDetail.js +++ b/src/main/webapp/assets/modules/common/model/challengeDetail.js @@ -1,4 +1,4 @@ -techlooper.filter("challengeDetail", function (apiService) { +techlooper.filter("challengeDetail", function (apiService, $rootScope) { return function (input, type) { if (!input || input.$isRich) return input; @@ -9,10 +9,15 @@ techlooper.filter("challengeDetail", function (apiService) { challengeId: challengeDetail.challengeId, challengeCriteria: challengeDetail.criteria } + delete challengeDetail.$savedCriteria; apiService.saveChallengeCriteria(criteria) .success(function(data) { - console.log(data); + $rootScope.$broadcast("saveChallengeCriteriaSuccessful", data); + challengeDetail.$savedCriteria = true; + }) + .error(function() { + challengeDetail.$savedCriteria = false; }); } diff --git a/src/main/webapp/assets/modules/common/model/challengeRegistrant.js b/src/main/webapp/assets/modules/common/model/challengeRegistrant.js index 1004fc97c..2779dcc74 100644 --- a/src/main/webapp/assets/modules/common/model/challengeRegistrant.js +++ b/src/main/webapp/assets/modules/common/model/challengeRegistrant.js @@ -1,4 +1,4 @@ -techlooper.filter("challengeRegistrant", function (apiService) { +techlooper.filter("challengeRegistrant", function (apiService, $rootScope) { return function (input, type) { if (!input || input.$isRich) return input; @@ -9,6 +9,7 @@ techlooper.filter("challengeRegistrant", function (apiService) { registrantId: registrant.registrantId, criteria: registrant.criteria } + delete registrant.$savedCriteria; apiService.saveChallengeRegistrantCriteria(criteria) .success(function(data) { $.each(data.criteria, function(i, cri) { @@ -21,9 +22,18 @@ techlooper.filter("challengeRegistrant", function (apiService) { registrant.criteria.push(cri); } }); + registrant.$savedCriteria = true; + }) + .error(function() { + registrant.$savedCriteria = false; }); } + $rootScope.$on("saveChallengeCriteriaSuccessful", function(scope, challengeCriteriaDto) { + var criteriaDto = _.findWhere(challengeCriteriaDto.registrantCriteria, {registrantId: registrant.registrantId}); + registrant.criteria = criteriaDto.criteria; + }); + registrant.$isRich = true; return registrant; } From 1baafa9133d209aa82c276f721324b0548ec514f Mon Sep 17 00:00:00 2001 From: Phuong H Date: Wed, 21 Oct 2015 13:57:13 +0700 Subject: [PATCH 60/80] Change default challenge criteria --- src/main/java/com/techlooper/util/DataUtils.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/techlooper/util/DataUtils.java b/src/main/java/com/techlooper/util/DataUtils.java index eb36d841a..243adee4b 100644 --- a/src/main/java/com/techlooper/util/DataUtils.java +++ b/src/main/java/com/techlooper/util/DataUtils.java @@ -32,15 +32,15 @@ public static List getAllEntities(ElasticsearchRepository reposi public static Set defaultChallengeCriterias() { Set defaultCriterias = new HashSet<>(); defaultCriterias.add(ChallengeCriteria.ChallengeCriteriaBuilder.challengeCriteria() - .withName("UI/UX implemented solution").withWeight(25L).build()); + .withName("UI/UX implemented solution").withWeight(20L).build()); defaultCriterias.add(ChallengeCriteria.ChallengeCriteriaBuilder.challengeCriteria() - .withName("Creativity on the proposed solution").withWeight(25L).build()); + .withName("Creativity on the proposed solution").withWeight(20L).build()); defaultCriterias.add(ChallengeCriteria.ChallengeCriteriaBuilder.challengeCriteria() - .withName("Source code quality").withWeight(25L).build()); + .withName("Source code quality").withWeight(20L).build()); defaultCriterias.add(ChallengeCriteria.ChallengeCriteriaBuilder.challengeCriteria() - .withName("Usage of top edge technology").withWeight(25L).build()); + .withName("Usage of top edge technology").withWeight(20L).build()); defaultCriterias.add(ChallengeCriteria.ChallengeCriteriaBuilder.challengeCriteria() - .withName("Application functionality").withWeight(25L).build()); + .withName("Application functionality").withWeight(20L).build()); return defaultCriterias; } From 1df90cdfe143721f78a078b35b22b5827930b60c Mon Sep 17 00:00:00 2001 From: khoa-nd Date: Wed, 21 Oct 2015 14:04:44 +0700 Subject: [PATCH 61/80] Load email template subject and body by user selection in the dropdownbox --- .../techlooper/controller/UserController.java | 5 ++++ .../com/techlooper/dto/EmailTemplateDto.java | 20 +++++++++++++ .../com/techlooper/service/EmailService.java | 2 ++ .../service/impl/EmailServiceImpl.java | 9 ++++++ .../assets/modules/common/apiService.js | 4 +++ .../modules/common/feedback/feedback.html | 2 +- .../common/feedback/feedbackDirective.js | 10 +++++++ .../assets/modules/common/resourcesService.js | 28 ++++++++++--------- 8 files changed, 66 insertions(+), 14 deletions(-) diff --git a/src/main/java/com/techlooper/controller/UserController.java b/src/main/java/com/techlooper/controller/UserController.java index 424e3d0e5..8c29b8193 100644 --- a/src/main/java/com/techlooper/controller/UserController.java +++ b/src/main/java/com/techlooper/controller/UserController.java @@ -419,4 +419,9 @@ public EmailSettingDto findEmployerEmailSetting(HttpServletRequest request) { public List getAvailableEmailTemplates() { return emailService.getAvailableEmailTemplates(); } + + @RequestMapping(value = "/emailTemplates/{templateId}", method = RequestMethod.GET) + public EmailTemplateDto getTemplateById(@PathVariable Long templateId) { + return emailService.getTemplateById(templateId); + } } diff --git a/src/main/java/com/techlooper/dto/EmailTemplateDto.java b/src/main/java/com/techlooper/dto/EmailTemplateDto.java index 054605bf6..cfc724eae 100644 --- a/src/main/java/com/techlooper/dto/EmailTemplateDto.java +++ b/src/main/java/com/techlooper/dto/EmailTemplateDto.java @@ -6,6 +6,10 @@ public class EmailTemplateDto { private String templateName; + private String subject; + + private String body; + public Long getTemplateId() { return templateId; } @@ -21,4 +25,20 @@ public String getTemplateName() { public void setTemplateName(String templateName) { this.templateName = templateName; } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } } diff --git a/src/main/java/com/techlooper/service/EmailService.java b/src/main/java/com/techlooper/service/EmailService.java index a62bcb2ea..ac6981c16 100644 --- a/src/main/java/com/techlooper/service/EmailService.java +++ b/src/main/java/com/techlooper/service/EmailService.java @@ -13,4 +13,6 @@ public interface EmailService { boolean sendEmail(EmailContent emailContent); List getAvailableEmailTemplates(); + + EmailTemplateDto getTemplateById(Long templateId); } diff --git a/src/main/java/com/techlooper/service/impl/EmailServiceImpl.java b/src/main/java/com/techlooper/service/impl/EmailServiceImpl.java index 19c442105..63f7b2cf5 100644 --- a/src/main/java/com/techlooper/service/impl/EmailServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/EmailServiceImpl.java @@ -94,4 +94,13 @@ public List getAvailableEmailTemplates() { } return emailTemplateDtoList; } + + @Override + public EmailTemplateDto getTemplateById(Long templateId) { + EmailTemplateEntity emailTemplateEntity = emailTemplateRepository.findOne(templateId); + if (emailTemplateEntity != null && emailTemplateEntity.getIsEnable()) { + return dozerMapper.map(emailTemplateEntity, EmailTemplateDto.class); + } + return null; + } } diff --git a/src/main/webapp/assets/modules/common/apiService.js b/src/main/webapp/assets/modules/common/apiService.js index 3acd29c1a..1a9e0fb86 100644 --- a/src/main/webapp/assets/modules/common/apiService.js +++ b/src/main/webapp/assets/modules/common/apiService.js @@ -270,6 +270,10 @@ techlooper.factory("apiService", function ($rootScope, $location, jsonValue, $ht getAvailableEmailTemplates : function () { return $http.get("emailTemplates"); + }, + + getTemplateById : function (templateId) { + return $http.get("emailTemplates/" + templateId); } }; diff --git a/src/main/webapp/assets/modules/common/feedback/feedback.html b/src/main/webapp/assets/modules/common/feedback/feedback.html index 285a5e981..7ad09f11e 100644 --- a/src/main/webapp/assets/modules/common/feedback/feedback.html +++ b/src/main/webapp/assets/modules/common/feedback/feedback.html @@ -12,7 +12,7 @@
    diff --git a/src/main/webapp/assets/modules/common/feedback/feedbackDirective.js b/src/main/webapp/assets/modules/common/feedback/feedbackDirective.js index 67f4f5ea4..a31e36464 100644 --- a/src/main/webapp/assets/modules/common/feedback/feedbackDirective.js +++ b/src/main/webapp/assets/modules/common/feedback/feedbackDirective.js @@ -13,6 +13,7 @@ techlooper.directive("feedbackForm", function (apiService, $timeout) { else { scope.composeEmail.names = scope.composeEmail.registrantFirstName; } + scope.send = function () { if (scope.feedbackContent == undefined || scope.feedbackContent == '') { return; @@ -32,6 +33,7 @@ techlooper.directive("feedbackForm", function (apiService, $timeout) { scope.composeEmail.error = false; }); } + scope.cancel = function () { if (!scope.composeEmail.visible) return; scope.composeEmail.subject = ''; @@ -40,6 +42,14 @@ techlooper.directive("feedbackForm", function (apiService, $timeout) { delete scope.composeEmail.visible; $('.feedback-loading').css('visibility', 'hidden'); } + + scope.loadEmailTemplate = function (templateId) { + apiService.getTemplateById(templateId) + .success(function (template) { + scope.composeEmail.subject = template.subject; + scope.feedbackContent = template.body; + }) + } } } }); \ No newline at end of file diff --git a/src/main/webapp/assets/modules/common/resourcesService.js b/src/main/webapp/assets/modules/common/resourcesService.js index 37eb08919..7550a109c 100644 --- a/src/main/webapp/assets/modules/common/resourcesService.js +++ b/src/main/webapp/assets/modules/common/resourcesService.js @@ -24,20 +24,22 @@ techlooper.factory("resourcesService", function ($translate, $q, apiService) { {translate: "theSolutionIsInnovative", id: "theSolutionIsInnovative"} ]; - var emailTemplateOptions = []; - - apiService.getAvailableEmailTemplates() - .success(function (data) { - $.each(data, function (i, template) { - var templateOption = { - translate: template.templateId, - id: template.templateName - }; - emailTemplateOptions.push(templateOption); - }); - }) + var emailTemplateOptions = [ + {translate: "welcomeContestant", id: 1} + ]; - console.log(emailTemplateOptions); + //apiService.getAvailableEmailTemplates() + // .success(function (data) { + // $.each(data, function (i, template) { + // var templateOption = { + // translate: template.templateId, + // id: template.templateName + // }; + // emailTemplateOptions.push(templateOption); + // }); + // }) + // + //console.log(emailTemplateOptions); var paymentOptions = [ {translate: "hourlyByByHour", reviewTranslate: "hourlyJob", id: "hourly"}, From 93104edfbdb8d254fd32f5bbf47f6d671a5eaeff Mon Sep 17 00:00:00 2001 From: Phuong H Date: Wed, 21 Oct 2015 14:11:25 +0700 Subject: [PATCH 62/80] Revert code of apiservice --- .../assets/modules/common/apiService.js | 27 ++++++++++++++++--- .../modules/common/model/challengeDetail.js | 5 ++++ .../contest-detail/evaluationCriteria.html | 2 +- 3 files changed, 30 insertions(+), 4 deletions(-) diff --git a/src/main/webapp/assets/modules/common/apiService.js b/src/main/webapp/assets/modules/common/apiService.js index 1a9e0fb86..3e326886c 100644 --- a/src/main/webapp/assets/modules/common/apiService.js +++ b/src/main/webapp/assets/modules/common/apiService.js @@ -34,7 +34,10 @@ techlooper.factory("apiService", function ($rootScope, $location, jsonValue, $ht }, getContestDetail: function (id) { - return $http.get("challenge/" + id); + return $http.get("challenge/" + id) + .success(function(data) { + $filter("challengeDetail")(data); + }); }, joinContest: function (contestId, firstName, lastName, registrantEmail, lang) { @@ -199,7 +202,12 @@ techlooper.factory("apiService", function ($rootScope, $location, jsonValue, $ht * @see com.techlooper.controller.ChallengeController.getRegistrantsById * */ getChallengeRegistrants: function (registrantFilterCondition) { - return $http.post("challenges/" + registrantFilterCondition.challengeId + "/registrants", registrantFilterCondition); + return $http.post("challenges/" + registrantFilterCondition.challengeId + "/registrants", registrantFilterCondition) + .success(function(registrants) { + $.each(registrants, function(i, registrant) { + $filter("challengeRegistrant")(registrant); + }); + }); }, /** @@ -274,8 +282,21 @@ techlooper.factory("apiService", function ($rootScope, $location, jsonValue, $ht getTemplateById : function (templateId) { return $http.get("emailTemplates/" + templateId); - } + }, + /** + * @see com.techlooper.controller.ChallengeCriteriaController.saveChallengeCriteria + * */ + saveChallengeCriteria: function(criteria) { + return $http.post("challenge/criteria", criteria); + }, + + /** + * @see com.techlooper.controller.ChallengeCriteriaController.saveChallengeRegistrantCriteria + * */ + saveChallengeRegistrantCriteria: function(criteria) { + return $http.post("challengeRegistrant/criteria", criteria); + } }; return instance; diff --git a/src/main/webapp/assets/modules/common/model/challengeDetail.js b/src/main/webapp/assets/modules/common/model/challengeDetail.js index 89ec6b06e..aad4b026f 100644 --- a/src/main/webapp/assets/modules/common/model/challengeDetail.js +++ b/src/main/webapp/assets/modules/common/model/challengeDetail.js @@ -21,6 +21,11 @@ techlooper.filter("challengeDetail", function (apiService, $rootScope) { }); } + challengeDetail.addCriteria = function() { + challengeDetail.criteria = challengeDetail.criteria || []; + challengeDetail.criteria.push({}); + } + challengeDetail.$isRich = true; return challengeDetail; } diff --git a/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html b/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html index ecbbb54bf..ee9df8d12 100644 --- a/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html +++ b/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html @@ -22,7 +22,7 @@
    - +
    From 95b896525f5656c97eb441e3bacbb91acc4d8c41 Mon Sep 17 00:00:00 2001 From: Phuong H Date: Wed, 21 Oct 2015 15:20:33 +0700 Subject: [PATCH 63/80] Add total weight to criteria --- .../modules/common/model/challengeDetail.js | 21 ++++++++++++++----- .../contest-detail/evaluationCriteria.html | 6 +++--- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/src/main/webapp/assets/modules/common/model/challengeDetail.js b/src/main/webapp/assets/modules/common/model/challengeDetail.js index aad4b026f..6de0f5869 100644 --- a/src/main/webapp/assets/modules/common/model/challengeDetail.js +++ b/src/main/webapp/assets/modules/common/model/challengeDetail.js @@ -1,10 +1,10 @@ -techlooper.filter("challengeDetail", function (apiService, $rootScope) { +techlooper.filter("challengeDetail", function (apiService, $rootScope, utils) { return function (input, type) { if (!input || input.$isRich) return input; var challengeDetail = input; - challengeDetail.saveCriteria = function() { + challengeDetail.saveCriteria = function () { var criteria = { challengeId: challengeDetail.challengeId, challengeCriteria: challengeDetail.criteria @@ -12,20 +12,31 @@ techlooper.filter("challengeDetail", function (apiService, $rootScope) { delete challengeDetail.$savedCriteria; apiService.saveChallengeCriteria(criteria) - .success(function(data) { + .success(function (data) { $rootScope.$broadcast("saveChallengeCriteriaSuccessful", data); challengeDetail.$savedCriteria = true; }) - .error(function() { + .error(function () { challengeDetail.$savedCriteria = false; }); } - challengeDetail.addCriteria = function() { + challengeDetail.addCriteria = function () { challengeDetail.criteria = challengeDetail.criteria || []; challengeDetail.criteria.push({}); } + challengeDetail.removeCriteria = function (cri) { + challengeDetail.criteria = _.reject(challengeDetail.criteria, function (criteria) {return criteria.criteriaId == cri.criteriaId;}) + } + + //TODO this function invoked 15 times in first load, then many times when change criteria + challengeDetail.totalWeight = function() { + var total = _.reduceRight(challengeDetail.criteria, function(sum, cri) { return sum + cri.weight; }, 0); + console.log(total); + return total; + } + challengeDetail.$isRich = true; return challengeDetail; } diff --git a/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html b/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html index ee9df8d12..8b4f7139a 100644 --- a/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html +++ b/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html @@ -15,8 +15,8 @@
    - - + +
    @@ -27,7 +27,7 @@
    - + {{contestDetail.totalWeight()}}

    From 64a527ef2ef0d0681e4caaa270ced2b6e12fcc5b Mon Sep 17 00:00:00 2001 From: Phuong H Date: Wed, 21 Oct 2015 15:44:40 +0700 Subject: [PATCH 64/80] Able to validate challenge criteria --- .../modules/common/model/challengeDetail.js | 5 ++++- .../contest-detail/challengeCriteriaInput.html | 13 +++++++++++++ .../challengeCriteriaInputDirective.js | 13 +++++++++++++ .../contest-detail/contestDetailController.js | 8 ++++++++ .../contest-detail/evaluationCriteria.html | 18 ++++++++++-------- 5 files changed, 48 insertions(+), 9 deletions(-) create mode 100644 src/main/webapp/assets/modules/contest-detail/challengeCriteriaInput.html create mode 100644 src/main/webapp/assets/modules/contest-detail/challengeCriteriaInputDirective.js diff --git a/src/main/webapp/assets/modules/common/model/challengeDetail.js b/src/main/webapp/assets/modules/common/model/challengeDetail.js index 6de0f5869..d0819f066 100644 --- a/src/main/webapp/assets/modules/common/model/challengeDetail.js +++ b/src/main/webapp/assets/modules/common/model/challengeDetail.js @@ -5,6 +5,7 @@ techlooper.filter("challengeDetail", function (apiService, $rootScope, utils) { var challengeDetail = input; challengeDetail.saveCriteria = function () { + //if (challengeDetail.$invalidCriteria) return; var criteria = { challengeId: challengeDetail.challengeId, challengeCriteria: challengeDetail.criteria @@ -32,8 +33,10 @@ techlooper.filter("challengeDetail", function (apiService, $rootScope, utils) { //TODO this function invoked 15 times in first load, then many times when change criteria challengeDetail.totalWeight = function() { + //console.log(arguments); var total = _.reduceRight(challengeDetail.criteria, function(sum, cri) { return sum + cri.weight; }, 0); - console.log(total); + //console.log(total); + //challengeDetail.$invalid = (total == 100); return total; } diff --git a/src/main/webapp/assets/modules/contest-detail/challengeCriteriaInput.html b/src/main/webapp/assets/modules/contest-detail/challengeCriteriaInput.html new file mode 100644 index 000000000..d549db0c6 --- /dev/null +++ b/src/main/webapp/assets/modules/contest-detail/challengeCriteriaInput.html @@ -0,0 +1,13 @@ + +
    + +
    +
    +
    + + +
    + \ No newline at end of file diff --git a/src/main/webapp/assets/modules/contest-detail/challengeCriteriaInputDirective.js b/src/main/webapp/assets/modules/contest-detail/challengeCriteriaInputDirective.js new file mode 100644 index 000000000..c6483f8a5 --- /dev/null +++ b/src/main/webapp/assets/modules/contest-detail/challengeCriteriaInputDirective.js @@ -0,0 +1,13 @@ +techlooper.directive('challengeCriteriaInput', function () { + return { + restrict: "E", + replace: true, + templateUrl: "modules/contest-detail/challengeCriteriaInput.html", + scope: { + cri: "=" + }, + link: function (scope, element, attr, ctrl) { + + } + }; +}); \ No newline at end of file diff --git a/src/main/webapp/assets/modules/contest-detail/contestDetailController.js b/src/main/webapp/assets/modules/contest-detail/contestDetailController.js index ef6fcdc1f..31b06525a 100644 --- a/src/main/webapp/assets/modules/contest-detail/contestDetailController.js +++ b/src/main/webapp/assets/modules/contest-detail/contestDetailController.js @@ -232,5 +232,13 @@ techlooper.controller('contestDetailController', function ($scope, apiService, l autoclose: true, format: 'dd/mm/yyyy' }); + + //TODO check valid before save + $scope.saveChallengeCriteria = function() { + console.log(123); + + //$scope.contestDetail.totalWeight(); + //$scope.contestDetail.saveCriteria(); + } }); diff --git a/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html b/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html index 8b4f7139a..53086509d 100644 --- a/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html +++ b/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html @@ -11,13 +11,14 @@
    -
    - -
    -
    - - -
    + + + + + + + +
    @@ -29,9 +30,10 @@ {{contestDetail.totalWeight()}}

    + invalid
    - +
    From 157c38c3129d33d7a335043d5e7adfda348bbc09 Mon Sep 17 00:00:00 2001 From: Phuong H Date: Wed, 21 Oct 2015 16:04:34 +0700 Subject: [PATCH 65/80] Fix hide form --- .../assets/modules/common/challenge/submissionChallenge.html | 2 +- .../assets/modules/common/challenge/submissionChallenge.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/webapp/assets/modules/common/challenge/submissionChallenge.html b/src/main/webapp/assets/modules/common/challenge/submissionChallenge.html index 73330fc39..b08cc2c72 100644 --- a/src/main/webapp/assets/modules/common/challenge/submissionChallenge.html +++ b/src/main/webapp/assets/modules/common/challenge/submissionChallenge.html @@ -36,7 +36,7 @@
    - +
    diff --git a/src/main/webapp/assets/modules/common/challenge/submissionChallenge.js b/src/main/webapp/assets/modules/common/challenge/submissionChallenge.js index 81fe0d99f..37d7ea7d4 100644 --- a/src/main/webapp/assets/modules/common/challenge/submissionChallenge.js +++ b/src/main/webapp/assets/modules/common/challenge/submissionChallenge.js @@ -35,7 +35,7 @@ techlooper.directive("submissionChallenge", function (localStorageService, apiSe // .success(function() { scope.challenge.visibleSubmitForm = true; //}); - scope.challenge.mixed = true; + //scope.challenge.mixed = true; } } From 236c93a615e8bee46fe165a4eb60d57d706cba3f Mon Sep 17 00:00:00 2001 From: johnsonpham Date: Wed, 21 Oct 2015 17:22:56 +0700 Subject: [PATCH 66/80] validation for total Points and show successful when submission criteria form --- .../challengeCriteriaInputDirective.js | 8 ++++++-- .../contest-detail/contestDetailController.js | 11 +++++++---- .../contest-detail/evaluationCriteria.html | 16 +++++++++++----- .../assets/modules/translation/messages_en.json | 3 ++- src/main/webapp/assets/sass/contest-detail.sass | 4 ++++ 5 files changed, 30 insertions(+), 12 deletions(-) diff --git a/src/main/webapp/assets/modules/contest-detail/challengeCriteriaInputDirective.js b/src/main/webapp/assets/modules/contest-detail/challengeCriteriaInputDirective.js index c6483f8a5..0b9ef64c3 100644 --- a/src/main/webapp/assets/modules/contest-detail/challengeCriteriaInputDirective.js +++ b/src/main/webapp/assets/modules/contest-detail/challengeCriteriaInputDirective.js @@ -4,10 +4,14 @@ techlooper.directive('challengeCriteriaInput', function () { replace: true, templateUrl: "modules/contest-detail/challengeCriteriaInput.html", scope: { - cri: "=" + cri: "=", + criteriaInvalid: "=" }, link: function (scope, element, attr, ctrl) { - + scope.criteriaForm.$setSubmitted(); + if(scope.criteriaForm.$invalid) { + scope.criteriaInvalid = false + } } }; }); \ No newline at end of file diff --git a/src/main/webapp/assets/modules/contest-detail/contestDetailController.js b/src/main/webapp/assets/modules/contest-detail/contestDetailController.js index 31b06525a..b526d0802 100644 --- a/src/main/webapp/assets/modules/contest-detail/contestDetailController.js +++ b/src/main/webapp/assets/modules/contest-detail/contestDetailController.js @@ -235,10 +235,13 @@ techlooper.controller('contestDetailController', function ($scope, apiService, l //TODO check valid before save $scope.saveChallengeCriteria = function() { - console.log(123); - - //$scope.contestDetail.totalWeight(); - //$scope.contestDetail.saveCriteria(); + if($scope.contestDetail.totalWeight() > 100){ + return false; + } + if($scope.criteriaInvalid == false){ + return false; + } + $scope.contestDetail.saveCriteria(); } }); diff --git a/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html b/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html index 53086509d..a8e3141a2 100644 --- a/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html +++ b/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html @@ -1,5 +1,11 @@

    +
    +

    +
    + + +

    @@ -9,7 +15,6 @@
    -
    @@ -27,10 +32,11 @@
    - - {{contestDetail.totalWeight()}} -

    - invalid + + + {{contestDetail.totalWeight() || 0}} +

    +

    diff --git a/src/main/webapp/assets/modules/translation/messages_en.json b/src/main/webapp/assets/modules/translation/messages_en.json index ee6f89124..475201b7a 100644 --- a/src/main/webapp/assets/modules/translation/messages_en.json +++ b/src/main/webapp/assets/modules/translation/messages_en.json @@ -803,5 +803,6 @@ "totalPoints": "Total Points", "automaticallySumCriteria": "Automatically sum from points above for each criteria", "emailSettingSuccessfully": "Your email settings are updated successfully.", - "errorSystem": "Error system. Please try again later." + "errorSystem": "Error system. Please try again later.", + "errorTotalWeight": "Total weight must be 100%." } \ No newline at end of file diff --git a/src/main/webapp/assets/sass/contest-detail.sass b/src/main/webapp/assets/sass/contest-detail.sass index 1508a782a..10a9cb7eb 100644 --- a/src/main/webapp/assets/sass/contest-detail.sass +++ b/src/main/webapp/assets/sass/contest-detail.sass @@ -1029,6 +1029,10 @@ width: auto float: right clear: both + p.error-messages + color: red + font-style: italic + font-size: 12px .save-evaluation width: 100% clear: both From 8fad0e32fd195de96f632d3939233b3b44004c9e Mon Sep 17 00:00:00 2001 From: Phuong H Date: Wed, 21 Oct 2015 17:23:58 +0700 Subject: [PATCH 67/80] Able to save registrant criteria --- .../modules/common/model/challengeDetail.js | 10 +++++++++ .../common/model/challengeRegistrant.js | 21 ++++++++++++++----- .../challengeCriteriaInputDirective.js | 3 ++- .../contest-detail/contestDetailScore.html | 11 +++++----- .../contestDetailScoreDirective.js | 16 ++++++++++++++ .../contest-detail/evaluationCriteria.html | 2 +- 6 files changed, 51 insertions(+), 12 deletions(-) create mode 100644 src/main/webapp/assets/modules/contest-detail/contestDetailScoreDirective.js diff --git a/src/main/webapp/assets/modules/common/model/challengeDetail.js b/src/main/webapp/assets/modules/common/model/challengeDetail.js index d0819f066..dae0d1b9b 100644 --- a/src/main/webapp/assets/modules/common/model/challengeDetail.js +++ b/src/main/webapp/assets/modules/common/model/challengeDetail.js @@ -40,6 +40,16 @@ techlooper.filter("challengeDetail", function (apiService, $rootScope, utils) { return total; } + challengeDetail.criteriaLoop = function () { + var criteria = challengeDetail.criteria; + if (!criteria) return []; + challengeDetail.totalWeight = 0; + return criteria.map(function (cri) { + challengeDetail.totalWeight += parseInt(cri.weight); + return cri; + }); + }; + challengeDetail.$isRich = true; return challengeDetail; } diff --git a/src/main/webapp/assets/modules/common/model/challengeRegistrant.js b/src/main/webapp/assets/modules/common/model/challengeRegistrant.js index 2779dcc74..3a31021a5 100644 --- a/src/main/webapp/assets/modules/common/model/challengeRegistrant.js +++ b/src/main/webapp/assets/modules/common/model/challengeRegistrant.js @@ -4,15 +4,26 @@ techlooper.filter("challengeRegistrant", function (apiService, $rootScope) { var registrant = input; - registrant.saveCriteria = function() { + registrant.criteriaLoop = function () { + var criteria = registrant.criteria; + if (!criteria) return []; + registrant.totalPoint = 0; + return criteria.map(function (cri) { + cri.point = cri.weight * cri.score; + registrant.totalPoint += parseInt(cri.point); + return cri; + }); + }; + + registrant.saveCriteria = function () { var criteria = { registrantId: registrant.registrantId, criteria: registrant.criteria } delete registrant.$savedCriteria; apiService.saveChallengeRegistrantCriteria(criteria) - .success(function(data) { - $.each(data.criteria, function(i, cri) { + .success(function (data) { + $.each(data.criteria, function (i, cri) { var registrantCri = _.findWhere(registrant.criteria, {criteriaId: cri.criteriaId}); if (registrantCri) { registrantCri.score = cri.score; @@ -24,12 +35,12 @@ techlooper.filter("challengeRegistrant", function (apiService, $rootScope) { }); registrant.$savedCriteria = true; }) - .error(function() { + .error(function () { registrant.$savedCriteria = false; }); } - $rootScope.$on("saveChallengeCriteriaSuccessful", function(scope, challengeCriteriaDto) { + $rootScope.$on("saveChallengeCriteriaSuccessful", function (scope, challengeCriteriaDto) { var criteriaDto = _.findWhere(challengeCriteriaDto.registrantCriteria, {registrantId: registrant.registrantId}); registrant.criteria = criteriaDto.criteria; }); diff --git a/src/main/webapp/assets/modules/contest-detail/challengeCriteriaInputDirective.js b/src/main/webapp/assets/modules/contest-detail/challengeCriteriaInputDirective.js index c6483f8a5..5ef683eb3 100644 --- a/src/main/webapp/assets/modules/contest-detail/challengeCriteriaInputDirective.js +++ b/src/main/webapp/assets/modules/contest-detail/challengeCriteriaInputDirective.js @@ -4,7 +4,8 @@ techlooper.directive('challengeCriteriaInput', function () { replace: true, templateUrl: "modules/contest-detail/challengeCriteriaInput.html", scope: { - cri: "=" + cri: "=", + contestDetail: "=" }, link: function (scope, element, attr, ctrl) { diff --git a/src/main/webapp/assets/modules/contest-detail/contestDetailScore.html b/src/main/webapp/assets/modules/contest-detail/contestDetailScore.html index c95772901..26d33b319 100644 --- a/src/main/webapp/assets/modules/contest-detail/contestDetailScore.html +++ b/src/main/webapp/assets/modules/contest-detail/contestDetailScore.html @@ -16,7 +16,7 @@

    -
  • +
  • {{cri.name}} @@ -28,12 +28,13 @@
    - + =
    - 0 + {{ cri.point }}
    @@ -45,11 +46,11 @@
    || - 0 + {{registrant.totalPoint}}

    - +
    diff --git a/src/main/webapp/assets/modules/contest-detail/contestDetailScoreDirective.js b/src/main/webapp/assets/modules/contest-detail/contestDetailScoreDirective.js new file mode 100644 index 000000000..faa08e33d --- /dev/null +++ b/src/main/webapp/assets/modules/contest-detail/contestDetailScoreDirective.js @@ -0,0 +1,16 @@ +techlooper.directive('contestDetailScore', function () { + return { + restrict: "E", + replace: true, + templateUrl: "modules/contest-detail/contestDetailScore.html", + scope: { + registrant: "=" + }, + link: function (scope, element, attr, ctrl) { + scope.saveScore = function() { + + scope.registrant.saveCriteria(); + } + } + }; +}); \ No newline at end of file diff --git a/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html b/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html index 53086509d..0e679b392 100644 --- a/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html +++ b/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html @@ -18,7 +18,7 @@ - +
    From 13e69a69f995cdb2034f68601d7f907658955c6f Mon Sep 17 00:00:00 2001 From: khoa-nd Date: Wed, 21 Oct 2015 17:36:27 +0700 Subject: [PATCH 68/80] Modify "Send Feedback" email service to bind template variables dynamically --- .../techlooper/service/CurrencyService.java | 7 +- .../com/techlooper/service/EmailService.java | 8 + .../service/impl/ChallengeServiceImpl.java | 1602 +++++++++-------- .../service/impl/CurrencyServiceImpl.java | 45 +- .../assets/modules/common/resourcesService.js | 5 +- 5 files changed, 851 insertions(+), 816 deletions(-) diff --git a/src/main/java/com/techlooper/service/CurrencyService.java b/src/main/java/com/techlooper/service/CurrencyService.java index 568873ea2..d516133e8 100644 --- a/src/main/java/com/techlooper/service/CurrencyService.java +++ b/src/main/java/com/techlooper/service/CurrencyService.java @@ -1,9 +1,14 @@ package com.techlooper.service; +import java.util.Locale; + /** * Created by phuonghqh on 5/28/15. */ public interface CurrencyService { - Long usdToVndRate(); + Long usdToVndRate(); + + String formatCurrency(Double value, Locale currentLocale); + } diff --git a/src/main/java/com/techlooper/service/EmailService.java b/src/main/java/com/techlooper/service/EmailService.java index ac6981c16..e347b8531 100644 --- a/src/main/java/com/techlooper/service/EmailService.java +++ b/src/main/java/com/techlooper/service/EmailService.java @@ -10,6 +10,14 @@ */ public interface EmailService { + final String VAR_CONTEST_NAME = "{contest_name}"; + + final String VAR_CONTEST_FIRST_PRIZE = "{contest_1st_prize}"; + + final String VAR_CONTESTANT_FIRST_NAME = "{contestant_first_name}"; + + final String VAR_MAIL_SIGNATURE = "{mail_signature}"; + boolean sendEmail(EmailContent emailContent); List getAvailableEmailTemplates(); diff --git a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java index 5cc924466..1044a5390 100644 --- a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java @@ -1,12 +1,15 @@ package com.techlooper.service.impl; +import com.techlooper.dto.EmailSettingDto; import com.techlooper.entity.*; import com.techlooper.model.*; import com.techlooper.repository.elasticsearch.ChallengeRegistrantRepository; import com.techlooper.repository.elasticsearch.ChallengeRepository; import com.techlooper.repository.elasticsearch.ChallengeSubmissionRepository; import com.techlooper.service.ChallengeService; +import com.techlooper.service.CurrencyService; import com.techlooper.service.EmailService; +import com.techlooper.service.EmployerService; import com.techlooper.util.DataUtils; import com.techlooper.util.DateTimeUtils; import freemarker.template.Template; @@ -61,450 +64,446 @@ @Service public class ChallengeServiceImpl implements ChallengeService { - private final static Logger LOGGER = LoggerFactory.getLogger(ChallengeServiceImpl.class); + private final static Logger LOGGER = LoggerFactory.getLogger(ChallengeServiceImpl.class); - private final static ChallengePhaseEnum CHALLENGE_TIMELINE[] = { - ChallengePhaseEnum.FINAL, - ChallengePhaseEnum.PROTOTYPE, - ChallengePhaseEnum.UIUX, - ChallengePhaseEnum.IDEA, - ChallengePhaseEnum.REGISTRATION - }; + private final static ChallengePhaseEnum CHALLENGE_TIMELINE[] = { + ChallengePhaseEnum.FINAL, + ChallengePhaseEnum.PROTOTYPE, + ChallengePhaseEnum.UIUX, + ChallengePhaseEnum.IDEA, + ChallengePhaseEnum.REGISTRATION + }; - @Resource - private ElasticsearchTemplate elasticsearchTemplateUserImport; + @Resource + private ElasticsearchTemplate elasticsearchTemplateUserImport; - @Resource - private MimeMessage postChallengeMailMessage; + @Resource + private MimeMessage postChallengeMailMessage; - @Resource - private Template postChallengeMailTemplateEn; + @Resource + private Template postChallengeMailTemplateEn; - @Resource - private Template postChallengeUpdateMailTemplateEn; + @Resource + private Template postChallengeUpdateMailTemplateEn; - @Resource - private Template postChallengeMailTemplateVi; + @Resource + private Template postChallengeMailTemplateVi; - @Value("${mail.postChallenge.subject.vn}") - private String postChallengeMailSubjectVn; + @Value("${mail.postChallenge.subject.vn}") + private String postChallengeMailSubjectVn; - @Value("${mail.postChallenge.subject.en}") - private String postChallengeMailSubjectEn; + @Value("${mail.postChallenge.subject.en}") + private String postChallengeMailSubjectEn; - @Value("${mail.postChallenge.techloopies.mailSubject}") - private String postChallengeTechloopiesMailSubject; + @Value("${mail.postChallenge.techloopies.mailSubject}") + private String postChallengeTechloopiesMailSubject; - @Value("${mail.postChallenge.techloopies.updateMailSubject}") - private String postChallengeTechloopiesUpdateMailSubject; + @Value("${mail.postChallenge.techloopies.updateMailSubject}") + private String postChallengeTechloopiesUpdateMailSubject; - @Value("${mail.postChallenge.techloopies.mailList}") - private String postChallengeTechloopiesMailList; + @Value("${mail.postChallenge.techloopies.mailList}") + private String postChallengeTechloopiesMailList; - @Value("${web.baseUrl}") - private String webBaseUrl; + @Value("${web.baseUrl}") + private String webBaseUrl; - @Resource - private Template confirmUserJoinChallengeMailTemplateEn; + @Resource + private Template confirmUserJoinChallengeMailTemplateEn; - @Resource - private Template confirmUserJoinChallengeMailTemplateVi; + @Resource + private Template confirmUserJoinChallengeMailTemplateVi; - @Value("${mail.confirmUserJoinChallenge.subject.vn}") - private String confirmUserJoinChallengeMailSubjectVn; + @Value("${mail.confirmUserJoinChallenge.subject.vn}") + private String confirmUserJoinChallengeMailSubjectVn; - @Value("${mail.confirmUserJoinChallenge.subject.en}") - private String confirmUserJoinChallengeMailSubjectEn; + @Value("${mail.confirmUserJoinChallenge.subject.en}") + private String confirmUserJoinChallengeMailSubjectEn; - @Resource - private Template alertEmployerChallengeMailTemplateEn; + @Resource + private Template alertEmployerChallengeMailTemplateEn; - @Resource - private Template alertEmployerChallengeMailTemplateVi; + @Resource + private Template alertEmployerChallengeMailTemplateVi; - @Value("${mail.alertEmployerChallenge.subject.vn}") - private String alertEmployerChallengeMailSubjectVn; + @Value("${mail.alertEmployerChallenge.subject.vn}") + private String alertEmployerChallengeMailSubjectVn; - @Value("${mail.alertEmployerChallenge.subject.en}") - private String alertEmployerChallengeMailSubjectEn; + @Value("${mail.alertEmployerChallenge.subject.en}") + private String alertEmployerChallengeMailSubjectEn; - @Value("${mail.techlooper.reply_to}") - private String mailTechlooperReplyTo; + @Value("${mail.techlooper.reply_to}") + private String mailTechlooperReplyTo; - @Resource - private JavaMailSender mailSender; + @Resource + private JavaMailSender mailSender; - @Resource - private ChallengeRepository challengeRepository; + @Resource + private ChallengeRepository challengeRepository; - @Resource - private ChallengeRegistrantRepository challengeRegistrantRepository; + @Resource + private ChallengeRegistrantRepository challengeRegistrantRepository; - @Resource - private ChallengeSubmissionRepository challengeSubmissionRepository; + @Resource + private ChallengeSubmissionRepository challengeSubmissionRepository; - @Resource - private Mapper dozerMapper; + @Resource + private Mapper dozerMapper; - @Value("${elasticsearch.userimport.index.name}") - private String techlooperIndex; + @Value("${elasticsearch.userimport.index.name}") + private String techlooperIndex; - @Value("${mail.notifyChallengeTimelineRegistration.subject.vn}") - private String notifyChallengeTimelineRegistrationMailSubjectVn; + @Value("${mail.notifyChallengeTimelineRegistration.subject.vn}") + private String notifyChallengeTimelineRegistrationMailSubjectVn; - @Value("${mail.notifyChallengeTimelineRegistration.subject.en}") - private String notifyChallengeTimelineRegistrationMailSubjectEn; + @Value("${mail.notifyChallengeTimelineRegistration.subject.en}") + private String notifyChallengeTimelineRegistrationMailSubjectEn; - @Value("${mail.notifyChallengeTimelineInProgress.subject.vn}") - private String notifyChallengeTimelineInProgressMailSubjectVn; + @Value("${mail.notifyChallengeTimelineInProgress.subject.vn}") + private String notifyChallengeTimelineInProgressMailSubjectVn; - @Value("${mail.notifyChallengeTimelineInProgress.subject.en}") - private String notifyChallengeTimelineInProgressMailSubjectEn; + @Value("${mail.notifyChallengeTimelineInProgress.subject.en}") + private String notifyChallengeTimelineInProgressMailSubjectEn; - @Value("${mail.dailyChallengeSummary.subject.en}") - private String dailyChallengeSummaryMailSubjectEn; + @Value("${mail.dailyChallengeSummary.subject.en}") + private String dailyChallengeSummaryMailSubjectEn; - @Value("${mail.dailyChallengeSummary.subject.vi}") - private String dailyChallengeSummaryMailSubjectVi; + @Value("${mail.dailyChallengeSummary.subject.vi}") + private String dailyChallengeSummaryMailSubjectVi; - @Resource - private Template notifyChallengeTimelineMailTemplateVi; + @Resource + private Template notifyChallengeTimelineMailTemplateVi; - @Resource - private Template notifyChallengeTimelineMailTemplateEn; + @Resource + private Template notifyChallengeTimelineMailTemplateEn; - @Resource - private Template dailyChallengeSummaryMailTemplateVi; + @Resource + private Template dailyChallengeSummaryMailTemplateVi; - @Resource - private Template dailyChallengeSummaryMailTemplateEn; + @Resource + private Template dailyChallengeSummaryMailTemplateEn; - @Resource - private EmailService emailService; + @Resource + private EmailService emailService; - public ChallengeEntity savePostChallenge(ChallengeDto challengeDto) throws Exception { - ChallengeEntity challengeEntity = dozerMapper.map(challengeDto, ChallengeEntity.class); - if (challengeDto.getChallengeId() == null) { - challengeEntity.setChallengeId(new Date().getTime()); - } + @Resource + private EmployerService employerService; - challengeEntity.setCriteria(DataUtils.defaultChallengeCriterias()); - return challengeRepository.save(challengeEntity); - } - - public void sendPostChallengeEmailToEmployer(ChallengeEntity challengeEntity) - throws MessagingException, IOException, TemplateException { - String mailSubject = challengeEntity.getLang() == Language.vi ? postChallengeMailSubjectVn : postChallengeMailSubjectEn; - Address[] recipientAddresses = getRecipientAddresses(challengeEntity, true); - Template template = challengeEntity.getLang() == Language.vi ? postChallengeMailTemplateVi : postChallengeMailTemplateEn; - sendPostChallengeEmail(challengeEntity, mailSubject, recipientAddresses, template); - } - - public void sendPostChallengeEmailToTechloopies(ChallengeEntity challengeEntity, Boolean isNewChallenge) - throws MessagingException, IOException, TemplateException { - String mailSubject = isNewChallenge ? postChallengeTechloopiesMailSubject : - String.format(postChallengeTechloopiesUpdateMailSubject, challengeEntity.getChallengeName()); - Template mailTemplate = isNewChallenge ? postChallengeMailTemplateEn : postChallengeUpdateMailTemplateEn; - Address[] recipientAddresses = InternetAddress.parse(postChallengeTechloopiesMailList); - sendPostChallengeEmail(challengeEntity, mailSubject, recipientAddresses, mailTemplate); - } - - @Override - public void sendEmailNotifyRegistrantAboutChallengeTimeline(ChallengeEntity challengeEntity, - ChallengeRegistrantEntity challengeRegistrantEntity, ChallengePhaseEnum challengePhase) throws Exception { - String mailSubject = getNotifyRegistrantChallengeTimelineSubject(challengeRegistrantEntity, challengePhase); - Address[] recipientAddresses = InternetAddress.parse(challengeRegistrantEntity.getRegistrantEmail()); - Template template = challengeRegistrantEntity.getLang() == Language.vi ? - notifyChallengeTimelineMailTemplateVi : notifyChallengeTimelineMailTemplateEn; - postChallengeMailMessage.setRecipients(Message.RecipientType.TO, recipientAddresses); - postChallengeMailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); - StringWriter stringWriter = new StringWriter(); - - Map templateModel = new HashMap<>(); - templateModel.put("challengeEntity", challengeEntity); - templateModel.put("webBaseUrl", webBaseUrl); - templateModel.put("technologies", StringUtils.join(challengeEntity.getTechnologies(), "
    ")); - templateModel.put("receivedEmails", StringUtils.join(challengeEntity.getReceivedEmails(), "
    ")); - templateModel.put("firstPlaceReward", challengeEntity.getFirstPlaceReward() != null ? challengeEntity.getFirstPlaceReward() : 0); - templateModel.put("secondPlaceReward", challengeEntity.getSecondPlaceReward() != null ? challengeEntity.getSecondPlaceReward() : 0); - templateModel.put("thirdPlaceReward", challengeEntity.getThirdPlaceReward() != null ? challengeEntity.getThirdPlaceReward() : 0); - templateModel.put("challengeId", challengeEntity.getChallengeId().toString()); - templateModel.put("challengeNameAlias", challengeEntity.getChallengeName().replaceAll("\\W", "-")); - - int numberOfDays = 0; - if (challengePhase == ChallengePhaseEnum.REGISTRATION) { - numberOfDays = daysBetween(currentDate(), challengeEntity.getRegistrationDateTime()) + 1; - } - else if (challengePhase == ChallengePhaseEnum.IN_PROGRESS) { - numberOfDays = daysBetween(currentDate(), challengeEntity.getSubmissionDateTime()) + 1; + @Resource + private CurrencyService currencyService; + + public ChallengeEntity savePostChallenge(ChallengeDto challengeDto) throws Exception { + ChallengeEntity challengeEntity = dozerMapper.map(challengeDto, ChallengeEntity.class); + if (challengeDto.getChallengeId() == null) { + challengeEntity.setChallengeId(new Date().getTime()); + } + + challengeEntity.setCriteria(DataUtils.defaultChallengeCriterias()); + return challengeRepository.save(challengeEntity); } - templateModel.put("numberOfDays", numberOfDays); - templateModel.put("challengePhase", challengePhase.getValue()); - templateModel.put("challengeRegistrant", challengeRegistrantEntity); - - template.process(templateModel, stringWriter); - mailSubject = String.format(mailSubject, numberOfDays, challengeEntity.getChallengeName()); - postChallengeMailMessage.setSubject(MimeUtility.encodeText(mailSubject, "UTF-8", null)); - postChallengeMailMessage.setText(stringWriter.toString(), "UTF-8", "html"); - - stringWriter.flush(); - postChallengeMailMessage.saveChanges(); - mailSender.send(postChallengeMailMessage); - LOGGER.info(postChallengeMailMessage.getMessageID() + " has been sent to users " + - postChallengeMailMessage.getAllRecipients() + " with challengeId = " + challengeEntity.getChallengeId()); - } - - private String getNotifyRegistrantChallengeTimelineSubject( - ChallengeRegistrantEntity challengeRegistrantEntity, ChallengePhaseEnum challengePhase) { - if (challengeRegistrantEntity.getLang() == Language.vi) { - if (challengePhase == ChallengePhaseEnum.REGISTRATION) { - return notifyChallengeTimelineRegistrationMailSubjectVn; - } - else { - return notifyChallengeTimelineInProgressMailSubjectVn; - } + public void sendPostChallengeEmailToEmployer(ChallengeEntity challengeEntity) + throws MessagingException, IOException, TemplateException { + String mailSubject = challengeEntity.getLang() == Language.vi ? postChallengeMailSubjectVn : postChallengeMailSubjectEn; + Address[] recipientAddresses = getRecipientAddresses(challengeEntity, true); + Template template = challengeEntity.getLang() == Language.vi ? postChallengeMailTemplateVi : postChallengeMailTemplateEn; + sendPostChallengeEmail(challengeEntity, mailSubject, recipientAddresses, template); } - else { - if (challengePhase == ChallengePhaseEnum.REGISTRATION) { - return notifyChallengeTimelineRegistrationMailSubjectEn; - } - else { - return notifyChallengeTimelineInProgressMailSubjectEn; - } + + public void sendPostChallengeEmailToTechloopies(ChallengeEntity challengeEntity, Boolean isNewChallenge) + throws MessagingException, IOException, TemplateException { + String mailSubject = isNewChallenge ? postChallengeTechloopiesMailSubject : + String.format(postChallengeTechloopiesUpdateMailSubject, challengeEntity.getChallengeName()); + Template mailTemplate = isNewChallenge ? postChallengeMailTemplateEn : postChallengeUpdateMailTemplateEn; + Address[] recipientAddresses = InternetAddress.parse(postChallengeTechloopiesMailList); + sendPostChallengeEmail(challengeEntity, mailSubject, recipientAddresses, mailTemplate); } - } - - public Long getNumberOfRegistrants(Long challengeId) { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withSearchType(SearchType.COUNT); - searchQueryBuilder.withFilter(FilterBuilders.termFilter("challengeId", challengeId)); - return challengeRegistrantRepository.search(searchQueryBuilder.build()).getTotalElements(); - } - - public void sendApplicationEmailToContestant(ChallengeEntity challengeEntity, ChallengeRegistrantEntity challengeRegistrantEntity) throws MessagingException, IOException, TemplateException { - Template template = challengeRegistrantEntity.getLang() == Language.vi ? - confirmUserJoinChallengeMailTemplateVi : confirmUserJoinChallengeMailTemplateEn; - String mailSubject = challengeRegistrantEntity.getLang() == Language.vi ? - confirmUserJoinChallengeMailSubjectVn : confirmUserJoinChallengeMailSubjectEn; - mailSubject = String.format(mailSubject, challengeEntity.getChallengeName()); - Address[] emailAddress = InternetAddress.parse(challengeRegistrantEntity.getRegistrantEmail()); - sendContestApplicationEmail(template, mailSubject, emailAddress, challengeEntity, challengeRegistrantEntity, false); - } - - public void sendApplicationEmailToEmployer(ChallengeEntity challengeEntity, ChallengeRegistrantEntity challengeRegistrantEntity) throws MessagingException, IOException, TemplateException { - Template template = challengeRegistrantEntity.getLang() == Language.vi ? - alertEmployerChallengeMailTemplateVi : alertEmployerChallengeMailTemplateEn; - String mailSubject = challengeRegistrantEntity.getLang() == Language.vi ? - alertEmployerChallengeMailSubjectVn : alertEmployerChallengeMailSubjectEn; - mailSubject = String.format(mailSubject, challengeEntity.getChallengeName()); - Address[] emailAddress = getRecipientAddresses(challengeEntity, false); - sendContestApplicationEmail(template, mailSubject, emailAddress, challengeEntity, challengeRegistrantEntity, true); - } - - public long joinChallenge(ChallengeRegistrantDto challengeRegistrantDto) { - ChallengeRegistrantEntity entity = joinChallengeEntity(challengeRegistrantDto); - if (entity != null) { - return getNumberOfRegistrants(challengeRegistrantDto.getChallengeId()); + + @Override + public void sendEmailNotifyRegistrantAboutChallengeTimeline(ChallengeEntity challengeEntity, + ChallengeRegistrantEntity challengeRegistrantEntity, ChallengePhaseEnum challengePhase) throws Exception { + String mailSubject = getNotifyRegistrantChallengeTimelineSubject(challengeRegistrantEntity, challengePhase); + Address[] recipientAddresses = InternetAddress.parse(challengeRegistrantEntity.getRegistrantEmail()); + Template template = challengeRegistrantEntity.getLang() == Language.vi ? + notifyChallengeTimelineMailTemplateVi : notifyChallengeTimelineMailTemplateEn; + postChallengeMailMessage.setRecipients(Message.RecipientType.TO, recipientAddresses); + postChallengeMailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); + StringWriter stringWriter = new StringWriter(); + + Map templateModel = new HashMap<>(); + templateModel.put("challengeEntity", challengeEntity); + templateModel.put("webBaseUrl", webBaseUrl); + templateModel.put("technologies", StringUtils.join(challengeEntity.getTechnologies(), "
    ")); + templateModel.put("receivedEmails", StringUtils.join(challengeEntity.getReceivedEmails(), "
    ")); + templateModel.put("firstPlaceReward", challengeEntity.getFirstPlaceReward() != null ? challengeEntity.getFirstPlaceReward() : 0); + templateModel.put("secondPlaceReward", challengeEntity.getSecondPlaceReward() != null ? challengeEntity.getSecondPlaceReward() : 0); + templateModel.put("thirdPlaceReward", challengeEntity.getThirdPlaceReward() != null ? challengeEntity.getThirdPlaceReward() : 0); + templateModel.put("challengeId", challengeEntity.getChallengeId().toString()); + templateModel.put("challengeNameAlias", challengeEntity.getChallengeName().replaceAll("\\W", "-")); + + int numberOfDays = 0; + if (challengePhase == ChallengePhaseEnum.REGISTRATION) { + numberOfDays = daysBetween(currentDate(), challengeEntity.getRegistrationDateTime()) + 1; + } else if (challengePhase == ChallengePhaseEnum.IN_PROGRESS) { + numberOfDays = daysBetween(currentDate(), challengeEntity.getSubmissionDateTime()) + 1; + } + + templateModel.put("numberOfDays", numberOfDays); + templateModel.put("challengePhase", challengePhase.getValue()); + templateModel.put("challengeRegistrant", challengeRegistrantEntity); + + template.process(templateModel, stringWriter); + mailSubject = String.format(mailSubject, numberOfDays, challengeEntity.getChallengeName()); + postChallengeMailMessage.setSubject(MimeUtility.encodeText(mailSubject, "UTF-8", null)); + postChallengeMailMessage.setText(stringWriter.toString(), "UTF-8", "html"); + + stringWriter.flush(); + postChallengeMailMessage.saveChanges(); + mailSender.send(postChallengeMailMessage); + LOGGER.info(postChallengeMailMessage.getMessageID() + " has been sent to users " + + postChallengeMailMessage.getAllRecipients() + " with challengeId = " + challengeEntity.getChallengeId()); } - return 0; - } - - public ChallengeRegistrantEntity joinChallengeEntity(ChallengeRegistrantDto challengeRegistrantDto) { - Long challengeId = challengeRegistrantDto.getChallengeId(); - boolean isExist = checkIfChallengeRegistrantExist(challengeId, challengeRegistrantDto.getRegistrantEmail()); - - if (!isExist) { - ChallengeRegistrantEntity challengeRegistrantEntity = dozerMapper.map(challengeRegistrantDto, ChallengeRegistrantEntity.class); - ChallengeEntity challengeEntity = challengeRepository.findOne(challengeId); - challengeRegistrantEntity.setRegistrantId(new Date().getTime()); - if (challengeEntity.getCriteria().size() > 0) { - final Set criteria = new HashSet<>(); - challengeEntity.getCriteria().forEach(cri -> criteria.add(dozerMapper.map(cri, ChallengeRegistrantCriteria.class))); - challengeRegistrantEntity.setCriteria(criteria); - } - challengeRegistrantEntity = challengeRegistrantRepository.save(challengeRegistrantEntity); - - try { - sendApplicationEmailToContestant(challengeEntity, challengeRegistrantEntity); - challengeRegistrantEntity.setMailSent(Boolean.TRUE); - return challengeRegistrantRepository.save(challengeRegistrantEntity); - } - catch (Exception e) { - LOGGER.debug("Can not send email", e); - } + + private String getNotifyRegistrantChallengeTimelineSubject( + ChallengeRegistrantEntity challengeRegistrantEntity, ChallengePhaseEnum challengePhase) { + if (challengeRegistrantEntity.getLang() == Language.vi) { + if (challengePhase == ChallengePhaseEnum.REGISTRATION) { + return notifyChallengeTimelineRegistrationMailSubjectVn; + } else { + return notifyChallengeTimelineInProgressMailSubjectVn; + } + } else { + if (challengePhase == ChallengePhaseEnum.REGISTRATION) { + return notifyChallengeTimelineRegistrationMailSubjectEn; + } else { + return notifyChallengeTimelineInProgressMailSubjectEn; + } + } } - return null; - } - - public List listChallenges() { - TermQueryBuilder notExpiredQuery = termQuery("expired", Boolean.TRUE); - Iterable challengeIterator = challengeRepository.search(boolQuery().mustNot(notExpiredQuery)); - ArrayList challenges = new ArrayList<>(); - challengeIterator.forEach(challengeEntity -> { - ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); - challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeEntity.getChallengeId())); - challenges.add(challengeDetailDto); - }); - return sortChallengesByDescendingStartDate(challenges); - } - - private void sendContestApplicationEmail(Template template, String mailSubject, Address[] recipientAddresses, - ChallengeEntity challengeEntity, ChallengeRegistrantEntity challengeRegistrantEntity, boolean hasReplyTo) - throws MessagingException, IOException, TemplateException { - postChallengeMailMessage.setRecipients(Message.RecipientType.TO, recipientAddresses); - - if (hasReplyTo) { - postChallengeMailMessage.setReplyTo(InternetAddress.parse(challengeRegistrantEntity.getRegistrantEmail())); + public Long getNumberOfRegistrants(Long challengeId) { + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withSearchType(SearchType.COUNT); + searchQueryBuilder.withFilter(FilterBuilders.termFilter("challengeId", challengeId)); + return challengeRegistrantRepository.search(searchQueryBuilder.build()).getTotalElements(); } - else { - postChallengeMailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); + + public void sendApplicationEmailToContestant(ChallengeEntity challengeEntity, ChallengeRegistrantEntity challengeRegistrantEntity) throws MessagingException, IOException, TemplateException { + Template template = challengeRegistrantEntity.getLang() == Language.vi ? + confirmUserJoinChallengeMailTemplateVi : confirmUserJoinChallengeMailTemplateEn; + String mailSubject = challengeRegistrantEntity.getLang() == Language.vi ? + confirmUserJoinChallengeMailSubjectVn : confirmUserJoinChallengeMailSubjectEn; + mailSubject = String.format(mailSubject, challengeEntity.getChallengeName()); + Address[] emailAddress = InternetAddress.parse(challengeRegistrantEntity.getRegistrantEmail()); + sendContestApplicationEmail(template, mailSubject, emailAddress, challengeEntity, challengeRegistrantEntity, false); } - StringWriter stringWriter = new StringWriter(); - Map templateModel = new HashMap<>(); - templateModel.put("webBaseUrl", webBaseUrl); - templateModel.put("challengeName", challengeEntity.getChallengeName()); - templateModel.put("businessRequirement", challengeEntity.getBusinessRequirement()); - templateModel.put("generalNote", challengeEntity.getGeneralNote()); - templateModel.put("technologies", StringUtils.join(challengeEntity.getTechnologies(), "
    ")); - templateModel.put("documents", challengeEntity.getDocuments()); - templateModel.put("deliverables", challengeEntity.getDeliverables()); - templateModel.put("receivedEmails", StringUtils.join(challengeEntity.getReceivedEmails(), "
    ")); - templateModel.put("reviewStyle", challengeEntity.getReviewStyle()); - templateModel.put("startDate", challengeEntity.getStartDateTime()); - templateModel.put("registrationDate", challengeEntity.getRegistrationDateTime()); - templateModel.put("submissionDate", challengeEntity.getSubmissionDateTime()); - templateModel.put("qualityIdea", challengeEntity.getQualityIdea()); - templateModel.put("firstPlaceReward", challengeEntity.getFirstPlaceReward() != null ? challengeEntity.getFirstPlaceReward() : 0); - templateModel.put("secondPlaceReward", challengeEntity.getSecondPlaceReward() != null ? challengeEntity.getSecondPlaceReward() : 0); - templateModel.put("thirdPlaceReward", challengeEntity.getThirdPlaceReward() != null ? challengeEntity.getThirdPlaceReward() : 0); - templateModel.put("challengeId", challengeEntity.getChallengeId().toString()); - templateModel.put("authorEmail", challengeEntity.getAuthorEmail()); - templateModel.put("challengeOverview", challengeEntity.getChallengeOverview()); - templateModel.put("firstName", challengeRegistrantEntity.getRegistrantFirstName()); - templateModel.put("lastName", challengeRegistrantEntity.getRegistrantLastName()); - templateModel.put("registrantEmail", challengeRegistrantEntity.getRegistrantEmail()); - templateModel.put("challengeNameAlias", challengeEntity.getChallengeName().replaceAll("\\W", "-")); - - template.process(templateModel, stringWriter); - postChallengeMailMessage.setSubject(MimeUtility.encodeText(mailSubject, "UTF-8", null)); - postChallengeMailMessage.setText(stringWriter.toString(), "UTF-8", "html"); - - stringWriter.flush(); - postChallengeMailMessage.saveChanges(); - mailSender.send(postChallengeMailMessage); - } - - private void sendPostChallengeEmail(ChallengeEntity challengeEntity, String mailSubject, - Address[] recipientAddresses, Template template) throws MessagingException, IOException, TemplateException { - postChallengeMailMessage.setRecipients(Message.RecipientType.TO, recipientAddresses); - postChallengeMailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); - StringWriter stringWriter = new StringWriter(); - - Map templateModel = new HashMap<>(); - templateModel.put("webBaseUrl", webBaseUrl); - templateModel.put("challengeName", challengeEntity.getChallengeName()); - templateModel.put("businessRequirement", challengeEntity.getBusinessRequirement()); - templateModel.put("generalNote", challengeEntity.getGeneralNote()); - templateModel.put("technologies", StringUtils.join(challengeEntity.getTechnologies(), "
    ")); - templateModel.put("documents", challengeEntity.getDocuments()); - templateModel.put("deliverables", challengeEntity.getDeliverables()); - templateModel.put("receivedEmails", StringUtils.join(challengeEntity.getReceivedEmails(), "
    ")); - templateModel.put("reviewStyle", challengeEntity.getReviewStyle()); - templateModel.put("startDate", challengeEntity.getStartDateTime()); - templateModel.put("registrationDate", challengeEntity.getRegistrationDateTime()); - templateModel.put("submissionDate", challengeEntity.getSubmissionDateTime()); - templateModel.put("qualityIdea", challengeEntity.getQualityIdea()); - templateModel.put("firstPlaceReward", challengeEntity.getFirstPlaceReward() != null ? challengeEntity.getFirstPlaceReward() : 0); - templateModel.put("secondPlaceReward", challengeEntity.getSecondPlaceReward() != null ? challengeEntity.getSecondPlaceReward() : 0); - templateModel.put("thirdPlaceReward", challengeEntity.getThirdPlaceReward() != null ? challengeEntity.getThirdPlaceReward() : 0); - templateModel.put("challengeId", challengeEntity.getChallengeId().toString()); - templateModel.put("authorEmail", challengeEntity.getAuthorEmail()); - templateModel.put("challengeOverview", challengeEntity.getChallengeOverview()); - templateModel.put("challengeNameAlias", challengeEntity.getChallengeName().replaceAll("\\W", "-")); - - template.process(templateModel, stringWriter); - String formatMailSubject = String.format(mailSubject, challengeEntity.getAuthorEmail(), challengeEntity.getChallengeName()); - postChallengeMailMessage.setSubject(MimeUtility.encodeText(formatMailSubject, "UTF-8", null)); - postChallengeMailMessage.setText(stringWriter.toString(), "UTF-8", "html"); - - stringWriter.flush(); - postChallengeMailMessage.saveChanges(); - mailSender.send(postChallengeMailMessage); - } - - private Address[] getRecipientAddresses(ChallengeEntity challengeEntity, boolean includeAuthor) throws AddressException { - Set emails = new HashSet<>(challengeEntity.getReceivedEmails()); - if (includeAuthor) { - emails.add(challengeEntity.getAuthorEmail()); + public void sendApplicationEmailToEmployer(ChallengeEntity challengeEntity, ChallengeRegistrantEntity challengeRegistrantEntity) throws MessagingException, IOException, TemplateException { + Template template = challengeRegistrantEntity.getLang() == Language.vi ? + alertEmployerChallengeMailTemplateVi : alertEmployerChallengeMailTemplateEn; + String mailSubject = challengeRegistrantEntity.getLang() == Language.vi ? + alertEmployerChallengeMailSubjectVn : alertEmployerChallengeMailSubjectEn; + mailSubject = String.format(mailSubject, challengeEntity.getChallengeName()); + Address[] emailAddress = getRecipientAddresses(challengeEntity, false); + sendContestApplicationEmail(template, mailSubject, emailAddress, challengeEntity, challengeRegistrantEntity, true); } - return InternetAddress.parse(StringUtils.join(emails, ',')); - } - - private List sortChallengesByDescendingStartDate(List challenges) { - SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); - return challenges.stream().sorted((challenge1, challenge2) -> { - try { - if (challenge2.getStartDateTime() == null) { - return -1; - } - else if (challenge1.getStartDateTime() == null) { - return 1; + + public long joinChallenge(ChallengeRegistrantDto challengeRegistrantDto) { + ChallengeRegistrantEntity entity = joinChallengeEntity(challengeRegistrantDto); + if (entity != null) { + return getNumberOfRegistrants(challengeRegistrantDto.getChallengeId()); } - long challenge2StartDate = sdf.parse(challenge2.getStartDateTime()).getTime(); - long challenge1StartDate = sdf.parse(challenge1.getStartDateTime()).getTime(); - if (challenge2StartDate - challenge1StartDate > 0) { - return 1; + return 0; + } + + public ChallengeRegistrantEntity joinChallengeEntity(ChallengeRegistrantDto challengeRegistrantDto) { + Long challengeId = challengeRegistrantDto.getChallengeId(); + boolean isExist = checkIfChallengeRegistrantExist(challengeId, challengeRegistrantDto.getRegistrantEmail()); + + if (!isExist) { + ChallengeRegistrantEntity challengeRegistrantEntity = dozerMapper.map(challengeRegistrantDto, ChallengeRegistrantEntity.class); + ChallengeEntity challengeEntity = challengeRepository.findOne(challengeId); + challengeRegistrantEntity.setRegistrantId(new Date().getTime()); + if (challengeEntity.getCriteria().size() > 0) { + final Set criteria = new HashSet<>(); + challengeEntity.getCriteria().forEach(cri -> criteria.add(dozerMapper.map(cri, ChallengeRegistrantCriteria.class))); + challengeRegistrantEntity.setCriteria(criteria); + } + challengeRegistrantEntity = challengeRegistrantRepository.save(challengeRegistrantEntity); + + try { + sendApplicationEmailToContestant(challengeEntity, challengeRegistrantEntity); + challengeRegistrantEntity.setMailSent(Boolean.TRUE); + return challengeRegistrantRepository.save(challengeRegistrantEntity); + } catch (Exception e) { + LOGGER.debug("Can not send email", e); + } } - else if (challenge2StartDate - challenge1StartDate < 0) { - return -1; + + return null; + } + + public List listChallenges() { + TermQueryBuilder notExpiredQuery = termQuery("expired", Boolean.TRUE); + Iterable challengeIterator = challengeRepository.search(boolQuery().mustNot(notExpiredQuery)); + ArrayList challenges = new ArrayList<>(); + challengeIterator.forEach(challengeEntity -> { + ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); + challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeEntity.getChallengeId())); + challenges.add(challengeDetailDto); + }); + return sortChallengesByDescendingStartDate(challenges); + } + + private void sendContestApplicationEmail(Template template, String mailSubject, Address[] recipientAddresses, + ChallengeEntity challengeEntity, ChallengeRegistrantEntity challengeRegistrantEntity, boolean hasReplyTo) + throws MessagingException, IOException, TemplateException { + postChallengeMailMessage.setRecipients(Message.RecipientType.TO, recipientAddresses); + + if (hasReplyTo) { + postChallengeMailMessage.setReplyTo(InternetAddress.parse(challengeRegistrantEntity.getRegistrantEmail())); + } else { + postChallengeMailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); } - else { - return 0; + + StringWriter stringWriter = new StringWriter(); + Map templateModel = new HashMap<>(); + templateModel.put("webBaseUrl", webBaseUrl); + templateModel.put("challengeName", challengeEntity.getChallengeName()); + templateModel.put("businessRequirement", challengeEntity.getBusinessRequirement()); + templateModel.put("generalNote", challengeEntity.getGeneralNote()); + templateModel.put("technologies", StringUtils.join(challengeEntity.getTechnologies(), "
    ")); + templateModel.put("documents", challengeEntity.getDocuments()); + templateModel.put("deliverables", challengeEntity.getDeliverables()); + templateModel.put("receivedEmails", StringUtils.join(challengeEntity.getReceivedEmails(), "
    ")); + templateModel.put("reviewStyle", challengeEntity.getReviewStyle()); + templateModel.put("startDate", challengeEntity.getStartDateTime()); + templateModel.put("registrationDate", challengeEntity.getRegistrationDateTime()); + templateModel.put("submissionDate", challengeEntity.getSubmissionDateTime()); + templateModel.put("qualityIdea", challengeEntity.getQualityIdea()); + templateModel.put("firstPlaceReward", challengeEntity.getFirstPlaceReward() != null ? challengeEntity.getFirstPlaceReward() : 0); + templateModel.put("secondPlaceReward", challengeEntity.getSecondPlaceReward() != null ? challengeEntity.getSecondPlaceReward() : 0); + templateModel.put("thirdPlaceReward", challengeEntity.getThirdPlaceReward() != null ? challengeEntity.getThirdPlaceReward() : 0); + templateModel.put("challengeId", challengeEntity.getChallengeId().toString()); + templateModel.put("authorEmail", challengeEntity.getAuthorEmail()); + templateModel.put("challengeOverview", challengeEntity.getChallengeOverview()); + templateModel.put("firstName", challengeRegistrantEntity.getRegistrantFirstName()); + templateModel.put("lastName", challengeRegistrantEntity.getRegistrantLastName()); + templateModel.put("registrantEmail", challengeRegistrantEntity.getRegistrantEmail()); + templateModel.put("challengeNameAlias", challengeEntity.getChallengeName().replaceAll("\\W", "-")); + + template.process(templateModel, stringWriter); + postChallengeMailMessage.setSubject(MimeUtility.encodeText(mailSubject, "UTF-8", null)); + postChallengeMailMessage.setText(stringWriter.toString(), "UTF-8", "html"); + + stringWriter.flush(); + postChallengeMailMessage.saveChanges(); + mailSender.send(postChallengeMailMessage); + } + + private void sendPostChallengeEmail(ChallengeEntity challengeEntity, String mailSubject, + Address[] recipientAddresses, Template template) throws MessagingException, IOException, TemplateException { + postChallengeMailMessage.setRecipients(Message.RecipientType.TO, recipientAddresses); + postChallengeMailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); + StringWriter stringWriter = new StringWriter(); + + Map templateModel = new HashMap<>(); + templateModel.put("webBaseUrl", webBaseUrl); + templateModel.put("challengeName", challengeEntity.getChallengeName()); + templateModel.put("businessRequirement", challengeEntity.getBusinessRequirement()); + templateModel.put("generalNote", challengeEntity.getGeneralNote()); + templateModel.put("technologies", StringUtils.join(challengeEntity.getTechnologies(), "
    ")); + templateModel.put("documents", challengeEntity.getDocuments()); + templateModel.put("deliverables", challengeEntity.getDeliverables()); + templateModel.put("receivedEmails", StringUtils.join(challengeEntity.getReceivedEmails(), "
    ")); + templateModel.put("reviewStyle", challengeEntity.getReviewStyle()); + templateModel.put("startDate", challengeEntity.getStartDateTime()); + templateModel.put("registrationDate", challengeEntity.getRegistrationDateTime()); + templateModel.put("submissionDate", challengeEntity.getSubmissionDateTime()); + templateModel.put("qualityIdea", challengeEntity.getQualityIdea()); + templateModel.put("firstPlaceReward", challengeEntity.getFirstPlaceReward() != null ? challengeEntity.getFirstPlaceReward() : 0); + templateModel.put("secondPlaceReward", challengeEntity.getSecondPlaceReward() != null ? challengeEntity.getSecondPlaceReward() : 0); + templateModel.put("thirdPlaceReward", challengeEntity.getThirdPlaceReward() != null ? challengeEntity.getThirdPlaceReward() : 0); + templateModel.put("challengeId", challengeEntity.getChallengeId().toString()); + templateModel.put("authorEmail", challengeEntity.getAuthorEmail()); + templateModel.put("challengeOverview", challengeEntity.getChallengeOverview()); + templateModel.put("challengeNameAlias", challengeEntity.getChallengeName().replaceAll("\\W", "-")); + + template.process(templateModel, stringWriter); + String formatMailSubject = String.format(mailSubject, challengeEntity.getAuthorEmail(), challengeEntity.getChallengeName()); + postChallengeMailMessage.setSubject(MimeUtility.encodeText(formatMailSubject, "UTF-8", null)); + postChallengeMailMessage.setText(stringWriter.toString(), "UTF-8", "html"); + + stringWriter.flush(); + postChallengeMailMessage.saveChanges(); + mailSender.send(postChallengeMailMessage); + } + + private Address[] getRecipientAddresses(ChallengeEntity challengeEntity, boolean includeAuthor) throws AddressException { + Set emails = new HashSet<>(challengeEntity.getReceivedEmails()); + if (includeAuthor) { + emails.add(challengeEntity.getAuthorEmail()); } - } - catch (ParseException e) { - return 0; - } - }).collect(toList()); - } - - public boolean checkIfChallengeRegistrantExist(Long challengeId, String email) { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder(); - searchQueryBuilder.withQuery(boolQuery() - .must(matchPhraseQuery("registrantEmail", email)) - .must(termQuery("challengeId", challengeId))); - - long total = challengeRegistrantRepository.search(searchQueryBuilder.build()).getTotalElements(); - return (total > 0); - } - - @Override - public Long getTotalNumberOfChallenges() { - return challengeRepository.count(); - } - - @Override - public Double getTotalAmountOfPrizeValues() { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withSearchType(SearchType.COUNT); - searchQueryBuilder.withQuery(matchAllQuery()); - - SumBuilder sumPrizeBuilder = sum("sumPrize").script("doc['firstPlaceReward'].value + doc['secondPlaceReward'].value + doc['thirdPlaceReward'].value"); - searchQueryBuilder.addAggregation(sumPrizeBuilder); - - Aggregations aggregations = elasticsearchTemplateUserImport.query(searchQueryBuilder.build(), SearchResponse::getAggregations); - Sum sumReponse = aggregations.get("sumPrize"); - return sumReponse != null ? sumReponse.getValue() : 0D; - } - - @Override - public Long getTotalNumberOfRegistrants() { - return challengeRegistrantRepository.count(); - } - - @Override - public ChallengeDetailDto getTheLatestChallenge() { + return InternetAddress.parse(StringUtils.join(emails, ',')); + } + + private List sortChallengesByDescendingStartDate(List challenges) { + SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); + return challenges.stream().sorted((challenge1, challenge2) -> { + try { + if (challenge2.getStartDateTime() == null) { + return -1; + } else if (challenge1.getStartDateTime() == null) { + return 1; + } + long challenge2StartDate = sdf.parse(challenge2.getStartDateTime()).getTime(); + long challenge1StartDate = sdf.parse(challenge1.getStartDateTime()).getTime(); + if (challenge2StartDate - challenge1StartDate > 0) { + return 1; + } else if (challenge2StartDate - challenge1StartDate < 0) { + return -1; + } else { + return 0; + } + } catch (ParseException e) { + return 0; + } + }).collect(toList()); + } + + public boolean checkIfChallengeRegistrantExist(Long challengeId, String email) { + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder(); + searchQueryBuilder.withQuery(boolQuery() + .must(matchPhraseQuery("registrantEmail", email)) + .must(termQuery("challengeId", challengeId))); + + long total = challengeRegistrantRepository.search(searchQueryBuilder.build()).getTotalElements(); + return (total > 0); + } + + @Override + public Long getTotalNumberOfChallenges() { + return challengeRepository.count(); + } + + @Override + public Double getTotalAmountOfPrizeValues() { + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withSearchType(SearchType.COUNT); + searchQueryBuilder.withQuery(matchAllQuery()); + + SumBuilder sumPrizeBuilder = sum("sumPrize").script("doc['firstPlaceReward'].value + doc['secondPlaceReward'].value + doc['thirdPlaceReward'].value"); + searchQueryBuilder.addAggregation(sumPrizeBuilder); + + Aggregations aggregations = elasticsearchTemplateUserImport.query(searchQueryBuilder.build(), SearchResponse::getAggregations); + Sum sumReponse = aggregations.get("sumPrize"); + return sumReponse != null ? sumReponse.getValue() : 0D; + } + + @Override + public Long getTotalNumberOfRegistrants() { + return challengeRegistrantRepository.count(); + } + + @Override + public ChallengeDetailDto getTheLatestChallenge() { // NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder(); // searchQueryBuilder.withQuery(QueryBuilders.matchAllQuery()); // searchQueryBuilder.withSort(SortBuilders.fieldSort("challengeId").order(SortOrder.DESC)); @@ -515,422 +514,455 @@ public ChallengeDetailDto getTheLatestChallenge() { // ChallengeEntity challengeEntity = challengeEntities.get(0); // return dozerMapper.map(challengeEntity, ChallengeDetailDto.class); // } - return listChallenges().get(0); - } - - public Collection findByOwnerAndCondition(String owner, - Predicate condition) { - NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().withIndices(techlooperIndex).withTypes("challenge"); - QueryStringQueryBuilder query = queryStringQuery(owner).defaultField("authorEmail"); - queryBuilder.withFilter(FilterBuilders.queryFilter(query)); - - int pageIndex = 0; - Set challenges = new HashSet<>(); - while (true) { - queryBuilder.withPageable(new PageRequest(pageIndex++, 100)); - FacetedPage page = challengeRepository.search(queryBuilder.build()); - if (!page.hasContent()) { - break; - } - - page.spliterator().forEachRemaining(challenge -> { - if (condition.test(challenge)) { - ChallengeDetailDto challengeDetailDto = dozerMapper.map(challenge, ChallengeDetailDto.class); - challengeDetailDto.setNumberOfRegistrants(countRegistrantsByChallengeId(challenge.getChallengeId())); - challenges.add(challengeDetailDto); + return listChallenges().get(0); + } + + public Collection findByOwnerAndCondition(String owner, + Predicate condition) { + NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().withIndices(techlooperIndex).withTypes("challenge"); + QueryStringQueryBuilder query = queryStringQuery(owner).defaultField("authorEmail"); + queryBuilder.withFilter(FilterBuilders.queryFilter(query)); + + int pageIndex = 0; + Set challenges = new HashSet<>(); + while (true) { + queryBuilder.withPageable(new PageRequest(pageIndex++, 100)); + FacetedPage page = challengeRepository.search(queryBuilder.build()); + if (!page.hasContent()) { + break; + } + + page.spliterator().forEachRemaining(challenge -> { + if (condition.test(challenge)) { + ChallengeDetailDto challengeDetailDto = dozerMapper.map(challenge, ChallengeDetailDto.class); + challengeDetailDto.setNumberOfRegistrants(countRegistrantsByChallengeId(challenge.getChallengeId())); + challenges.add(challengeDetailDto); + } + }); } - }); + return challenges; } - return challenges; - } - - public List listChallenges(String ownerEmail) { - List result = new ArrayList<>(); - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challenge"); - MatchQueryBuilder authorEmailQuery = matchQuery("authorEmail", ownerEmail).minimumShouldMatch("100%"); - TermQueryBuilder notExpiredQuery = termQuery("expired", Boolean.TRUE); - - searchQueryBuilder.withQuery(boolQuery().must(authorEmailQuery).mustNot(notExpiredQuery)); - List challengeEntities = DataUtils.getAllEntities(challengeRepository, searchQueryBuilder); - - for (ChallengeEntity challengeEntity : challengeEntities) { - ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); - challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeDetailDto.getChallengeId())); - result.add(challengeDetailDto); + + public List listChallenges(String ownerEmail) { + List result = new ArrayList<>(); + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challenge"); + MatchQueryBuilder authorEmailQuery = matchQuery("authorEmail", ownerEmail).minimumShouldMatch("100%"); + TermQueryBuilder notExpiredQuery = termQuery("expired", Boolean.TRUE); + + searchQueryBuilder.withQuery(boolQuery().must(authorEmailQuery).mustNot(notExpiredQuery)); + List challengeEntities = DataUtils.getAllEntities(challengeRepository, searchQueryBuilder); + + for (ChallengeEntity challengeEntity : challengeEntities) { + ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); + challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeDetailDto.getChallengeId())); + result.add(challengeDetailDto); + } + return result; } - return result; - } - - public Collection findInProgressChallenges(String owner) { - DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("dd/MM/yyyy"); - return findByOwnerAndCondition(owner, challengeEntity -> { - DateTime startDate = dateTimeFormatter.parseDateTime(challengeEntity.getStartDateTime()); - DateTime submissionDate = dateTimeFormatter.parseDateTime(challengeEntity.getSubmissionDateTime()); - DateTime now = DateTime.now(); - boolean inRange = now.isAfter(startDate) && now.isBefore(submissionDate); - boolean atBoundary = now.isEqual(startDate) || now.isEqual(submissionDate); - return inRange || atBoundary; - }); - } - - public Long countRegistrantsByChallengeId(Long challengeId) { - NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().withIndices(techlooperIndex).withTypes("challengeRegistrant"); - queryBuilder.withFilter(FilterBuilders.queryFilter(termQuery("challengeId", challengeId))) - .withSearchType(SearchType.COUNT); - return challengeRegistrantRepository.search(queryBuilder.build()).getTotalElements(); - } - - public boolean delete(Long id, String ownerEmail) { - ChallengeEntity challenge = challengeRepository.findOne(id); - if (challenge.getAuthorEmail().equalsIgnoreCase(ownerEmail)) { - challenge.setExpired(Boolean.TRUE); - challengeRepository.save(challenge); - return true; + + public Collection findInProgressChallenges(String owner) { + DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("dd/MM/yyyy"); + return findByOwnerAndCondition(owner, challengeEntity -> { + DateTime startDate = dateTimeFormatter.parseDateTime(challengeEntity.getStartDateTime()); + DateTime submissionDate = dateTimeFormatter.parseDateTime(challengeEntity.getSubmissionDateTime()); + DateTime now = DateTime.now(); + boolean inRange = now.isAfter(startDate) && now.isBefore(submissionDate); + boolean atBoundary = now.isEqual(startDate) || now.isEqual(submissionDate); + return inRange || atBoundary; + }); } - return false; - } - - public ChallengeDto findChallengeById(Long id) { - return dozerMapper.map(challengeRepository.findOne(id), ChallengeDto.class); - } - - public Set findRegistrantsByOwner(RegistrantFilterCondition condition) throws ParseException { - Set result = new HashSet<>(); - Long challengeId = condition.getChallengeId(); - ChallengeEntity challengeEntity = challengeRepository.findOne(challengeId); - - if (challengeEntity != null && challengeEntity.getAuthorEmail().equals(condition.getAuthorEmail())) { - List registrants = filterChallengeRegistrantByDate(condition); - for (ChallengeRegistrantEntity registrant : registrants) { - ChallengeRegistrantDto registrantDto = dozerMapper.map(registrant, ChallengeRegistrantDto.class); - registrantDto.setSubmissions(findChallengeSubmissionByRegistrant(challengeId, registrant.getRegistrantId())); - result.add(registrantDto); - } + + public Long countRegistrantsByChallengeId(Long challengeId) { + NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().withIndices(techlooperIndex).withTypes("challengeRegistrant"); + queryBuilder.withFilter(FilterBuilders.queryFilter(termQuery("challengeId", challengeId))) + .withSearchType(SearchType.COUNT); + return challengeRegistrantRepository.search(queryBuilder.build()).getTotalElements(); } - return result; - } - - public ChallengeRegistrantDto saveRegistrant(String ownerEmail, ChallengeRegistrantDto challengeRegistrantDto) { - ChallengeRegistrantDto resultChallengeRegistrantDto = challengeRegistrantDto; - ChallengeEntity challenge = challengeRepository.findOne(challengeRegistrantDto.getChallengeId()); - if (ownerEmail.equalsIgnoreCase(challenge.getAuthorEmail())) { - ChallengeRegistrantEntity registrant = challengeRegistrantRepository.findOne(challengeRegistrantDto.getRegistrantId()); - challengeRegistrantDto.setRegistrantEmail(registrant.getRegistrantEmail()); - dozerMapper.map(challengeRegistrantDto, registrant); - registrant = challengeRegistrantRepository.save(registrant); - resultChallengeRegistrantDto = dozerMapper.map(registrant, ChallengeRegistrantDto.class); + public boolean delete(Long id, String ownerEmail) { + ChallengeEntity challenge = challengeRepository.findOne(id); + if (challenge.getAuthorEmail().equalsIgnoreCase(ownerEmail)) { + challenge.setExpired(Boolean.TRUE); + challengeRepository.save(challenge); + return true; + } + return false; + } + + public ChallengeDto findChallengeById(Long id) { + return dozerMapper.map(challengeRepository.findOne(id), ChallengeDto.class); } - return resultChallengeRegistrantDto; - } - - @Override - public List findChallengeRegistrantWithinPeriod( - Long challengeId, Long currentDateTime, TimePeriodEnum period) { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeRegistrant"); - - BoolQueryBuilder boolQueryBuilder = boolQuery(); - boolQueryBuilder.must(termQuery("challengeId", challengeId)); - - Long pastTime = currentDateTime - period.getMiliseconds() > 0 ? currentDateTime - period.getMiliseconds() : 0; - boolQueryBuilder.must(rangeQuery("registrantId").from(pastTime)); - searchQueryBuilder.withQuery(boolQueryBuilder); - searchQueryBuilder.withSort(fieldSort("registrantId").order(SortOrder.DESC)); - return DataUtils.getAllEntities(challengeRegistrantRepository, searchQueryBuilder); - } - - @Override - public List filterChallengeRegistrantByDate(RegistrantFilterCondition condition) throws ParseException { - List result = new ArrayList<>(); - - if (ChallengeRegistrantFilterTypeEnum.BY_SUBMISSION.getValue().equals(condition.getFilterType())) { - Set registrantIds = findRegistrantByChallengeSubmissionDate( - condition.getChallengeId(), condition.getFromDate(), condition.getToDate()); - for (Long registrantId : registrantIds) { - ChallengeRegistrantEntity registrantEntity = challengeRegistrantRepository.findOne(registrantId); - if (registrantEntity != null) { - result.add(registrantEntity); + + public Set findRegistrantsByOwner(RegistrantFilterCondition condition) throws ParseException { + Set result = new HashSet<>(); + Long challengeId = condition.getChallengeId(); + ChallengeEntity challengeEntity = challengeRepository.findOne(challengeId); + + if (challengeEntity != null && challengeEntity.getAuthorEmail().equals(condition.getAuthorEmail())) { + List registrants = filterChallengeRegistrantByDate(condition); + for (ChallengeRegistrantEntity registrant : registrants) { + ChallengeRegistrantDto registrantDto = dozerMapper.map(registrant, ChallengeRegistrantDto.class); + registrantDto.setSubmissions(findChallengeSubmissionByRegistrant(challengeId, registrant.getRegistrantId())); + result.add(registrantDto); + } } - } - if (StringUtils.isNotEmpty(condition.getPhase())) { - result = result.stream().filter(registrantEntity -> - condition.getPhase().equals(registrantEntity.getActivePhase().getValue())).collect(toList()); - } + return result; } - else { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeRegistrant"); - BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); - final String registrationPhase = ChallengePhaseEnum.REGISTRATION.getValue(); - - if (condition.getChallengeId() != null) { - boolQueryBuilder.must(termQuery("challengeId", condition.getChallengeId())); - } - - if (StringUtils.isNotEmpty(condition.getPhase()) && !registrationPhase.equals(condition.getPhase())) { - boolQueryBuilder.must(matchPhraseQuery("activePhase", condition.getPhase())); - } - - if (StringUtils.isNotEmpty(condition.getFilterType()) && - (StringUtils.isNotEmpty(condition.getFromDate()) || StringUtils.isNotEmpty(condition.getToDate()))) { - RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(condition.getFilterType()); - - if (StringUtils.isNotEmpty(condition.getFromDate())) { - Long from = string2Date(condition.getFromDate(), BASIC_DATE_PATTERN).getTime(); - rangeQueryBuilder.from(from); + + public ChallengeRegistrantDto saveRegistrant(String ownerEmail, ChallengeRegistrantDto challengeRegistrantDto) { + ChallengeRegistrantDto resultChallengeRegistrantDto = challengeRegistrantDto; + ChallengeEntity challenge = challengeRepository.findOne(challengeRegistrantDto.getChallengeId()); + if (ownerEmail.equalsIgnoreCase(challenge.getAuthorEmail())) { + ChallengeRegistrantEntity registrant = challengeRegistrantRepository.findOne(challengeRegistrantDto.getRegistrantId()); + challengeRegistrantDto.setRegistrantEmail(registrant.getRegistrantEmail()); + dozerMapper.map(challengeRegistrantDto, registrant); + registrant = challengeRegistrantRepository.save(registrant); + resultChallengeRegistrantDto = dozerMapper.map(registrant, ChallengeRegistrantDto.class); } - if (StringUtils.isNotEmpty(condition.getToDate())) { - Long to = string2Date(condition.getToDate(), BASIC_DATE_PATTERN).getTime() + - TimePeriodEnum.TWENTY_FOUR_HOURS.getMiliseconds(); - rangeQueryBuilder.to(to); + return resultChallengeRegistrantDto; + } + + @Override + public List findChallengeRegistrantWithinPeriod( + Long challengeId, Long currentDateTime, TimePeriodEnum period) { + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeRegistrant"); + + BoolQueryBuilder boolQueryBuilder = boolQuery(); + boolQueryBuilder.must(termQuery("challengeId", challengeId)); + + Long pastTime = currentDateTime - period.getMiliseconds() > 0 ? currentDateTime - period.getMiliseconds() : 0; + boolQueryBuilder.must(rangeQuery("registrantId").from(pastTime)); + searchQueryBuilder.withQuery(boolQueryBuilder); + searchQueryBuilder.withSort(fieldSort("registrantId").order(SortOrder.DESC)); + return DataUtils.getAllEntities(challengeRegistrantRepository, searchQueryBuilder); + } + + @Override + public List filterChallengeRegistrantByDate(RegistrantFilterCondition condition) throws ParseException { + List result = new ArrayList<>(); + + if (ChallengeRegistrantFilterTypeEnum.BY_SUBMISSION.getValue().equals(condition.getFilterType())) { + Set registrantIds = findRegistrantByChallengeSubmissionDate( + condition.getChallengeId(), condition.getFromDate(), condition.getToDate()); + for (Long registrantId : registrantIds) { + ChallengeRegistrantEntity registrantEntity = challengeRegistrantRepository.findOne(registrantId); + if (registrantEntity != null) { + result.add(registrantEntity); + } + } + + if (StringUtils.isNotEmpty(condition.getPhase())) { + result = result.stream().filter(registrantEntity -> + condition.getPhase().equals(registrantEntity.getActivePhase().getValue())).collect(toList()); + } + } else { + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeRegistrant"); + BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); + final String registrationPhase = ChallengePhaseEnum.REGISTRATION.getValue(); + + if (condition.getChallengeId() != null) { + boolQueryBuilder.must(termQuery("challengeId", condition.getChallengeId())); + } + + if (StringUtils.isNotEmpty(condition.getPhase()) && !registrationPhase.equals(condition.getPhase())) { + boolQueryBuilder.must(matchPhraseQuery("activePhase", condition.getPhase())); + } + + if (StringUtils.isNotEmpty(condition.getFilterType()) && + (StringUtils.isNotEmpty(condition.getFromDate()) || StringUtils.isNotEmpty(condition.getToDate()))) { + RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(condition.getFilterType()); + + if (StringUtils.isNotEmpty(condition.getFromDate())) { + Long from = string2Date(condition.getFromDate(), BASIC_DATE_PATTERN).getTime(); + rangeQueryBuilder.from(from); + } + if (StringUtils.isNotEmpty(condition.getToDate())) { + Long to = string2Date(condition.getToDate(), BASIC_DATE_PATTERN).getTime() + + TimePeriodEnum.TWENTY_FOUR_HOURS.getMiliseconds(); + rangeQueryBuilder.to(to); + } + + boolQueryBuilder.must(rangeQueryBuilder); + } + + searchQueryBuilder.withQuery(boolQueryBuilder); + result.addAll(DataUtils.getAllEntities(challengeRegistrantRepository, searchQueryBuilder)); + + if (registrationPhase.equals(condition.getPhase())) { + result = result.stream().filter(registrantEntity -> registrantEntity.getActivePhase() == null + || registrationPhase.equals(registrantEntity.getActivePhase().getValue())).collect(toList()); + } } - boolQueryBuilder.must(rangeQueryBuilder); - } + return result; + } + + @Override + public List findChallengeSubmissionWithinPeriod( + Long challengeId, Long currentDateTime, TimePeriodEnum period) { + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeSubmission"); + + BoolQueryBuilder boolQueryBuilder = boolQuery(); + boolQueryBuilder.must(termQuery("challengeId", challengeId)); - searchQueryBuilder.withQuery(boolQueryBuilder); - result.addAll(DataUtils.getAllEntities(challengeRegistrantRepository, searchQueryBuilder)); + boolQueryBuilder.must(rangeQuery("submissionDateTime").from(yesterdayDate())); + searchQueryBuilder.withQuery(boolQueryBuilder); + searchQueryBuilder.withSort(fieldSort("challengeSubmissionId").order(SortOrder.DESC)); - if (registrationPhase.equals(condition.getPhase())) { - result = result.stream().filter(registrantEntity -> registrantEntity.getActivePhase() == null - || registrationPhase.equals(registrantEntity.getActivePhase().getValue())).collect(toList()); - } + return DataUtils.getAllEntities(challengeSubmissionRepository, searchQueryBuilder); } - return result; - } - - @Override - public List findChallengeSubmissionWithinPeriod( - Long challengeId, Long currentDateTime, TimePeriodEnum period) { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeSubmission"); - - BoolQueryBuilder boolQueryBuilder = boolQuery(); - boolQueryBuilder.must(termQuery("challengeId", challengeId)); - - boolQueryBuilder.must(rangeQuery("submissionDateTime").from(yesterdayDate())); - searchQueryBuilder.withQuery(boolQueryBuilder); - searchQueryBuilder.withSort(fieldSort("challengeSubmissionId").order(SortOrder.DESC)); - - return DataUtils.getAllEntities(challengeSubmissionRepository, searchQueryBuilder); - } - - @Override - public List listChallengesByPhase(ChallengePhaseEnum challengePhase) { - List challengeEntities = new ArrayList<>(); - // from <= NOW < to - RangeFilterBuilder fromFilter = rangeFilter(challengePhase.getFromDateTimeField()).lt("now/d"); - RangeFilterBuilder toFilter = rangeFilter(challengePhase.getToDateTimeField()).gte("now/d"); - TermFilterBuilder expiredChallengeFilter = termFilter("expired", Boolean.TRUE); - BoolFilterBuilder dateTimeRangeFilter = boolFilter().must(fromFilter).must(toFilter).mustNot(expiredChallengeFilter); - - Iterator challengeIterator = - challengeRepository.search(filteredQuery(matchAllQuery(), dateTimeRangeFilter)).iterator(); - while (challengeIterator.hasNext()) { - challengeEntities.add(challengeIterator.next()); + @Override + public List listChallengesByPhase(ChallengePhaseEnum challengePhase) { + List challengeEntities = new ArrayList<>(); + // from <= NOW < to + RangeFilterBuilder fromFilter = rangeFilter(challengePhase.getFromDateTimeField()).lt("now/d"); + RangeFilterBuilder toFilter = rangeFilter(challengePhase.getToDateTimeField()).gte("now/d"); + TermFilterBuilder expiredChallengeFilter = termFilter("expired", Boolean.TRUE); + BoolFilterBuilder dateTimeRangeFilter = boolFilter().must(fromFilter).must(toFilter).mustNot(expiredChallengeFilter); + + Iterator challengeIterator = + challengeRepository.search(filteredQuery(matchAllQuery(), dateTimeRangeFilter)).iterator(); + while (challengeIterator.hasNext()) { + challengeEntities.add(challengeIterator.next()); + } + + return challengeEntities; } - return challengeEntities; - } - - @Override - public void sendDailySummaryEmailToChallengeOwner(ChallengeEntity challengeEntity) throws Exception { - String mailSubject = challengeEntity.getLang() == Language.vi ? dailyChallengeSummaryMailSubjectVi : - dailyChallengeSummaryMailSubjectEn; - Address[] recipientAddresses = getRecipientAddresses(challengeEntity, true); - Template template = challengeEntity.getLang() == Language.vi ? - dailyChallengeSummaryMailTemplateVi : dailyChallengeSummaryMailTemplateEn; - postChallengeMailMessage.setRecipients(Message.RecipientType.TO, recipientAddresses); - Address[] replyToAddresses = InternetAddress.parse(postChallengeTechloopiesMailList); - postChallengeMailMessage.setReplyTo(replyToAddresses); - StringWriter stringWriter = new StringWriter(); - - Map templateModel = new HashMap<>(); - templateModel.put("webBaseUrl", webBaseUrl); - templateModel.put("challengeName", challengeEntity.getChallengeName()); - templateModel.put("challengeId", challengeEntity.getChallengeId().toString()); - templateModel.put("challengeNameAlias", challengeEntity.getChallengeName().replaceAll("\\W", "-")); - templateModel.put("currentDateTime", String.valueOf(new Date().getTime())); - templateModel.put("yesterdayDateTime", DateTimeUtils.yesterdayDate()); - - Long currentDateTime = new Date().getTime(); - List latestRegistrants = findChallengeRegistrantWithinPeriod( - challengeEntity.getChallengeId(), currentDateTime, TimePeriodEnum.TWENTY_FOUR_HOURS); - templateModel.put("numberOfRegistrants", latestRegistrants.size()); - templateModel.put("latestRegistrants", latestRegistrants); - - List latestSubmissions = findChallengeSubmissionWithinPeriod( - challengeEntity.getChallengeId(), currentDateTime, TimePeriodEnum.TWENTY_FOUR_HOURS); - templateModel.put("numberOfSubmissions", latestSubmissions.size()); - templateModel.put("latestSubmissions", latestSubmissions); - - template.process(templateModel, stringWriter); - mailSubject = String.format(mailSubject, challengeEntity.getChallengeName()); - postChallengeMailMessage.setSubject(MimeUtility.encodeText(mailSubject, "UTF-8", null)); - postChallengeMailMessage.setText(stringWriter.toString(), "UTF-8", "html"); - - stringWriter.flush(); - postChallengeMailMessage.saveChanges(); - mailSender.send(postChallengeMailMessage); - } - - public boolean isOwnerOfChallenge(String ownerEmail, Long challengeId) { - ChallengeEntity challenge = challengeRepository.findOne(challengeId); - return challenge.getAuthorEmail().equalsIgnoreCase(ownerEmail); - } - - public ChallengeEntity findChallengeIdAndOwnerEmail(Long challengeId, String ownerEmail) { - ChallengeEntity challenge = challengeRepository.findOne(challengeId); - if (challenge == null || !challenge.getAuthorEmail().equalsIgnoreCase(ownerEmail)) { - return null; + @Override + public void sendDailySummaryEmailToChallengeOwner(ChallengeEntity challengeEntity) throws Exception { + String mailSubject = challengeEntity.getLang() == Language.vi ? dailyChallengeSummaryMailSubjectVi : + dailyChallengeSummaryMailSubjectEn; + Address[] recipientAddresses = getRecipientAddresses(challengeEntity, true); + Template template = challengeEntity.getLang() == Language.vi ? + dailyChallengeSummaryMailTemplateVi : dailyChallengeSummaryMailTemplateEn; + postChallengeMailMessage.setRecipients(Message.RecipientType.TO, recipientAddresses); + Address[] replyToAddresses = InternetAddress.parse(postChallengeTechloopiesMailList); + postChallengeMailMessage.setReplyTo(replyToAddresses); + StringWriter stringWriter = new StringWriter(); + + Map templateModel = new HashMap<>(); + templateModel.put("webBaseUrl", webBaseUrl); + templateModel.put("challengeName", challengeEntity.getChallengeName()); + templateModel.put("challengeId", challengeEntity.getChallengeId().toString()); + templateModel.put("challengeNameAlias", challengeEntity.getChallengeName().replaceAll("\\W", "-")); + templateModel.put("currentDateTime", String.valueOf(new Date().getTime())); + templateModel.put("yesterdayDateTime", DateTimeUtils.yesterdayDate()); + + Long currentDateTime = new Date().getTime(); + List latestRegistrants = findChallengeRegistrantWithinPeriod( + challengeEntity.getChallengeId(), currentDateTime, TimePeriodEnum.TWENTY_FOUR_HOURS); + templateModel.put("numberOfRegistrants", latestRegistrants.size()); + templateModel.put("latestRegistrants", latestRegistrants); + + List latestSubmissions = findChallengeSubmissionWithinPeriod( + challengeEntity.getChallengeId(), currentDateTime, TimePeriodEnum.TWENTY_FOUR_HOURS); + templateModel.put("numberOfSubmissions", latestSubmissions.size()); + templateModel.put("latestSubmissions", latestSubmissions); + + template.process(templateModel, stringWriter); + mailSubject = String.format(mailSubject, challengeEntity.getChallengeName()); + postChallengeMailMessage.setSubject(MimeUtility.encodeText(mailSubject, "UTF-8", null)); + postChallengeMailMessage.setText(stringWriter.toString(), "UTF-8", "html"); + + stringWriter.flush(); + postChallengeMailMessage.saveChanges(); + mailSender.send(postChallengeMailMessage); } - return challenge; - } - - public boolean sendEmailToDailyChallengeRegistrants(String challengeOwner, Long challengeId, Long now, EmailContent emailContent) { - if (isOwnerOfChallenge(challengeOwner, challengeId)) { - List registrants = findChallengeRegistrantWithinPeriod(challengeId, now, TimePeriodEnum.TWENTY_FOUR_HOURS); - String csvEmails = registrants.stream().map(ChallengeRegistrantEntity::getRegistrantEmail).distinct().collect(joining(",")); - try { - emailContent.setRecipients(InternetAddress.parse(csvEmails)); - } - catch (AddressException e) { - LOGGER.debug("Can not parse email address", e); - return false; - } + + public boolean isOwnerOfChallenge(String ownerEmail, Long challengeId) { + ChallengeEntity challenge = challengeRepository.findOne(challengeId); + return challenge.getAuthorEmail().equalsIgnoreCase(ownerEmail); } - return emailService.sendEmail(emailContent); - } - - public boolean sendEmailToRegistrant(String challengeOwner, Long challengeId, Long registrantId, EmailContent emailContent) { - if (isOwnerOfChallenge(challengeOwner, challengeId)) { - ChallengeRegistrantEntity registrant = challengeRegistrantRepository.findOne(registrantId); - String csvEmails = registrant.getRegistrantEmail(); - try { - emailContent.setRecipients(InternetAddress.parse(csvEmails)); - } - catch (AddressException e) { - LOGGER.debug("Can not parse email address", e); - return false; - } + + public ChallengeEntity findChallengeIdAndOwnerEmail(Long challengeId, String ownerEmail) { + ChallengeEntity challenge = challengeRepository.findOne(challengeId); + if (challenge == null || !challenge.getAuthorEmail().equalsIgnoreCase(ownerEmail)) { + return null; + } + return challenge; } - return emailService.sendEmail(emailContent); - } - - @Override - public List findChallengeSubmissionByRegistrant(Long challengeId, Long registrantId) { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeSubmission"); - BoolFilterBuilder boolFilterBuilder = new BoolFilterBuilder(); - boolFilterBuilder.must(termFilter("challengeId", challengeId)); - boolFilterBuilder.must(termFilter("registrantId", registrantId)); - - searchQueryBuilder.withQuery(filteredQuery(matchAllQuery(), boolFilterBuilder)); - List submissions = DataUtils.getAllEntities(challengeSubmissionRepository, searchQueryBuilder); - return submissions.stream().map(submission -> dozerMapper.map(submission, ChallengeSubmissionDto.class)).collect(toList()); - } - - @Override - public void updateSendEmailToContestantResultCode(ChallengeRegistrantEntity challengeRegistrantEntity, EmailSentResultEnum code) { - if (challengeRegistrantEntity != null) { - challengeRegistrantEntity.setLastEmailSentDateTime(currentDate(BASIC_DATE_TIME_PATTERN)); - challengeRegistrantEntity.setLastEmailSentResultCode(code.getValue()); - challengeRegistrantRepository.save(challengeRegistrantEntity); + + public boolean sendEmailToDailyChallengeRegistrants(String challengeOwner, Long challengeId, Long now, EmailContent emailContent) { + if (isOwnerOfChallenge(challengeOwner, challengeId)) { + List registrants = findChallengeRegistrantWithinPeriod(challengeId, now, TimePeriodEnum.TWENTY_FOUR_HOURS); + String csvEmails = registrants.stream().map(ChallengeRegistrantEntity::getRegistrantEmail).distinct().collect(joining(",")); + ChallengeDto challengeDto = findChallengeById(challengeId); + try { + // In case sending email to only one registrant of this challenge (feedback action form) + if (registrants.size() == 1) { + bindEmailTemplateVariables(emailContent, challengeDto, registrants.get(0)); + } + emailContent.setRecipients(InternetAddress.parse(csvEmails)); + } catch (AddressException e) { + LOGGER.debug("Can not parse email address", e); + return false; + } + } + return emailService.sendEmail(emailContent); } - } - public void updateSendEmailToChallengeOwnerResultCode(ChallengeEntity challengeEntity, EmailSentResultEnum code) { - if (challengeEntity != null) { - challengeEntity.setLastEmailSentDateTime(currentDate(BASIC_DATE_TIME_PATTERN)); - challengeEntity.setLastEmailSentResultCode(code.getValue()); - challengeRepository.save(challengeEntity); + private void bindEmailTemplateVariables(EmailContent emailContent, ChallengeDto challengeDto, ChallengeRegistrantEntity registrant) { + String subject = emailContent.getSubject(); + String body = emailContent.getContent(); + // Process email subject + subject = processEmailVariables(challengeDto, registrant, subject); + // Process email body + body = processEmailVariables(challengeDto, registrant, body); + + emailContent.setSubject(subject); + emailContent.setContent(body); } - } - public Set findRegistrantByChallengeSubmissionDate(Long challengeId, String fromDate, String toDate) { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeSubmission"); - BoolQueryBuilder boolQueryBuilder = boolQuery(); - boolQueryBuilder.must(termQuery("challengeId", challengeId)); + private String processEmailVariables(ChallengeDto challengeDto, ChallengeRegistrantEntity registrant, String replacementCandidate) { + String result = replacementCandidate; + if (StringUtils.isNotEmpty(result)) { + if (result.contains(EmailService.VAR_CONTEST_NAME)) { + result = result.replace(EmailService.VAR_CONTEST_NAME, challengeDto.getChallengeName()); + } + if (result.contains(EmailService.VAR_CONTEST_FIRST_PRIZE)) { + String formatPrize = currencyService.formatCurrency(Double.valueOf(challengeDto.getFirstPlaceReward()), Locale.US); + result = result.replace(EmailService.VAR_CONTEST_FIRST_PRIZE, formatPrize); + } + if (result.contains(EmailService.VAR_CONTESTANT_FIRST_NAME)) { + result = result.replace(EmailService.VAR_CONTESTANT_FIRST_NAME, registrant.getRegistrantFirstName()); + } + if (result.contains(EmailService.VAR_MAIL_SIGNATURE)) { + EmailSettingDto emailSettingDto = employerService.findEmployerEmailSetting(challengeDto.getAuthorEmail()); + result = result.replace(EmailService.VAR_MAIL_SIGNATURE, emailSettingDto.getEmailSignature()); + } + } + return result; + } - RangeQueryBuilder submissionDateQuery = QueryBuilders.rangeQuery("submissionDateTime"); - if (StringUtils.isNotEmpty(fromDate) || StringUtils.isNotEmpty(toDate)) { - if (StringUtils.isNotEmpty(fromDate)) { - submissionDateQuery.from(fromDate); - } + public boolean sendEmailToRegistrant(String challengeOwner, Long challengeId, Long registrantId, EmailContent emailContent) { + if (isOwnerOfChallenge(challengeOwner, challengeId)) { + ChallengeRegistrantEntity registrant = challengeRegistrantRepository.findOne(registrantId); + String csvEmails = registrant.getRegistrantEmail(); + try { + emailContent.setRecipients(InternetAddress.parse(csvEmails)); + } catch (AddressException e) { + LOGGER.debug("Can not parse email address", e); + return false; + } + } + return emailService.sendEmail(emailContent); + } - if (StringUtils.isNotEmpty(toDate)) { - submissionDateQuery.to(toDate); - } + @Override + public List findChallengeSubmissionByRegistrant(Long challengeId, Long registrantId) { + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeSubmission"); + BoolFilterBuilder boolFilterBuilder = new BoolFilterBuilder(); + boolFilterBuilder.must(termFilter("challengeId", challengeId)); + boolFilterBuilder.must(termFilter("registrantId", registrantId)); - boolQueryBuilder.must(submissionDateQuery); + searchQueryBuilder.withQuery(filteredQuery(matchAllQuery(), boolFilterBuilder)); + List submissions = DataUtils.getAllEntities(challengeSubmissionRepository, searchQueryBuilder); + return submissions.stream().map(submission -> dozerMapper.map(submission, ChallengeSubmissionDto.class)).collect(toList()); } - searchQueryBuilder.withQuery(boolQueryBuilder); - List submissions = DataUtils.getAllEntities(challengeSubmissionRepository, searchQueryBuilder); - return submissions.stream().map(submission -> submission.getRegistrantId()).collect(toSet()); - } - - public ChallengeDetailDto getChallengeDetail(Long challengeId, String loginEmail) { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challenge"); - TermQueryBuilder challengeIdQuery = termQuery("challengeId", challengeId); - //MatchQueryBuilder authorEmailQuery = matchQuery("authorEmail", loginEmail).minimumShouldMatch("100%"); - TermQueryBuilder expiredChallengeQuery = termQuery("expired", Boolean.TRUE); - - searchQueryBuilder.withQuery(boolQuery().must(challengeIdQuery).mustNot(expiredChallengeQuery)); - List challengeEntities = DataUtils.getAllEntities(challengeRepository, searchQueryBuilder); - - if (!challengeEntities.isEmpty()) { - ChallengeEntity challengeEntity = challengeEntities.get(0); - ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); - challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeId)); - calculateChallengePhases(challengeDetailDto); -// challengeDetailDto.setCurrentPhase(getChallengeCurrentPhase(challengeEntity)); -// challengeDetailDto.setNextPhase(getChallengeNextPhase(challengeEntity)); - calculateChallengePhases(challengeDetailDto); - boolean isAuthor = challengeEntity.getAuthorEmail().equals(loginEmail); - challengeDetailDto.setIsAuthor(isAuthor); - if (!isAuthor) { - challengeDetailDto.setCriteria(null); - } - return challengeDetailDto; + @Override + public void updateSendEmailToContestantResultCode(ChallengeRegistrantEntity challengeRegistrantEntity, EmailSentResultEnum code) { + if (challengeRegistrantEntity != null) { + challengeRegistrantEntity.setLastEmailSentDateTime(currentDate(BASIC_DATE_TIME_PATTERN)); + challengeRegistrantEntity.setLastEmailSentResultCode(code.getValue()); + challengeRegistrantRepository.save(challengeRegistrantEntity); + } } - return null; - } - - public void calculateChallengePhases(ChallengeDetailDto challengeDetailDto) { - String now = DateTimeUtils.currentDate(); - - String timeline[] = { - challengeDetailDto.getSubmissionDateTime(), - challengeDetailDto.getPrototypeSubmissionDateTime(), - challengeDetailDto.getUxSubmissionDateTime(), - challengeDetailDto.getIdeaSubmissionDateTime(), - challengeDetailDto.getRegistrationDateTime() - }; - int currentIndex = -1; - int nextIndex = -1; - for (int i = 0; i < timeline.length; ++i) { - try { - String milestone = timeline[i]; - if (DateTimeUtils.daysBetween(now, milestone) >= 0) { - nextIndex = currentIndex; - currentIndex = i; + public void updateSendEmailToChallengeOwnerResultCode(ChallengeEntity challengeEntity, EmailSentResultEnum code) { + if (challengeEntity != null) { + challengeEntity.setLastEmailSentDateTime(currentDate(BASIC_DATE_TIME_PATTERN)); + challengeEntity.setLastEmailSentResultCode(code.getValue()); + challengeRepository.save(challengeEntity); } - } - catch (Exception e) { - continue; - } } - if (currentIndex == -1) {//FINAL - challengeDetailDto.setCurrentPhase(ChallengePhaseEnum.FINAL); - challengeDetailDto.setNextPhase(ChallengePhaseEnum.FINAL); + public Set findRegistrantByChallengeSubmissionDate(Long challengeId, String fromDate, String toDate) { + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeSubmission"); + BoolQueryBuilder boolQueryBuilder = boolQuery(); + boolQueryBuilder.must(termQuery("challengeId", challengeId)); + + RangeQueryBuilder submissionDateQuery = QueryBuilders.rangeQuery("submissionDateTime"); + if (StringUtils.isNotEmpty(fromDate) || StringUtils.isNotEmpty(toDate)) { + if (StringUtils.isNotEmpty(fromDate)) { + submissionDateQuery.from(fromDate); + } + + if (StringUtils.isNotEmpty(toDate)) { + submissionDateQuery.to(toDate); + } + + boolQueryBuilder.must(submissionDateQuery); + } + + searchQueryBuilder.withQuery(boolQueryBuilder); + List submissions = DataUtils.getAllEntities(challengeSubmissionRepository, searchQueryBuilder); + return submissions.stream().map(submission -> submission.getRegistrantId()).collect(toSet()); } - else { - challengeDetailDto.setCurrentPhase(CHALLENGE_TIMELINE[currentIndex]); - challengeDetailDto.setNextPhase(CHALLENGE_TIMELINE[nextIndex > -1 ? nextIndex : currentIndex]); + + public ChallengeDetailDto getChallengeDetail(Long challengeId, String loginEmail) { + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challenge"); + TermQueryBuilder challengeIdQuery = termQuery("challengeId", challengeId); + //MatchQueryBuilder authorEmailQuery = matchQuery("authorEmail", loginEmail).minimumShouldMatch("100%"); + TermQueryBuilder expiredChallengeQuery = termQuery("expired", Boolean.TRUE); + + searchQueryBuilder.withQuery(boolQuery().must(challengeIdQuery).mustNot(expiredChallengeQuery)); + List challengeEntities = DataUtils.getAllEntities(challengeRepository, searchQueryBuilder); + + if (!challengeEntities.isEmpty()) { + ChallengeEntity challengeEntity = challengeEntities.get(0); + ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); + challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeId)); + calculateChallengePhases(challengeDetailDto); +// challengeDetailDto.setCurrentPhase(getChallengeCurrentPhase(challengeEntity)); +// challengeDetailDto.setNextPhase(getChallengeNextPhase(challengeEntity)); + calculateChallengePhases(challengeDetailDto); + boolean isAuthor = challengeEntity.getAuthorEmail().equals(loginEmail); + challengeDetailDto.setIsAuthor(isAuthor); + if (!isAuthor) { + challengeDetailDto.setCriteria(null); + } + return challengeDetailDto; + } + return null; + } + + public void calculateChallengePhases(ChallengeDetailDto challengeDetailDto) { + String now = DateTimeUtils.currentDate(); + + String timeline[] = { + challengeDetailDto.getSubmissionDateTime(), + challengeDetailDto.getPrototypeSubmissionDateTime(), + challengeDetailDto.getUxSubmissionDateTime(), + challengeDetailDto.getIdeaSubmissionDateTime(), + challengeDetailDto.getRegistrationDateTime() + }; + + int currentIndex = -1; + int nextIndex = -1; + for (int i = 0; i < timeline.length; ++i) { + try { + String milestone = timeline[i]; + if (DateTimeUtils.daysBetween(now, milestone) >= 0) { + nextIndex = currentIndex; + currentIndex = i; + } + } catch (Exception e) { + continue; + } + } + + if (currentIndex == -1) {//FINAL + challengeDetailDto.setCurrentPhase(ChallengePhaseEnum.FINAL); + challengeDetailDto.setNextPhase(ChallengePhaseEnum.FINAL); + } else { + challengeDetailDto.setCurrentPhase(CHALLENGE_TIMELINE[currentIndex]); + challengeDetailDto.setNextPhase(CHALLENGE_TIMELINE[nextIndex > -1 ? nextIndex : currentIndex]); + } } - } // public static void main(String[] args) { // ChallengeDetailDto challengeDetailDto = new ChallengeDetailDto(); @@ -972,27 +1004,27 @@ public void calculateChallengePhases(ChallengeDetailDto challengeDetailDto) { //// System.out.println(challengeDetailDto.getNextPhase()); // } - public ChallengeRegistrantDto acceptRegistrant(String ownerEmail, Long registrantId) { - ChallengeRegistrantEntity registrant = challengeRegistrantRepository.findOne(registrantId); - if (registrant == null) { - return null; - } + public ChallengeRegistrantDto acceptRegistrant(String ownerEmail, Long registrantId) { + ChallengeRegistrantEntity registrant = challengeRegistrantRepository.findOne(registrantId); + if (registrant == null) { + return null; + } - ChallengeEntity challenge = challengeRepository.findOne(registrant.getChallengeId()); - if (!ownerEmail.equalsIgnoreCase(challenge.getAuthorEmail())) { - return null; - } + ChallengeEntity challenge = challengeRepository.findOne(registrant.getChallengeId()); + if (!ownerEmail.equalsIgnoreCase(challenge.getAuthorEmail())) { + return null; + } - ChallengeDetailDto challengeDetailDto = dozerMapper.map(challenge, ChallengeDetailDto.class); - calculateChallengePhases(challengeDetailDto); - ChallengePhaseEnum activePhase = challengeDetailDto.getNextPhase(); - if (activePhase != registrant.getActivePhase()) { - registrant.setActivePhase(activePhase); - registrant = challengeRegistrantRepository.save(registrant); - } + ChallengeDetailDto challengeDetailDto = dozerMapper.map(challenge, ChallengeDetailDto.class); + calculateChallengePhases(challengeDetailDto); + ChallengePhaseEnum activePhase = challengeDetailDto.getNextPhase(); + if (activePhase != registrant.getActivePhase()) { + registrant.setActivePhase(activePhase); + registrant = challengeRegistrantRepository.save(registrant); + } - return dozerMapper.map(registrant, ChallengeRegistrantDto.class); - } + return dozerMapper.map(registrant, ChallengeRegistrantDto.class); + } // private ChallengePhaseEnum getChallengeNextPhase(ChallengeEntity challengeEntity) { // int nextMilestoneIndex = getChallengeCurrentPhaseIndex(challengeEntity); diff --git a/src/main/java/com/techlooper/service/impl/CurrencyServiceImpl.java b/src/main/java/com/techlooper/service/impl/CurrencyServiceImpl.java index f0c7a578d..9b639930f 100644 --- a/src/main/java/com/techlooper/service/impl/CurrencyServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/CurrencyServiceImpl.java @@ -1,13 +1,13 @@ package com.techlooper.service.impl; import com.techlooper.service.CurrencyService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; -import org.springframework.web.client.RestTemplate; -import javax.annotation.Resource; +import java.text.DecimalFormat; +import java.text.NumberFormat; +import java.util.Currency; +import java.util.Locale; /** * Created by phuonghqh on 5/28/15. @@ -15,31 +15,18 @@ @Service public class CurrencyServiceImpl implements CurrencyService { - private final static Logger LOGGER = LoggerFactory.getLogger(CurrencyServiceImpl.class); + @Value("${usd2vnd}") + private Long usd2vnd; - @Resource - private RestTemplate restTemplate; + public Long usdToVndRate() { + return usd2vnd; + } - @Value("${api.exchangeRateUrl}") - private String apiExchangeRateUrl; - - @Value("${usd2vnd}") - private Long usd2vnd; - - public Long usdToVndRate() { -// String url = String.format(apiExchangeRateUrl, "USD", "VND"); - Long result = usd2vnd; -// try { -// String rate = restTemplate.getForEntity(url, String.class).getBody(); -// Scanner scanner = new Scanner(rate); -// while (!scanner.hasNextDouble()) { -// scanner.next(); -// } -// result = Double.valueOf(scanner.nextDouble()).longValue(); -// } -// catch (Exception e) { -// LOGGER.error("Failed load currency from api {}", url); -// } - return result; - } + public String formatCurrency(Double value, Locale currentLocale) { + NumberFormat numberFormatter = NumberFormat.getNumberInstance(currentLocale); + DecimalFormat decimalFormatter = (DecimalFormat) numberFormatter; + String fullPattern = Currency.getInstance(currentLocale).getSymbol() + "###,###"; + decimalFormatter.applyPattern(fullPattern); + return decimalFormatter.format(value); + } } \ No newline at end of file diff --git a/src/main/webapp/assets/modules/common/resourcesService.js b/src/main/webapp/assets/modules/common/resourcesService.js index 7550a109c..a8bf2411d 100644 --- a/src/main/webapp/assets/modules/common/resourcesService.js +++ b/src/main/webapp/assets/modules/common/resourcesService.js @@ -25,7 +25,10 @@ techlooper.factory("resourcesService", function ($translate, $q, apiService) { ]; var emailTemplateOptions = [ - {translate: "welcomeContestant", id: 1} + {translate: "chooseATemplate", id: 0}, + {translate: "welcomeContestant", id: 1}, + {translate: "askContestantSubmission", id: 2}, + {translate: "disqualifyContestant", id: 3} ]; //apiService.getAvailableEmailTemplates() From acd5927908b5d49dc77f90f9012bdd65a4df099f Mon Sep 17 00:00:00 2001 From: johnsonpham Date: Wed, 21 Oct 2015 18:00:06 +0700 Subject: [PATCH 69/80] validation for email onblur --- .../assets/modules/email-setting/email-setting.html | 11 +++++++++-- .../assets/modules/email-setting/emailSetting.js | 5 ++--- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/src/main/webapp/assets/modules/email-setting/email-setting.html b/src/main/webapp/assets/modules/email-setting/email-setting.html index 1d623cd68..18c48f273 100644 --- a/src/main/webapp/assets/modules/email-setting/email-setting.html +++ b/src/main/webapp/assets/modules/email-setting/email-setting.html @@ -13,8 +13,15 @@

    - -
    {{error.replyEmail}}
    + +
    +
    diff --git a/src/main/webapp/assets/modules/email-setting/emailSetting.js b/src/main/webapp/assets/modules/email-setting/emailSetting.js index 6421737fc..0ba83119d 100644 --- a/src/main/webapp/assets/modules/email-setting/emailSetting.js +++ b/src/main/webapp/assets/modules/email-setting/emailSetting.js @@ -19,9 +19,8 @@ techlooper.controller("emailSetting", function ($scope, utils, jsonValue, apiSer $scope.saveEmailSetting = function () { $scope.saved = false; $scope.fail = false; - var error = validatorService.validate($(".email-setting-form").find('input')); - $scope.error = error; - if (!$.isEmptyObject(error)) { + $scope.emailSetting.$setSubmitted(); + if($scope.emailSetting.$invalid) { return; } utils.sendNotification(jsonValue.notifications.switchScope); From 5f53eb8601eb78b5556f46b4c057486dfc443846 Mon Sep 17 00:00:00 2001 From: Phuong H Date: Wed, 21 Oct 2015 18:02:32 +0700 Subject: [PATCH 70/80] Fix error of UI --- .../modules/common/model/challengeDetail.js | 11 ++--- .../contest-detail/contestDetailController.js | 10 ++-- .../contest-detail/contestDetailDirective.js | 46 ++++++++----------- .../contestDetailScoreDirective.js | 11 ++--- .../contest-detail/evaluationCriteria.html | 27 +++++------ 5 files changed, 45 insertions(+), 60 deletions(-) diff --git a/src/main/webapp/assets/modules/common/model/challengeDetail.js b/src/main/webapp/assets/modules/common/model/challengeDetail.js index dae0d1b9b..d8b7241d8 100644 --- a/src/main/webapp/assets/modules/common/model/challengeDetail.js +++ b/src/main/webapp/assets/modules/common/model/challengeDetail.js @@ -31,12 +31,8 @@ techlooper.filter("challengeDetail", function (apiService, $rootScope, utils) { challengeDetail.criteria = _.reject(challengeDetail.criteria, function (criteria) {return criteria.criteriaId == cri.criteriaId;}) } - //TODO this function invoked 15 times in first load, then many times when change criteria - challengeDetail.totalWeight = function() { - //console.log(arguments); + challengeDetail.caculateTotalWeight = function() { var total = _.reduceRight(challengeDetail.criteria, function(sum, cri) { return sum + cri.weight; }, 0); - //console.log(total); - //challengeDetail.$invalid = (total == 100); return total; } @@ -45,11 +41,14 @@ techlooper.filter("challengeDetail", function (apiService, $rootScope, utils) { if (!criteria) return []; challengeDetail.totalWeight = 0; return criteria.map(function (cri) { - challengeDetail.totalWeight += parseInt(cri.weight); + var weight = _.isNumber(cri.weight) ? cri.weight : 0; + challengeDetail.totalWeight += weight; return cri; }); }; + challengeDetail.totalWeight = _.reduceRight(challengeDetail.criteria, function(sum, cri) { return sum + cri.weight; }, 0); + challengeDetail.$isRich = true; return challengeDetail; } diff --git a/src/main/webapp/assets/modules/contest-detail/contestDetailController.js b/src/main/webapp/assets/modules/contest-detail/contestDetailController.js index b526d0802..c0dc229d1 100644 --- a/src/main/webapp/assets/modules/contest-detail/contestDetailController.js +++ b/src/main/webapp/assets/modules/contest-detail/contestDetailController.js @@ -233,14 +233,14 @@ techlooper.controller('contestDetailController', function ($scope, apiService, l format: 'dd/mm/yyyy' }); - //TODO check valid before save $scope.saveChallengeCriteria = function() { - if($scope.contestDetail.totalWeight() > 100){ - return false; - } - if($scope.criteriaInvalid == false){ + if($scope.contestDetail.totalWeight > 100){ return false; } + + //if($scope.criteriaInvalid == false){ + // return false; + //} $scope.contestDetail.saveCriteria(); } }); diff --git a/src/main/webapp/assets/modules/contest-detail/contestDetailDirective.js b/src/main/webapp/assets/modules/contest-detail/contestDetailDirective.js index b0ce1bc11..2a54eebab 100644 --- a/src/main/webapp/assets/modules/contest-detail/contestDetailDirective.js +++ b/src/main/webapp/assets/modules/contest-detail/contestDetailDirective.js @@ -58,13 +58,13 @@ techlooper scope.registrant.disqualify = function () { scope.registrant.disqualified = true; apiService.saveChallengeRegistrant(scope.registrant) - .success(function(rt) { + .success(function (rt) { scope.registrant.disqualifiedReason = rt.disqualifiedReason; }); delete scope.registrant.visible; }; - scope.registrant.score = function() { + scope.registrant.score = function () { //apiService.acceptChallengeRegistrant(scope.registrant.registrantId) // .success(function(registrant) { // scope.registrant.activePhase = registrant.activePhase; @@ -72,14 +72,14 @@ techlooper delete scope.registrant.visible; }; - scope.registrant.hide = function() { + scope.registrant.hide = function () { if (!scope.registrant.visible) return; delete scope.registrant.visible; }; - scope.registrant.accept = function() { + scope.registrant.accept = function () { apiService.acceptChallengeRegistrant(scope.registrant.registrantId) - .success(function(registrant) { + .success(function (registrant) { scope.registrant.activePhase = registrant.activePhase; }); delete scope.registrant.visible; @@ -91,7 +91,7 @@ techlooper scope.registrant.hide(); }); - scope.$on("success-submission-challenge", function(sc, submission) { + scope.$on("success-submission-challenge", function (sc, submission) { if (scope.registrant.registrantId != submission.registrantId) return; scope.registrant.submissions.unshift(submission); console.log(scope.registrant.submissions); @@ -106,9 +106,9 @@ techlooper restrict: "E", replace: true, templateUrl: "modules/contest-detail/contestDetailReviewSubmission.html", - link: function (scope, element, attr, ctrl){ - scope.goToSubmissionLink = function(link){ - var url = (link.indexOf("https://") >= 0 || link.indexOf("http://") >= 0) ? link : "http://"+link; + link: function (scope, element, attr, ctrl) { + scope.goToSubmissionLink = function (link) { + var url = (link.indexOf("https://") >= 0 || link.indexOf("http://") >= 0) ? link : "http://" + link; window.open(url, '_newtab'); } } @@ -132,7 +132,7 @@ techlooper } }; }) - .directive('acceptance', function () { + .directive('acceptance', function () { return { restrict: "E", replace: true, @@ -141,20 +141,12 @@ techlooper } }; }) -.directive('contestDetailScore', function () { - return { - restrict: "E", - replace: true, - templateUrl: "modules/contest-detail/contestDetailScore.html", - link: function (scope, element, attr, ctrl) { - } - }; -}).directive('evaluationCriteria', function () { - return { - restrict: "E", - replace: true, - templateUrl: "modules/contest-detail/evaluationCriteria.html", - link: function (scope, element, attr, ctrl) { - } - }; -}); \ No newline at end of file + .directive('evaluationCriteria', function () { + return { + restrict: "E", + replace: true, + templateUrl: "modules/contest-detail/evaluationCriteria.html", + link: function (scope, element, attr, ctrl) { + } + }; + }); \ No newline at end of file diff --git a/src/main/webapp/assets/modules/contest-detail/contestDetailScoreDirective.js b/src/main/webapp/assets/modules/contest-detail/contestDetailScoreDirective.js index faa08e33d..318057fa3 100644 --- a/src/main/webapp/assets/modules/contest-detail/contestDetailScoreDirective.js +++ b/src/main/webapp/assets/modules/contest-detail/contestDetailScoreDirective.js @@ -3,14 +3,11 @@ techlooper.directive('contestDetailScore', function () { restrict: "E", replace: true, templateUrl: "modules/contest-detail/contestDetailScore.html", - scope: { - registrant: "=" - }, link: function (scope, element, attr, ctrl) { - scope.saveScore = function() { - - scope.registrant.saveCriteria(); - } + //scope.saveScore = function() { + // + // scope.registrant.saveCriteria(); + //} } }; }); \ No newline at end of file diff --git a/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html b/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html index 87aefd64a..978a83639 100644 --- a/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html +++ b/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html @@ -1,10 +1,11 @@

    +

    - +
    @@ -15,14 +16,7 @@
    -
    - - - - - - - +
    @@ -32,14 +26,17 @@
    - - - {{contestDetail.totalWeight() || 0}} -

    -

    + + + {{contestDetail.totalWeight}} + +

    + +

    - +
    From eaaa8531ff603f7651fffc78dbd0e6bb08731bfc Mon Sep 17 00:00:00 2001 From: johnsonpham Date: Wed, 21 Oct 2015 18:05:52 +0700 Subject: [PATCH 71/80] add selectbox for email template --- .../webapp/assets/modules/common/email/popupEmail.html | 8 ++++++++ .../webapp/assets/modules/common/feedback/feedback.html | 1 - 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/main/webapp/assets/modules/common/email/popupEmail.html b/src/main/webapp/assets/modules/common/email/popupEmail.html index db8de88ec..87b650da6 100644 --- a/src/main/webapp/assets/modules/common/email/popupEmail.html +++ b/src/main/webapp/assets/modules/common/email/popupEmail.html @@ -11,6 +11,14 @@
    +
    + +
    + +
    +
    diff --git a/src/main/webapp/assets/modules/common/feedback/feedback.html b/src/main/webapp/assets/modules/common/feedback/feedback.html index 7ad09f11e..c575a790a 100644 --- a/src/main/webapp/assets/modules/common/feedback/feedback.html +++ b/src/main/webapp/assets/modules/common/feedback/feedback.html @@ -36,5 +36,4 @@
    -
    From 4ad113d91b76c1a3f4dff97601909e1d898ac889 Mon Sep 17 00:00:00 2001 From: khoa-nd Date: Wed, 21 Oct 2015 18:13:09 +0700 Subject: [PATCH 72/80] Load email template from Feedback link of daily email challenge --- .../techlooper/service/impl/ChallengeServiceImpl.java | 2 ++ .../assets/modules/common/email/popupEmailDirective.js | 9 ++++++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java index 1044a5390..da98d31db 100644 --- a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java @@ -841,7 +841,9 @@ public boolean sendEmailToRegistrant(String challengeOwner, Long challengeId, Lo if (isOwnerOfChallenge(challengeOwner, challengeId)) { ChallengeRegistrantEntity registrant = challengeRegistrantRepository.findOne(registrantId); String csvEmails = registrant.getRegistrantEmail(); + ChallengeDto challengeDto = findChallengeById(challengeId); try { + bindEmailTemplateVariables(emailContent, challengeDto, registrant); emailContent.setRecipients(InternetAddress.parse(csvEmails)); } catch (AddressException e) { LOGGER.debug("Can not parse email address", e); diff --git a/src/main/webapp/assets/modules/common/email/popupEmailDirective.js b/src/main/webapp/assets/modules/common/email/popupEmailDirective.js index 22bc46f16..73fa6bb4a 100644 --- a/src/main/webapp/assets/modules/common/email/popupEmailDirective.js +++ b/src/main/webapp/assets/modules/common/email/popupEmailDirective.js @@ -1,4 +1,4 @@ -techlooper.directive("popupEmail", function () { +techlooper.directive("popupEmail", function (apiService) { return { restrict: "E", replace: true, @@ -7,6 +7,13 @@ techlooper.directive("popupEmail", function () { composeEmail: "=" }, link: function (scope, element, attr, ctrl) { + scope.loadEmailTemplate = function (templateId) { + apiService.getTemplateById(templateId) + .success(function (template) { + scope.composeEmail.subject = template.subject; + scope.feedbackContent = template.body; + }) + } } } }).controller('feedbackCtrl', function($scope) { From 4ff73a0cfd103b24c4336e2280a0ff11bedbfa23 Mon Sep 17 00:00:00 2001 From: Phuong H Date: Wed, 21 Oct 2015 18:14:07 +0700 Subject: [PATCH 73/80] Able to show registrant score --- .../assets/modules/common/model/challengeRegistrant.js | 7 ++++--- .../assets/modules/contest-detail/contestDetailScore.html | 4 ++-- .../modules/contest-detail/contestDetailScoreDirective.js | 4 ++-- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/main/webapp/assets/modules/common/model/challengeRegistrant.js b/src/main/webapp/assets/modules/common/model/challengeRegistrant.js index 3a31021a5..40024e3d5 100644 --- a/src/main/webapp/assets/modules/common/model/challengeRegistrant.js +++ b/src/main/webapp/assets/modules/common/model/challengeRegistrant.js @@ -1,4 +1,4 @@ -techlooper.filter("challengeRegistrant", function (apiService, $rootScope) { +techlooper.filter("challengeRegistrant", function (apiService, $rootScope, $filter) { return function (input, type) { if (!input || input.$isRich) return input; @@ -9,8 +9,9 @@ techlooper.filter("challengeRegistrant", function (apiService, $rootScope) { if (!criteria) return []; registrant.totalPoint = 0; return criteria.map(function (cri) { - cri.point = cri.weight * cri.score; - registrant.totalPoint += parseInt(cri.point); + cri.point = $filter('number')((cri.weight / 100) * cri.score, 1); + registrant.totalPoint += parseFloat(cri.point); + registrant.totalPoint = $filter('number')(registrant.totalPoint, 1); return cri; }); }; diff --git a/src/main/webapp/assets/modules/contest-detail/contestDetailScore.html b/src/main/webapp/assets/modules/contest-detail/contestDetailScore.html index 26d33b319..08386c574 100644 --- a/src/main/webapp/assets/modules/contest-detail/contestDetailScore.html +++ b/src/main/webapp/assets/modules/contest-detail/contestDetailScore.html @@ -1,6 +1,6 @@
    - +
    • @@ -56,6 +56,6 @@
    - +
    \ No newline at end of file diff --git a/src/main/webapp/assets/modules/contest-detail/contestDetailScoreDirective.js b/src/main/webapp/assets/modules/contest-detail/contestDetailScoreDirective.js index 318057fa3..19af06e52 100644 --- a/src/main/webapp/assets/modules/contest-detail/contestDetailScoreDirective.js +++ b/src/main/webapp/assets/modules/contest-detail/contestDetailScoreDirective.js @@ -4,10 +4,10 @@ techlooper.directive('contestDetailScore', function () { replace: true, templateUrl: "modules/contest-detail/contestDetailScore.html", link: function (scope, element, attr, ctrl) { - //scope.saveScore = function() { + scope.saveScore = function() { // // scope.registrant.saveCriteria(); - //} + } } }; }); \ No newline at end of file From 9d6e6573fe86ae03a22cb057091431bd22bf6cbc Mon Sep 17 00:00:00 2001 From: Phuong H Date: Wed, 21 Oct 2015 18:22:33 +0700 Subject: [PATCH 74/80] Able to save challenge registrant score --- .../assets/modules/common/model/challengeRegistrant.js | 9 +++++++++ .../contest-detail/contestDetailScoreDirective.js | 8 ++++++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src/main/webapp/assets/modules/common/model/challengeRegistrant.js b/src/main/webapp/assets/modules/common/model/challengeRegistrant.js index 40024e3d5..92399ef55 100644 --- a/src/main/webapp/assets/modules/common/model/challengeRegistrant.js +++ b/src/main/webapp/assets/modules/common/model/challengeRegistrant.js @@ -16,6 +16,15 @@ techlooper.filter("challengeRegistrant", function (apiService, $rootScope, $filt }); }; + registrant.validate = function () { + $.each(registrant.criteria, function(i, cri) { + if (parseInt(cri.score) > 100) { + registrant.$invalid = true; + } + return !registrant.$invalid; + }); + } + registrant.saveCriteria = function () { var criteria = { registrantId: registrant.registrantId, diff --git a/src/main/webapp/assets/modules/contest-detail/contestDetailScoreDirective.js b/src/main/webapp/assets/modules/contest-detail/contestDetailScoreDirective.js index 19af06e52..22f25ac0d 100644 --- a/src/main/webapp/assets/modules/contest-detail/contestDetailScoreDirective.js +++ b/src/main/webapp/assets/modules/contest-detail/contestDetailScoreDirective.js @@ -5,8 +5,12 @@ techlooper.directive('contestDetailScore', function () { templateUrl: "modules/contest-detail/contestDetailScore.html", link: function (scope, element, attr, ctrl) { scope.saveScore = function() { - // - // scope.registrant.saveCriteria(); + scope.registrant.validate(); + if (scope.registrant.$invalid) { + return; + } + + scope.registrant.saveCriteria(); } } }; From eeec0949db70671abbc49b8a1d2cb33b98801e09 Mon Sep 17 00:00:00 2001 From: johnsonpham Date: Wed, 21 Oct 2015 18:23:01 +0700 Subject: [PATCH 75/80] update code --- .../contest-detail/evaluationCriteria.html | 6 ++---- src/main/webapp/assets/sass/contest-detail.sass | 15 ++++++++++++++- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html b/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html index 978a83639..36baed438 100644 --- a/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html +++ b/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html @@ -28,11 +28,9 @@
    - {{contestDetail.totalWeight}} + {{contestDetail.totalWeight}} -

    - -

    +

    Date: Wed, 21 Oct 2015 18:30:41 +0700 Subject: [PATCH 76/80] Fix total point not shown --- .../webapp/assets/modules/common/model/challengeRegistrant.js | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/webapp/assets/modules/common/model/challengeRegistrant.js b/src/main/webapp/assets/modules/common/model/challengeRegistrant.js index 92399ef55..77cdb3da1 100644 --- a/src/main/webapp/assets/modules/common/model/challengeRegistrant.js +++ b/src/main/webapp/assets/modules/common/model/challengeRegistrant.js @@ -11,7 +11,6 @@ techlooper.filter("challengeRegistrant", function (apiService, $rootScope, $filt return criteria.map(function (cri) { cri.point = $filter('number')((cri.weight / 100) * cri.score, 1); registrant.totalPoint += parseFloat(cri.point); - registrant.totalPoint = $filter('number')(registrant.totalPoint, 1); return cri; }); }; From 6ee1613a8a8e428bfcb6246cca9d36ebd19ba5a3 Mon Sep 17 00:00:00 2001 From: johnsonpham Date: Wed, 21 Oct 2015 18:34:10 +0700 Subject: [PATCH 77/80] validation for point number of score details --- .../assets/modules/contest-detail/contestDetailScore.html | 2 +- src/main/webapp/assets/sass/main.sass | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/webapp/assets/modules/contest-detail/contestDetailScore.html b/src/main/webapp/assets/modules/contest-detail/contestDetailScore.html index 08386c574..d9a04b3e0 100644 --- a/src/main/webapp/assets/modules/contest-detail/contestDetailScore.html +++ b/src/main/webapp/assets/modules/contest-detail/contestDetailScore.html @@ -29,7 +29,7 @@
    + ng-class="{'input-error': cri.score > 100}" input-number="" maxlength="3"/> =
    diff --git a/src/main/webapp/assets/sass/main.sass b/src/main/webapp/assets/sass/main.sass index 948c4ef7a..0dc57dba9 100644 --- a/src/main/webapp/assets/sass/main.sass +++ b/src/main/webapp/assets/sass/main.sass @@ -51,6 +51,9 @@ input.input-style height: 34px line-height: 34px padding: 0 10px +input.input-error + border: 1px solid red + color: red textarea.textarea-style width: 100% clear: both From 699a91ed65a5daf8142d8e30a5fe49886b760e55 Mon Sep 17 00:00:00 2001 From: Phuong H Date: Wed, 21 Oct 2015 18:43:28 +0700 Subject: [PATCH 78/80] Fix validation of contest detail --- .../assets/modules/common/model/challengeDetail.js | 13 ++++++++++--- .../challengeCriteriaInputDirective.js | 7 +------ .../contest-detail/contestDetailController.js | 5 +---- 3 files changed, 12 insertions(+), 13 deletions(-) diff --git a/src/main/webapp/assets/modules/common/model/challengeDetail.js b/src/main/webapp/assets/modules/common/model/challengeDetail.js index d8b7241d8..2ccef3d7c 100644 --- a/src/main/webapp/assets/modules/common/model/challengeDetail.js +++ b/src/main/webapp/assets/modules/common/model/challengeDetail.js @@ -31,8 +31,8 @@ techlooper.filter("challengeDetail", function (apiService, $rootScope, utils) { challengeDetail.criteria = _.reject(challengeDetail.criteria, function (criteria) {return criteria.criteriaId == cri.criteriaId;}) } - challengeDetail.caculateTotalWeight = function() { - var total = _.reduceRight(challengeDetail.criteria, function(sum, cri) { return sum + cri.weight; }, 0); + challengeDetail.caculateTotalWeight = function () { + var total = _.reduceRight(challengeDetail.criteria, function (sum, cri) { return sum + cri.weight; }, 0); return total; } @@ -47,7 +47,14 @@ techlooper.filter("challengeDetail", function (apiService, $rootScope, utils) { }); }; - challengeDetail.totalWeight = _.reduceRight(challengeDetail.criteria, function(sum, cri) { return sum + cri.weight; }, 0); + challengeDetail.totalWeight = _.reduceRight(challengeDetail.criteria, function (sum, cri) { return sum + cri.weight; }, 0); + + //challengeDetail.validate = function () { + // $.each(challengeDetail.criteria, function (i, cri) { + // challengeDetail.$invalid = (cri.name == ""); + // return !challengeDetail.$invalid; + // }); + //} challengeDetail.$isRich = true; return challengeDetail; diff --git a/src/main/webapp/assets/modules/contest-detail/challengeCriteriaInputDirective.js b/src/main/webapp/assets/modules/contest-detail/challengeCriteriaInputDirective.js index 3506630a5..bd26031d7 100644 --- a/src/main/webapp/assets/modules/contest-detail/challengeCriteriaInputDirective.js +++ b/src/main/webapp/assets/modules/contest-detail/challengeCriteriaInputDirective.js @@ -6,15 +6,10 @@ techlooper.directive('challengeCriteriaInput', function () { scope: { cri: "=", contestDetail: "=" -//======= -// criteriaInvalid: "=" -//>>>>>>> 236c93a615e8bee46fe165a4eb60d57d706cba3f }, link: function (scope, element, attr, ctrl) { scope.criteriaForm.$setSubmitted(); - if(scope.criteriaForm.$invalid) { - scope.criteriaInvalid = false - } + scope.contestDetail.$invalid = scope.criteriaForm.$invalid; } }; }); \ No newline at end of file diff --git a/src/main/webapp/assets/modules/contest-detail/contestDetailController.js b/src/main/webapp/assets/modules/contest-detail/contestDetailController.js index c0dc229d1..c1140ec73 100644 --- a/src/main/webapp/assets/modules/contest-detail/contestDetailController.js +++ b/src/main/webapp/assets/modules/contest-detail/contestDetailController.js @@ -234,13 +234,10 @@ techlooper.controller('contestDetailController', function ($scope, apiService, l }); $scope.saveChallengeCriteria = function() { - if($scope.contestDetail.totalWeight > 100){ + if($scope.contestDetail.totalWeight > 100 || $scope.contestDetail.$invalid){ return false; } - //if($scope.criteriaInvalid == false){ - // return false; - //} $scope.contestDetail.saveCriteria(); } }); From 334dacd15bd94e77ea777d5bffc45f1a6c0783c1 Mon Sep 17 00:00:00 2001 From: Phuong H Date: Wed, 21 Oct 2015 18:59:39 +0700 Subject: [PATCH 79/80] Validation for challenge criteria --- .../assets/modules/common/model/challengeDetail.js | 12 ++++++------ .../contest-detail/challengeCriteriaInput.html | 2 +- .../challengeCriteriaInputDirective.js | 4 ++-- .../contest-detail/contestDetailController.js | 1 + 4 files changed, 10 insertions(+), 9 deletions(-) diff --git a/src/main/webapp/assets/modules/common/model/challengeDetail.js b/src/main/webapp/assets/modules/common/model/challengeDetail.js index 2ccef3d7c..510560378 100644 --- a/src/main/webapp/assets/modules/common/model/challengeDetail.js +++ b/src/main/webapp/assets/modules/common/model/challengeDetail.js @@ -49,12 +49,12 @@ techlooper.filter("challengeDetail", function (apiService, $rootScope, utils) { challengeDetail.totalWeight = _.reduceRight(challengeDetail.criteria, function (sum, cri) { return sum + cri.weight; }, 0); - //challengeDetail.validate = function () { - // $.each(challengeDetail.criteria, function (i, cri) { - // challengeDetail.$invalid = (cri.name == ""); - // return !challengeDetail.$invalid; - // }); - //} + challengeDetail.validate = function () { + $.each(challengeDetail.criteria, function (i, cri) { + challengeDetail.$invalid = (!cri.name); + return !challengeDetail.$invalid; + }); + } challengeDetail.$isRich = true; return challengeDetail; diff --git a/src/main/webapp/assets/modules/contest-detail/challengeCriteriaInput.html b/src/main/webapp/assets/modules/contest-detail/challengeCriteriaInput.html index d549db0c6..8952bb154 100644 --- a/src/main/webapp/assets/modules/contest-detail/challengeCriteriaInput.html +++ b/src/main/webapp/assets/modules/contest-detail/challengeCriteriaInput.html @@ -2,7 +2,7 @@
    diff --git a/src/main/webapp/assets/modules/contest-detail/challengeCriteriaInputDirective.js b/src/main/webapp/assets/modules/contest-detail/challengeCriteriaInputDirective.js index bd26031d7..c62e56df0 100644 --- a/src/main/webapp/assets/modules/contest-detail/challengeCriteriaInputDirective.js +++ b/src/main/webapp/assets/modules/contest-detail/challengeCriteriaInputDirective.js @@ -8,8 +8,8 @@ techlooper.directive('challengeCriteriaInput', function () { contestDetail: "=" }, link: function (scope, element, attr, ctrl) { - scope.criteriaForm.$setSubmitted(); - scope.contestDetail.$invalid = scope.criteriaForm.$invalid; + //scope.criteriaForm.$setSubmitted(); + //scope.contestDetail.$invalid = scope.criteriaForm.$invalid; } }; }); \ No newline at end of file diff --git a/src/main/webapp/assets/modules/contest-detail/contestDetailController.js b/src/main/webapp/assets/modules/contest-detail/contestDetailController.js index c1140ec73..be0d83b40 100644 --- a/src/main/webapp/assets/modules/contest-detail/contestDetailController.js +++ b/src/main/webapp/assets/modules/contest-detail/contestDetailController.js @@ -234,6 +234,7 @@ techlooper.controller('contestDetailController', function ($scope, apiService, l }); $scope.saveChallengeCriteria = function() { + $scope.contestDetail.validate(); if($scope.contestDetail.totalWeight > 100 || $scope.contestDetail.$invalid){ return false; } From 1b01742a31482a33fb923290c2c0a12e07d6cc11 Mon Sep 17 00:00:00 2001 From: Phuong H Date: Wed, 21 Oct 2015 19:02:46 +0700 Subject: [PATCH 80/80] Fix challenge registrant criteria --- src/main/webapp/assets/modules/common/model/challengeDetail.js | 1 + .../webapp/assets/modules/common/model/challengeRegistrant.js | 1 + 2 files changed, 2 insertions(+) diff --git a/src/main/webapp/assets/modules/common/model/challengeDetail.js b/src/main/webapp/assets/modules/common/model/challengeDetail.js index 510560378..3d16392cc 100644 --- a/src/main/webapp/assets/modules/common/model/challengeDetail.js +++ b/src/main/webapp/assets/modules/common/model/challengeDetail.js @@ -50,6 +50,7 @@ techlooper.filter("challengeDetail", function (apiService, $rootScope, utils) { challengeDetail.totalWeight = _.reduceRight(challengeDetail.criteria, function (sum, cri) { return sum + cri.weight; }, 0); challengeDetail.validate = function () { + delete challengeDetail.$invalid; $.each(challengeDetail.criteria, function (i, cri) { challengeDetail.$invalid = (!cri.name); return !challengeDetail.$invalid; diff --git a/src/main/webapp/assets/modules/common/model/challengeRegistrant.js b/src/main/webapp/assets/modules/common/model/challengeRegistrant.js index 77cdb3da1..e00584589 100644 --- a/src/main/webapp/assets/modules/common/model/challengeRegistrant.js +++ b/src/main/webapp/assets/modules/common/model/challengeRegistrant.js @@ -16,6 +16,7 @@ techlooper.filter("challengeRegistrant", function (apiService, $rootScope, $filt }; registrant.validate = function () { + delete registrant.$invalid; $.each(registrant.criteria, function(i, cri) { if (parseInt(cri.score) > 100) { registrant.$invalid = true;