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/config/CouchbaseConfiguration.java b/src/main/java/com/techlooper/config/CouchbaseConfiguration.java index 2d8594010..fec2921cf 100644 --- a/src/main/java/com/techlooper/config/CouchbaseConfiguration.java +++ b/src/main/java/com/techlooper/config/CouchbaseConfiguration.java @@ -1,12 +1,7 @@ package com.techlooper.config; -import com.couchbase.client.CouchbaseClient; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.DependsOn; import org.springframework.core.env.Environment; import org.springframework.data.couchbase.config.AbstractCouchbaseConfiguration; -import org.springframework.data.couchbase.repository.config.EnableCouchbaseRepositories; import javax.annotation.Resource; import java.net.URI; diff --git a/src/main/java/com/techlooper/config/SocialConfiguration.java b/src/main/java/com/techlooper/config/SocialConfiguration.java index 9a467c440..7891992d8 100644 --- a/src/main/java/com/techlooper/config/SocialConfiguration.java +++ b/src/main/java/com/techlooper/config/SocialConfiguration.java @@ -9,7 +9,6 @@ import org.springframework.social.github.connect.GitHubConnectionFactory; import org.springframework.social.google.connect.GoogleConnectionFactory; import org.springframework.social.linkedin.connect.LinkedInConnectionFactory; -import org.springframework.social.twitter.connect.TwitterConnectionFactory; import javax.annotation.Resource; diff --git a/src/main/java/com/techlooper/config/web/WebConfiguration.java b/src/main/java/com/techlooper/config/web/WebConfiguration.java index 0a260c70a..6ae2f7277 100644 --- a/src/main/java/com/techlooper/config/web/WebConfiguration.java +++ b/src/main/java/com/techlooper/config/web/WebConfiguration.java @@ -1,18 +1,12 @@ package com.techlooper.config.web; -import org.apache.commons.lang.ArrayUtils; -import org.springframework.cache.CacheManager; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; import org.springframework.core.env.Environment; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.*; -import org.springframework.web.servlet.resource.CachingResourceResolver; -import org.springframework.web.servlet.resource.CachingResourceTransformer; -import org.springframework.web.servlet.resource.CssLinkResourceTransformer; import org.springframework.web.servlet.resource.GzipResourceResolver; import org.springframework.web.servlet.view.InternalResourceViewResolver; diff --git a/src/main/java/com/techlooper/config/web/sec/SecurityConfiguration.java b/src/main/java/com/techlooper/config/web/sec/SecurityConfiguration.java index ae859d301..3528d22ce 100644 --- a/src/main/java/com/techlooper/config/web/sec/SecurityConfiguration.java +++ b/src/main/java/com/techlooper/config/web/sec/SecurityConfiguration.java @@ -10,13 +10,10 @@ import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; -import org.springframework.security.web.authentication.rememberme.InMemoryTokenRepositoryImpl; -import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository; import javax.servlet.http.HttpServletResponse; import java.util.Arrays; diff --git a/src/main/java/com/techlooper/config/web/sec/SocialAuthenticationProvider.java b/src/main/java/com/techlooper/config/web/sec/SocialAuthenticationProvider.java index faebbc767..bbb5e7d29 100644 --- a/src/main/java/com/techlooper/config/web/sec/SocialAuthenticationProvider.java +++ b/src/main/java/com/techlooper/config/web/sec/SocialAuthenticationProvider.java @@ -7,7 +7,6 @@ import com.techlooper.model.Language; import com.techlooper.model.SocialProvider; import com.techlooper.model.UserProfileDto; -import com.techlooper.repository.JsonConfigRepository; import com.techlooper.service.SocialService; import com.techlooper.service.UserService; import com.techlooper.service.VietnamWorksUserService; 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..f848b413b --- /dev/null +++ b/src/main/java/com/techlooper/controller/ChallengeCriteriaController.java @@ -0,0 +1,47 @@ +package com.techlooper.controller; + +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. + */ +@RestController +public class ChallengeCriteriaController { + + @Resource + private ChallengeCriteriaService challengeCriteriaService; + + @PreAuthorize("hasAuthority('EMPLOYER')") + @RequestMapping(value = "challenge/criteria", method = RequestMethod.POST) + 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/controller/JobAlertController.java b/src/main/java/com/techlooper/controller/JobAlertController.java index 9514fa80b..916060c99 100644 --- a/src/main/java/com/techlooper/controller/JobAlertController.java +++ b/src/main/java/com/techlooper/controller/JobAlertController.java @@ -17,9 +17,7 @@ import javax.annotation.Resource; import javax.servlet.http.HttpServletResponse; -import static com.techlooper.model.JobAlertEmailResultEnum.EMAIL_SENT; -import static com.techlooper.model.JobAlertEmailResultEnum.JOB_NOT_FOUND; -import static com.techlooper.model.JobAlertEmailResultEnum.SERVER_ERROR; +import static com.techlooper.model.JobAlertEmailResultEnum.*; /** * Job alert registration controller diff --git a/src/main/java/com/techlooper/controller/JobSearchController.java b/src/main/java/com/techlooper/controller/JobSearchController.java index 8bfd95a0e..0a2c43b99 100644 --- a/src/main/java/com/techlooper/controller/JobSearchController.java +++ b/src/main/java/com/techlooper/controller/JobSearchController.java @@ -1,10 +1,8 @@ package com.techlooper.controller; import com.techlooper.entity.SalaryReviewEntity; -import com.techlooper.model.JobSearchResponse; import com.techlooper.model.VNWJobSearchRequest; import com.techlooper.model.VNWJobSearchResponse; -import com.techlooper.model.VNWJobSearchResponseDataItem; import com.techlooper.service.JobSearchService; import org.dozer.Mapper; import org.springframework.beans.factory.annotation.Value; @@ -13,8 +11,6 @@ import org.springframework.stereotype.Controller; import javax.annotation.Resource; -import java.util.stream.Collectors; -import java.util.stream.Stream; @Controller public class JobSearchController { diff --git a/src/main/java/com/techlooper/controller/JobStatisticController.java b/src/main/java/com/techlooper/controller/JobStatisticController.java index 0f56a31d7..625b8d6b0 100644 --- a/src/main/java/com/techlooper/controller/JobStatisticController.java +++ b/src/main/java/com/techlooper/controller/JobStatisticController.java @@ -7,7 +7,10 @@ import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.web.bind.annotation.*; +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 java.util.Collections; diff --git a/src/main/java/com/techlooper/controller/SocialController.java b/src/main/java/com/techlooper/controller/SocialController.java index 46564dc47..c3be743db 100644 --- a/src/main/java/com/techlooper/controller/SocialController.java +++ b/src/main/java/com/techlooper/controller/SocialController.java @@ -17,7 +17,6 @@ import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; -import javax.mail.MessagingException; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.net.URLEncoder; diff --git a/src/main/java/com/techlooper/controller/SuggestionController.java b/src/main/java/com/techlooper/controller/SuggestionController.java index e43ceee30..2761eb08c 100644 --- a/src/main/java/com/techlooper/controller/SuggestionController.java +++ b/src/main/java/com/techlooper/controller/SuggestionController.java @@ -3,7 +3,6 @@ import com.techlooper.model.SuggestionItem; import com.techlooper.model.SuggestionResponse; import com.techlooper.service.SuggestionService; -import org.apache.commons.lang3.StringUtils; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @@ -13,7 +12,7 @@ import java.util.List; import java.util.stream.Collectors; -import static org.apache.commons.lang3.StringUtils.*; +import static org.apache.commons.lang3.StringUtils.trim; @RestController public class SuggestionController { diff --git a/src/main/java/com/techlooper/controller/UserController.java b/src/main/java/com/techlooper/controller/UserController.java index 527111c6d..8c29b8193 100644 --- a/src/main/java/com/techlooper/controller/UserController.java +++ b/src/main/java/com/techlooper/controller/UserController.java @@ -1,8 +1,6 @@ package com.techlooper.controller; -import com.techlooper.dto.DashBoardInfo; -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; @@ -42,85 +40,87 @@ @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); + @Resource + private EmailService emailService; - @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); - } + private final static Logger LOGGER = LoggerFactory.getLogger(UserController.class); - @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,271 @@ 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); - } - 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(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); + 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); } - else { - httpServletResponse.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); + + @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); + } } - } - @RequestMapping("promotion/citibank/creditCard") - public void placeCitibankCreditCardPromotion(@Valid @RequestBody CitibankCreditCardPromotion citibankCreditCardPromotion) throws IOException, TemplateException { - promotionService.placePromotion(citibankCreditCardPromotion); - } + @RequestMapping(value = "/priceJob", method = RequestMethod.POST) + public PriceJobEntity priceJob(@RequestBody PriceJobEntity priceJobEntity) { + userEvaluationService.priceJob(priceJobEntity); + return priceJobEntity; + } - @RequestMapping(value = "salaryReview/placeSalaryReviewReport", method = RequestMethod.POST) - public void placeSalaryReviewReport(@Valid @RequestBody EmailRequest emailRequest) throws TemplateException, IOException, MessagingException { - salaryReviewService.sendSalaryReviewReportEmail(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); + } + } - @MessageMapping("/jobs/createJobAlert") - public void createJobAlert(VnwJobAlertRequest vnwJobAlertRequest) { - salaryReviewService.createVnwJobAlert(vnwJobAlertRequest); - } + @RequestMapping("promotion/citibank/creditCard") + public void placeCitibankCreditCardPromotion(@Valid @RequestBody CitibankCreditCardPromotion citibankCreditCardPromotion) throws IOException, TemplateException { + promotionService.placePromotion(citibankCreditCardPromotion); + } - @RequestMapping(value = "/promotion/citibank/title/{lang}", method = RequestMethod.GET) - public String getCitiBankPromotionTitle(@PathVariable String lang) { - return "vn".equalsIgnoreCase(lang) ? citibankTitleVn : citibankTitleEn; - } + @RequestMapping(value = "salaryReview/placeSalaryReviewReport", method = RequestMethod.POST) + public void placeSalaryReviewReport(@Valid @RequestBody EmailRequest emailRequest) throws TemplateException, IOException, MessagingException { + salaryReviewService.sendSalaryReviewReportEmail(emailRequest); + } - @RequestMapping(value = "/getPromoted/email", method = RequestMethod.POST) - public long sendTopDemandedSkillsEmail(@Valid @RequestBody GetPromotedEmailRequest emailRequest) throws MessagingException, IOException, TemplateException { - long getPromotedId = salaryReviewService.saveGetPromotedInformation(emailRequest); + @MessageMapping("/jobs/createJobAlert") + public void createJobAlert(VnwJobAlertRequest vnwJobAlertRequest) { + salaryReviewService.createVnwJobAlert(vnwJobAlertRequest); + } - if (getPromotedId != -1L && emailRequest.getHasResult()) { - salaryReviewService.sendTopDemandedSkillsEmail(getPromotedId, emailRequest); + @RequestMapping(value = "/promotion/citibank/title/{lang}", method = RequestMethod.GET) + public String getCitiBankPromotionTitle(@PathVariable String lang) { + return "vn".equalsIgnoreCase(lang) ? citibankTitleVn : citibankTitleEn; } - return getPromotedId; - } + @RequestMapping(value = "/getPromoted/email", method = RequestMethod.POST) + public long sendTopDemandedSkillsEmail(@Valid @RequestBody GetPromotedEmailRequest emailRequest) throws MessagingException, IOException, TemplateException { + long getPromotedId = salaryReviewService.saveGetPromotedInformation(emailRequest); - @RequestMapping(value = "/getPromoted/survey", method = RequestMethod.POST) - public long saveGetPromotedSurvey(@RequestBody GetPromotedSurveyRequest getPromotedSurveyRequest, HttpServletResponse httpServletResponse) { - return salaryReviewService.saveGetPromotedSurvey(getPromotedSurveyRequest); - } + if (getPromotedId != -1L && emailRequest.getHasResult()) { + salaryReviewService.sendTopDemandedSkillsEmail(getPromotedId, emailRequest); + } - @RequestMapping(value = "/getPromotedResult/{id}", method = RequestMethod.GET) - public GetPromotedEntity getPromotedResult(@PathVariable Long id) { - return salaryReviewService.getPromotedEntity(id); - } + return getPromotedId; + } - @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(value = "/getPromoted/survey", method = RequestMethod.POST) + public long saveGetPromotedSurvey(@RequestBody GetPromotedSurveyRequest getPromotedSurveyRequest, HttpServletResponse httpServletResponse) { + return salaryReviewService.saveGetPromotedSurvey(getPromotedSurveyRequest); } - 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()); - } - - @RequestMapping(value = "/personalHomepage", method = RequestMethod.GET) - public PersonalHomepageDto getPersonalHomepageDto() { - PersonalHomepageDto personalHomepage = new PersonalHomepageDto(); + @RequestMapping(value = "/getPromotedResult/{id}", method = RequestMethod.GET) + public GetPromotedEntity getPromotedResult(@PathVariable Long id) { + return salaryReviewService.getPromotedEntity(id); + } - 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; - } - - @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()); - } - - @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()); - } - 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/accept/{registrantId}", method = RequestMethod.GET) - public ChallengeRegistrantDto acceptChallengeRegistrant(HttpServletRequest request, @PathVariable Long registrantId) { - return challengeService.acceptRegistrant(request.getRemoteUser(), registrantId); - } + @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()); + } + + @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; + } + + @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()); + } + + @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()); + } + 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/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); + } + + @PreAuthorize("hasAnyAuthority('EMPLOYER')") + @RequestMapping(value = "/user/employer/emailSetting", method = RequestMethod.GET) + public EmailSettingDto findEmployerEmailSetting(HttpServletRequest request) { + return employerService.findEmployerEmailSetting(request.getRemoteUser()); + } + + @RequestMapping(value = "/emailTemplates", method = RequestMethod.GET) + 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/DashBoardInfo.java b/src/main/java/com/techlooper/dto/DashBoardInfo.java index 84c822f82..4e8c21049 100644 --- a/src/main/java/com/techlooper/dto/DashBoardInfo.java +++ b/src/main/java/com/techlooper/dto/DashBoardInfo.java @@ -11,49 +11,49 @@ */ public class DashBoardInfo implements Serializable { - Collection challenges; + private Collection challenges; - Collection projects; + private Collection projects; - public Collection getChallenges() { - return challenges; - } + public Collection getChallenges() { + return challenges; + } - public void setChallenges(Collection challenges) { - this.challenges = challenges; - } + public void setChallenges(Collection challenges) { + this.challenges = challenges; + } - public Collection getProjects() { - return projects; - } + public Collection getProjects() { + return projects; + } - public void setProjects(Collection projects) { - this.projects = projects; - } + public void setProjects(Collection projects) { + this.projects = projects; + } - public static class DashBoardInfoBuilder { - private DashBoardInfo dashBoardInfo; + public static class DashBoardInfoBuilder { + private DashBoardInfo dashBoardInfo; - private DashBoardInfoBuilder() { - dashBoardInfo = new DashBoardInfo(); - } + private DashBoardInfoBuilder() { + dashBoardInfo = new DashBoardInfo(); + } - public DashBoardInfoBuilder withChallenges(Collection challenges) { - dashBoardInfo.challenges = challenges; - return this; - } + public DashBoardInfoBuilder withChallenges(Collection challenges) { + dashBoardInfo.challenges = challenges; + return this; + } - public DashBoardInfoBuilder withProjects(Collection projects) { - dashBoardInfo.projects = projects; - return this; - } + public DashBoardInfoBuilder withProjects(Collection projects) { + dashBoardInfo.projects = projects; + return this; + } - public static DashBoardInfoBuilder dashBoardInfo() { - return new DashBoardInfoBuilder(); - } + public static DashBoardInfoBuilder dashBoardInfo() { + return new DashBoardInfoBuilder(); + } - public DashBoardInfo build() { - return dashBoardInfo; + public DashBoardInfo build() { + return dashBoardInfo; + } } - } } 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/dto/EmailTemplateDto.java b/src/main/java/com/techlooper/dto/EmailTemplateDto.java new file mode 100644 index 000000000..cfc724eae --- /dev/null +++ b/src/main/java/com/techlooper/dto/EmailTemplateDto.java @@ -0,0 +1,44 @@ +package com.techlooper.dto; + +public class EmailTemplateDto { + + private Long templateId; + + private String templateName; + + private String subject; + + private String body; + + 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 String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } +} 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..51a731a42 --- /dev/null +++ b/src/main/java/com/techlooper/entity/ChallengeCriteria.java @@ -0,0 +1,91 @@ +package com.techlooper.entity; + +import com.techlooper.util.DataUtils; +import org.springframework.data.elasticsearch.annotations.Field; +import org.springframework.data.elasticsearch.annotations.FieldIndex; + +import java.io.Serializable; + +import static org.springframework.data.elasticsearch.annotations.FieldType.String; + +/** + * Created by phuonghqh on 10/16/15. + */ +public class ChallengeCriteria implements Serializable { + + @Field(type = String, index = FieldIndex.not_analyzed) + private String criteriaId = DataUtils.generateStringId(); + + private String name; + + private Long weight; + + public java.lang.String getCriteriaId() { + return criteriaId; + } + + public void setCriteriaId(java.lang.String criteriaId) { + this.criteriaId = criteriaId; + } + + 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; + } + + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + ChallengeCriteria that = (ChallengeCriteria) o; + + return !(criteriaId != null ? !criteriaId.equals(that.criteriaId) : that.criteriaId != null); + + } + + public int hashCode() { + return criteriaId != null ? criteriaId.hashCode() : 0; + } + + public static class ChallengeCriteriaBuilder { + private ChallengeCriteria challengeCriteria; + + private ChallengeCriteriaBuilder() { + challengeCriteria = new ChallengeCriteria(); + } + + public ChallengeCriteriaBuilder withCriteriaId(String criteriaId) { + challengeCriteria.criteriaId = criteriaId; + return this; + } + + 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/entity/ChallengeEntity.java b/src/main/java/com/techlooper/entity/ChallengeEntity.java index 3f7d409ed..5c7aeb810 100644 --- a/src/main/java/com/techlooper/entity/ChallengeEntity.java +++ b/src/main/java/com/techlooper/entity/ChallengeEntity.java @@ -7,7 +7,9 @@ import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; +import java.util.HashSet; 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,278 +21,290 @@ @Document(indexName = "techlooper", type = "challenge") public class ChallengeEntity { - @Id - private Long challengeId; + @Id + private Long challengeId; - @Field(type = String) - private String challengeName; + @Field(type = FieldType.Nested) + private Set criteria; - @Field(type = String) - private String challengeOverview; + @Field(type = String) + private String challengeName; - @Field(type = String) - private String businessRequirement; + @Field(type = String) + private String challengeOverview; - @Field(type = String) - private String generalNote; + @Field(type = String) + private String businessRequirement; - @Field(type = String) - private List technologies; + @Field(type = String) + private String generalNote; - @Field(type = String) - private String documents; + @Field(type = String) + private List technologies; - @Field(type = String) - private String deliverables; + @Field(type = String) + private String documents; - @Field(type = String) - private List receivedEmails; + @Field(type = String) + private String deliverables; - @Field(type = String) - private String reviewStyle; + @Field(type = String) + private List receivedEmails; - @Field(type = FieldType.Date, format = DateFormat.custom, pattern = "dd/MM/yyyy") - private String startDateTime; + @Field(type = String) + private String reviewStyle; - @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 startDateTime; - @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 registrationDateTime; - @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 ideaSubmissionDateTime; - @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 uxSubmissionDateTime; - @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 prototypeSubmissionDateTime; - @Field(type = FieldType.Integer) - private Integer firstPlaceReward; + @Field(type = FieldType.Date, format = DateFormat.custom, pattern = "dd/MM/yyyy") + private String submissionDateTime; - @Field(type = FieldType.Integer) - private Integer secondPlaceReward; + @Field(type = FieldType.Integer) + private Integer firstPlaceReward; - @Field(type = FieldType.Integer) - private Integer thirdPlaceReward; + @Field(type = FieldType.Integer) + private Integer secondPlaceReward; - @Field(type = String) - private String qualityIdea; + @Field(type = FieldType.Integer) + private Integer thirdPlaceReward; - @Field(type = String) - private String authorEmail; + @Field(type = String) + private String qualityIdea; - @Field(type = String) - private Language lang; + @Field(type = String) + private String authorEmail; - @Field(type = Boolean) - private Boolean expired; + @Field(type = String) + private Language lang; - @Field(type = FieldType.Date, format = DateFormat.custom, pattern = "dd/MM/yyyy HH:mm") - private String lastEmailSentDateTime; + @Field(type = Boolean) + private Boolean expired; - @Field(type = Integer) - private int lastEmailSentResultCode; + @Field(type = FieldType.Date, format = DateFormat.custom, pattern = "dd/MM/yyyy HH:mm") + private String lastEmailSentDateTime; - public Boolean getExpired() { - return expired; - } + @Field(type = Integer) + private int lastEmailSentResultCode; - public void setExpired(Boolean expired) { - this.expired = expired; - } + public Set getCriteria() { + if (criteria == null) criteria = new HashSet<>(); + return criteria; + } - public Long getChallengeId() { - return challengeId; - } + public void setCriteria(Set criteria) { + this.criteria = criteria; + } - public void setChallengeId(Long challengeId) { - this.challengeId = challengeId; - } + public Boolean getExpired() { + return expired; + } - public String getChallengeName() { - return challengeName; - } + public void setExpired(Boolean expired) { + this.expired = expired; + } - public void setChallengeName(String challengeName) { - this.challengeName = challengeName; - } + public Long getChallengeId() { + return challengeId; + } - public String getBusinessRequirement() { - return businessRequirement; - } + public void setChallengeId(Long challengeId) { + this.challengeId = challengeId; + } - public void setBusinessRequirement(String businessRequirement) { - this.businessRequirement = businessRequirement; - } + public String getChallengeName() { + return challengeName; + } - public String getGeneralNote() { - return generalNote; - } + public void setChallengeName(String challengeName) { + this.challengeName = challengeName; + } - public void setGeneralNote(String generalNote) { - this.generalNote = generalNote; - } + public String getBusinessRequirement() { + return businessRequirement; + } - public List getTechnologies() { - return technologies; - } + public void setBusinessRequirement(String businessRequirement) { + this.businessRequirement = businessRequirement; + } - public void setTechnologies(List technologies) { - this.technologies = technologies; - } + public String getGeneralNote() { + return generalNote; + } - public String getDocuments() { - return documents; - } + public void setGeneralNote(String generalNote) { + this.generalNote = generalNote; + } - public void setDocuments(String documents) { - this.documents = documents; - } + public List getTechnologies() { + return technologies; + } - public String getDeliverables() { - return deliverables; - } + public void setTechnologies(List technologies) { + this.technologies = technologies; + } - public void setDeliverables(String deliverables) { - this.deliverables = deliverables; - } + public String getDocuments() { + return documents; + } - public List getReceivedEmails() { - return receivedEmails; - } + public void setDocuments(String documents) { + this.documents = documents; + } - public void setReceivedEmails(List receivedEmails) { - this.receivedEmails = receivedEmails; - } + public String getDeliverables() { + return deliverables; + } - public String getReviewStyle() { - return reviewStyle; - } + public void setDeliverables(String deliverables) { + this.deliverables = deliverables; + } - public void setReviewStyle(String reviewStyle) { - this.reviewStyle = reviewStyle; - } + public List getReceivedEmails() { + return receivedEmails; + } - public String getStartDateTime() { - return startDateTime; - } + public void setReceivedEmails(List receivedEmails) { + this.receivedEmails = receivedEmails; + } - public void setStartDateTime(String startDateTime) { - this.startDateTime = startDateTime; - } + public String getReviewStyle() { + return reviewStyle; + } - public String getRegistrationDateTime() { - return registrationDateTime; - } + public void setReviewStyle(String reviewStyle) { + this.reviewStyle = reviewStyle; + } - public void setRegistrationDateTime(String registrationDateTime) { - this.registrationDateTime = registrationDateTime; - } + public String getStartDateTime() { + return startDateTime; + } - public String getIdeaSubmissionDateTime() { - return ideaSubmissionDateTime; - } + public void setStartDateTime(String startDateTime) { + this.startDateTime = startDateTime; + } - public void setIdeaSubmissionDateTime(String ideaSubmissionDateTime) { - this.ideaSubmissionDateTime = ideaSubmissionDateTime; - } + public String getRegistrationDateTime() { + return registrationDateTime; + } - public String getUxSubmissionDateTime() { - return uxSubmissionDateTime; - } + public void setRegistrationDateTime(String registrationDateTime) { + this.registrationDateTime = registrationDateTime; + } - public void setUxSubmissionDateTime(String uxSubmissionDateTime) { - this.uxSubmissionDateTime = uxSubmissionDateTime; - } + public String getIdeaSubmissionDateTime() { + return ideaSubmissionDateTime; + } - public String getPrototypeSubmissionDateTime() { - return prototypeSubmissionDateTime; - } + public void setIdeaSubmissionDateTime(String ideaSubmissionDateTime) { + this.ideaSubmissionDateTime = ideaSubmissionDateTime; + } - public void setPrototypeSubmissionDateTime(String prototypeSubmissionDateTime) { - this.prototypeSubmissionDateTime = prototypeSubmissionDateTime; - } + public String getUxSubmissionDateTime() { + return uxSubmissionDateTime; + } - public String getSubmissionDateTime() { - return submissionDateTime; - } + public void setUxSubmissionDateTime(String uxSubmissionDateTime) { + this.uxSubmissionDateTime = uxSubmissionDateTime; + } - public void setSubmissionDateTime(String submissionDateTime) { - this.submissionDateTime = submissionDateTime; - } + public String getPrototypeSubmissionDateTime() { + return prototypeSubmissionDateTime; + } - public Integer getFirstPlaceReward() { - return firstPlaceReward; - } + public void setPrototypeSubmissionDateTime(String prototypeSubmissionDateTime) { + this.prototypeSubmissionDateTime = prototypeSubmissionDateTime; + } - public void setFirstPlaceReward(Integer firstPlaceReward) { - this.firstPlaceReward = firstPlaceReward; - } + public String getSubmissionDateTime() { + return submissionDateTime; + } - public Integer getSecondPlaceReward() { - return secondPlaceReward; - } + public void setSubmissionDateTime(String submissionDateTime) { + this.submissionDateTime = submissionDateTime; + } - public void setSecondPlaceReward(Integer secondPlaceReward) { - this.secondPlaceReward = secondPlaceReward; - } + public Integer getFirstPlaceReward() { + return firstPlaceReward; + } - public Integer getThirdPlaceReward() { - return thirdPlaceReward; - } + public void setFirstPlaceReward(Integer firstPlaceReward) { + this.firstPlaceReward = firstPlaceReward; + } - public void setThirdPlaceReward(Integer thirdPlaceReward) { - this.thirdPlaceReward = thirdPlaceReward; - } + public Integer getSecondPlaceReward() { + return secondPlaceReward; + } - public String getQualityIdea() { - return qualityIdea; - } + public void setSecondPlaceReward(Integer secondPlaceReward) { + this.secondPlaceReward = secondPlaceReward; + } - public void setQualityIdea(String qualityIdea) { - this.qualityIdea = qualityIdea; - } + public Integer getThirdPlaceReward() { + return thirdPlaceReward; + } - public String getAuthorEmail() { - return authorEmail; - } + public void setThirdPlaceReward(Integer thirdPlaceReward) { + this.thirdPlaceReward = thirdPlaceReward; + } - public void setAuthorEmail(String authorEmail) { - this.authorEmail = authorEmail; - } + public String getQualityIdea() { + return qualityIdea; + } - public Language getLang() { - return lang; - } + public void setQualityIdea(String qualityIdea) { + this.qualityIdea = qualityIdea; + } - public void setLang(Language lang) { - this.lang = lang; - } + public String getAuthorEmail() { + return authorEmail; + } - public String getChallengeOverview() { - return challengeOverview; - } + public void setAuthorEmail(String authorEmail) { + this.authorEmail = authorEmail; + } - public void setChallengeOverview(String challengeOverview) { - this.challengeOverview = challengeOverview; - } + public Language getLang() { + return lang; + } - public String getLastEmailSentDateTime() { - return lastEmailSentDateTime; - } + public void setLang(Language lang) { + this.lang = lang; + } - public void setLastEmailSentDateTime(String lastEmailSentDateTime) { - this.lastEmailSentDateTime = lastEmailSentDateTime; - } + public String getChallengeOverview() { + return challengeOverview; + } - public int getLastEmailSentResultCode() { - return lastEmailSentResultCode; - } + public void setChallengeOverview(String challengeOverview) { + this.challengeOverview = challengeOverview; + } - public void setLastEmailSentResultCode(int lastEmailSentResultCode) { - this.lastEmailSentResultCode = lastEmailSentResultCode; - } + public String getLastEmailSentDateTime() { + return lastEmailSentDateTime; + } + + public void setLastEmailSentDateTime(String lastEmailSentDateTime) { + this.lastEmailSentDateTime = lastEmailSentDateTime; + } + + public int getLastEmailSentResultCode() { + return lastEmailSentResultCode; + } + + public void setLastEmailSentResultCode(int lastEmailSentResultCode) { + this.lastEmailSentResultCode = lastEmailSentResultCode; + } } 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..ca2f3357f --- /dev/null +++ b/src/main/java/com/techlooper/entity/ChallengeRegistrantCriteria.java @@ -0,0 +1,78 @@ +package com.techlooper.entity; + +import org.springframework.data.elasticsearch.annotations.Field; +import org.springframework.data.elasticsearch.annotations.FieldIndex; + +import java.io.Serializable; +import java.util.Collections; +import java.util.HashSet; + +import static org.springframework.data.elasticsearch.annotations.FieldType.String; + +/** + * Created by phuonghqh on 10/19/15. + */ +public class ChallengeRegistrantCriteria implements Serializable { + + @Field(type = String, index = FieldIndex.not_analyzed) + private String criteriaId; + + private String name; + + private Long weight; + + 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; + } + + public void setCriteriaId(java.lang.String criteriaId) { + this.criteriaId = criteriaId; + } + + public java.lang.String getName() { + return name; + } + + public void setName(java.lang.String name) { + this.name = name; + } + + public Long getWeight() { + return weight; + } + + public void setWeight(Long weight) { + this.weight = weight; + } + + public Long getScore() { + return score; + } + + public void setScore(Long score) { + this.score = score; + } + + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + ChallengeRegistrantCriteria that = (ChallengeRegistrantCriteria) o; + return !(criteriaId != null ? !criteriaId.equals(that.criteriaId) : that.criteriaId != null); + } + + public int hashCode() { + return criteriaId != null ? criteriaId.hashCode() : 0; + } +} diff --git a/src/main/java/com/techlooper/entity/ChallengeRegistrantDto.java b/src/main/java/com/techlooper/entity/ChallengeRegistrantDto.java index 7845ccc81..e0d6612e2 100644 --- a/src/main/java/com/techlooper/entity/ChallengeRegistrantDto.java +++ b/src/main/java/com/techlooper/entity/ChallengeRegistrantDto.java @@ -5,6 +5,7 @@ import com.techlooper.model.Language; import java.util.List; +import java.util.Set; /** * Created by NguyenDangKhoa on 7/6/15. @@ -35,6 +36,16 @@ public class ChallengeRegistrantDto { private ChallengePhaseEnum activePhase; + private Set criteria; + + public Set getCriteria() { + return criteria; + } + + public void setCriteria(Set criteria) { + this.criteria = criteria; + } + 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..564a23d6a 100644 --- a/src/main/java/com/techlooper/entity/ChallengeRegistrantEntity.java +++ b/src/main/java/com/techlooper/entity/ChallengeRegistrantEntity.java @@ -5,6 +5,9 @@ import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.*; +import java.util.HashSet; +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,14 +59,16 @@ public class ChallengeRegistrantEntity { @Field(type = String, index = FieldIndex.not_analyzed) private ChallengePhaseEnum activePhase; - public ChallengeRegistrantEntity() { + @Field(type = FieldType.Nested) + private Set criteria; + + public Set getCriteria() { + if (criteria == null) criteria = new HashSet<>(); + return criteria; } - public ChallengeRegistrantEntity(Long registrantId, java.lang.String registrantEmail, java.lang.String registrantFirstName, String registrantLastName) { - this.registrantId = registrantId; - this.registrantEmail = registrantEmail; - this.registrantLastName = registrantLastName; - this.registrantFirstName = registrantFirstName; + public void setCriteria(Set criteria) { + this.criteria = criteria; } public java.lang.String getDisqualifiedReason() { 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/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/entity/EmployerEntity.java b/src/main/java/com/techlooper/entity/EmployerEntity.java index f70422695..d8abc6cfb 100644 --- a/src/main/java/com/techlooper/entity/EmployerEntity.java +++ b/src/main/java/com/techlooper/entity/EmployerEntity.java @@ -9,7 +9,7 @@ import java.util.List; import static org.springframework.data.elasticsearch.annotations.FieldType.Integer; -import static org.springframework.data.elasticsearch.annotations.FieldType.Nested; +import static org.springframework.data.elasticsearch.annotations.FieldType.*; import static org.springframework.data.elasticsearch.annotations.FieldType.String; @Document(indexName = "employerInformation", type = "company") diff --git a/src/main/java/com/techlooper/entity/GetPromotedEntity.java b/src/main/java/com/techlooper/entity/GetPromotedEntity.java index 4b584d001..e9801d360 100644 --- a/src/main/java/com/techlooper/entity/GetPromotedEntity.java +++ b/src/main/java/com/techlooper/entity/GetPromotedEntity.java @@ -8,7 +8,10 @@ import java.util.List; +import static org.springframework.data.elasticsearch.annotations.FieldType.Boolean; +import static org.springframework.data.elasticsearch.annotations.FieldType.Long; import static org.springframework.data.elasticsearch.annotations.FieldType.*; +import static org.springframework.data.elasticsearch.annotations.FieldType.String; @Document(indexName = "techlooper", type = "getPromoted") public class GetPromotedEntity { diff --git a/src/main/java/com/techlooper/entity/JobEntity.java b/src/main/java/com/techlooper/entity/JobEntity.java index 93a9b23e1..2c7ba6a99 100644 --- a/src/main/java/com/techlooper/entity/JobEntity.java +++ b/src/main/java/com/techlooper/entity/JobEntity.java @@ -1,7 +1,6 @@ package com.techlooper.entity; import com.techlooper.model.JobSkill; -import org.apache.commons.lang3.builder.ToStringBuilder; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.DateFormat; import org.springframework.data.elasticsearch.annotations.Document; @@ -11,6 +10,9 @@ import java.util.List; import static org.springframework.data.elasticsearch.annotations.FieldType.*; +import static org.springframework.data.elasticsearch.annotations.FieldType.Integer; +import static org.springframework.data.elasticsearch.annotations.FieldType.Long; +import static org.springframework.data.elasticsearch.annotations.FieldType.String; /** * Created by chrisshayan on 7/10/14. @@ -113,9 +115,7 @@ public boolean equals(Object o) { JobEntity jobEntity = (JobEntity) o; - if (!id.equals(jobEntity.id)) return false; - - return true; + return id.equals(jobEntity.id); } @Override diff --git a/src/main/java/com/techlooper/entity/ScrapeJobEntity.java b/src/main/java/com/techlooper/entity/ScrapeJobEntity.java index 17b167217..72447e3d9 100644 --- a/src/main/java/com/techlooper/entity/ScrapeJobEntity.java +++ b/src/main/java/com/techlooper/entity/ScrapeJobEntity.java @@ -7,6 +7,7 @@ import java.util.List; import static org.springframework.data.elasticsearch.annotations.FieldType.Boolean; +import static org.springframework.data.elasticsearch.annotations.FieldType.Integer; import static org.springframework.data.elasticsearch.annotations.FieldType.Long; import static org.springframework.data.elasticsearch.annotations.FieldType.*; import static org.springframework.data.elasticsearch.annotations.FieldType.String; diff --git a/src/main/java/com/techlooper/entity/userimport/GithubUserImportProfile.java b/src/main/java/com/techlooper/entity/userimport/GithubUserImportProfile.java index 0d2a469e8..e0cf15fef 100644 --- a/src/main/java/com/techlooper/entity/userimport/GithubUserImportProfile.java +++ b/src/main/java/com/techlooper/entity/userimport/GithubUserImportProfile.java @@ -3,7 +3,6 @@ import com.techlooper.model.SocialProvider; import java.util.ArrayList; -import java.util.Date; import java.util.List; /** diff --git a/src/main/java/com/techlooper/entity/userimport/UserImportEntity.java b/src/main/java/com/techlooper/entity/userimport/UserImportEntity.java index 99c829f69..d69f5713c 100644 --- a/src/main/java/com/techlooper/entity/userimport/UserImportEntity.java +++ b/src/main/java/com/techlooper/entity/userimport/UserImportEntity.java @@ -2,15 +2,12 @@ import com.techlooper.model.SocialProvider; import com.techlooper.util.JsonUtils; -import org.apache.commons.beanutils.BeanMap; -import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.lang3.StringUtils; 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.FieldType; -import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; diff --git a/src/main/java/com/techlooper/entity/vnw/dto/VnwUserDto.java b/src/main/java/com/techlooper/entity/vnw/dto/VnwUserDto.java index 03bebadf7..9b4b72cec 100644 --- a/src/main/java/com/techlooper/entity/vnw/dto/VnwUserDto.java +++ b/src/main/java/com/techlooper/entity/vnw/dto/VnwUserDto.java @@ -2,11 +2,6 @@ import com.techlooper.entity.vnw.RoleName; -import javax.persistence.Column; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.Id; - /** * Created by phuonghqh on 6/26/15. */ 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..286bfb740 --- /dev/null +++ b/src/main/java/com/techlooper/model/ChallengeCriteriaDto.java @@ -0,0 +1,75 @@ +package com.techlooper.model; + +import com.techlooper.entity.ChallengeCriteria; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +/** + * Created by phuonghqh on 10/16/15. + */ +public class ChallengeCriteriaDto implements Serializable { + + private Long challengeId; + + private Set challengeCriteria; + + private Set registrantCriteria; + + public Set getRegistrantCriteria() { + if (registrantCriteria == null) registrantCriteria = new HashSet<>(); + return registrantCriteria; + } + + public void setRegistrantCriteria(Set registrantCriteria) { + this.registrantCriteria = registrantCriteria; + } + + public Long getChallengeId() { + return challengeId; + } + + public void setChallengeId(Long challengeId) { + this.challengeId = challengeId; + } + + public Set getChallengeCriteria() { + return challengeCriteria; + } + + public void setChallengeCriteria(Set challengeCriteria) { + this.challengeCriteria = challengeCriteria; + } + + public static class ChallengeCriteriaDtoBuilder { + private ChallengeCriteriaDto challengeCriteriaDto; + + private ChallengeCriteriaDtoBuilder() { + challengeCriteriaDto = new ChallengeCriteriaDto(); + } + + public ChallengeCriteriaDtoBuilder withChallengeId(Long challengeId) { + challengeCriteriaDto.challengeId = challengeId; + return this; + } + + public ChallengeCriteriaDtoBuilder withChallengeCriteria(Set challengeCriteria) { + challengeCriteriaDto.challengeCriteria = challengeCriteria; + return this; + } + + public ChallengeCriteriaDtoBuilder withRegistrantCriteria(Set registrantCriteria) { + challengeCriteriaDto.registrantCriteria = registrantCriteria; + return this; + } + + public static ChallengeCriteriaDtoBuilder challengeCriteriaDto() { + return new ChallengeCriteriaDtoBuilder(); + } + + public ChallengeCriteriaDto build() { + return challengeCriteriaDto; + } + } +} diff --git a/src/main/java/com/techlooper/model/ChallengeDetailDto.java b/src/main/java/com/techlooper/model/ChallengeDetailDto.java index fd5245c6d..5d139db95 100644 --- a/src/main/java/com/techlooper/model/ChallengeDetailDto.java +++ b/src/main/java/com/techlooper/model/ChallengeDetailDto.java @@ -1,259 +1,280 @@ package com.techlooper.model; +import com.techlooper.entity.ChallengeCriteria; + import java.util.List; +import java.util.Set; /** * Created by NguyenDangKhoa on 7/3/15. */ 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 Set criteria; - private Boolean expired; + public Set getCriteria() { + return criteria; + } - private ChallengePhaseEnum currentPhase; + public void setCriteria(Set 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/model/ChallengeRegistrantCriteriaDto.java b/src/main/java/com/techlooper/model/ChallengeRegistrantCriteriaDto.java new file mode 100644 index 000000000..c8124d22f --- /dev/null +++ b/src/main/java/com/techlooper/model/ChallengeRegistrantCriteriaDto.java @@ -0,0 +1,60 @@ +package com.techlooper.model; + +import com.techlooper.entity.ChallengeRegistrantCriteria; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +/** + * Created by phuonghqh on 10/20/15. + */ +public class ChallengeRegistrantCriteriaDto implements Serializable { + + private Long registrantId; + + private Set criteria; + + public Long getRegistrantId() { + return registrantId; + } + + public void setRegistrantId(Long registrantId) { + this.registrantId = registrantId; + } + + public Set getCriteria() { + if (criteria == null) criteria = new HashSet<>(); + return criteria; + } + + public void setCriteria(Set criteria) { + this.criteria = criteria; + } + + public static class ChallengeRegistrantCriteriaDtoBuilder { + private ChallengeRegistrantCriteriaDto challengeRegistrantCriteriaDto; + + private ChallengeRegistrantCriteriaDtoBuilder() { + challengeRegistrantCriteriaDto = new ChallengeRegistrantCriteriaDto(); + } + + public ChallengeRegistrantCriteriaDtoBuilder withRegistrantId(Long registrantId) { + challengeRegistrantCriteriaDto.registrantId = registrantId; + return this; + } + + public ChallengeRegistrantCriteriaDtoBuilder withCriteria(Set criteria) { + challengeRegistrantCriteriaDto.criteria = criteria; + return this; + } + + public static ChallengeRegistrantCriteriaDtoBuilder challengeRegistrantCriteriaDto() { + return new ChallengeRegistrantCriteriaDtoBuilder(); + } + + public ChallengeRegistrantCriteriaDto build() { + return challengeRegistrantCriteriaDto; + } + } +} diff --git a/src/main/java/com/techlooper/model/EmployerDto.java b/src/main/java/com/techlooper/model/EmployerDto.java index 15fb6adff..6f4f26239 100644 --- a/src/main/java/com/techlooper/model/EmployerDto.java +++ b/src/main/java/com/techlooper/model/EmployerDto.java @@ -1,13 +1,5 @@ package com.techlooper.model; -import org.springframework.data.elasticsearch.annotations.Field; -import org.springframework.data.elasticsearch.annotations.FieldIndex; - -import java.util.Date; - -import static org.springframework.data.elasticsearch.annotations.FieldType.Integer; -import static org.springframework.data.elasticsearch.annotations.FieldType.String; - /** * Created by NguyenDangKhoa on 7/17/15. */ diff --git a/src/main/java/com/techlooper/model/GetPromotedResponse.java b/src/main/java/com/techlooper/model/GetPromotedResponse.java index 78496b820..634db0835 100644 --- a/src/main/java/com/techlooper/model/GetPromotedResponse.java +++ b/src/main/java/com/techlooper/model/GetPromotedResponse.java @@ -13,7 +13,7 @@ public class GetPromotedResponse { private Double salaryMax; - List topDemandedSkills; + private List topDemandedSkills; public Long getTotalJob() { return totalJob; diff --git a/src/main/java/com/techlooper/model/JobResponse.java b/src/main/java/com/techlooper/model/JobResponse.java index cc673c8d7..269781e8f 100644 --- a/src/main/java/com/techlooper/model/JobResponse.java +++ b/src/main/java/com/techlooper/model/JobResponse.java @@ -128,9 +128,7 @@ public boolean equals(Object o) { JobResponse that = (JobResponse) o; - if (url != null ? !url.equals(that.url) : that.url != null) return false; - - return true; + return url != null ? !url.equals(that.url) : that.url != null; } public int hashCode() { diff --git a/src/main/java/com/techlooper/model/ProjectDetailDto.java b/src/main/java/com/techlooper/model/ProjectDetailDto.java index 34605fb79..74515af84 100644 --- a/src/main/java/com/techlooper/model/ProjectDetailDto.java +++ b/src/main/java/com/techlooper/model/ProjectDetailDto.java @@ -1,7 +1,5 @@ package com.techlooper.model; -import com.techlooper.entity.Company; - /** * Created by NguyenDangKhoa on 7/17/15. */ 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/model/SalaryRange.java b/src/main/java/com/techlooper/model/SalaryRange.java index 1f07923a8..79d2f7659 100644 --- a/src/main/java/com/techlooper/model/SalaryRange.java +++ b/src/main/java/com/techlooper/model/SalaryRange.java @@ -39,9 +39,7 @@ public boolean equals(Object o) { SalaryRange that = (SalaryRange) o; - if (!percentile.equals(that.percentile)) return false; - - return true; + return percentile.equals(that.percentile); } @Override diff --git a/src/main/java/com/techlooper/model/Talent.java b/src/main/java/com/techlooper/model/Talent.java index c1d9e9d72..aa2589ab9 100644 --- a/src/main/java/com/techlooper/model/Talent.java +++ b/src/main/java/com/techlooper/model/Talent.java @@ -113,9 +113,7 @@ public boolean equals(Object o) { Talent talent = (Talent) o; - if (!email.equals(talent.email)) return false; - - return true; + return email.equals(talent.email); } public int hashCode() { diff --git a/src/main/java/com/techlooper/model/TalentProfile.java b/src/main/java/com/techlooper/model/TalentProfile.java index 06f3b7ee5..84c237603 100644 --- a/src/main/java/com/techlooper/model/TalentProfile.java +++ b/src/main/java/com/techlooper/model/TalentProfile.java @@ -2,7 +2,6 @@ import com.techlooper.entity.userimport.UserImportEntity; -import java.util.List; import java.util.Map; /** diff --git a/src/main/java/com/techlooper/model/TopicList.java b/src/main/java/com/techlooper/model/TopicList.java index 4aff677aa..89be6a58f 100644 --- a/src/main/java/com/techlooper/model/TopicList.java +++ b/src/main/java/com/techlooper/model/TopicList.java @@ -4,7 +4,6 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; -import java.util.ArrayList; import java.util.List; @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/src/main/java/com/techlooper/model/VnwJobAlertRequest.java b/src/main/java/com/techlooper/model/VnwJobAlertRequest.java index dc937b28d..6c653eec9 100644 --- a/src/main/java/com/techlooper/model/VnwJobAlertRequest.java +++ b/src/main/java/com/techlooper/model/VnwJobAlertRequest.java @@ -1,7 +1,5 @@ package com.techlooper.model; -import org.springframework.data.annotation.Id; - import java.util.List; /** diff --git a/src/main/java/com/techlooper/repository/couchbase/UserRegistrationRepository.java b/src/main/java/com/techlooper/repository/couchbase/UserRegistrationRepository.java index 78e5d8c89..586b69fb7 100644 --- a/src/main/java/com/techlooper/repository/couchbase/UserRegistrationRepository.java +++ b/src/main/java/com/techlooper/repository/couchbase/UserRegistrationRepository.java @@ -1,6 +1,5 @@ package com.techlooper.repository.couchbase; -import com.techlooper.entity.UserEntity; import com.techlooper.entity.UserRegistration; import org.springframework.data.couchbase.repository.CouchbaseRepository; import org.springframework.stereotype.Repository; 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/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/repository/elasticsearch/WebinarRepository.java b/src/main/java/com/techlooper/repository/elasticsearch/WebinarRepository.java index 3b9e583df..01a40c89d 100644 --- a/src/main/java/com/techlooper/repository/elasticsearch/WebinarRepository.java +++ b/src/main/java/com/techlooper/repository/elasticsearch/WebinarRepository.java @@ -1,6 +1,5 @@ package com.techlooper.repository.elasticsearch; -import com.techlooper.entity.SalaryReviewEntity; import com.techlooper.entity.WebinarEntity; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import org.springframework.stereotype.Repository; diff --git a/src/main/java/com/techlooper/repository/vnw/VnwUserRepoLocal.java b/src/main/java/com/techlooper/repository/vnw/VnwUserRepoLocal.java index 43b4e10d7..877e89162 100644 --- a/src/main/java/com/techlooper/repository/vnw/VnwUserRepoLocal.java +++ b/src/main/java/com/techlooper/repository/vnw/VnwUserRepoLocal.java @@ -5,7 +5,6 @@ import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Service; -import java.util.Collection; import java.util.Collections; import java.util.List; 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..f5fde522c --- /dev/null +++ b/src/main/java/com/techlooper/service/ChallengeCriteriaService.java @@ -0,0 +1,14 @@ +package com.techlooper.service; + +import com.techlooper.model.ChallengeCriteriaDto; +import com.techlooper.model.ChallengeRegistrantCriteriaDto; + +/** + * Created by phuonghqh on 10/16/15. + */ +public interface ChallengeCriteriaService { + + ChallengeCriteriaDto saveChallengeCriteria(ChallengeCriteriaDto challengeCriteriaDto, String owner); + + ChallengeRegistrantCriteriaDto saveScoreChallengeRegistrantCriteria(ChallengeRegistrantCriteriaDto registrantCriteriaDto, String ownerEmail); +} diff --git a/src/main/java/com/techlooper/service/ChallengeService.java b/src/main/java/com/techlooper/service/ChallengeService.java index 8a7237d4e..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); @@ -101,4 +103,6 @@ List findChallengeSubmissionWithinPeriod( ChallengeRegistrantDto acceptRegistrant(String ownerEmail, Long registrantId); + void calculateChallengePhases(ChallengeDetailDto challengeDetailDto); + } 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 181b55bdb..e347b8531 100644 --- a/src/main/java/com/techlooper/service/EmailService.java +++ b/src/main/java/com/techlooper/service/EmailService.java @@ -1,11 +1,26 @@ 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); + 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(); + + EmailTemplateDto getTemplateById(Long templateId); } diff --git a/src/main/java/com/techlooper/service/EmployerService.java b/src/main/java/com/techlooper/service/EmployerService.java index 94d90c13b..8724a4607 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,7 @@ public interface EmployerService { VnwUser findEmployerByUsername(String employerUsername); + EmailSettingDto saveEmployerEmailSetting(EmailSettingDto emailSettingDto); + + EmailSettingDto findEmployerEmailSetting(String employerEmail); } diff --git a/src/main/java/com/techlooper/service/ProjectService.java b/src/main/java/com/techlooper/service/ProjectService.java index 4fdea79f8..2c0bdfede 100644 --- a/src/main/java/com/techlooper/service/ProjectService.java +++ b/src/main/java/com/techlooper/service/ProjectService.java @@ -1,9 +1,7 @@ package com.techlooper.service; -import com.techlooper.entity.ChallengeEntity; import com.techlooper.entity.ProjectEntity; import com.techlooper.entity.ProjectRegistrantEntity; -import com.techlooper.model.ChallengeDetailDto; import com.techlooper.model.ProjectDetailDto; import com.techlooper.model.ProjectDto; import com.techlooper.model.ProjectRegistrantDto; @@ -13,7 +11,6 @@ import java.io.IOException; import java.util.Collection; import java.util.List; -import java.util.function.Predicate; /** * Created by NguyenDangKhoa on 7/10/15. diff --git a/src/main/java/com/techlooper/service/SocialService.java b/src/main/java/com/techlooper/service/SocialService.java index 862db6ba0..e1a8f625d 100644 --- a/src/main/java/com/techlooper/service/SocialService.java +++ b/src/main/java/com/techlooper/service/SocialService.java @@ -1,7 +1,6 @@ package com.techlooper.service; import com.techlooper.entity.AccessGrant; -import com.techlooper.entity.UserEntity; import com.techlooper.entity.UserProfile; import com.techlooper.model.SocialConfig; diff --git a/src/main/java/com/techlooper/service/UserService.java b/src/main/java/com/techlooper/service/UserService.java index 0c1bc97c7..4a6dba0f5 100644 --- a/src/main/java/com/techlooper/service/UserService.java +++ b/src/main/java/com/techlooper/service/UserService.java @@ -1,6 +1,5 @@ package com.techlooper.service; -import com.techlooper.entity.UserEntity; import com.techlooper.entity.userimport.UserImportEntity; import com.techlooper.entity.vnw.dto.VnwUserDto; import com.techlooper.model.*; diff --git a/src/main/java/com/techlooper/service/impl/AbstractSocialService.java b/src/main/java/com/techlooper/service/impl/AbstractSocialService.java index 7b6019620..c08a1f9bf 100644 --- a/src/main/java/com/techlooper/service/impl/AbstractSocialService.java +++ b/src/main/java/com/techlooper/service/impl/AbstractSocialService.java @@ -1,14 +1,10 @@ package com.techlooper.service.impl; -import com.techlooper.entity.SimpleUserProfile; -import com.techlooper.entity.UserEntity; import com.techlooper.entity.UserProfile; -import com.techlooper.exception.EntityNotFoundException; import com.techlooper.model.SocialConfig; import com.techlooper.model.SocialProvider; import com.techlooper.repository.JsonConfigRepository; import com.techlooper.service.SocialService; -import com.techlooper.service.UserService; import org.dozer.Mapper; import org.jasypt.util.text.TextEncryptor; import org.springframework.social.connect.support.OAuth1ConnectionFactory; @@ -21,10 +17,8 @@ import javax.annotation.Resource; import java.util.Optional; -import java.util.concurrent.CompletableFuture; import static com.techlooper.entity.AccessGrant.AccessGrantBuilder.accessGrant; -import static com.techlooper.entity.UserEntity.UserEntityBuilder.userEntity; /** * Created by phuonghqh on 12/15/14. 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..19484806f --- /dev/null +++ b/src/main/java/com/techlooper/service/impl/ChallengeCriteriaServiceImpl.java @@ -0,0 +1,114 @@ +package com.techlooper.service.impl; + +import com.techlooper.entity.ChallengeCriteria; +import com.techlooper.entity.ChallengeEntity; +import com.techlooper.entity.ChallengeRegistrantCriteria; +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; +import com.techlooper.service.ChallengeService; +import com.techlooper.util.DataUtils; +import org.dozer.Mapper; +import org.elasticsearch.index.query.QueryBuilders; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +/** + * Created by phuonghqh on 10/16/15. + */ +@Service +public class ChallengeCriteriaServiceImpl implements ChallengeCriteriaService { + + @Resource + private ChallengeRepository challengeRepository; + + @Resource + private ChallengeService challengeService; + + @Resource + private ChallengeRegistrantRepository challengeRegistrantRepository; + + @Resource + private Mapper dozerMapper; + + public ChallengeCriteriaDto saveChallengeCriteria(ChallengeCriteriaDto challengeCriteriaDto, String ownerEmail) { + ChallengeEntity challenge = challengeService.findChallengeIdAndOwnerEmail(challengeCriteriaDto.getChallengeId(), ownerEmail); + if (challenge == null) { + return null; + } + + Set criteria = new HashSet<>(); + challengeCriteriaDto.getChallengeCriteria().forEach(cri -> { + if (cri.getCriteriaId() == null) cri.setCriteriaId(DataUtils.generateStringId()); + criteria.add(cri); + }); + + Set challengeRegistrantEntities = new HashSet<>(); + Iterator challengeIterator = challengeRegistrantRepository.search( + QueryBuilders.termQuery("challengeId", challengeCriteriaDto.getChallengeId())).iterator(); + + while (challengeIterator.hasNext()) { + final ChallengeRegistrantEntity registrantEntity = challengeIterator.next(); + final Set registrantCriteria = new HashSet<>(); + + criteria.forEach(challengeCri -> { + ChallengeRegistrantCriteria registrantCri = registrantEntity.getCriteria().stream() + .filter(cri -> challengeCri.getCriteriaId().equals(cri.getCriteriaId())) + .findFirst().orElse(new ChallengeRegistrantCriteria()); + dozerMapper.map(challengeCri, registrantCri); + registrantCriteria.add(registrantCri); + registrantEntity.getCriteria().remove(registrantCri); + }); + registrantEntity.setCriteria(registrantCriteria); + challengeRegistrantEntities.add(registrantEntity); + } + + challenge.setCriteria(criteria); + if (challengeRegistrantEntities.size() > 0) { + Set registrantCriteria = new HashSet<>(); + challengeRegistrantRepository.save(challengeRegistrantEntities) + .forEach(registrant -> registrantCriteria.add(toChallengeRegistrantCriteriaDto(registrant))); + challengeCriteriaDto.setRegistrantCriteria(registrantCriteria); + } + + 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(); + + // only save score and comment + cri.setScore(criteriaDto.getScore()); + cri.setComment(criteriaDto.getComment()); + 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 ddcd96da2..da98d31db 100644 --- a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java @@ -1,15 +1,15 @@ 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.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; @@ -64,452 +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()); - } - 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; - } - - 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; - } - } - } - - 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()); - } - 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() { -// List challenges = new ArrayList<>(); -// Iterator challengeIter = challengeRepository.findAll().iterator(); -// while (challengeIter.hasNext()) { -// ChallengeEntity challengeEntity = challengeIter.next(); -// 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())); - } - 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); - } - - 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()); - } - 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; + @Resource + private EmployerService employerService; + + @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()); } - long challenge2StartDate = sdf.parse(challenge2.getStartDateTime()).getTime(); - long challenge1StartDate = sdf.parse(challenge1.getStartDateTime()).getTime(); - if (challenge2StartDate - challenge1StartDate > 0) { - return 1; + + 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; } - else if (challenge2StartDate - challenge1StartDate < 0) { - return -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; + } } - else { - return 0; + } + + 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()); } - } - 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() { + } + + 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); + } + } + + 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)); + } + + 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()); + } + 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,395 +514,457 @@ 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; - } - - 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; - } - 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); -// 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); + 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; } - else { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withTypes("challengeRegistrant"); - BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); - if (condition.getChallengeId() != null) { - boolQueryBuilder.must(termQuery("challengeId", condition.getChallengeId())); - } + 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; + }); + } - if (StringUtils.isNotEmpty(condition.getFilterType()) && - (StringUtils.isNotEmpty(condition.getFromDate()) || StringUtils.isNotEmpty(condition.getToDate()))) { - RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(condition.getFilterType()); + 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(); + } - if (StringUtils.isNotEmpty(condition.getFromDate())) { - Long from = string2Date(condition.getFromDate(), BASIC_DATE_PATTERN).getTime(); - rangeQueryBuilder.from(from); + 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; } - if (StringUtils.isNotEmpty(condition.getToDate())) { - Long to = string2Date(condition.getToDate(), BASIC_DATE_PATTERN).getTime() + - TimePeriodEnum.TWENTY_FOUR_HOURS.getMiliseconds(); - rangeQueryBuilder.to(to); + 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); + } } - boolQueryBuilder.must(rangeQueryBuilder); - } - - searchQueryBuilder.withQuery(boolQueryBuilder); - result.addAll(DataUtils.getAllEntities(challengeRegistrantRepository, 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()); - } - - 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 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); - } - - 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); - } - - @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 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()); - } - - 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; - } - - public static void calculateChallengePhases(ChallengeDetailDto challengeDetailDto) { - String now = DateTimeUtils.currentDate(); - - String timeline[] = { - challengeDetailDto.getSubmissionDateTime(), - challengeDetailDto.getPrototypeSubmissionDateTime(), - challengeDetailDto.getUxSubmissionDateTime(), - challengeDetailDto.getIdeaSubmissionDateTime(), - challengeDetailDto.getRegistrationDateTime() - }; + 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); + } + 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()); + } + } + + 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()); + } + + 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); + } - 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 ChallengeEntity findChallengeIdAndOwnerEmail(Long challengeId, String ownerEmail) { + ChallengeEntity challenge = challengeRepository.findOne(challengeId); + if (challenge == null || !challenge.getAuthorEmail().equalsIgnoreCase(ownerEmail)) { + return null; } - } - catch (Exception e) { - continue; - } + return challenge; } - if (currentIndex == -1) {//FINAL - challengeDetailDto.setCurrentPhase(ChallengePhaseEnum.FINAL); - challengeDetailDto.setNextPhase(ChallengePhaseEnum.FINAL); + 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); } - else { - challengeDetailDto.setCurrentPhase(CHALLENGE_TIMELINE[currentIndex]); - challengeDetailDto.setNextPhase(CHALLENGE_TIMELINE[nextIndex > -1 ? nextIndex : currentIndex]); + + 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); + } + + 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; + } + + public boolean sendEmailToRegistrant(String challengeOwner, Long challengeId, Long registrantId, EmailContent emailContent) { + 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); + return false; + } + } + 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 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()); + } + + 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(); @@ -950,27 +1006,27 @@ public static void calculateChallengePhases(ChallengeDetailDto challengeDetailDt //// 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/ChallengeSubmissionServiceImpl.java b/src/main/java/com/techlooper/service/impl/ChallengeSubmissionServiceImpl.java index 0d5720a18..ba8df4002 100644 --- a/src/main/java/com/techlooper/service/impl/ChallengeSubmissionServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/ChallengeSubmissionServiceImpl.java @@ -17,7 +17,6 @@ import org.springframework.stereotype.Service; import javax.annotation.Resource; - import java.util.Iterator; import static org.elasticsearch.index.query.QueryBuilders.*; diff --git a/src/main/java/com/techlooper/service/impl/CompanyServiceImpl.java b/src/main/java/com/techlooper/service/impl/CompanyServiceImpl.java index f91b63a5e..886f38db1 100644 --- a/src/main/java/com/techlooper/service/impl/CompanyServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/CompanyServiceImpl.java @@ -37,101 +37,101 @@ @Service public class CompanyServiceImpl implements CompanyService { - @Resource - private ElasticsearchTemplate elasticsearchTemplateUserImport; + @Resource + private ElasticsearchTemplate elasticsearchTemplateUserImport; - @Resource - private CompanyRepository companyRepository; + @Resource + private CompanyRepository companyRepository; - @Value("${elasticsearch.userimport.index.name}") - private String indexName; + @Value("${elasticsearch.userimport.index.name}") + private String indexName; - @Resource - private JsonConfigRepository jsonConfigRepository; + @Resource + private JsonConfigRepository jsonConfigRepository; - @Resource - private CompanySearchResultRepository companySearchResultRepository; + @Resource + private CompanySearchResultRepository companySearchResultRepository; - @Resource - private Mapper dozerMapper; + @Resource + private Mapper dozerMapper; - public CompanyEntity findById(Long id) { - CompanyEntity company = companyRepository.findOne(id); - if (company != null) { - refineCompany(company); + public CompanyEntity findById(Long id) { + CompanyEntity company = companyRepository.findOne(id); + if (company != null) { + refineCompany(company); + } + return company; } - return company; - } - - public CompanyEntity findByName(String companyName) { - NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().withIndices(indexName) - .withTypes("company"); - queryBuilder.withFilter(FilterBuilders.queryFilter(QueryBuilders.matchPhraseQuery("companyName", companyName))); - - CompanyEntity company = null; - List companies = elasticsearchTemplateUserImport.queryForList(queryBuilder.build(), CompanyEntity.class); - if (companies.size() > 0) { - company = companies.get(0); - refineCompany(company); + + public CompanyEntity findByName(String companyName) { + NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().withIndices(indexName) + .withTypes("company"); + queryBuilder.withFilter(FilterBuilders.queryFilter(QueryBuilders.matchPhraseQuery("companyName", companyName))); + + CompanyEntity company = null; + List companies = elasticsearchTemplateUserImport.queryForList(queryBuilder.build(), CompanyEntity.class); + if (companies.size() > 0) { + company = companies.get(0); + refineCompany(company); + } + return company; } - return company; - } - - @Override - public EmployerEntity findEmployerByCompanyId(Long companyId) { - return companySearchResultRepository.findOne(companyId); - } - - public EmployerDto findByUserName(String username) { - if (username == null) return null; - NestedQueryBuilder queryBuilder = QueryBuilders.nestedQuery("employers", matchPhraseQuery("employers.userName", username)); - FacetedPage result = companySearchResultRepository.search(queryBuilder, new PageRequest(0, 1)); - if (result.hasContent()) { - EmployerEntity employer = result.getContent().get(0); - return dozerMapper.map(employer, EmployerDto.class); + + @Override + public EmployerEntity findEmployerByCompanyId(Long companyId) { + return companySearchResultRepository.findOne(companyId); } - return null; - } - - private void refineCompany(CompanyEntity company) { - List topJobs = company.getJobs().stream().sorted((job1, job2) -> { - if (job1.getExpiredDate() == null || job2.getExpiredDate() == null) { - return -1; - } - return -1 * job1.getExpiredDate().compareTo(job2.getExpiredDate()); - }).collect(Collectors.toList()); - company.setJobs(topJobs); - - NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().withIndices(indexName); - final String[] companyName = {company.getCompanyName().toLowerCase()}; - jsonConfigRepository.getCommonTerm().forEach(term -> { - companyName[0] = companyName[0].replaceAll(term.toLowerCase(), ""); - }); - String[] prefixes = companyName[0].split(" "); - BoolFilterBuilder shouldFilter = FilterBuilders.boolFilter().should(); - StringBuilder prefixBuilder = new StringBuilder(); - for (String prefix : prefixes) { - if (prefix.length() == 0) { - continue; - } - prefixBuilder.append(prefix).append(prefixBuilder.length() > 0 ? " " : ""); - shouldFilter.should(FilterBuilders.prefixFilter("company", prefixBuilder.toString().toLowerCase().trim())); + + public EmployerDto findByUserName(String username) { + if (username == null) return null; + NestedQueryBuilder queryBuilder = QueryBuilders.nestedQuery("employers", matchPhraseQuery("employers.userName", username)); + FacetedPage result = companySearchResultRepository.search(queryBuilder, new PageRequest(0, 1)); + if (result.hasContent()) { + EmployerEntity employer = result.getContent().get(0); + return dozerMapper.map(employer, EmployerDto.class); + } + return null; + } + + private void refineCompany(CompanyEntity company) { + List topJobs = company.getJobs().stream().sorted((job1, job2) -> { + if (job1.getExpiredDate() == null || job2.getExpiredDate() == null) { + return -1; + } + return -1 * job1.getExpiredDate().compareTo(job2.getExpiredDate()); + }).collect(Collectors.toList()); + company.setJobs(topJobs); + + NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().withIndices(indexName); + final String[] companyName = {company.getCompanyName().toLowerCase()}; + jsonConfigRepository.getCommonTerm().forEach(term -> { + companyName[0] = companyName[0].replaceAll(term.toLowerCase(), ""); + }); + String[] prefixes = companyName[0].split(" "); + BoolFilterBuilder shouldFilter = FilterBuilders.boolFilter().should(); + StringBuilder prefixBuilder = new StringBuilder(); + for (String prefix : prefixes) { + if (prefix.length() == 0) { + continue; + } + prefixBuilder.append(prefix).append(prefixBuilder.length() > 0 ? " " : ""); + shouldFilter.should(FilterBuilders.prefixFilter("company", prefixBuilder.toString().toLowerCase().trim())); + } + queryBuilder.withTypes("user").withFilter(FilterBuilders.nestedFilter("profiles", shouldFilter)); + + final CompanyEntity finalCompany = company; + elasticsearchTemplateUserImport.queryForList(queryBuilder.build(), UserImportEntity.class).forEach(userEntity -> { + Optional.ofNullable(userEntity.getProfiles().get(SocialProvider.GITHUB)).ifPresent(profile -> { + GitHubUserProfile employee = new GitHubUserProfile(); + LinkedHashMap map = (LinkedHashMap) profile; + employee.setEmail((String) map.get("email")); + employee.setProfileImageUrl((String) map.get("imageUrl")); + employee.setName((String) map.get("fullName")); + employee.setUsername((String) map.get("username")); + employee.setSkills((List) map.get("skills")); + finalCompany.getEmployees().add(employee); + }); + }); } - queryBuilder.withTypes("user").withFilter(FilterBuilders.nestedFilter("profiles", shouldFilter)); - - final CompanyEntity finalCompany = company; - elasticsearchTemplateUserImport.queryForList(queryBuilder.build(), UserImportEntity.class).forEach(userEntity -> { - Optional.ofNullable(userEntity.getProfiles().get(SocialProvider.GITHUB)).ifPresent(profile -> { - GitHubUserProfile employee = new GitHubUserProfile(); - LinkedHashMap map = (LinkedHashMap) profile; - employee.setEmail((String) map.get("email")); - employee.setProfileImageUrl((String) map.get("imageUrl")); - employee.setName((String) map.get("fullName")); - employee.setUsername((String) map.get("username")); - employee.setSkills((List) map.get("skills")); - finalCompany.getEmployees().add(employee); - }); - }); - } } diff --git a/src/main/java/com/techlooper/service/impl/CurrencyServiceImpl.java b/src/main/java/com/techlooper/service/impl/CurrencyServiceImpl.java index cb0751842..9b639930f 100644 --- a/src/main/java/com/techlooper/service/impl/CurrencyServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/CurrencyServiceImpl.java @@ -1,14 +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.util.Scanner; +import java.text.DecimalFormat; +import java.text.NumberFormat; +import java.util.Currency; +import java.util.Locale; /** * Created by phuonghqh on 5/28/15. @@ -16,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/java/com/techlooper/service/impl/EmailServiceImpl.java b/src/main/java/com/techlooper/service/impl/EmailServiceImpl.java index 0e82dd19d..63f7b2cf5 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,26 @@ 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; + } + + @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/java/com/techlooper/service/impl/EmployerServiceImpl.java b/src/main/java/com/techlooper/service/impl/EmployerServiceImpl.java index 93622834b..738aebd26 100644 --- a/src/main/java/com/techlooper/service/impl/EmployerServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/EmployerServiceImpl.java @@ -1,14 +1,21 @@ 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.model.EmployerDto; 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.CompanyService; import com.techlooper.service.EmployerService; import com.techlooper.service.ProjectService; +import org.dozer.Mapper; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import javax.annotation.Resource; @@ -34,6 +41,18 @@ public class EmployerServiceImpl implements EmployerService { @Resource private ChallengeRegistrantRepository challengeRegistrantRepository; + @Resource + private EmailSettingRepository emailSettingRepository; + + @Resource + private CompanyService companyService; + + @Resource + private Mapper dozerMapper; + + @Value("${mail.techlooper.reply_to}") + private String mailTechlooperReplyTo; + public DashBoardInfo getDashboardInfo(String owner) { VnwUser user = vnwUserRepo.findByUsernameIgnoreCase(owner); String email = user.getEmail(); @@ -53,4 +72,30 @@ 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; + } + + @Override + public EmailSettingDto findEmployerEmailSetting(String employerEmail) { + EmailSettingEntity emailSettingEntity = emailSettingRepository.findOne(employerEmail); + EmailSettingDto emailSettingDto = new EmailSettingDto(); + if (emailSettingEntity != null) { + emailSettingDto = dozerMapper.map(emailSettingEntity, EmailSettingDto.class); + } else { + emailSettingDto.setEmployerEmail(employerEmail); + emailSettingDto.setReplyEmail(mailTechlooperReplyTo); + EmployerDto employerDto = companyService.findByUserName(employerEmail); + if (employerDto != null) { + StringBuilder emailSignatureBuilder = new StringBuilder(""); + emailSignatureBuilder.append(employerDto.getCompanyName()).append("
").append(employerDto.getAddress()); + emailSettingDto.setEmailSignature(emailSignatureBuilder.toString()); + } + } + return emailSettingDto; + } } diff --git a/src/main/java/com/techlooper/service/impl/FacebookService.java b/src/main/java/com/techlooper/service/impl/FacebookService.java index c146e5423..99790220f 100644 --- a/src/main/java/com/techlooper/service/impl/FacebookService.java +++ b/src/main/java/com/techlooper/service/impl/FacebookService.java @@ -5,7 +5,6 @@ import com.techlooper.entity.UserProfile; import com.techlooper.model.SocialConfig; import com.techlooper.repository.JsonConfigRepository; -import org.apache.commons.collections.map.MultiValueMap; import org.springframework.social.connect.Connection; import org.springframework.social.connect.support.OAuth2ConnectionFactory; import org.springframework.social.facebook.api.Facebook; @@ -16,9 +15,6 @@ import javax.annotation.Resource; import javax.inject.Inject; -import java.util.HashMap; -import java.util.Map; - import static com.techlooper.model.SocialProvider.FACEBOOK; /** diff --git a/src/main/java/com/techlooper/service/impl/JobAggregatorServiceImpl.java b/src/main/java/com/techlooper/service/impl/JobAggregatorServiceImpl.java index 572541d24..777d2732b 100644 --- a/src/main/java/com/techlooper/service/impl/JobAggregatorServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/JobAggregatorServiceImpl.java @@ -315,7 +315,7 @@ private NativeSearchQueryBuilder getJobListingQueryBuilder(JobSearchCriteria cri filterBuilder.mustNot(termFilter("isActive", 0)); filterBuilder.must(rangeFilter("createdDateTime").from("now-30d/d")); if (criteria.getTopPriority() != null) { - if (criteria.getTopPriority() == true) { + if (criteria.getTopPriority()) { filterBuilder.must(termFilter("topPriority", true)); } else { filterBuilder.mustNot(termFilter("topPriority", true)); @@ -356,7 +356,6 @@ private void mapJobCrawlSource(JobSearchResponse jobSearchResponse) { while (tokenizer.hasMoreTokens()) { String sourceName = tokenizer.nextToken(); job.setCrawlSource(sourceName.toUpperCase()); - break; } } } diff --git a/src/main/java/com/techlooper/service/impl/LooperPointServiceImpl.java b/src/main/java/com/techlooper/service/impl/LooperPointServiceImpl.java index 176ec2d53..21944721e 100644 --- a/src/main/java/com/techlooper/service/impl/LooperPointServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/LooperPointServiceImpl.java @@ -1,29 +1,18 @@ package com.techlooper.service.impl; -import com.techlooper.entity.userimport.UserImportEntity; -import com.techlooper.model.HistogramEnum; import com.techlooper.repository.userimport.UserImportRepository; import com.techlooper.service.JobStatisticService; import com.techlooper.service.LooperPointService; import com.techlooper.service.UserEvaluationService; -import org.elasticsearch.action.search.SearchType; import org.elasticsearch.index.query.FilterBuilder; import org.elasticsearch.index.query.FilterBuilders; -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.domain.PageRequest; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; -import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; -import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import javax.annotation.Resource; -import java.time.Duration; -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; import java.util.Map; /** @@ -49,7 +38,7 @@ public class LooperPointServiceImpl implements LooperPointService { @Resource private JobStatisticService jobStatisticService; - final String[] countries = {"japan", "singapore", "myanmar", "cambodia", "thailand", "malaysia", "indonesia", "australia", "china", "india", "korea", "taiwan", + private final String[] countries = {"japan", "singapore", "myanmar", "cambodia", "thailand", "malaysia", "indonesia", "australia", "china", "india", "korea", "taiwan", "spain", "ukraine", "poland", "russia", "bulgaria", "turkey", "greece", "serbia", "romania", "belarus", "lithuania", "estonia", "italy", "portugal", "colombia", "brazil", "chile", "argentina", "venezuela", "bolivia", "mexico"}; // final String[] countries = {"vietnam"}; diff --git a/src/main/java/com/techlooper/service/impl/ProjectServiceImpl.java b/src/main/java/com/techlooper/service/impl/ProjectServiceImpl.java index e0e730447..90dd904e7 100644 --- a/src/main/java/com/techlooper/service/impl/ProjectServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/ProjectServiceImpl.java @@ -47,351 +47,347 @@ @Service public class ProjectServiceImpl implements ProjectService { - @Resource - private ProjectRepository projectRepository; + @Resource + private ProjectRepository projectRepository; - @Resource - private CompanySearchResultRepository companySearchResultRepository; + @Resource + private CompanySearchResultRepository companySearchResultRepository; - @Resource - private ProjectRegistrantRepository projectRegistrantRepository; + @Resource + private ProjectRegistrantRepository projectRegistrantRepository; - @Resource - private Mapper dozerMapper; + @Resource + private Mapper dozerMapper; - @Resource - private MimeMessage applyJobMailMessage; + @Resource + private MimeMessage applyJobMailMessage; - @Resource - private JavaMailSender mailSender; + @Resource + private JavaMailSender mailSender; - @Value("${web.baseUrl}") - private String webBaseUrl; + @Value("${web.baseUrl}") + private String webBaseUrl; - @Resource - private Template alertJobSeekerApplyJobMailTemplateEn; + @Resource + private Template alertJobSeekerApplyJobMailTemplateEn; - @Resource - private Template alertJobSeekerApplyJobMailTemplateVi; + @Resource + private Template alertJobSeekerApplyJobMailTemplateVi; - @Resource - private Template alertEmployerApplyJobMailTemplateEn; + @Resource + private Template alertEmployerApplyJobMailTemplateEn; - @Resource - private Template alertEmployerApplyJobMailTemplateVi; + @Resource + private Template alertEmployerApplyJobMailTemplateVi; - @Resource - private Template alertEmployerPostJobMailTemplateVi; + @Resource + private Template alertEmployerPostJobMailTemplateVi; - @Resource - private Template alertEmployerPostJobMailTemplateEn; + @Resource + private Template alertEmployerPostJobMailTemplateEn; - @Resource - private Template alertTechloopiesPostJobMailTemplateEn; + @Resource + private Template alertTechloopiesPostJobMailTemplateEn; - @Value("${mail.alertJobSeekerApplyJob.subject.en}") - private String alertJobSeekerApplyJobMailSubjectEn; + @Value("${mail.alertJobSeekerApplyJob.subject.en}") + private String alertJobSeekerApplyJobMailSubjectEn; - @Value("${mail.alertJobSeekerApplyJob.subject.vn}") - private String alertJobSeekerApplyJobMailSubjectVn; + @Value("${mail.alertJobSeekerApplyJob.subject.vn}") + private String alertJobSeekerApplyJobMailSubjectVn; - @Value("${mail.alertEmployerApplyJob.subject.en}") - private String alertEmployerApplyJobMailSubjectEn; + @Value("${mail.alertEmployerApplyJob.subject.en}") + private String alertEmployerApplyJobMailSubjectEn; - @Value("${mail.alertEmployerApplyJob.subject.vn}") - private String alertEmployerApplyJobMailSubjectVn; + @Value("${mail.alertEmployerApplyJob.subject.vn}") + private String alertEmployerApplyJobMailSubjectVn; - @Value("${mail.alertEmployerPostJob.subject.vn}") - private String alertEmployerPostJobMailSubjectVn; + @Value("${mail.alertEmployerPostJob.subject.vn}") + private String alertEmployerPostJobMailSubjectVn; - @Value("${mail.alertEmployerPostJob.subject.en}") - private String alertEmployerPostJobMailSubjectEn; + @Value("${mail.alertEmployerPostJob.subject.en}") + private String alertEmployerPostJobMailSubjectEn; - @Value("${mail.alertTechloopiesPostJob.subject.en}") - private String alertTechloopiesPostJobMailSubjectEn; + @Value("${mail.alertTechloopiesPostJob.subject.en}") + private String alertTechloopiesPostJobMailSubjectEn; - @Value("${mail.postChallenge.techloopies.mailList}") - private String techloopiesMailList; + @Value("${mail.postChallenge.techloopies.mailList}") + private String techloopiesMailList; - @Value("${mail.techlooper.reply_to}") - private String mailTechlooperReplyTo; + @Value("${mail.techlooper.reply_to}") + private String mailTechlooperReplyTo; - private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy"); + private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy"); - @Value("${elasticsearch.userimport.index.name}") - private String techlooperIndex; + @Value("${elasticsearch.userimport.index.name}") + private String techlooperIndex; - @Resource - private CompanyService companyService; + @Resource + private CompanyService companyService; - private static final Logger LOGGER = LoggerFactory.getLogger(ProjectServiceImpl.class); + private static final Logger LOGGER = LoggerFactory.getLogger(ProjectServiceImpl.class); - @Override - public ProjectEntity saveProject(ProjectDto projectDto) { - ProjectEntity projectEntity = dozerMapper.map(projectDto, ProjectEntity.class); - Date currentDate = new Date(); - projectEntity.setProjectId(currentDate.getTime()); - projectEntity.setCreatedDate(simpleDateFormat.format(currentDate)); - projectEntity = projectRepository.save(projectEntity); + @Override + public ProjectEntity saveProject(ProjectDto projectDto) { + ProjectEntity projectEntity = dozerMapper.map(projectDto, ProjectEntity.class); + Date currentDate = new Date(); + projectEntity.setProjectId(currentDate.getTime()); + projectEntity.setCreatedDate(simpleDateFormat.format(currentDate)); + projectEntity = projectRepository.save(projectEntity); - if (projectEntity != null) { - try { - sendEmailAlertEmployerPostJob(projectEntity); - sendEmailAlertTechloopiesPostJob(projectEntity); - } - catch (Exception ex) { - LOGGER.error(ex.getMessage(), ex); - } + if (projectEntity != null) { + try { + sendEmailAlertEmployerPostJob(projectEntity); + sendEmailAlertTechloopiesPostJob(projectEntity); + } catch (Exception ex) { + LOGGER.error(ex.getMessage(), ex); + } + } + + return projectEntity; + } + + @Override + public void sendEmailAlertEmployerPostJob(ProjectEntity projectEntity) + throws MessagingException, IOException, TemplateException { + Template template = projectEntity.getLang() == Language.vi ? + alertEmployerPostJobMailTemplateVi : alertEmployerPostJobMailTemplateEn; + String mailSubject = projectEntity.getLang() == Language.vi ? + alertEmployerPostJobMailSubjectVn : alertEmployerPostJobMailSubjectEn; + mailSubject = String.format(mailSubject, projectEntity.getProjectTitle()); + Address[] emailAddress = InternetAddress.parse(projectEntity.getAuthorEmail()); + sendEmailAlertApplyJob(projectEntity, null, mailSubject, emailAddress, template, false); + } + + @Override + public void sendEmailAlertTechloopiesPostJob(ProjectEntity projectEntity) + throws MessagingException, IOException, TemplateException { + Address[] emailAddress = InternetAddress.parse(techloopiesMailList); + sendEmailAlertApplyJob(projectEntity, null, alertTechloopiesPostJobMailSubjectEn, + emailAddress, alertTechloopiesPostJobMailTemplateEn, false); + } + + @Override + public Long countTotalNumberOfProjects() { + return projectRepository.count(); + } + + @Override + public Long countTotalNumberOfSkills() { + Long total = 0L; + Iterator projectIterator = projectRepository.findAll().iterator(); + while (projectIterator.hasNext()) { + ProjectEntity projectEntity = projectIterator.next(); + if (!projectEntity.getSkills().isEmpty()) { + total += projectEntity.getSkills().size(); + } + } + return total; + } + + @Override + public List listProject() { + List projects = new ArrayList<>(); + Iterator projectIterator = projectRepository.findAll().iterator(); + while (projectIterator.hasNext()) { + ProjectEntity projectEntity = projectIterator.next(); + ProjectDto projectDto = dozerMapper.map(projectEntity, ProjectDto.class); + EmployerDto employerDto = companyService.findByUserName(projectDto.getAuthorEmail()); + + if (employerDto != null) { + projectDto.setCompanyName(employerDto.getCompanyName()); + projectDto.setCompanyLogoURL(employerDto.getCompanyLogoURL()); + } + projects.add(projectDto); + } + + return projects.stream().sorted((project1, project2) -> { + if (project2.getProjectId() > project1.getProjectId()) { + return 1; + } else if (project2.getProjectId() < project1.getProjectId()) { + return -1; + } + return 0; + }).collect(Collectors.toList()); } - return projectEntity; - } - - @Override - public void sendEmailAlertEmployerPostJob(ProjectEntity projectEntity) - throws MessagingException, IOException, TemplateException { - Template template = projectEntity.getLang() == Language.vi ? - alertEmployerPostJobMailTemplateVi : alertEmployerPostJobMailTemplateEn; - String mailSubject = projectEntity.getLang() == Language.vi ? - alertEmployerPostJobMailSubjectVn : alertEmployerPostJobMailSubjectEn; - mailSubject = String.format(mailSubject, projectEntity.getProjectTitle()); - Address[] emailAddress = InternetAddress.parse(projectEntity.getAuthorEmail()); - sendEmailAlertApplyJob(projectEntity, null, mailSubject, emailAddress, template, false); - } - - @Override - public void sendEmailAlertTechloopiesPostJob(ProjectEntity projectEntity) - throws MessagingException, IOException, TemplateException { - Address[] emailAddress = InternetAddress.parse(techloopiesMailList); - sendEmailAlertApplyJob(projectEntity, null, alertTechloopiesPostJobMailSubjectEn, - emailAddress, alertTechloopiesPostJobMailTemplateEn, false); - } - - @Override - public Long countTotalNumberOfProjects() { - return projectRepository.count(); - } - - @Override - public Long countTotalNumberOfSkills() { - Long total = 0L; - Iterator projectIterator = projectRepository.findAll().iterator(); - while (projectIterator.hasNext()) { - ProjectEntity projectEntity = projectIterator.next(); - if (!projectEntity.getSkills().isEmpty()) { - total += projectEntity.getSkills().size(); - } + @Override + public ProjectDetailDto getProjectDetail(Long projectId) { + ProjectDetailDto projectDetail = new ProjectDetailDto(); + ProjectEntity projectEntity = projectRepository.findOne(projectId); + ProjectDto project = dozerMapper.map(projectEntity, ProjectDto.class); + project.setNumberOfApplications(getNumberOfRegistrants(projectId)); + projectDetail.setProject(project); + + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder(); + searchQueryBuilder.withQuery(nestedQuery("employers", + matchPhraseQuery("employers.userName", project.getAuthorEmail()))); + List employerEntities = companySearchResultRepository.search(searchQueryBuilder.build()).getContent(); + + if (!employerEntities.isEmpty()) { + EmployerEntity employerEntity = employerEntities.get(0); + EmployerDto employerDto = dozerMapper.map(employerEntity, EmployerDto.class); + if (!employerEntity.getEmployers().isEmpty()) { + Employer employer = employerEntity.getEmployers().get(0); + employerDto.setCreatedDate(simpleDateFormat.format(employer.getCreatedDate())); + } + projectDetail.setCompany(employerDto); + } + return projectDetail; } - return total; - } - - @Override - public List listProject() { - List projects = new ArrayList<>(); - Iterator projectIterator = projectRepository.findAll().iterator(); - while (projectIterator.hasNext()) { - ProjectEntity projectEntity = projectIterator.next(); - ProjectDto projectDto = dozerMapper.map(projectEntity, ProjectDto.class); - EmployerDto employerDto = companyService.findByUserName(projectDto.getAuthorEmail()); - - if (employerDto != null) { - projectDto.setCompanyName(employerDto.getCompanyName()); - projectDto.setCompanyLogoURL(employerDto.getCompanyLogoURL()); - } - projects.add(projectDto); + + @Override + public long joinProject(ProjectRegistrantDto projectRegistrantDto) throws MessagingException, IOException, TemplateException { + Long projectId = projectRegistrantDto.getProjectId(); + boolean isExist = checkIfProjectRegistrantExist(projectId, projectRegistrantDto.getRegistrantEmail()); + + if (!isExist) { + ProjectRegistrantEntity projectRegistrantEntity = dozerMapper.map(projectRegistrantDto, ProjectRegistrantEntity.class); + ProjectEntity projectEntity = projectRepository.findOne(projectId); + + try { + sendEmailAlertJobSeekerApplyJob(projectEntity, projectRegistrantEntity); + sendEmailAlertEmployerApplyJob(projectEntity, projectRegistrantEntity); + projectRegistrantEntity.setMailSent(Boolean.TRUE); + } catch (Exception ex) { + LOGGER.error(ex.getMessage(), ex); + } + + projectRegistrantEntity.setProjectRegistrantId(new Date().getTime()); + projectRegistrantRepository.save(projectRegistrantEntity); + } + return getNumberOfRegistrants(projectId); } - return projects.stream().sorted((project1, project2) -> { - if (project2.getProjectId() > project1.getProjectId()) { - return 1; - } - else if (project2.getProjectId() < project1.getProjectId()) { - return -1; - } - return 0; - }).collect(Collectors.toList()); - } - - @Override - public ProjectDetailDto getProjectDetail(Long projectId) { - ProjectDetailDto projectDetail = new ProjectDetailDto(); - ProjectEntity projectEntity = projectRepository.findOne(projectId); - ProjectDto project = dozerMapper.map(projectEntity, ProjectDto.class); - project.setNumberOfApplications(getNumberOfRegistrants(projectId)); - projectDetail.setProject(project); - - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder(); - searchQueryBuilder.withQuery(nestedQuery("employers", - matchPhraseQuery("employers.userName", project.getAuthorEmail()))); - List employerEntities = companySearchResultRepository.search(searchQueryBuilder.build()).getContent(); - - if (!employerEntities.isEmpty()) { - EmployerEntity employerEntity = employerEntities.get(0); - EmployerDto employerDto = dozerMapper.map(employerEntity, EmployerDto.class); - if (!employerEntity.getEmployers().isEmpty()) { - Employer employer = employerEntity.getEmployers().get(0); - employerDto.setCreatedDate(simpleDateFormat.format(employer.getCreatedDate())); - } - projectDetail.setCompany(employerDto); + @Override + public void sendEmailAlertJobSeekerApplyJob(ProjectEntity projectEntity, ProjectRegistrantEntity projectRegistrantEntity) + throws MessagingException, IOException, TemplateException { + Template template = projectRegistrantEntity.getLang() == Language.vi ? + alertJobSeekerApplyJobMailTemplateVi : alertJobSeekerApplyJobMailTemplateEn; + String mailSubject = projectRegistrantEntity.getLang() == Language.vi ? + alertJobSeekerApplyJobMailSubjectVn : alertJobSeekerApplyJobMailSubjectEn; + mailSubject = String.format(mailSubject, projectEntity.getProjectTitle()); + Address[] emailAddress = InternetAddress.parse(projectRegistrantEntity.getRegistrantEmail()); + sendEmailAlertApplyJob(projectEntity, projectRegistrantEntity, mailSubject, emailAddress, template, false); } - return projectDetail; - } - - @Override - public long joinProject(ProjectRegistrantDto projectRegistrantDto) throws MessagingException, IOException, TemplateException { - Long projectId = projectRegistrantDto.getProjectId(); - boolean isExist = checkIfProjectRegistrantExist(projectId, projectRegistrantDto.getRegistrantEmail()); - - if (!isExist) { - ProjectRegistrantEntity projectRegistrantEntity = dozerMapper.map(projectRegistrantDto, ProjectRegistrantEntity.class); - ProjectEntity projectEntity = projectRepository.findOne(projectId); - - try { - sendEmailAlertJobSeekerApplyJob(projectEntity, projectRegistrantEntity); - sendEmailAlertEmployerApplyJob(projectEntity, projectRegistrantEntity); - projectRegistrantEntity.setMailSent(Boolean.TRUE); - } - catch (Exception ex) { - LOGGER.error(ex.getMessage(), ex); - } - - projectRegistrantEntity.setProjectRegistrantId(new Date().getTime()); - projectRegistrantRepository.save(projectRegistrantEntity); + + @Override + public void sendEmailAlertEmployerApplyJob(ProjectEntity projectEntity, ProjectRegistrantEntity projectRegistrantEntity) + throws MessagingException, IOException, TemplateException { + Template template = projectRegistrantEntity.getLang() == Language.vi ? + alertEmployerApplyJobMailTemplateVi : alertEmployerApplyJobMailTemplateEn; + String mailSubject = projectRegistrantEntity.getLang() == Language.vi ? + alertEmployerApplyJobMailSubjectVn : alertEmployerApplyJobMailSubjectEn; + mailSubject = String.format(mailSubject, projectEntity.getProjectTitle()); + Address[] emailAddress = InternetAddress.parse(projectEntity.getAuthorEmail()); + sendEmailAlertApplyJob(projectEntity, projectRegistrantEntity, mailSubject, emailAddress, template, true); + } + + @Override + public Long getNumberOfRegistrants(Long projectId) { + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withSearchType(SearchType.COUNT); + searchQueryBuilder.withFilter(FilterBuilders.termFilter("projectId", projectId)); + return projectRegistrantRepository.search(searchQueryBuilder.build()).getTotalElements(); } - return getNumberOfRegistrants(projectId); - } - - @Override - public void sendEmailAlertJobSeekerApplyJob(ProjectEntity projectEntity, ProjectRegistrantEntity projectRegistrantEntity) - throws MessagingException, IOException, TemplateException { - Template template = projectRegistrantEntity.getLang() == Language.vi ? - alertJobSeekerApplyJobMailTemplateVi : alertJobSeekerApplyJobMailTemplateEn; - String mailSubject = projectRegistrantEntity.getLang() == Language.vi ? - alertJobSeekerApplyJobMailSubjectVn : alertJobSeekerApplyJobMailSubjectEn; - mailSubject = String.format(mailSubject, projectEntity.getProjectTitle()); - Address[] emailAddress = InternetAddress.parse(projectRegistrantEntity.getRegistrantEmail()); - sendEmailAlertApplyJob(projectEntity, projectRegistrantEntity, mailSubject, emailAddress, template, false); - } - - @Override - public void sendEmailAlertEmployerApplyJob(ProjectEntity projectEntity, ProjectRegistrantEntity projectRegistrantEntity) - throws MessagingException, IOException, TemplateException { - Template template = projectRegistrantEntity.getLang() == Language.vi ? - alertEmployerApplyJobMailTemplateVi : alertEmployerApplyJobMailTemplateEn; - String mailSubject = projectRegistrantEntity.getLang() == Language.vi ? - alertEmployerApplyJobMailSubjectVn : alertEmployerApplyJobMailSubjectEn; - mailSubject = String.format(mailSubject, projectEntity.getProjectTitle()); - Address[] emailAddress = InternetAddress.parse(projectEntity.getAuthorEmail()); - sendEmailAlertApplyJob(projectEntity, projectRegistrantEntity, mailSubject, emailAddress, template, true); - } - - @Override - public Long getNumberOfRegistrants(Long projectId) { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withSearchType(SearchType.COUNT); - searchQueryBuilder.withFilter(FilterBuilders.termFilter("projectId", projectId)); - return projectRegistrantRepository.search(searchQueryBuilder.build()).getTotalElements(); - } - - private void sendEmailAlertApplyJob(ProjectEntity projectEntity, ProjectRegistrantEntity projectRegistrantEntity, - String mailSubject, Address[] recipientAddresses, Template template, boolean hasReplyTo) - throws MessagingException, IOException, TemplateException { - applyJobMailMessage.setRecipients(Message.RecipientType.TO, recipientAddresses); - - if (hasReplyTo) { - applyJobMailMessage.setReplyTo(InternetAddress.parse(projectRegistrantEntity.getRegistrantEmail())); + + private void sendEmailAlertApplyJob(ProjectEntity projectEntity, ProjectRegistrantEntity projectRegistrantEntity, + String mailSubject, Address[] recipientAddresses, Template template, boolean hasReplyTo) + throws MessagingException, IOException, TemplateException { + applyJobMailMessage.setRecipients(Message.RecipientType.TO, recipientAddresses); + + if (hasReplyTo) { + applyJobMailMessage.setReplyTo(InternetAddress.parse(projectRegistrantEntity.getRegistrantEmail())); + } else { + applyJobMailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); + } + + StringWriter stringWriter = new StringWriter(); + Map templateModel = new HashMap<>(); + templateModel.put("webBaseUrl", webBaseUrl); + templateModel.put("projectTitle", projectEntity.getProjectTitle()); + templateModel.put("projectDescription", projectEntity.getProjectDescription()); + templateModel.put("skills", StringUtils.join(projectEntity.getSkills(), "
")); + templateModel.put("payMethod", projectEntity.getPayMethod()); + templateModel.put("estimatedEndDate", projectEntity.getEstimatedEndDate()); + templateModel.put("budget", projectEntity.getBudget()); + templateModel.put("estimatedDuration", projectEntity.getEstimatedDuration()); + templateModel.put("estimatedWorkload", projectEntity.getEstimatedWorkload()); + templateModel.put("hourlyRate", projectEntity.getHourlyRate()); + templateModel.put("numberOfHires", projectEntity.getNumberOfHires()); + templateModel.put("projectId", projectEntity.getProjectId().toString()); + templateModel.put("projectAlias", projectEntity.getProjectTitle().replaceAll("\\W", "-")); + templateModel.put("authorEmail", projectEntity.getAuthorEmail()); + + if (projectRegistrantEntity != null) { + templateModel.put("registrantFirstName", projectRegistrantEntity.getRegistrantFirstName()); + templateModel.put("registrantLastName", projectRegistrantEntity.getRegistrantLastName()); + templateModel.put("registrantEmail", projectRegistrantEntity.getRegistrantEmail()); + templateModel.put("resumeLink", projectRegistrantEntity.getResumeLink()); + } + + template.process(templateModel, stringWriter); + String formatMailSubject = String.format(mailSubject, projectEntity.getProjectTitle()); + applyJobMailMessage.setSubject(MimeUtility.encodeText(formatMailSubject, "UTF-8", null)); + applyJobMailMessage.setText(stringWriter.toString(), "UTF-8", "html"); + + stringWriter.flush(); + applyJobMailMessage.saveChanges(); + mailSender.send(applyJobMailMessage); } - else { - applyJobMailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); + + public boolean checkIfProjectRegistrantExist(Long projectId, String email) { + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder(); + searchQueryBuilder.withQuery(boolQuery() + .must(matchPhraseQuery("registrantEmail", email)) + .must(termQuery("projectId", projectId)) + .must(termQuery("mailSent", true))); + + long total = projectRegistrantRepository.search(searchQueryBuilder.build()).getTotalElements(); + return (total > 0); } - StringWriter stringWriter = new StringWriter(); - Map templateModel = new HashMap<>(); - templateModel.put("webBaseUrl", webBaseUrl); - templateModel.put("projectTitle", projectEntity.getProjectTitle()); - templateModel.put("projectDescription", projectEntity.getProjectDescription()); - templateModel.put("skills", StringUtils.join(projectEntity.getSkills(), "
")); - templateModel.put("payMethod", projectEntity.getPayMethod()); - templateModel.put("estimatedEndDate", projectEntity.getEstimatedEndDate()); - templateModel.put("budget", projectEntity.getBudget()); - templateModel.put("estimatedDuration", projectEntity.getEstimatedDuration()); - templateModel.put("estimatedWorkload", projectEntity.getEstimatedWorkload()); - templateModel.put("hourlyRate", projectEntity.getHourlyRate()); - templateModel.put("numberOfHires", projectEntity.getNumberOfHires()); - templateModel.put("projectId", projectEntity.getProjectId().toString()); - templateModel.put("projectAlias", projectEntity.getProjectTitle().replaceAll("\\W", "-")); - templateModel.put("authorEmail", projectEntity.getAuthorEmail()); - - if (projectRegistrantEntity != null) { - templateModel.put("registrantFirstName", projectRegistrantEntity.getRegistrantFirstName()); - templateModel.put("registrantLastName", projectRegistrantEntity.getRegistrantLastName()); - templateModel.put("registrantEmail", projectRegistrantEntity.getRegistrantEmail()); - templateModel.put("resumeLink", projectRegistrantEntity.getResumeLink()); + + public Collection findByOwner(String owner) { + NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().withIndices(techlooperIndex).withTypes("project"); + QueryStringQueryBuilder query = QueryBuilders.queryStringQuery(owner).defaultField("authorEmail"); + queryBuilder.withFilter(FilterBuilders.queryFilter(query)); + + int pageIndex = 0; + Set projects = new HashSet<>(); + while (true) { + queryBuilder.withPageable(new PageRequest(pageIndex++, 100)); + FacetedPage page = projectRepository.search(queryBuilder.build()); + if (!page.hasContent()) { + break; + } + page.spliterator().forEachRemaining(project -> { + ProjectDto projectDto = dozerMapper.map(project, ProjectDto.class); + projectDto.setNumberOfApplications(countRegistrantsByProjectId(project.getProjectId())); + projects.add(projectDto); + }); + } + return projects; } - template.process(templateModel, stringWriter); - mailSubject = String.format(mailSubject, projectEntity.getProjectTitle()); - applyJobMailMessage.setSubject(MimeUtility.encodeText(mailSubject, "UTF-8", null)); - applyJobMailMessage.setText(stringWriter.toString(), "UTF-8", "html"); - - stringWriter.flush(); - applyJobMailMessage.saveChanges(); - mailSender.send(applyJobMailMessage); - } - - public boolean checkIfProjectRegistrantExist(Long projectId, String email) { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder(); - searchQueryBuilder.withQuery(boolQuery() - .must(matchPhraseQuery("registrantEmail", email)) - .must(termQuery("projectId", projectId)) - .must(termQuery("mailSent", true))); - - long total = projectRegistrantRepository.search(searchQueryBuilder.build()).getTotalElements(); - return (total > 0); - } - - - public Collection findByOwner(String owner) { - NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().withIndices(techlooperIndex).withTypes("project"); - QueryStringQueryBuilder query = QueryBuilders.queryStringQuery(owner).defaultField("authorEmail"); - queryBuilder.withFilter(FilterBuilders.queryFilter(query)); - - int pageIndex = 0; - Set projects = new HashSet<>(); - while (true) { - queryBuilder.withPageable(new PageRequest(pageIndex++, 100)); - FacetedPage page = projectRepository.search(queryBuilder.build()); - if (!page.hasContent()) { - break; - } - page.spliterator().forEachRemaining(project -> { - ProjectDto projectDto = dozerMapper.map(project, ProjectDto.class); - projectDto.setNumberOfApplications(countRegistrantsByProjectId(project.getProjectId())); - projects.add(projectDto); - }); + public Collection findRegistrantsByProjectId(Long projectId) { + NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().withIndices(techlooperIndex).withTypes("projectRegistrant"); + queryBuilder.withFilter(FilterBuilders.queryFilter(QueryBuilders.termQuery("projectId", projectId))); + + int pageIndex = 0; + Set registrants = new HashSet<>(); + while (true) { + queryBuilder.withPageable(new PageRequest(pageIndex++, 100)); + FacetedPage page = projectRegistrantRepository.search(queryBuilder.build()); + if (!page.hasContent()) { + break; + } + page.spliterator().forEachRemaining(registrant -> registrants.add(dozerMapper.map(registrant, ProjectRegistrantDto.class))); + } + return registrants; } - return projects; - } - - public Collection findRegistrantsByProjectId(Long projectId) { - NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().withIndices(techlooperIndex).withTypes("projectRegistrant"); - queryBuilder.withFilter(FilterBuilders.queryFilter(QueryBuilders.termQuery("projectId", projectId))); - - int pageIndex = 0; - Set registrants = new HashSet<>(); - while (true) { - queryBuilder.withPageable(new PageRequest(pageIndex++, 100)); - FacetedPage page = projectRegistrantRepository.search(queryBuilder.build()); - if (!page.hasContent()) { - break; - } - page.spliterator().forEachRemaining(registrant -> registrants.add(dozerMapper.map(registrant, ProjectRegistrantDto.class))); + + public Long countRegistrantsByProjectId(Long projectId) { + NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().withIndices(techlooperIndex).withTypes("projectRegistrant"); + queryBuilder.withFilter(FilterBuilders.queryFilter(QueryBuilders.termQuery("projectId", projectId))).withSearchType(SearchType.COUNT); + return projectRegistrantRepository.search(queryBuilder.build()).getTotalElements(); } - return registrants; - } - - public Long countRegistrantsByProjectId(Long projectId) { - NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().withIndices(techlooperIndex).withTypes("projectRegistrant"); - queryBuilder.withFilter(FilterBuilders.queryFilter(QueryBuilders.termQuery("projectId", projectId))).withSearchType(SearchType.COUNT); - return projectRegistrantRepository.search(queryBuilder.build()).getTotalElements(); - } } diff --git a/src/main/java/com/techlooper/service/impl/SuggestionServiceImpl.java b/src/main/java/com/techlooper/service/impl/SuggestionServiceImpl.java index cc03812dc..d6e42632c 100644 --- a/src/main/java/com/techlooper/service/impl/SuggestionServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/SuggestionServiceImpl.java @@ -1,7 +1,6 @@ package com.techlooper.service.impl; import com.techlooper.service.SuggestionService; -import org.apache.commons.lang3.StringUtils; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.index.query.QueryBuilders; @@ -15,7 +14,8 @@ import java.util.function.Function; import java.util.stream.Collectors; -import static org.apache.commons.lang3.StringUtils.*; +import static org.apache.commons.lang3.StringUtils.strip; +import static org.apache.commons.lang3.StringUtils.trim; /** * Created by NguyenDangKhoa on 5/29/15. diff --git a/src/main/java/com/techlooper/service/impl/UserServiceImpl.java b/src/main/java/com/techlooper/service/impl/UserServiceImpl.java index 0b3808c40..2d2eb2085 100644 --- a/src/main/java/com/techlooper/service/impl/UserServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/UserServiceImpl.java @@ -187,6 +187,7 @@ public int addCrawledUserAll(List users, SocialProvider social } else { shouldBeSavedUsers.add(user); } + break; default: //MERGE if (userImportEntity != null) { userImportEntity.mergeProfile(socialProvider, user.getProfiles().get(socialProvider)); @@ -194,6 +195,7 @@ public int addCrawledUserAll(List users, SocialProvider social } else { shouldBeSavedUsers.add(user); } + break; } } catch (Exception ex) { LOGGER.error("User Import Fail : " + user.getEmail(), ex); @@ -248,13 +250,14 @@ public TalentSearchResponse findTalent(TalentSearchRequest param) { TalentSearchDataProcessor talentSearchDataProcessor = applicationContext.getBean(socialProvider + "TalentSearchDataProcessor", TalentSearchDataProcessor.class); + TalentSearchRequest customizedParam = param; if (param != null) { talentSearchDataProcessor.normalizeInputParameter(param); } else { - param = talentSearchDataProcessor.getSearchAllRequestParameter(); + customizedParam = talentSearchDataProcessor.getSearchAllRequestParameter(); } - FacetedPage pageResult = talentSearchRepository.search(talentSearchQuery.getSearchQuery(param)); + FacetedPage pageResult = talentSearchRepository.search(talentSearchQuery.getSearchQuery(customizedParam)); builder.withTotal(pageResult.getTotalElements()); builder.withResult(talentSearchDataProcessor.process(pageResult.getContent())); } diff --git a/src/main/java/com/techlooper/service/impl/VietnamWorksJobSearchService.java b/src/main/java/com/techlooper/service/impl/VietnamWorksJobSearchService.java index 524c39c82..eef30d084 100644 --- a/src/main/java/com/techlooper/service/impl/VietnamWorksJobSearchService.java +++ b/src/main/java/com/techlooper/service/impl/VietnamWorksJobSearchService.java @@ -179,8 +179,9 @@ private String translateConfigurationId(String id, String itemType, VNWConfigura .filter(item -> item.getDegreeId().equals(id)) .findFirst(); return degreeOptional.isPresent() ? degreeOptional.get().getEnglish() : EMPTY; + default: + return EMPTY; } - return EMPTY; } public List getHigherSalaryJobs(SalaryReviewEntity salaryReviewEntity) { @@ -214,14 +215,14 @@ private int jobSalaryComparator(JobEntity job1, JobEntity job2, int sortOrder) { } public Double getAverageSalary(Long salaryMin, Long salaryMax) { - salaryMin = convertVND2ToUSD(salaryMin); - salaryMax = convertVND2ToUSD(salaryMax); - if (salaryMin == 0) { - return salaryMax * 0.75D; - } else if (salaryMax == 0) { - return salaryMin * 1.25D; + Long salaryMinUsd = convertVND2ToUSD(salaryMin); + Long salaryMaxUsd = convertVND2ToUSD(salaryMax); + if (salaryMinUsd == 0) { + return salaryMaxUsd * 0.75D; + } else if (salaryMaxUsd == 0) { + return salaryMinUsd * 1.25D; } - return (salaryMin + salaryMax) / 2D; + return (salaryMinUsd + salaryMaxUsd) / 2D; } @Override diff --git a/src/main/java/com/techlooper/util/DataUtils.java b/src/main/java/com/techlooper/util/DataUtils.java index 6e95cc172..243adee4b 100644 --- a/src/main/java/com/techlooper/util/DataUtils.java +++ b/src/main/java/com/techlooper/util/DataUtils.java @@ -1,31 +1,50 @@ 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.List; +import java.util.*; /** * 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(20L).build()); + defaultCriterias.add(ChallengeCriteria.ChallengeCriteriaBuilder.challengeCriteria() + .withName("Creativity on the proposed solution").withWeight(20L).build()); + defaultCriterias.add(ChallengeCriteria.ChallengeCriteriaBuilder.challengeCriteria() + .withName("Source code quality").withWeight(20L).build()); + defaultCriterias.add(ChallengeCriteria.ChallengeCriteriaBuilder.challengeCriteria() + .withName("Usage of top edge technology").withWeight(20L).build()); + defaultCriterias.add(ChallengeCriteria.ChallengeCriteriaBuilder.challengeCriteria() + .withName("Application functionality").withWeight(20L).build()); + return defaultCriterias; + } + + public static String generateStringId() { + return UUID.randomUUID().toString(); + } } diff --git a/src/main/java/com/techlooper/util/ExcelUtils.java b/src/main/java/com/techlooper/util/ExcelUtils.java index 163c49a08..94ad754f4 100644 --- a/src/main/java/com/techlooper/util/ExcelUtils.java +++ b/src/main/java/com/techlooper/util/ExcelUtils.java @@ -13,7 +13,10 @@ import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; -import java.util.*; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; /** * Created by NguyenDangKhoa on 5/6/15. diff --git a/src/main/java/com/techlooper/util/JsonUtils.java b/src/main/java/com/techlooper/util/JsonUtils.java index e8d3d1c00..ebcc37e8d 100644 --- a/src/main/java/com/techlooper/util/JsonUtils.java +++ b/src/main/java/com/techlooper/util/JsonUtils.java @@ -3,7 +3,6 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.CollectionType; -import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/main/test/resources/google-auth/StoredCredential b/src/main/test/resources/google-auth/StoredCredential deleted file mode 100644 index c5975123e..000000000 Binary files a/src/main/test/resources/google-auth/StoredCredential and /dev/null differ diff --git a/src/main/webapp/assets/images/ic-navi-job-seeker.png b/src/main/webapp/assets/images/ic-navi-job-seeker.png index ae14934c4..9e9733254 100644 Binary files a/src/main/webapp/assets/images/ic-navi-job-seeker.png and b/src/main/webapp/assets/images/ic-navi-job-seeker.png differ 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/apiService.js b/src/main/webapp/assets/modules/common/apiService.js index 3386d0b6e..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); + }); + }); }, /** @@ -258,6 +266,36 @@ techlooper.factory("apiService", function ($rootScope, $location, jsonValue, $ht * */ getUrlResponseCode: function (url) { return $http.post("resource/getUrlResponseCode", {url: url}, {transformResponse: function (d, h) {return d;}}); + }, + + saveEmailSetting: function (emailSetting) { + return $http.post("user/employer/saveEmailSetting", emailSetting); + }, + + loadEmailSetting: function () { + return $http.get("user/employer/emailSetting"); + }, + + getAvailableEmailTemplates : function () { + return $http.get("emailTemplates"); + }, + + 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); } }; 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; } } 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/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) { diff --git a/src/main/webapp/assets/modules/common/feedback/feedback.html b/src/main/webapp/assets/modules/common/feedback/feedback.html index c41067334..c575a790a 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 @@
+
+ +
+ +
+
@@ -28,5 +36,4 @@
- diff --git a/src/main/webapp/assets/modules/common/feedback/feedbackDirective.js b/src/main/webapp/assets/modules/common/feedback/feedbackDirective.js index 32a297e4a..a31e36464 100644 --- a/src/main/webapp/assets/modules/common/feedback/feedbackDirective.js +++ b/src/main/webapp/assets/modules/common/feedback/feedbackDirective.js @@ -33,6 +33,7 @@ techlooper.directive("feedbackForm", function (apiService, $timeout) { scope.composeEmail.error = false; }); } + scope.cancel = function () { if (!scope.composeEmail.visible) return; scope.composeEmail.subject = ''; @@ -41,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/json.val.js b/src/main/webapp/assets/modules/common/json.val.js index afae4d3e3..66ad2618e 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: [ @@ -1043,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/common/model/challengeDetail.js b/src/main/webapp/assets/modules/common/model/challengeDetail.js new file mode 100644 index 000000000..3d16392cc --- /dev/null +++ b/src/main/webapp/assets/modules/common/model/challengeDetail.js @@ -0,0 +1,63 @@ +techlooper.filter("challengeDetail", function (apiService, $rootScope, utils) { + return function (input, type) { + if (!input || input.$isRich) return input; + + var challengeDetail = input; + + challengeDetail.saveCriteria = function () { + //if (challengeDetail.$invalidCriteria) return; + var criteria = { + challengeId: challengeDetail.challengeId, + challengeCriteria: challengeDetail.criteria + } + delete challengeDetail.$savedCriteria; + + apiService.saveChallengeCriteria(criteria) + .success(function (data) { + $rootScope.$broadcast("saveChallengeCriteriaSuccessful", data); + challengeDetail.$savedCriteria = true; + }) + .error(function () { + challengeDetail.$savedCriteria = false; + }); + } + + 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;}) + } + + challengeDetail.caculateTotalWeight = function () { + var total = _.reduceRight(challengeDetail.criteria, function (sum, cri) { return sum + cri.weight; }, 0); + return total; + } + + challengeDetail.criteriaLoop = function () { + var criteria = challengeDetail.criteria; + if (!criteria) return []; + challengeDetail.totalWeight = 0; + return criteria.map(function (cri) { + 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.validate = function () { + delete challengeDetail.$invalid; + $.each(challengeDetail.criteria, function (i, cri) { + challengeDetail.$invalid = (!cri.name); + return !challengeDetail.$invalid; + }); + } + + 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..e00584589 --- /dev/null +++ b/src/main/webapp/assets/modules/common/model/challengeRegistrant.js @@ -0,0 +1,61 @@ +techlooper.filter("challengeRegistrant", function (apiService, $rootScope, $filter) { + return function (input, type) { + if (!input || input.$isRich) return input; + + var registrant = input; + + registrant.criteriaLoop = function () { + var criteria = registrant.criteria; + if (!criteria) return []; + registrant.totalPoint = 0; + return criteria.map(function (cri) { + cri.point = $filter('number')((cri.weight / 100) * cri.score, 1); + registrant.totalPoint += parseFloat(cri.point); + return cri; + }); + }; + + registrant.validate = function () { + delete registrant.$invalid; + $.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, + criteria: registrant.criteria + } + delete registrant.$savedCriteria; + apiService.saveChallengeRegistrantCriteria(criteria) + .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); + } + }); + 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; + } +}); \ 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 084c7794a..a8bf2411d 100644 --- a/src/main/webapp/assets/modules/common/resourcesService.js +++ b/src/main/webapp/assets/modules/common/resourcesService.js @@ -1,9 +1,18 @@ -techlooper.factory("resourcesService", function ($translate, $q) { +techlooper.factory("resourcesService", function ($translate, $q, apiService) { var registrantsFilterOptions = [ {translate: "allContestants", id: "registrantId"}, {translate: "allSubmission", id: "challengeSubmission"} ]; + var registrantsPhaseOptions = [ + {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"} ]; @@ -15,6 +24,26 @@ techlooper.factory("resourcesService", function ($translate, $q) { {translate: "theSolutionIsInnovative", id: "theSolutionIsInnovative"} ]; + var emailTemplateOptions = [ + {translate: "chooseATemplate", id: 0}, + {translate: "welcomeContestant", id: 1}, + {translate: "askContestantSubmission", id: 2}, + {translate: "disqualifyContestant", id: 3} + ]; + + //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"}, {translate: "fixedPricePayByProject", reviewTranslate: "fixedPrice", id: "fixedPrice"} @@ -74,11 +103,13 @@ 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")), estimatedDurationConfig: $.extend(true, {}, {options: estimatedDurationOptions}, idSelectize("estimatedDurationConfig")), estimatedWorkloadConfig: $.extend(true, {}, {options: estimatedWorkloadOptions}, idSelectize("estimatedWorkloadConfig")), + emailTemplateConfig: $.extend(true, {}, {options: emailTemplateOptions}, idSelectize("emailTemplateConfig")), inOptions: function (title, config) { var index = -1; $.each(config.options, function (i, opt) { @@ -105,11 +136,13 @@ 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"}, {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/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/challengeCriteriaInput.html b/src/main/webapp/assets/modules/contest-detail/challengeCriteriaInput.html new file mode 100644 index 000000000..8952bb154 --- /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..c62e56df0 --- /dev/null +++ b/src/main/webapp/assets/modules/contest-detail/challengeCriteriaInputDirective.js @@ -0,0 +1,15 @@ +techlooper.directive('challengeCriteriaInput', function () { + return { + restrict: "E", + replace: true, + templateUrl: "modules/contest-detail/challengeCriteriaInput.html", + scope: { + cri: "=", + contestDetail: "=" + }, + link: function (scope, element, attr, ctrl) { + //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/contestDetail.html b/src/main/webapp/assets/modules/contest-detail/contestDetail.html index 6ffb3e0e7..a5fcb03c8 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'}} +

@@ -9,6 +12,9 @@

{{contestDetail.challengeName}}

  • {{'registrants' | translate}} ({{contestDetail.numberOfRegistrants}})
  • +
  • + +
  • @@ -45,7 +51,12 @@

    {{contestDetail.challengeName}}

    -

    +

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

    @@ -235,18 +246,21 @@

    +

    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/contestDetailController.js b/src/main/webapp/assets/modules/contest-detail/contestDetailController.js index 60d1cb2c7..be0d83b40 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 { @@ -213,21 +222,24 @@ 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 + 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' }); + + $scope.saveChallengeCriteria = function() { + $scope.contestDetail.validate(); + if($scope.contestDetail.totalWeight > 100 || $scope.contestDetail.$invalid){ + 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 5057cc948..2a54eebab 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"); } @@ -54,20 +58,28 @@ 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.hide = function() { + 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; }; - 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; @@ -79,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); @@ -94,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'); } } @@ -120,12 +132,21 @@ techlooper } }; }) - .directive('acceptance', function () { - return { - restrict: "E", - replace: true, - templateUrl: "modules/contest-detail/contestDetailAcceptance.html", - link: function (scope, element, attr, ctrl) { - } - }; -}); \ No newline at end of file + .directive('acceptance', function () { + return { + restrict: "E", + replace: true, + templateUrl: "modules/contest-detail/contestDetailAcceptance.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 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..d9a04b3e0 --- /dev/null +++ b/src/main/webapp/assets/modules/contest-detail/contestDetailScore.html @@ -0,0 +1,61 @@ +
    +
    + +
      +
    • +
      +

      +
      +
      +

      +
      +
      +

      +
      +
      +

      +
      +
    • +
    • +
      + + {{cri.name}} +
      +
      + + {{cri.weight}} + x +
      +
      + + + = +
      +
      + + {{ cri.point }} +
      +
      + +
      +
    • +
    • +
      +
      +
      +
      + || + {{registrant.totalPoint}} +
      +

      +
      + + +
      +
      +
    • +
    +
    +
    +
    \ 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 new file mode 100644 index 000000000..22f25ac0d --- /dev/null +++ b/src/main/webapp/assets/modules/contest-detail/contestDetailScoreDirective.js @@ -0,0 +1,17 @@ +techlooper.directive('contestDetailScore', function () { + return { + restrict: "E", + replace: true, + templateUrl: "modules/contest-detail/contestDetailScore.html", + link: function (scope, element, attr, ctrl) { + scope.saveScore = function() { + scope.registrant.validate(); + if (scope.registrant.$invalid) { + return; + } + + 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 new file mode 100644 index 000000000..36baed438 --- /dev/null +++ b/src/main/webapp/assets/modules/contest-detail/evaluationCriteria.html @@ -0,0 +1,42 @@ +
    +

    + +
    +

    +
    + + + +
    +
    +

    +
    +
    +

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

    +
    +
    + +
    +
    +
    +
    +
    \ 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 new file mode 100644 index 000000000..18c48f273 --- /dev/null +++ b/src/main/webapp/assets/modules/email-setting/email-setting.html @@ -0,0 +1,44 @@ + diff --git a/src/main/webapp/assets/modules/translation/messages_en.json b/src/main/webapp/assets/modules/translation/messages_en.json index cb6d2d6e6..475201b7a 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: *", @@ -772,7 +774,35 @@ "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." + "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", + "winnerAnnouncement": "Winner announcement", + "exChooseATemplate": "Choose a template", + "points": "Points", + "comment": "Comment", + "totalPoints": "Total Points", + "contestantsReturned": "{{number}} contestant(s) returned", + "evaluationCriteria": "Evaluation Criteria", + "criteriaName": "Criteria Name", + "criteriaWeight": "Weight %", + "criteriaTotalWeight": "Total weight %", + "maximumScore": "Maximum Score", + "emailSetting": "Email Setting", + "replyTo": "Reply-To Email Address: *", + "emailSignature": "Email Signature:", + "evaluationCriteriaDes": "Input scoring criteria and their weight that will be used for final score calculation", + "addCriteria": "Add Criteria", + "makeSure100Percent": "Make sure total weight is 100%", + "givenPoints": "Given Points", + "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.", + "errorTotalWeight": "Total weight must be 100%." } \ 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..95034a1d0 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": "Mọi giai đoạn", "prototype": "Prototype", "idea": "Ý Tưởng", "uiux": "UI/UX", + "exRegistrantsPhaseConfig": "Mọi giai đoạn", "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: *", @@ -777,6 +779,22 @@ "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": "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", + "winnerAnnouncement": "Winner announcement", + "exChooseATemplate": "Lựa chọn mẫu Email", + "points": "Điểm", + "comment": "Nhận xét", + "totalPoints": "Tổng Điểm", + "contestantsReturned": "Tìm thấy {{number}} thí sinh", + "evaluationCriteria": "Tiêu Chí Đánh Giá", + "criteriaName": "Tiêu Chí", + "criteriaWeight": "Trọng Số %", + "criteriaTotalWeight": "Tổng Trọng Số %", + "maximumScore": "Điểm Tối Đa" } diff --git a/src/main/webapp/assets/sass/contest-detail.sass b/src/main/webapp/assets/sass/contest-detail.sass index 3bfa3cf70..0449cbff5 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 @@ -244,11 +262,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% @@ -273,9 +294,12 @@ .registrants-paging display: inline-block clear: both - text-align: right + text-align: left width: 100% padding: 0 10px + ul.pagination + float: right + table.contests-table margin: 5px 0 10px 0 td @@ -368,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 @@ -536,8 +563,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 +582,8 @@ .form-group margin: 0 padding: 0 20px + input + border-radius: 4px .note-editor background-color: #fff min-height: 200px @@ -575,7 +610,152 @@ 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 + .label-col + display: none + p + margin: 0 + padding: 0 + .points-name + width: 25% + float: left + display: inline-block + .weight-input + width: 8% + float: left + span + height: 34px + line-height: 34px + text-align: center + span.points + border: 1px solid #d4d7d8 + border-radius: 5px + padding: 0 10px + width: 60% + display: inline-block + background-color: #fff + span.math + width: 40px + text-align: center + padding-left: 8px + .points-input + width: 10% + float: left + display: inline-block + padding: 0 5px + input + width: 75% + float: left + text-align: center + span + height: 34px + line-height: 34px + text-align: center + float: right + display: inline-block + span.math + width: 15px + .all-points + width: 5% + float: left + input + width: 75% + float: left + max-width: 45px + span + height: 34px + line-height: 34px + text-align: center + span.points + border: 1px solid #d4d7d8 + border-radius: 5px + padding: 0 10px + width: 100% + display: inline-block + background-color: #fff + .points-comment + width: 52% + float: left + display: inline-block + padding-left: 10px + 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 + li.header + font-weight: 400 + border-bottom: 1px solid #fff + .points-input + width: 10% + padding-right: 15px + li.total + text-align: right + .points-comment + width: 57% + float: right + text-align: left + padding-left: 0 + .score + width: 10% + float: left + span + clear: both + width: 100% + display: inline-block + text-align: center + span.math + padding-bottom: 10px + max-width: 45px + span.points + border: 1px solid #d4d7d8 + border-radius: 5px + padding: 0 10px + width: 100% + display: inline-block + background-color: #fff + height: 34px + line-height: 34px + max-width: 45px + p + width: 90% + float: left + clear: none + padding: 36px 0 0 5px + .submission-criteria + clear: both + width: 100% + display: inline-block + text-align: right + padding-top: 20px + a + margin: auto auto auto 5px .submit-phase-contest.show height: 280px background-color: #f1f2f7 @@ -583,8 +763,6 @@ padding: 10px 20px margin-top: 10px float: left - - .col-md-12 padding: 0 .contest-content-item @@ -796,4 +974,121 @@ .popover.top > .arrow border-top-color: #fff .alert - margin-top: 20px \ No newline at end of file + margin-top: 20px + .evaluation-criteria + width: 100% + clear: both + padding: 0 20px + .evaluation-criteria-head + width: 100% + display: inline-block + padding: 10px 0 0 0 + font-weight: 500 + clear: both + .evaluation-criteria-body + width: 100% + clear: both + display: inline-block + .evaluation-criteria-item + display: inline-block + clear: both + width: 100% + padding: 5px 0 + .add-criteria-and-save + width: 100% + clear: both + padding-top: 5px + display: inline-block + .add-criteria + float: left + width: 30% + a + font-weight: 500 + .save-evaluation-criteria + width: 70% + float: left + text-align: right + input + width: 80px + float: right + clear: none + span + width: 53px + float: right + font-size: 30px + line-height: 100% + text-align: center + padding-left: 15px + i + margin-top: -5px + span.total-points + background-color: white + border: 1px solid #337ab7 + border-radius: 5px + display: inline-block + padding: 10px + color: #337ab7 + width: 78px + font-size: 14px + font-weight: 500 + span.total-points-fail + border: 1px solid red + color: red + span.successful + color: #337ab7 + span.fail + color: red + p + width: auto + float: right + clear: both + p.error-messages + color: red + font-style: italic + font-size: 12px + .save-evaluation + width: 100% + clear: both + display: inline-block + padding: 30px 0 0 0 + text-align: right + a + margin: auto auto auto 10px + padding: 6px 30px + height: 32px + .evaluation-criteria-name + width: 85% + float: left + padding-right: 10px + .evaluation-criteria-weight + width: 15% + float: left + padding-left: 5px + input + width: 60% + margin-right: 10px + text-align: center + float: left + button + padding: 4px 10px + width: 30% + height: 32px + float: right + button.remove + background-color: #fff + color: #333 + button.add + background-color: #337ab7 + color: #fff + .evaluation-criteria-total-weight + width: 50% + float: left + padding-right: 10px + input + text-align: center + .evaluation-criteria-maximum-score + width: 50% + float: left + input + text-align: center + width: 50% \ No newline at end of file diff --git a/src/main/webapp/assets/sass/home.sass b/src/main/webapp/assets/sass/home.sass index 29ea008ba..e56417aed 100644 --- a/src/main/webapp/assets/sass/home.sass +++ b/src/main/webapp/assets/sass/home.sass @@ -401,6 +401,8 @@ a.post-evaluation background-position: 0 -416px padding-left: 30px + a.email-setting + background-position: 0 -635px a.no-icon background: transparent padding-left: 0 @@ -417,6 +419,32 @@ li.here background-color: #f4f4f4 border-top: 1px solid #d1d1d1 + li.mobile + display: none + li.first + position: relative + .sub-menu + display: none + position: absolute + left: 0 + right: 0 + top: 39px + background-color: #fff + border: 1px solid #d1d1d1 + z-index: 999 + width: 200px + a + color: #333 + text-align: left + padding: 10px 10px 10px 45px + a.email-setting + background-position: 10px -631px + border-bottom: 1px solid #d1d1d1 + a.sign-out + background-position: 10px -677px + li.first:hover + .sub-menu + display: block .ic-menu-mobile display: none .no-submenu diff --git a/src/main/webapp/assets/sass/main.sass b/src/main/webapp/assets/sass/main.sass index c2f56be34..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 @@ -70,10 +73,15 @@ textarea.change-color color: #0573c7 !important .gray background-color: #dfdede +.btn-primary.gray + background-color: #dfdede + text-shadow: inherit + color: #333 !important +.btn-primary.gray:hover + background-color: #dfdede !important .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 +2284,43 @@ 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 + font-weight: 500 + strong + font-weight: 500 + color: red + .form-group + width: 100% + clear: both + display: inline-block + label + width: 100% + clear: both + input + width: 100% + margin: 0 + .error-messages + text-align: left + .mail-text + border: 0 + text-align: left + .mail-body + border: 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 508046bab..772065358 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 @@ -1400,9 +1405,62 @@ label width: 100% 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: 35% + padding-left: 0 + .all-points + width: 30% + .points-comment + 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 + .evaluation-criteria + padding: 0 5px + .evaluation-criteria-name + width: 60% + .evaluation-criteria-weight + width: 40% + .evaluation-criteria-body + .add-criteria-and-save + .save-evaluation + a + padding: 6px 15px .contestant-page table.contests-table border: 0 @@ -1832,6 +1890,11 @@ padding-left: 45px a.post-evaluation padding-left: 45px + li.mobile + display: block + li.first:hover + .sub-menu + display: none .header-site height: auto .personal-header-block @@ -2112,7 +2175,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 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/config/DozerBeanConfigurationTest.java b/src/test/java/com/techlooper/config/DozerBeanConfigurationTest.java new file mode 100644 index 000000000..b4c064343 --- /dev/null +++ b/src/test/java/com/techlooper/config/DozerBeanConfigurationTest.java @@ -0,0 +1,101 @@ +package com.techlooper.config; + +import com.techlooper.converter.ListCSVStringConverter; +import com.techlooper.converter.LocaleConverter; +import com.techlooper.converter.ProfileNameConverter; +import com.techlooper.dto.WebinarInfoDto; +import com.techlooper.entity.*; +import com.techlooper.model.*; +import org.dozer.DozerBeanMapper; +import org.dozer.Mapper; +import org.dozer.loader.api.BeanMappingBuilder; +import org.dozer.loader.api.FieldsMappingOptions; +import org.dozer.loader.api.TypeMappingOptions; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.social.facebook.api.FacebookProfile; +import org.springframework.social.google.api.plus.Person; + +/** + * Created by phuonghqh on 10/20/15. + */ +@Configuration +public class DozerBeanConfigurationTest { + + @Bean + public Mapper dozerBeanMapper() { + DozerBeanMapper dozerBeanMapper = new DozerBeanMapper(); + dozerBeanMapper.addMapping(new BeanMappingBuilder() { + protected void configure() { + mapping(FacebookProfile.class, com.techlooper.entity.FacebookProfile.class) + .fields("locale", "locale", FieldsMappingOptions.customConverter(LocaleConverter.class)); + + mapping(TwitterProfile.class, com.techlooper.entity.UserEntity.class, TypeMappingOptions.oneWay()) + .fields("name", "firstName", FieldsMappingOptions.copyByReference()) + .fields("screenName", "userName", FieldsMappingOptions.copyByReference()); + + mapping(GitHubUserProfile.class, com.techlooper.entity.UserEntity.class, TypeMappingOptions.oneWay()) + .fields("name", "firstName", FieldsMappingOptions.copyByReference()) + .fields("email", "emailAddress", FieldsMappingOptions.copyByReference()); + + mapping(Person.class, com.techlooper.entity.UserEntity.class, TypeMappingOptions.oneWay()) + .fields("givenName", "firstName", FieldsMappingOptions.copyByReference()) + .fields("familyName", "lastName", FieldsMappingOptions.copyByReference()) + .fields("accountEmail", "emailAddress", FieldsMappingOptions.copyByReference()) + .fields("imageUrl", "profileImageUrl", FieldsMappingOptions.copyByReference()); + + mapping(com.techlooper.entity.FacebookProfile.class, com.techlooper.entity.UserEntity.class, TypeMappingOptions.oneWay()) + .fields("email", "emailAddress", FieldsMappingOptions.copyByReference()); + + mapping(LinkedInProfile.class, com.techlooper.entity.UserEntity.class, TypeMappingOptions.oneWay()) + .fields("profilePictureUrl", "profileImageUrl", FieldsMappingOptions.copyByReference()); + + mapping(UserEntity.class, UserInfo.class, TypeMappingOptions.oneWay()) + .fields("profiles", "profileNames", FieldsMappingOptions.customConverter(ProfileNameConverter.class)); + + mapping(UserInfo.class, UserEntity.class, TypeMappingOptions.oneWay()) + .fields("profileNames", "profiles", FieldsMappingOptions.customConverter(ProfileNameConverter.class)); + + mapping(UserEntity.class, VnwUserProfile.class).exclude("accessGrant"); + + mapping(SalaryReviewEntity.class, VNWJobSearchRequest.class) + .fields("jobLevelIds", "jobLevel") + .fields("jobCategories", "jobCategories", FieldsMappingOptions.customConverter(ListCSVStringConverter.class)) + .fields("netSalary", "jobSalary") + .fields("locationId", "jobLocation"); + + mapping(VnwJobAlert.class, VnwJobAlertRequest.class) + .fields("jobLocations", "locationId", FieldsMappingOptions.customConverter(ListCSVStringConverter.class)) + .fields("minSalary", "netSalary"); + + mapping(WebinarInfoDto.class, WebinarEntity.class, TypeMappingOptions.oneWay()) + .exclude("createdDateTime"); + + mapping(ScrapeJobEntity.class, VNWJobSearchResponseDataItem.class) + .fields("jobTitle", "title") + .fields("jobTitleUrl", "url") + .fields("companyLogoUrl", "logoUrl") + .fields("createdDateTime", "postedOn"); + + mapping(ScrapeJobEntity.class, JobResponse.class) + .fields("jobTitle", "title") + .fields("jobTitleUrl", "url") + .fields("createdDateTime", "postedOn") + .fields("companyLogoUrl", "logoUrl"); + + mapping(ChallengeEntity.class, ChallengeDto.class) + .fields("startDateTime", "startDate") + .fields("submissionDateTime", "submissionDate") + .fields("registrationDateTime", "registrationDate") + .fields("ideaSubmissionDateTime", "ideaSubmissionDate") + .fields("uxSubmissionDateTime", "uxSubmissionDate") + .fields("prototypeSubmissionDateTime", "prototypeSubmissionDate"); + + mapping(ChallengeRegistrantDto.class, ChallengeRegistrantEntity.class, TypeMappingOptions.oneWay()) + .exclude("activePhase"); + + } + }); + return dozerBeanMapper; + } +} 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..ac9cfe2b3 --- /dev/null +++ b/src/test/java/com/techlooper/service/impl/ChallengeCriteriaServiceImplTest.java @@ -0,0 +1,133 @@ +package com.techlooper.service.impl; + +import com.techlooper.config.BaseConfigurationTest; +import com.techlooper.config.DozerBeanConfigurationTest; +import com.techlooper.config.ElasticsearchConfiguration; +import com.techlooper.entity.ChallengeCriteria; +import com.techlooper.entity.ChallengeEntity; +import com.techlooper.entity.ChallengeRegistrantCriteria; +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.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, DozerBeanConfigurationTest.class, ElasticsearchConfiguration.class}) +public class ChallengeCriteriaServiceImplTest { + + private ChallengeCriteriaService challengeCriteriaService; + + private ChallengeService challengeService; + + @Resource + private ChallengeRepository challengeRepository; + + @Resource + private ChallengeRegistrantRepository challengeRegistrantRepository; + + @Resource + private Mapper dozerMapper; + + @Before + public void before() { + challengeService = new ChallengeServiceImpl(); + ReflectionTestUtils.setField(challengeService, "challengeRepository", challengeRepository); + + challengeCriteriaService = new ChallengeCriteriaServiceImpl(); + ReflectionTestUtils.setField(challengeCriteriaService, "challengeService", challengeService); + ReflectionTestUtils.setField(challengeCriteriaService, "challengeRegistrantRepository", challengeRegistrantRepository); + ReflectionTestUtils.setField(challengeCriteriaService, "challengeRepository", challengeRepository); + ReflectionTestUtils.setField(challengeCriteriaService, "dozerMapper", dozerMapper); + } + + @Test + public void testEmpty() { + } + + public void testSaveChallengeCriteria() { + Long id = 1436339203843L; + String owner = "thu.hoang@navigosgroup.com"; + + Set defaultCriterias = new HashSet<>(); + defaultCriterias.add(ChallengeCriteria.ChallengeCriteriaBuilder.challengeCriteria() + .withName("UI/UX implemented solution").withWeight(25L).withCriteriaId("1").build()); + defaultCriterias.add(ChallengeCriteria.ChallengeCriteriaBuilder.challengeCriteria() + .withName("Creativity on the proposed solution").withWeight(25L).withCriteriaId("2").build()); + defaultCriterias.add(ChallengeCriteria.ChallengeCriteriaBuilder.challengeCriteria() + .withName("Source code quality").withWeight(25L).withCriteriaId("3").build()); + defaultCriterias.add(ChallengeCriteria.ChallengeCriteriaBuilder.challengeCriteria() + .withName("Usage of top edge technology").withWeight(25L).withCriteriaId("4").build()); + defaultCriterias.add(ChallengeCriteria.ChallengeCriteriaBuilder.challengeCriteria() + .withName("Application functionality").withWeight(25L).withCriteriaId("5").build()); + + Long registrantId = 27L; + ChallengeRegistrantEntity registrant = challengeRegistrantRepository.findOne(registrantId); + long notNullScoreCount = registrant.getCriteria().stream().filter(cri -> cri.getScore() != null).count(); + + ChallengeCriteriaDto challengeCriteriaDto = ChallengeCriteriaDto.ChallengeCriteriaDtoBuilder.challengeCriteriaDto() + .withChallengeId(id).withChallengeCriteria(defaultCriterias).build(); + + challengeCriteriaDto = challengeCriteriaService.saveChallengeCriteria(challengeCriteriaDto, owner); + ChallengeEntity challenge = challengeRepository.findOne(id); + Assert.assertEquals(challenge.getCriteria().size(), defaultCriterias.size()); + + challengeCriteriaDto.getRegistrantCriteria().forEach(registrantCriteria -> { + Assert.assertEquals(registrantCriteria.getCriteria().size(), defaultCriterias.size()); + }); + + registrant = challengeRegistrantRepository.findOne(registrantId); + if (registrant != null) { + Assert.assertEquals(registrant.getCriteria().size(), registrant.getCriteria().size()); + long newNotNullScoreCount = registrant.getCriteria().stream().filter(cri -> cri.getScore() != null).count(); + Assert.assertEquals(newNotNullScoreCount, notNullScoreCount); + } + } + + 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").withWeight(100L).build(); + challengeCriteria.add(sampleCriteria); + challenge = challengeRepository.save(challenge); + + ChallengeCriteriaDto challengeCriteriaDto = ChallengeCriteriaDto.ChallengeCriteriaDtoBuilder.challengeCriteriaDto() + .withChallengeId(id).withChallengeCriteria(challengeCriteria).build(); + challengeCriteriaService.saveChallengeCriteria(challengeCriteriaDto, owner); + + Long registrantId = 27L; + ChallengeRegistrantEntity registrant = challengeRegistrantRepository.findOne(registrantId); + if (registrant != null) { + 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.getName().equals(sampleCriteria.getName())).findFirst().get(); + Assert.assertNotNull(registrantCriteria); + } + } +} 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; diff --git a/src/test/java/com/techlooper/service/impl/UserEvaluationServiceImplTest.java b/src/test/java/com/techlooper/service/impl/UserEvaluationServiceImplTest.java index 02de77273..6d4154e45 100644 --- a/src/test/java/com/techlooper/service/impl/UserEvaluationServiceImplTest.java +++ b/src/test/java/com/techlooper/service/impl/UserEvaluationServiceImplTest.java @@ -18,6 +18,7 @@ import java.util.Arrays; import java.util.List; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @@ -197,7 +198,7 @@ public void testSavePriceJobSurvey() throws Exception { priceJobSurvey.setIsUnderstandable(true); priceJobSurvey.setFeedback("Good Report"); boolean isSaved = userEvaluationService.savePriceJobSurvey(priceJobSurvey); - assertTrue(isSaved == true); + assertTrue(isSaved); } @Test @@ -208,6 +209,6 @@ public void testSavePriceJobSurveyNotSave() throws Exception { priceJobSurvey.setIsUnderstandable(true); priceJobSurvey.setFeedback("Bad Report"); boolean isSaved = userEvaluationService.savePriceJobSurvey(priceJobSurvey); - assertTrue(isSaved == false); + assertFalse(isSaved); } } \ No newline at end of file