From 90162193e48db0f8b73d521a7ecad4697f519a5d Mon Sep 17 00:00:00 2001 From: johnsonpham Date: Thu, 1 Oct 2015 10:17:39 +0700 Subject: [PATCH 01/29] hide video and images tags on summernote js --- .../employerDashboardController.js | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js b/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js index b1bf6de19..69aca6433 100644 --- a/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js +++ b/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js @@ -1,5 +1,17 @@ techlooper.controller('employerDashboardController', function ($scope, jsonValue, utils, apiService, $location, $filter) { - $('.summernote').summernote(); + $('.summernote').summernote({ + toolbar: [ + ['fontname', ['fontname']], + ['fontsize', ['fontsize']], + ['style', ['bold', 'italic', 'underline', 'clear']], + ['color', ['color']], + ['para', ['ul', 'ol', 'paragraph']], + ['height', ['height']], + ['table', ['table']], + ['insert', ['link']], + ['misc', ['undo', 'redo', 'codeview', 'fullscreen']] + ] + }); var edit = function() { $('.click2edit').summernote({ focus: true From 5905e596e9e6ff9f199c4619892045bcba34618f Mon Sep 17 00:00:00 2001 From: Phuong H Date: Thu, 1 Oct 2015 10:24:32 +0700 Subject: [PATCH 02/29] Able to send email to contestants --- .../techlooper/config/CoreConfiguration.java | 890 ++++++------- .../techlooper/controller/UserController.java | 19 + .../com/techlooper/model/EmailContent.java | 29 + .../techlooper/service/ChallengeService.java | 69 +- .../service/impl/ChallengeServiceImpl.java | 1182 +++++++++-------- .../assets/modules/common/apiService.js | 9 +- .../employer-dashboard.html | 4 +- .../employerDashboardController.js | 27 +- 8 files changed, 1158 insertions(+), 1071 deletions(-) create mode 100644 src/main/java/com/techlooper/model/EmailContent.java diff --git a/src/main/java/com/techlooper/config/CoreConfiguration.java b/src/main/java/com/techlooper/config/CoreConfiguration.java index a3a1acd29..648716873 100644 --- a/src/main/java/com/techlooper/config/CoreConfiguration.java +++ b/src/main/java/com/techlooper/config/CoreConfiguration.java @@ -61,456 +61,456 @@ @Configuration @ComponentScan(basePackages = "com.techlooper") @PropertySources({ - @PropertySource("classpath:techlooper.properties"), - @PropertySource("classpath:secret.properties")}) + @PropertySource("classpath:techlooper.properties"), + @PropertySource("classpath:secret.properties")}) @EnableScheduling @EnableAspectJAutoProxy @EnableCaching(proxyTargetClass = true) public class CoreConfiguration implements ApplicationContextAware { - @Resource - private Environment environment; - - @Value("${mail.techlooper.form}") - private String mailTechlooperForm; + @Resource + private Environment environment; + + @Value("${mail.techlooper.form}") + private String mailTechlooperForm; - @Value("${mail.techlooper.reply_to}") - private String mailTechlooperReplyTo; + @Value("${mail.techlooper.reply_to}") + private String mailTechlooperReplyTo; - @Value("${mail.form}") - private String mailForm; - - @Value("${mail.reply_to}") - private String mailReplyTo; - - @Value("${mail.citibank.cc_promotion.to}") - private String mailCitibankCreditCardPromotionTo; - - @Value("${mail.citibank.cc_promotion.subject}") - private String mailCitibankCreditCardPromotionSubject; - - @Value("classpath:vnwConfig.json") - private org.springframework.core.io.Resource vnwConfigRes; - - @Value("classpath:google-auth/techLooper.p12") - private org.springframework.core.io.Resource googleApiAuthResource; - - private ApplicationContext applicationContext; - - @Bean - public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { - PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer(); - configurer.setFileEncoding("UTF-8"); - return configurer; - } - - @Bean - public CacheManager cacheManager() { - CompositeCacheManager manager = new CompositeCacheManager(); - manager.setCacheManagers(Arrays.asList( - new ConcurrentMapCacheManager("SOCIAL_CONFIG"), - new ConcurrentMapCacheManager("COMMON_TERM"), - new ConcurrentMapCacheManager("SKILL_CONFIG"))); - return manager; - } - - @Bean - public RestTemplate restTemplate() { - return new RestTemplate(clientHttpRequestFactory()); - } - - @Bean - public MultipartResolver multipartResolver() { - CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); - multipartResolver.setMaxUploadSize(500000); - return multipartResolver; - } - - @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"); - - } - }); - return dozerBeanMapper; - } - - @Bean - public TextEncryptor textEncryptor() { - BasicTextEncryptor textEncryptor = new BasicTextEncryptor(); - textEncryptor.setPassword(environment.getProperty("core.textEncryptor.password")); - return textEncryptor; - } - - @Bean - public JavaMailSender mailSender() { - JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); - mailSender.setHost("localhost"); - mailSender.setPort(25); - - Properties javaMailProperties = new Properties(); - javaMailProperties.put("mail.transport.protocol", "smtp"); - mailSender.setJavaMailProperties(javaMailProperties); - return mailSender; - } - - @Bean - public SimpleMailMessage citibankCreditCardPromotionMailMessage() { - SimpleMailMessage mailMessage = new SimpleMailMessage(); - mailMessage.setFrom(mailForm); - mailMessage.setTo(mailCitibankCreditCardPromotionTo); - mailMessage.setReplyTo(mailReplyTo); - mailMessage.setSubject(mailCitibankCreditCardPromotionSubject); - return mailMessage; - } - - @Bean - public freemarker.template.Configuration freemakerConfig() throws IOException, URISyntaxException { - freemarker.template.Configuration cfg = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_22); - cfg.setDirectoryForTemplateLoading(Paths.get(this.getClass().getClassLoader().getResource("/template").toURI()).toFile()); - cfg.setDefaultEncoding("UTF-8"); - cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); - return cfg; - } - - @Bean - public Template citibankCreditCardPromotionTemplate(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("citibankCreditCardPromotion.ftl"); - return template; - } - - @Bean - public Map locationMap() { - Map locations = new HashMap<>(); - locations.put(29L, "Ho Chi Minh"); - locations.put(24L, "Ha Noi"); - return locations; - } - - @Bean - public MimeMessage salaryReviewMailMessage(JavaMailSender mailSender) throws MessagingException, UnsupportedEncodingException { - MimeMessage mailMessage = mailSender.createMimeMessage(); - mailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); - mailMessage.setFrom(new InternetAddress(mailTechlooperForm, "TechLooper", "UTF-8")); - return mailMessage; - } - - @Bean - public MimeMessage getPromotedMailMessage(JavaMailSender mailSender) throws MessagingException, UnsupportedEncodingException { - MimeMessage mailMessage = mailSender.createMimeMessage(); - mailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); - mailMessage.setFrom(new InternetAddress(mailTechlooperForm, "TechLooper", "UTF-8")); - return mailMessage; - } - - @Bean - public MimeMessage postChallengeMailMessage(JavaMailSender mailSender) throws MessagingException, UnsupportedEncodingException { - MimeMessage mailMessage = mailSender.createMimeMessage(); - mailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); - mailMessage.setFrom(new InternetAddress(mailTechlooperForm, "TechLooper", "UTF-8")); - return mailMessage; - } - - @Bean - public MimeMessage applyJobMailMessage(JavaMailSender mailSender) throws MessagingException, UnsupportedEncodingException { - MimeMessage mailMessage = mailSender.createMimeMessage(); - mailMessage.setFrom(new InternetAddress(mailTechlooperForm, "TechLooper", "UTF-8")); - return mailMessage; - } - - @Bean - public MimeMessage jobAlertMailMessage(JavaMailSender mailSender) throws MessagingException, UnsupportedEncodingException { - MimeMessage mailMessage = mailSender.createMimeMessage(); - mailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); - mailMessage.setFrom(new InternetAddress(mailTechlooperForm, "TechLooper", "UTF-8")); - return mailMessage; - } - - @Bean - public MimeMessage alertEventOrganiserMailMessage(JavaMailSender mailSender) throws MessagingException, UnsupportedEncodingException { - MimeMessage mailMessage = mailSender.createMimeMessage(); - mailMessage.setFrom(new InternetAddress(mailTechlooperForm, "TechLooper", "UTF-8")); - return mailMessage; - } - - @Bean - public Template salaryReviewReportTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("salaryReviewReport.en.ftl"); - return template; - } - - @Bean - public Template salaryReviewReportTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("salaryReviewReport.vi.ftl"); - return template; - } - - @Bean - public Template getPromotedTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("getPromoted.en.ftl"); - return template; - } - - @Bean - public Template getPromotedTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("getPromoted.vi.ftl"); - return template; - } - - @Bean - public Template postChallengeMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("postChallenge.en.ftl"); - return template; - } - - @Bean - public Template notifyChallengeTimelineMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("notifyChallengeTimeline.vi.ftl"); - return template; - } - - @Bean - public Template notifyChallengeTimelineMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("notifyChallengeTimeline.en.ftl"); - return template; - } - - @Bean - public Template postChallengeUpdateMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("updateChallenge.en.ftl"); - return template; - } - - @Bean - public Template postChallengeMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("postChallenge.vi.ftl"); - return template; - } - - @Bean - public Template confirmUserJoinChallengeMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("confirmUserJoinChallenge.en.ftl"); - return template; - } - - @Bean - public Template confirmUserJoinChallengeMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("confirmUserJoinChallenge.vi.ftl"); - return template; - } - - @Bean - public Template alertEmployerChallengeMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("alertEmployerChallenge.en.ftl"); - return template; - } - - @Bean - public Template alertEmployerChallengeMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("alertEmployerChallenge.vi.ftl"); - return template; - } - - @Bean - public Template alertJobSeekerApplyJobMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("alertJobSeekerApplyJob.en.ftl"); - return template; - } - - @Bean - public Template alertJobSeekerApplyJobMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("alertJobSeekerApplyJob.vi.ftl"); - return template; - } - - @Bean - public Template alertEmployerApplyJobMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("alertEmployerApplyJob.en.ftl"); - return template; - } - - @Bean - public Template alertEmployerApplyJobMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("alertEmployerApplyJob.vi.ftl"); - return template; - } - - @Bean - public Template alertEmployerPostJobMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("alertEmployerPostJob.vi.ftl"); - return template; - } - - @Bean - public Template alertEmployerPostJobMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("alertEmployerPostJob.en.ftl"); - return template; - } - - @Bean - public Template alertTechloopiesPostJobMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("alertTechloopiesApplyJob.en.ftl"); - return template; - } - - @Bean - public Template jobAlertMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("jobAlert.en.ftl"); - return template; - } - - @Bean - public Template jobAlertMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("jobAlert.vi.ftl"); - return template; - } - - @Bean - public Template alertEventOrganiserMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("webinar.en.ftl"); - return template; - } - - @Bean - public Template alertEventOrganiserMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("webinar.vi.ftl"); - return template; - } - - @Bean - public Template onBoardingMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("onboarding.en.ftl"); - return template; - } - - @Bean - public Template onBoardingMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("onboarding.vi.ftl"); - return template; - } - - @Bean - public Template dailyChallengeSummaryMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("challengeDailySummary.en.ftl"); - return template; - } - - @Bean - public Template dailyChallengeSummaryMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("challengeDailySummary.vi.ftl"); - return template; - } - - @Bean - public JsonNode vietnamworksConfiguration() throws IOException { - return new ObjectMapper().readTree(vnwConfigRes.getInputStream()); - } - - @Bean - @DependsOn("jsonConfigRepository") - public SocialConfig googleSocialConfig() { - return applicationContext.getBean(JsonConfigRepository.class).getSocialConfig().stream() - .filter(socialConfig -> socialConfig.getProvider() == SocialProvider.GOOGLE) - .findFirst().get(); - } - - @Bean - public Calendar googleCalendar() throws GeneralSecurityException, IOException { - JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance(); - HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport(); - SocialConfig googleConfig = googleSocialConfig(); - HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); - GoogleCredential credential = new GoogleCredential.Builder() - .setTransport(httpTransport) - .setJsonFactory(jsonFactory) - .setServiceAccountId(googleConfig.getServiceAccountEmail()) - .setServiceAccountPrivateKeyFromP12File(googleApiAuthResource.getFile()) - .setServiceAccountScopes(Collections.singleton(CalendarScopes.CALENDAR)) - .setServiceAccountUser(googleConfig.getCalendarOwner()) - .build(); - - return new Calendar.Builder(transport, jsonFactory, credential) - .setApplicationName("Techlooper").build(); - } - - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - this.applicationContext = applicationContext; - this.applicationContext.getEnvironment().acceptsProfiles(environment.getProperty("spring.profiles.active")); - } - - @Bean - public MimeMessage fromTechlooperMailMessage(JavaMailSender mailSender) throws MessagingException, UnsupportedEncodingException { - MimeMessage mailMessage = mailSender.createMimeMessage(); - mailMessage.setFrom(new InternetAddress(mailTechlooperForm, "TechLooper", "UTF-8")); - return mailMessage; - } - - private ClientHttpRequestFactory clientHttpRequestFactory() { - HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); - factory.setReadTimeout(5000); - factory.setConnectTimeout(5000); - return factory; - } + @Value("${mail.form}") + private String mailForm; + + @Value("${mail.reply_to}") + private String mailReplyTo; + + @Value("${mail.citibank.cc_promotion.to}") + private String mailCitibankCreditCardPromotionTo; + + @Value("${mail.citibank.cc_promotion.subject}") + private String mailCitibankCreditCardPromotionSubject; + + @Value("classpath:vnwConfig.json") + private org.springframework.core.io.Resource vnwConfigRes; + + @Value("classpath:google-auth/techLooper.p12") + private org.springframework.core.io.Resource googleApiAuthResource; + + private ApplicationContext applicationContext; + + @Bean + public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { + PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer(); + configurer.setFileEncoding("UTF-8"); + return configurer; + } + + @Bean + public CacheManager cacheManager() { + CompositeCacheManager manager = new CompositeCacheManager(); + manager.setCacheManagers(Arrays.asList( + new ConcurrentMapCacheManager("SOCIAL_CONFIG"), + new ConcurrentMapCacheManager("COMMON_TERM"), + new ConcurrentMapCacheManager("SKILL_CONFIG"))); + return manager; + } + + @Bean + public RestTemplate restTemplate() { + return new RestTemplate(clientHttpRequestFactory()); + } + + @Bean + public MultipartResolver multipartResolver() { + CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); + multipartResolver.setMaxUploadSize(500000); + return multipartResolver; + } + + @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"); + + } + }); + return dozerBeanMapper; + } + + @Bean + public TextEncryptor textEncryptor() { + BasicTextEncryptor textEncryptor = new BasicTextEncryptor(); + textEncryptor.setPassword(environment.getProperty("core.textEncryptor.password")); + return textEncryptor; + } + + @Bean + public JavaMailSender mailSender() { + JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); + mailSender.setHost("localhost"); + mailSender.setPort(25); + + Properties javaMailProperties = new Properties(); + javaMailProperties.put("mail.transport.protocol", "smtp"); + mailSender.setJavaMailProperties(javaMailProperties); + return mailSender; + } + + @Bean + public SimpleMailMessage citibankCreditCardPromotionMailMessage() { + SimpleMailMessage mailMessage = new SimpleMailMessage(); + mailMessage.setFrom(mailForm); + mailMessage.setTo(mailCitibankCreditCardPromotionTo); + mailMessage.setReplyTo(mailReplyTo); + mailMessage.setSubject(mailCitibankCreditCardPromotionSubject); + return mailMessage; + } + + @Bean + public freemarker.template.Configuration freemakerConfig() throws IOException, URISyntaxException { + freemarker.template.Configuration cfg = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_22); + cfg.setDirectoryForTemplateLoading(Paths.get(this.getClass().getClassLoader().getResource("/template").toURI()).toFile()); + cfg.setDefaultEncoding("UTF-8"); + cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); + return cfg; + } + + @Bean + public Template citibankCreditCardPromotionTemplate(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("citibankCreditCardPromotion.ftl"); + return template; + } + + @Bean + public Map locationMap() { + Map locations = new HashMap<>(); + locations.put(29L, "Ho Chi Minh"); + locations.put(24L, "Ha Noi"); + return locations; + } + + @Bean + public MimeMessage salaryReviewMailMessage(JavaMailSender mailSender) throws MessagingException, UnsupportedEncodingException { + MimeMessage mailMessage = mailSender.createMimeMessage(); + mailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); + mailMessage.setFrom(new InternetAddress(mailTechlooperForm, "TechLooper", "UTF-8")); + return mailMessage; + } + + @Bean + public MimeMessage getPromotedMailMessage(JavaMailSender mailSender) throws MessagingException, UnsupportedEncodingException { + MimeMessage mailMessage = mailSender.createMimeMessage(); + mailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); + mailMessage.setFrom(new InternetAddress(mailTechlooperForm, "TechLooper", "UTF-8")); + return mailMessage; + } + + @Bean + public MimeMessage postChallengeMailMessage(JavaMailSender mailSender) throws MessagingException, UnsupportedEncodingException { + MimeMessage mailMessage = mailSender.createMimeMessage(); + mailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); + mailMessage.setFrom(new InternetAddress(mailTechlooperForm, "TechLooper", "UTF-8")); + return mailMessage; + } + + @Bean + public MimeMessage applyJobMailMessage(JavaMailSender mailSender) throws MessagingException, UnsupportedEncodingException { + MimeMessage mailMessage = mailSender.createMimeMessage(); + mailMessage.setFrom(new InternetAddress(mailTechlooperForm, "TechLooper", "UTF-8")); + return mailMessage; + } + + @Bean + public MimeMessage jobAlertMailMessage(JavaMailSender mailSender) throws MessagingException, UnsupportedEncodingException { + MimeMessage mailMessage = mailSender.createMimeMessage(); + mailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); + mailMessage.setFrom(new InternetAddress(mailTechlooperForm, "TechLooper", "UTF-8")); + return mailMessage; + } + + @Bean + public MimeMessage alertEventOrganiserMailMessage(JavaMailSender mailSender) throws MessagingException, UnsupportedEncodingException { + MimeMessage mailMessage = mailSender.createMimeMessage(); + mailMessage.setFrom(new InternetAddress(mailTechlooperForm, "TechLooper", "UTF-8")); + return mailMessage; + } + + @Bean + public Template salaryReviewReportTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("salaryReviewReport.en.ftl"); + return template; + } + + @Bean + public Template salaryReviewReportTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("salaryReviewReport.vi.ftl"); + return template; + } + + @Bean + public Template getPromotedTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("getPromoted.en.ftl"); + return template; + } + + @Bean + public Template getPromotedTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("getPromoted.vi.ftl"); + return template; + } + + @Bean + public Template postChallengeMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("postChallenge.en.ftl"); + return template; + } + + @Bean + public Template notifyChallengeTimelineMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("notifyChallengeTimeline.vi.ftl"); + return template; + } + + @Bean + public Template notifyChallengeTimelineMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("notifyChallengeTimeline.en.ftl"); + return template; + } + + @Bean + public Template postChallengeUpdateMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("updateChallenge.en.ftl"); + return template; + } + + @Bean + public Template postChallengeMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("postChallenge.vi.ftl"); + return template; + } + + @Bean + public Template confirmUserJoinChallengeMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("confirmUserJoinChallenge.en.ftl"); + return template; + } + + @Bean + public Template confirmUserJoinChallengeMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("confirmUserJoinChallenge.vi.ftl"); + return template; + } + + @Bean + public Template alertEmployerChallengeMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("alertEmployerChallenge.en.ftl"); + return template; + } + + @Bean + public Template alertEmployerChallengeMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("alertEmployerChallenge.vi.ftl"); + return template; + } + + @Bean + public Template alertJobSeekerApplyJobMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("alertJobSeekerApplyJob.en.ftl"); + return template; + } + + @Bean + public Template alertJobSeekerApplyJobMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("alertJobSeekerApplyJob.vi.ftl"); + return template; + } + + @Bean + public Template alertEmployerApplyJobMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("alertEmployerApplyJob.en.ftl"); + return template; + } + + @Bean + public Template alertEmployerApplyJobMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("alertEmployerApplyJob.vi.ftl"); + return template; + } + + @Bean + public Template alertEmployerPostJobMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("alertEmployerPostJob.vi.ftl"); + return template; + } + + @Bean + public Template alertEmployerPostJobMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("alertEmployerPostJob.en.ftl"); + return template; + } + + @Bean + public Template alertTechloopiesPostJobMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("alertTechloopiesApplyJob.en.ftl"); + return template; + } + + @Bean + public Template jobAlertMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("jobAlert.en.ftl"); + return template; + } + + @Bean + public Template jobAlertMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("jobAlert.vi.ftl"); + return template; + } + + @Bean + public Template alertEventOrganiserMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("webinar.en.ftl"); + return template; + } + + @Bean + public Template alertEventOrganiserMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("webinar.vi.ftl"); + return template; + } + + @Bean + public Template onBoardingMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("onboarding.en.ftl"); + return template; + } + + @Bean + public Template onBoardingMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("onboarding.vi.ftl"); + return template; + } + + @Bean + public Template dailyChallengeSummaryMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("challengeDailySummary.en.ftl"); + return template; + } + + @Bean + public Template dailyChallengeSummaryMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("challengeDailySummary.vi.ftl"); + return template; + } + + @Bean + public JsonNode vietnamworksConfiguration() throws IOException { + return new ObjectMapper().readTree(vnwConfigRes.getInputStream()); + } + + @Bean + @DependsOn("jsonConfigRepository") + public SocialConfig googleSocialConfig() { + return applicationContext.getBean(JsonConfigRepository.class).getSocialConfig().stream() + .filter(socialConfig -> socialConfig.getProvider() == SocialProvider.GOOGLE) + .findFirst().get(); + } + + @Bean + public Calendar googleCalendar() throws GeneralSecurityException, IOException { + JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance(); + HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport(); + SocialConfig googleConfig = googleSocialConfig(); + HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); + GoogleCredential credential = new GoogleCredential.Builder() + .setTransport(httpTransport) + .setJsonFactory(jsonFactory) + .setServiceAccountId(googleConfig.getServiceAccountEmail()) + .setServiceAccountPrivateKeyFromP12File(googleApiAuthResource.getFile()) + .setServiceAccountScopes(Collections.singleton(CalendarScopes.CALENDAR)) + .setServiceAccountUser(googleConfig.getCalendarOwner()) + .build(); + + return new Calendar.Builder(transport, jsonFactory, credential) + .setApplicationName("Techlooper").build(); + } + + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + this.applicationContext = applicationContext; + this.applicationContext.getEnvironment().acceptsProfiles(environment.getProperty("spring.profiles.active")); + } + + @Bean + public MimeMessage fromTechlooperMailMessage(JavaMailSender mailSender) throws MessagingException, UnsupportedEncodingException { + MimeMessage mailMessage = mailSender.createMimeMessage(); + mailMessage.setFrom(new InternetAddress(mailTechlooperForm, "TechLooper", "UTF-8")); + return mailMessage; + } + + private ClientHttpRequestFactory clientHttpRequestFactory() { + HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); + factory.setReadTimeout(5000); + factory.setConnectTimeout(5000); + return factory; + } } \ No newline at end of file diff --git a/src/main/java/com/techlooper/controller/UserController.java b/src/main/java/com/techlooper/controller/UserController.java index 629dc5baf..e018729e3 100644 --- a/src/main/java/com/techlooper/controller/UserController.java +++ b/src/main/java/com/techlooper/controller/UserController.java @@ -3,6 +3,7 @@ import com.techlooper.dto.DashBoardInfo; import com.techlooper.dto.JoinBySocialDto; import com.techlooper.dto.WebinarInfoDto; +import com.techlooper.entity.ChallengeRegistrantEntity; import com.techlooper.entity.GetPromotedEntity; import com.techlooper.entity.PriceJobEntity; import com.techlooper.entity.SalaryReviewEntity; @@ -33,6 +34,8 @@ import java.util.Arrays; import java.util.Collection; import java.util.List; +import java.util.stream.Collector; +import java.util.stream.Collectors; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toSet; @@ -373,4 +376,20 @@ public WebinarInfoDto findWebinarById(@PathVariable Long id) { 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; + } + + } diff --git a/src/main/java/com/techlooper/model/EmailContent.java b/src/main/java/com/techlooper/model/EmailContent.java new file mode 100644 index 000000000..5e0bba349 --- /dev/null +++ b/src/main/java/com/techlooper/model/EmailContent.java @@ -0,0 +1,29 @@ +package com.techlooper.model; + +import java.io.Serializable; + +/** + * Created by phuonghqh on 10/1/15. + */ +public class EmailContent implements Serializable { + + private String subject; + + private String content; + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } +} diff --git a/src/main/java/com/techlooper/service/ChallengeService.java b/src/main/java/com/techlooper/service/ChallengeService.java index 6147739e1..a7fd4fb56 100644 --- a/src/main/java/com/techlooper/service/ChallengeService.java +++ b/src/main/java/com/techlooper/service/ChallengeService.java @@ -22,64 +22,67 @@ */ public interface ChallengeService { - ChallengeEntity savePostChallenge(ChallengeDto challengeDto) throws Exception; + ChallengeEntity savePostChallenge(ChallengeDto challengeDto) throws Exception; - void sendPostChallengeEmailToEmployer(ChallengeEntity challengeEntity) - throws MessagingException, IOException, TemplateException; + void sendPostChallengeEmailToEmployer(ChallengeEntity challengeEntity) + throws MessagingException, IOException, TemplateException; - void sendPostChallengeEmailToTechloopies(ChallengeEntity challengeEntity, Boolean isNewChallenge) - throws MessagingException, IOException, TemplateException; + void sendPostChallengeEmailToTechloopies(ChallengeEntity challengeEntity, Boolean isNewChallenge) + throws MessagingException, IOException, TemplateException; - void sendEmailNotifyRegistrantAboutChallengeTimeline(ChallengeEntity challengeEntity, - ChallengeRegistrantEntity challengeRegistrantEntity, ChallengePhaseEnum challengePhase) throws Exception; + void sendEmailNotifyRegistrantAboutChallengeTimeline(ChallengeEntity challengeEntity, + ChallengeRegistrantEntity challengeRegistrantEntity, ChallengePhaseEnum challengePhase) throws Exception; - ChallengeDetailDto getChallengeDetail(Long challengeId); + ChallengeDetailDto getChallengeDetail(Long challengeId); - Long getNumberOfRegistrants(Long challengeId); + Long getNumberOfRegistrants(Long challengeId); - void sendApplicationEmailToContestant(ChallengeEntity challengeEntity, ChallengeRegistrantEntity challengeRegistrantEntity) - throws MessagingException, IOException, TemplateException; + void sendApplicationEmailToContestant(ChallengeEntity challengeEntity, ChallengeRegistrantEntity challengeRegistrantEntity) + throws MessagingException, IOException, TemplateException; - void sendApplicationEmailToEmployer(ChallengeEntity challengeEntity, ChallengeRegistrantEntity challengeRegistrantEntity) - throws MessagingException, IOException, TemplateException; + void sendApplicationEmailToEmployer(ChallengeEntity challengeEntity, ChallengeRegistrantEntity challengeRegistrantEntity) + throws MessagingException, IOException, TemplateException; - long joinChallenge(ChallengeRegistrantDto challengeRegistrantDto) throws MessagingException, IOException, TemplateException; + long joinChallenge(ChallengeRegistrantDto challengeRegistrantDto) throws MessagingException, IOException, TemplateException; - List listChallenges(); + List listChallenges(); - List listChallenges(String ownerEmail); + List listChallenges(String ownerEmail); - List listChallengesByPhase(ChallengePhaseEnum challengePhase); + List listChallengesByPhase(ChallengePhaseEnum challengePhase); - Long getTotalNumberOfChallenges(); + Long getTotalNumberOfChallenges(); - Double getTotalAmountOfPrizeValues(); + Double getTotalAmountOfPrizeValues(); - Long getTotalNumberOfRegistrants(); + Long getTotalNumberOfRegistrants(); - ChallengeDetailDto getTheLatestChallenge(); + ChallengeDetailDto getTheLatestChallenge(); - Collection findByOwnerAndCondition(String owner, Predicate condition); + Collection findByOwnerAndCondition(String owner, Predicate condition); - Collection findInProgressChallenges(String owner); + Collection findInProgressChallenges(String owner); // Collection findRegistrantsByChallengeId(Long challengeId); - Long countRegistrantsByChallengeId(Long challengeId); + Long countRegistrantsByChallengeId(Long challengeId); - boolean delete(Long id, String ownerEmail); + boolean delete(Long id, String ownerEmail); - ChallengeDto findChallengeById(Long id); + ChallengeDto findChallengeById(Long id); - Set findRegistrantsByOwner(String ownerEmail, Long challengeId); + Set findRegistrantsByOwner(String ownerEmail, Long challengeId); - ChallengeRegistrantDto saveRegistrant(String ownerEmail, ChallengeRegistrantDto challengeRegistrantDto); + ChallengeRegistrantDto saveRegistrant(String ownerEmail, ChallengeRegistrantDto challengeRegistrantDto); - List findChallengeRegistrantWithinPeriod( - Long challengeId, Long currentDateTime, TimePeriodEnum period); + List findChallengeRegistrantWithinPeriod( + Long challengeId, Long currentDateTime, TimePeriodEnum period); - List findChallengeSubmissionWithinPeriod( - Long challengeId, Long currentDateTime, TimePeriodEnum period); + List findChallengeSubmissionWithinPeriod( + Long challengeId, Long currentDateTime, TimePeriodEnum period); + + void sendDailySummaryEmailToChallengeOwner(ChallengeEntity challengeEntity) throws Exception; + + boolean isOwnerOfChallenge(String ownerEmail, Long challengeId); - void sendDailySummaryEmailToChallengeOwner(ChallengeEntity challengeEntity) throws Exception; } diff --git a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java index 77cab5637..83e12df66 100644 --- a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java @@ -59,253 +59,257 @@ @Service public class ChallengeServiceImpl implements ChallengeService { - @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; - 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 = DateTimeUtils.daysBetween(DateTimeUtils.currentDate(), challengeEntity.getRegistrationDateTime()) + 1; - } else if (challengePhase == ChallengePhaseEnum.IN_PROGRESS) { - numberOfDays = DateTimeUtils.daysBetween(DateTimeUtils.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); - } - - 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 ChallengeDetailDto getChallengeDetail(Long challengeId) { - ChallengeEntity challengeEntity = challengeRepository.findOne(challengeId); - if (challengeEntity != null && !Boolean.TRUE.equals(challengeEntity.getExpired())) { - ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); - challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeId)); - return challengeDetailDto; - } - return null; - } - - 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) throws MessagingException, IOException, TemplateException { - Long challengeId = challengeRegistrantDto.getChallengeId(); - boolean isExist = checkIfChallengeRegistrantExist(challengeId, challengeRegistrantDto.getRegistrantEmail()); - - if (!isExist) { - ChallengeRegistrantEntity challengeRegistrantEntity = dozerMapper.map(challengeRegistrantDto, ChallengeRegistrantEntity.class); - ChallengeEntity challengeEntity = challengeRepository.findOne(challengeId); - sendApplicationEmailToContestant(challengeEntity, challengeRegistrantEntity); - sendApplicationEmailToEmployer(challengeEntity, challengeRegistrantEntity); - challengeRegistrantEntity.setMailSent(Boolean.TRUE); - challengeRegistrantEntity.setRegistrantId(new Date().getTime()); - challengeRegistrantRepository.save(challengeRegistrantEntity); - } - - return getNumberOfRegistrants(challengeId); + public ChallengeEntity savePostChallenge(ChallengeDto challengeDto) throws Exception { + ChallengeEntity challengeEntity = dozerMapper.map(challengeDto, ChallengeEntity.class); + if (challengeDto.getChallengeId() == null) { + challengeEntity.setChallengeId(new Date().getTime()); } - - public List listChallenges() { + 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 = DateTimeUtils.daysBetween(DateTimeUtils.currentDate(), challengeEntity.getRegistrationDateTime()) + 1; + } + else if (challengePhase == ChallengePhaseEnum.IN_PROGRESS) { + numberOfDays = DateTimeUtils.daysBetween(DateTimeUtils.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); + } + + 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 ChallengeDetailDto getChallengeDetail(Long challengeId) { + ChallengeEntity challengeEntity = challengeRepository.findOne(challengeId); + if (challengeEntity != null && !Boolean.TRUE.equals(challengeEntity.getExpired())) { + ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); + challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeId)); + return challengeDetailDto; + } + return null; + } + + 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) throws MessagingException, IOException, TemplateException { + Long challengeId = challengeRegistrantDto.getChallengeId(); + boolean isExist = checkIfChallengeRegistrantExist(challengeId, challengeRegistrantDto.getRegistrantEmail()); + + if (!isExist) { + ChallengeRegistrantEntity challengeRegistrantEntity = dozerMapper.map(challengeRegistrantDto, ChallengeRegistrantEntity.class); + ChallengeEntity challengeEntity = challengeRepository.findOne(challengeId); + sendApplicationEmailToContestant(challengeEntity, challengeRegistrantEntity); + sendApplicationEmailToEmployer(challengeEntity, challengeRegistrantEntity); + challengeRegistrantEntity.setMailSent(Boolean.TRUE); + challengeRegistrantEntity.setRegistrantId(new Date().getTime()); + challengeRegistrantRepository.save(challengeRegistrantEntity); + } + + return getNumberOfRegistrants(challengeId); + } + + public List listChallenges() { // List challenges = new ArrayList<>(); // Iterator challengeIter = challengeRepository.findAll().iterator(); // while (challengeIter.hasNext()) { @@ -315,169 +319,174 @@ public List listChallenges() { // challenges.add(challengeDetailDto); // } // return sortChallengesByDescendingStartDate(challenges); - TermQueryBuilder notExpiredQuery = termQuery("expired", Boolean.TRUE); - Iterable challengeIterator = challengeRepository.search(boolQuery().mustNot(notExpiredQuery)); - ArrayList challenges = new ArrayList<>(); - challengeIterator.forEach(challengeEntity -> { - ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); - challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeEntity.getChallengeId())); - challenges.add(challengeDetailDto); - }); - return sortChallengesByDescendingStartDate(challenges); - } - - private void sendContestApplicationEmail(Template template, String mailSubject, Address[] recipientAddresses, - ChallengeEntity challengeEntity, ChallengeRegistrantEntity challengeRegistrantEntity, boolean hasReplyTo) - throws MessagingException, IOException, TemplateException { - postChallengeMailMessage.setRecipients(Message.RecipientType.TO, recipientAddresses); - - if (hasReplyTo) { - postChallengeMailMessage.setReplyTo(InternetAddress.parse(challengeRegistrantEntity.getRegistrantEmail())); - } else { - postChallengeMailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); + 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; } - - 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()); + else if (challenge1.getStartDateTime() == null) { + return 1; } - return InternetAddress.parse(StringUtils.join(emails, ',')); - } - - private List sortChallengesByDescendingStartDate(List challenges) { - SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); - return challenges.stream().sorted((challenge1, challenge2) -> { - try { - if (challenge2.getStartDateTime() == null) { - return -1; - } else if (challenge1.getStartDateTime() == null) { - return 1; - } - long challenge2StartDate = sdf.parse(challenge2.getStartDateTime()).getTime(); - long challenge1StartDate = sdf.parse(challenge1.getStartDateTime()).getTime(); - if (challenge2StartDate - challenge1StartDate > 0) { - return 1; - } else if (challenge2StartDate - challenge1StartDate < 0) { - return -1; - } else { - return 0; - } - } catch (ParseException e) { - return 0; - } - }).collect(Collectors.toList()); - } - - public boolean checkIfChallengeRegistrantExist(Long challengeId, String email) { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder(); - searchQueryBuilder.withQuery(boolQuery() - .must(matchPhraseQuery("registrantEmail", email)) - .must(termQuery("challengeId", challengeId)) - .must(termQuery("mailSent", true))); - - 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() { + 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(Collectors.toList()); + } + + public boolean checkIfChallengeRegistrantExist(Long challengeId, String email) { + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder(); + searchQueryBuilder.withQuery(boolQuery() + .must(matchPhraseQuery("registrantEmail", email)) + .must(termQuery("challengeId", challengeId)) + .must(termQuery("mailSent", true))); + + 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)); @@ -488,221 +497,226 @@ 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 challenges; - } - - public List listChallenges(String ownerEmail) { - MatchQueryBuilder authorEmailQuery = matchQuery("authorEmail", ownerEmail).minimumShouldMatch("100%"); - TermQueryBuilder notExpiredQuery = termQuery("expired", Boolean.TRUE); - Iterable challenges = challengeRepository.search(boolQuery().must(authorEmailQuery).mustNot(notExpiredQuery)); - ArrayList dtos = new ArrayList<>(); - challenges.forEach(challengeEntity -> { - ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); - challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeEntity.getChallengeId())); - dtos.add(challengeDetailDto); - }); - dozerMapper.map(challenges, dtos); - return dtos; - } - - 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(String ownerEmail, Long challengeId) { - BoolQueryBuilder boolQueryBuilder = boolQuery(); - - if (StringUtils.isNotEmpty(ownerEmail)) { - boolQueryBuilder.must(matchQuery("authorEmail", ownerEmail).minimumShouldMatch("100%")); - } - - TermQueryBuilder challengeQuery = termQuery("challengeId", challengeId); - if (challengeId != null) { - boolQueryBuilder.must(challengeQuery); - } - - boolQueryBuilder.mustNot(termQuery("expired", Boolean.TRUE)); - Iterator challengeIterator = challengeRepository.search(boolQueryBuilder).iterator(); - Set registrantDtos = new HashSet<>(); - - if (challengeIterator.hasNext()) { - Iterator registrants = challengeRegistrantRepository.search(challengeQuery).iterator(); - registrants.forEachRemaining(registrant -> registrantDtos.add(dozerMapper.map(registrant, ChallengeRegistrantDto.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 registrantDtos; - } - - public ChallengeRegistrantDto saveRegistrant(String ownerEmail, ChallengeRegistrantDto challengeRegistrantDto) { - ChallengeEntity challenge = challengeRepository.findOne(challengeRegistrantDto.getChallengeId()); - if (ownerEmail.equalsIgnoreCase(challenge.getAuthorEmail())) { - ChallengeRegistrantEntity registrant = challengeRegistrantRepository.findOne(challengeRegistrantDto.getRegistrantId()); - challengeRegistrantDto.setRegistrantEmail(registrant.getRegistrantEmail()); - dozerMapper.map(challengeRegistrantDto, registrant); - registrant = challengeRegistrantRepository.save(registrant); - challengeRegistrantDto = dozerMapper.map(registrant, ChallengeRegistrantDto.class); + }); + } + return challenges; + } + + public List listChallenges(String ownerEmail) { + MatchQueryBuilder authorEmailQuery = matchQuery("authorEmail", ownerEmail).minimumShouldMatch("100%"); + TermQueryBuilder notExpiredQuery = termQuery("expired", Boolean.TRUE); + Iterable challenges = challengeRepository.search(boolQuery().must(authorEmailQuery).mustNot(notExpiredQuery)); + ArrayList dtos = new ArrayList<>(); + challenges.forEach(challengeEntity -> { + ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); + challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeEntity.getChallengeId())); + dtos.add(challengeDetailDto); + }); + dozerMapper.map(challenges, dtos); + return dtos; + } + + 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(String ownerEmail, Long challengeId) { + BoolQueryBuilder boolQueryBuilder = boolQuery(); + + if (StringUtils.isNotEmpty(ownerEmail)) { + boolQueryBuilder.must(matchQuery("authorEmail", ownerEmail).minimumShouldMatch("100%")); + } + + TermQueryBuilder challengeQuery = termQuery("challengeId", challengeId); + if (challengeId != null) { + boolQueryBuilder.must(challengeQuery); + } + + boolQueryBuilder.mustNot(termQuery("expired", Boolean.TRUE)); + Iterator challengeIterator = challengeRepository.search(boolQueryBuilder).iterator(); + Set registrantDtos = new HashSet<>(); + + if (challengeIterator.hasNext()) { + Iterator registrants = challengeRegistrantRepository.search(challengeQuery).iterator(); + registrants.forEachRemaining(registrant -> registrantDtos.add(dozerMapper.map(registrant, ChallengeRegistrantDto.class))); + } + + return registrantDtos; + } + + 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)); - searchQueryBuilder.withPageable(new PageRequest(0, 100)); - - List result = new ArrayList<>(); - Iterator iterator = challengeRegistrantRepository.search(searchQueryBuilder.build()).iterator(); - while (iterator.hasNext()) { - result.add(iterator.next()); - } - - 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)); - - Long pastTime = currentDateTime - period.getMiliseconds() > 0 ? currentDateTime - period.getMiliseconds() : 0; - boolQueryBuilder.must(rangeQuery("challengeSubmissionId").from(pastTime)); - searchQueryBuilder.withQuery(boolQueryBuilder); - searchQueryBuilder.withSort(fieldSort("challengeSubmissionId").order(SortOrder.DESC)); - searchQueryBuilder.withPageable(new PageRequest(0, 100)); - - List result = new ArrayList<>(); - Iterator iterator = challengeSubmissionRepository.search(searchQueryBuilder.build()).iterator(); - while (iterator.hasNext()) { - result.add(iterator.next()); - } - - return result; - } - - @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())); - - Long currentDateTime = new Date().getTime(); - List latestRegistrants = findChallengeRegistrantWithinPeriod( - challengeEntity.getChallengeId(), currentDateTime, TimePeriodEnum.TWENTY_FOUR_HOURS); - templateModel.put("numberOfRegistrants", latestRegistrants.size()); - templateModel.put("latestRegistrants", latestRegistrants); - - List latestSubmissions = findChallengeSubmissionWithinPeriod( - challengeEntity.getChallengeId(), currentDateTime, TimePeriodEnum.TWENTY_FOUR_HOURS); - templateModel.put("numberOfSubmissions", latestSubmissions.size()); - templateModel.put("latestSubmissions", latestSubmissions); - - template.process(templateModel, stringWriter); - mailSubject = String.format(mailSubject, challengeEntity.getChallengeName()); - postChallengeMailMessage.setSubject(MimeUtility.encodeText(mailSubject, "UTF-8", null)); - postChallengeMailMessage.setText(stringWriter.toString(), "UTF-8", "html"); - - stringWriter.flush(); - postChallengeMailMessage.saveChanges(); - mailSender.send(postChallengeMailMessage); } + return 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)); + searchQueryBuilder.withPageable(new PageRequest(0, 100)); + + List result = new ArrayList<>(); + Iterator iterator = challengeRegistrantRepository.search(searchQueryBuilder.build()).iterator(); + while (iterator.hasNext()) { + result.add(iterator.next()); + } + + 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)); + + Long pastTime = currentDateTime - period.getMiliseconds() > 0 ? currentDateTime - period.getMiliseconds() : 0; + boolQueryBuilder.must(rangeQuery("challengeSubmissionId").from(pastTime)); + searchQueryBuilder.withQuery(boolQueryBuilder); + searchQueryBuilder.withSort(fieldSort("challengeSubmissionId").order(SortOrder.DESC)); + searchQueryBuilder.withPageable(new PageRequest(0, 100)); + + List result = new ArrayList<>(); + Iterator iterator = challengeSubmissionRepository.search(searchQueryBuilder.build()).iterator(); + while (iterator.hasNext()) { + result.add(iterator.next()); + } + + return result; + } + + @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())); + + 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); + } } diff --git a/src/main/webapp/assets/modules/common/apiService.js b/src/main/webapp/assets/modules/common/apiService.js index be1a8393a..7acdb7d33 100644 --- a/src/main/webapp/assets/modules/common/apiService.js +++ b/src/main/webapp/assets/modules/common/apiService.js @@ -199,8 +199,15 @@ techlooper.factory("apiService", function ($rootScope, $location, jsonValue, $ht * */ saveChallengeRegistrant: function(registrant) { return $http.post("challengeDetail/registrant", registrant); + }, + + /** + * @see com.techlooper.controller.UserController.getDailyChallengeRegistrantNames + * */ + getDailyChallengeRegistrantNames: function(challengeId, now) { + return $http.get("user/challengeRegistrantNames/" + challengeId + "/" + now); } - } + }; return instance; }); \ No newline at end of file diff --git a/src/main/webapp/assets/modules/employer-dashboard/employer-dashboard.html b/src/main/webapp/assets/modules/employer-dashboard/employer-dashboard.html index f063039f7..e8dd024ec 100644 --- a/src/main/webapp/assets/modules/employer-dashboard/employer-dashboard.html +++ b/src/main/webapp/assets/modules/employer-dashboard/employer-dashboard.html @@ -173,7 +173,7 @@

- +
@@ -194,7 +194,7 @@

diff --git a/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js b/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js index b1bf6de19..963703de5 100644 --- a/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js +++ b/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js @@ -1,11 +1,11 @@ -techlooper.controller('employerDashboardController', function ($scope, jsonValue, utils, apiService, $location, $filter) { +techlooper.controller('employerDashboardController', function ($scope, jsonValue, utils, apiService, $location, $filter, $route) { $('.summernote').summernote(); - var edit = function() { + var edit = function () { $('.click2edit').summernote({ focus: true }); }; - var save = function() { + var save = function () { var aHTML = $('.click2edit').code(); //save HTML If you need(aHTML: array). $('.click2edit').destroy(); }; @@ -13,17 +13,32 @@ techlooper.controller('employerDashboardController', function ($scope, jsonValue utils.sendNotification(jsonValue.notifications.loading, $(window).height()); var param = $location.search(); - if (!$.isEmptyObject(param) && param.a == "challenge-daily-mail-registrants") { - //TODO send email to all new registrants + if (!$.isEmptyObject(param)) { + if (param.a == "challenge-daily-mail-registrants") { + var challengeId = param.challengeId; + var now = param.currentDateTime; + $scope.composeEmail = {}; + apiService.getDailyChallengeRegistrantNames(challengeId, now) + .success(function (names) { + $scope.composeEmail.names = names.join("; "); + $("#emailCompose").modal(); + }); + } } + $scope.cancelSendEmail = function () { + $location.search({}); + }; + apiService.getEmployerDashboardInfo() .success(function (data) { utils.sortByDate(data.challenges, "startDateTime"); data.projects.sort(function (left, right) {return right.projectId - left.projectId;}); $scope.dashboardInfo = data; }) - .finally(function () {utils.sendNotification(jsonValue.notifications.loaded, $(window).height());}); + .finally(function () { + utils.sendNotification(jsonValue.notifications.loaded, $(window).height()); + }); $scope.changeChallengeStatus = function (status) { $scope.challengeStatus = status; From b033501075ec0f47f5a8d073a9f36518d0888597 Mon Sep 17 00:00:00 2001 From: khoa-nd Date: Thu, 1 Oct 2015 10:35:26 +0700 Subject: [PATCH 03/29] Log out the number of emails will be sent from cronjob (job alert, daily challenge summary or notify challenge weekly ) to debug duplicated email --- .../com/techlooper/cron/ChallengeTimelineNotifier.java | 3 +++ .../techlooper/cron/DailyChallengeSummaryEmailSender.java | 5 ++++- src/main/java/com/techlooper/cron/JobAlertEmailSender.java | 7 +++++++ .../com/techlooper/service/impl/ChallengeServiceImpl.java | 6 ++++++ 4 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/techlooper/cron/ChallengeTimelineNotifier.java b/src/main/java/com/techlooper/cron/ChallengeTimelineNotifier.java index fd2cfd980..786464401 100644 --- a/src/main/java/com/techlooper/cron/ChallengeTimelineNotifier.java +++ b/src/main/java/com/techlooper/cron/ChallengeTimelineNotifier.java @@ -37,6 +37,7 @@ public void notifyRegistrantAboutChallengeTimeline() throws Exception { if (enableJobAlert) { List challengePhases = Arrays.asList(ChallengePhaseEnum.REGISTRATION, ChallengePhaseEnum.IN_PROGRESS); + int count = 0; for (ChallengePhaseEnum challengePhase : challengePhases) { List challengeEntities = challengeService.listChallengesByPhase(challengePhase); @@ -50,6 +51,7 @@ public void notifyRegistrantAboutChallengeTimeline() throws Exception { if (StringUtils.isNotEmpty(challengeRegistrantEntity.getRegistrantEmail())) { challengeService.sendEmailNotifyRegistrantAboutChallengeTimeline( challengeEntity, challengeRegistrantEntity, challengePhase); + count++; } } catch (Exception ex) { LOGGER.error(ex.getMessage(), ex); @@ -57,6 +59,7 @@ public void notifyRegistrantAboutChallengeTimeline() throws Exception { } } } + LOGGER.info("There are " + count + " emails has been sent to notify challenge timeline"); } } diff --git a/src/main/java/com/techlooper/cron/DailyChallengeSummaryEmailSender.java b/src/main/java/com/techlooper/cron/DailyChallengeSummaryEmailSender.java index 2bdb6530d..18af951bd 100644 --- a/src/main/java/com/techlooper/cron/DailyChallengeSummaryEmailSender.java +++ b/src/main/java/com/techlooper/cron/DailyChallengeSummaryEmailSender.java @@ -25,21 +25,24 @@ public class DailyChallengeSummaryEmailSender { private Boolean enableJobAlert; @Scheduled(cron = "${scheduled.cron.dailyChallengeSummary}") - public void notifyRegistrantAboutChallengeTimeline() throws Exception { + public void sendDailyEmailAboutChallengeSummary() throws Exception { if (enableJobAlert) { List challengePhases = Arrays.asList(ChallengePhaseEnum.REGISTRATION, ChallengePhaseEnum.IN_PROGRESS); + int count = 0; for (ChallengePhaseEnum challengePhase : challengePhases) { List challengeEntities = challengeService.listChallengesByPhase(challengePhase); for (ChallengeEntity challengeEntity : challengeEntities) { try { challengeService.sendDailySummaryEmailToChallengeOwner(challengeEntity); + count++; } catch (Exception ex) { LOGGER.error(ex.getMessage(), ex); } } } + LOGGER.info("There are " + count + " daily emails has been sent about challenge summary"); } } } diff --git a/src/main/java/com/techlooper/cron/JobAlertEmailSender.java b/src/main/java/com/techlooper/cron/JobAlertEmailSender.java index 2bcc183f0..a67b9f829 100644 --- a/src/main/java/com/techlooper/cron/JobAlertEmailSender.java +++ b/src/main/java/com/techlooper/cron/JobAlertEmailSender.java @@ -6,6 +6,8 @@ import com.techlooper.model.JobSearchResponse; import com.techlooper.service.JobAggregatorService; import org.dozer.Mapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; @@ -25,6 +27,8 @@ @Service public class JobAlertEmailSender { + private final static Logger LOGGER = LoggerFactory.getLogger(JobAlertEmailSender.class); + @Value("${jobAlert.enable}") private Boolean enableJobAlert; @@ -48,16 +52,19 @@ public void sendJobAlertEmail() throws Exception { jobAggregatorService.findJobAlertRegistration(JobAlertPeriodEnum.WEEKLY); if (!jobAlertRegistrationEntities.isEmpty()) { + int count = 0; for (JobAlertRegistrationEntity jobAlertRegistrationEntity : jobAlertRegistrationEntities) { JobSearchCriteria criteria = dozerMapper.map(jobAlertRegistrationEntity, JobSearchCriteria.class); JobSearchResponse jobSearchResponse = jobAggregatorService.findJob(criteria); if (jobSearchResponse.getTotalJob() > 0) { jobAggregatorService.sendEmail(jobAlertRegistrationEntity, jobSearchResponse); jobAggregatorService.updateSendEmailResultCode(jobAlertRegistrationEntity, EMAIL_SENT); + count++; } else { jobAggregatorService.updateSendEmailResultCode(jobAlertRegistrationEntity, JOB_NOT_FOUND); } } + LOGGER.info("There are " + count + " job alert emails has been sent"); } } } diff --git a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java index 77cab5637..29dfd8f13 100644 --- a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java @@ -24,6 +24,8 @@ import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; +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; @@ -59,6 +61,8 @@ @Service public class ChallengeServiceImpl implements ChallengeService { + private final static Logger LOGGER = LoggerFactory.getLogger(ChallengeServiceImpl.class); + @Resource private ElasticsearchTemplate elasticsearchTemplateUserImport; @@ -233,6 +237,8 @@ public void sendEmailNotifyRegistrantAboutChallengeTimeline(ChallengeEntity chal 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( From 31b0b4c6e183e6404dd523fd85f6f638f3660317 Mon Sep 17 00:00:00 2001 From: Phuong H Date: Thu, 1 Oct 2015 10:42:32 +0700 Subject: [PATCH 04/29] Make email popup to be a component --- .../assets/modules/common/popupEmail.html | 38 +++++++++++++++++ .../modules/common/popupEmailDirective.js | 25 +++++++++++ .../employer-dashboard.html | 39 +---------------- .../employerDashboardController.js | 42 +++++++++++-------- 4 files changed, 88 insertions(+), 56 deletions(-) create mode 100644 src/main/webapp/assets/modules/common/popupEmail.html create mode 100644 src/main/webapp/assets/modules/common/popupEmailDirective.js diff --git a/src/main/webapp/assets/modules/common/popupEmail.html b/src/main/webapp/assets/modules/common/popupEmail.html new file mode 100644 index 000000000..8173ee6a6 --- /dev/null +++ b/src/main/webapp/assets/modules/common/popupEmail.html @@ -0,0 +1,38 @@ + \ No newline at end of file diff --git a/src/main/webapp/assets/modules/common/popupEmailDirective.js b/src/main/webapp/assets/modules/common/popupEmailDirective.js new file mode 100644 index 000000000..38eba2439 --- /dev/null +++ b/src/main/webapp/assets/modules/common/popupEmailDirective.js @@ -0,0 +1,25 @@ +techlooper.directive("popupEmail", function () { + return { + restrict: "E", + replace: true, + templateUrl: "modules/common/popupEmail.html", + scope: { + composeEmail: "=" + }, + link: function (scope, element, attr, ctrl) { + $('.summernote').summernote({ + toolbar: [ + ['fontname', ['fontname']], + ['fontsize', ['fontsize']], + ['style', ['bold', 'italic', 'underline', 'clear']], + ['color', ['color']], + ['para', ['ul', 'ol', 'paragraph']], + ['height', ['height']], + ['table', ['table']], + ['insert', ['link']], + ['misc', ['undo', 'redo', 'codeview', 'fullscreen']] + ] + }); + } + } +}); \ No newline at end of file diff --git a/src/main/webapp/assets/modules/employer-dashboard/employer-dashboard.html b/src/main/webapp/assets/modules/employer-dashboard/employer-dashboard.html index e8dd024ec..bec94b022 100644 --- a/src/main/webapp/assets/modules/employer-dashboard/employer-dashboard.html +++ b/src/main/webapp/assets/modules/employer-dashboard/employer-dashboard.html @@ -163,43 +163,6 @@

- + diff --git a/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js b/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js index 3b89f8bc6..19ff6b6c4 100644 --- a/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js +++ b/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js @@ -1,19 +1,19 @@ techlooper.controller('employerDashboardController', function ($scope, jsonValue, utils, apiService, $location, $filter, $route) { //$('.summernote').summernote(); //var edit = function () { - $('.summernote').summernote({ - toolbar: [ - ['fontname', ['fontname']], - ['fontsize', ['fontsize']], - ['style', ['bold', 'italic', 'underline', 'clear']], - ['color', ['color']], - ['para', ['ul', 'ol', 'paragraph']], - ['height', ['height']], - ['table', ['table']], - ['insert', ['link']], - ['misc', ['undo', 'redo', 'codeview', 'fullscreen']] - ] - }); + //$('.summernote').summernote({ + // toolbar: [ + // ['fontname', ['fontname']], + // ['fontsize', ['fontsize']], + // ['style', ['bold', 'italic', 'underline', 'clear']], + // ['color', ['color']], + // ['para', ['ul', 'ol', 'paragraph']], + // ['height', ['height']], + // ['table', ['table']], + // ['insert', ['link']], + // ['misc', ['undo', 'redo', 'codeview', 'fullscreen']] + // ] + //}); //var save = function () { // var aHTML = $('.click2edit').code(); //save HTML If you need(aHTML: array). // $('.click2edit').destroy(); @@ -21,12 +21,22 @@ techlooper.controller('employerDashboardController', function ($scope, jsonValue utils.sendNotification(jsonValue.notifications.loading, $(window).height()); + $scope.composeEmail = { + send: function() { + console.log($scope.composeEmail); + var content = $('.click2edit').code(); + console.log(content); + }, + cancel: function() { + $location.search({}); + } + }; + var param = $location.search(); if (!$.isEmptyObject(param)) { if (param.a == "challenge-daily-mail-registrants") { var challengeId = param.challengeId; var now = param.currentDateTime; - $scope.composeEmail = {}; apiService.getDailyChallengeRegistrantNames(challengeId, now) .success(function (names) { $scope.composeEmail.names = names.join("; "); @@ -35,10 +45,6 @@ techlooper.controller('employerDashboardController', function ($scope, jsonValue } } - $scope.cancelSendEmail = function () { - $location.search({}); - }; - apiService.getEmployerDashboardInfo() .success(function (data) { utils.sortByDate(data.challenges, "startDateTime"); From 475ded78d1350be1db615847ea4baec71dc6e23d Mon Sep 17 00:00:00 2001 From: khoa-nd Date: Thu, 1 Oct 2015 11:05:02 +0700 Subject: [PATCH 05/29] Translate email to VI --- .../template/challengeDailySummary.vi.ftl | 1017 +++++++---------- 1 file changed, 387 insertions(+), 630 deletions(-) diff --git a/src/main/resources/template/challengeDailySummary.vi.ftl b/src/main/resources/template/challengeDailySummary.vi.ftl index 28a006a21..bf5fdf81d 100644 --- a/src/main/resources/template/challengeDailySummary.vi.ftl +++ b/src/main/resources/template/challengeDailySummary.vi.ftl @@ -2,652 +2,409 @@ - - - - - - + @media (device-width: 320px) { + body { + max-width: 100% !important; + } + [class=hidden] { + display: none + } + [class=body-content] { + max-width: 100% !important; + width: 100% !important; + } + p[class=bottom-links] span { + display: block; + } + [class=cta-large] { + font-size: 24px !important; + } + [class=candidate] td { + font-size: 24px !important; + line-height: 30px !important; + } + [class=content-padding] { + padding: 20px !important; + } + [class=email] { + color: #00b9f2; + display: inline-block; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + max-width: 100%; + vertical-align: middle; + width: 240px; + } + [class=small-text] { + font-size: 13px !important; + white-space: nowrap !important + } + [class=logo] img { + width: 100px; + } + [class=fullWidth] { + width: 100% !important; + } + [class=btnFull] { + width: 100% !important; + padding: 10px 0 !important + } + .fullWidth { + width: 100% !important; + } + } + + - -
- - - - -
-
- - + +
+ + + - - - -
- - - - - - - -
- - - - - -
- - - - - + +
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

Thử Thách Trực Tuyến

-
-

Xây Dựng Đội Ngũ Phát Triển Sản Phẩm Của Chính Bạn Thông Qua Các Cuộc Thi Trực Tuyến.

-
- -
-

Xin chào thu.hoang@navigosgroup.com,

-
- -
-

Dưới đây là báo cáo hằng ngày cho thử thách Challenge Name

-
- -
- - - - - - - - - - -
- - - - -
Thử thách của bạn mở rộng như thế nào trong 24 giờ qua
- - - - - - - -
- -
- Bạn nhận được thêm 5 đăng ký. Các thí sinh mới tham gia bao gồm: -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - -
01Johnson Pham
- - - -
02Huynh Phuong
- - - -
03Huynh Phuong
- - - -
04Huynh Phuong
- - - -
05Huynh Phuong
- - - -
-
- - - - -
- Gửi Email Cho Tất Cả -
-
- -
-
- -
- - - - -
- - - - -
Đây có phải là thời điểm để quảng bá cho thử thách của bạn?
- - - - - - - - - - -
- -
Nếu bạn muốn nhận thêm nhiều lượt đăng ký, trả lời email này để chúng tôi có thể hỗ trợ bạn.
- -
-
-
- -
- - - - + + +
- - - - -
Khám phá số lượng bài nộp mới vào thử thách
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- Bạn nhận được thêm 10 bài nộp mới cho giai đoạn "Ý Tưởng" trong vòng 24 giờ qua: -
- -
- - - - - -
01Johnson Pham
- - - - - - -
- XemPhản hồi
-
- -
- - - - - -
02Johnson Pham
- - - - - - -
- XemPhản hồi
-
- -
- - - - - -
03Johnson Pham
- - - - - - -
- XemPhản hồi
-
- -
- - - - - -
04Johnson Pham
- - - - + - - - - - -
- XemPhản hồi +
+ + + + + + +
+ + + + + + + +
+ + + + + +
+
+ + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <#if latestSubmissions?has_content> + + + + + + + + + + + + +
+

Thử Thách Trực Tuyến

+
+

Xây Dựng Đội Ngũ Phát Triển Sản Phẩm Của Chính Bạn Thông Qua Các Cuộc Thi Trực Tuyến.

+
+ +
+

Xin chào,

+
+ +
+

Dưới đây là báo cáo hằng ngày cho thử thách ${challengeName} trong vòng 24 giờ qua

+
+ +
+ + + + + <#if latestRegistrants?has_content> + + + + + + + +
+ + + + +
Thử thách của bạn mở rộng như thế nào trong 24 giờ qua
+ + + + + + + +
+ +
+ Bạn nhận được thêm ${numberOfRegistrants} đăng ký mới +
+ <#if latestRegistrants?has_content> + + <#list latestRegistrants as registrant> + + + + + + + + + + + + + +
+ + + +
${registrant_index + 1}${registrant.registrantFirstName} ${registrant.registrantLastName}
+ + + +
+ +
+ + + + +
+ Gửi Email Cho Tất Cả +
+
+ +
+
+ +
+ + + + +
+ + + + +
Đây có phải là thời điểm để quảng bá cho thử thách của bạn?
+ + + + + + + + + + +
+ +
Nếu bạn muốn nhận thêm nhiều lượt đăng ký, trả lời email này để chúng tôi có thể hỗ trợ bạn.
+ +
+
+
+ +
+ + + + - + + + +
+ + + + +
Khám phá số lượng bài nộp mới vào thử thách
+ + + + + + + + <#list latestSubmissions as latestSubmission> + + + + + + + +
+ +
+ Bạn nhận được thêm ${numberOfSubmissions} bài nộp mới : +
+ +
+ + + + + +
${latestSubmission_index + 1}${latestSubmission.registrantName}
+ + + + + +
+ Xem Trước + Phản Hồi +
+
+
+ +
+
+ +
+ + + + +
+ +
+
+ + + + + + + +
+

KẾT NỐI VỚI CHÚNG TÔI

+
+ + LinkedIn + +
+ + + + + +
+
-
- -
- - - - - -
05Johnson Pham
- - - - - - -
- XemPhản hồi
-
- -
- - - - - -
06Johnson Pham
- - - - - - -
- XemPhản hồi
-
- -
- - - - - -
07Johnson Pham
- - - - - - -
- XemPhản hồi
-
- -
- - - - - -
08Johnson Pham
- - - - - - -
- XemPhản hồi
-
- -
- - - - - -
09Johnson Pham
- - - - - - -
- XemPhản hồi
-
- -
- - - - - -
10Johnson Pham
- - - - - - -
- XemPhản hồi
-
-
- -
-
- -
- - - - + +
- -
-
- - - - - - - -
-

KẾT NỐI VỚI CHÚNG TÔI

-
- - LinkedIn - -
- - - - -
-
-
-
-
From bd3d1e3d9ae0940401c9995b8d5a5c66efa2af31 Mon Sep 17 00:00:00 2001 From: Phuong H Date: Thu, 1 Oct 2015 11:13:45 +0700 Subject: [PATCH 06/29] Add composeEmail model to controller to send mail to daily registrant --- src/main/webapp/assets/modules/common/apiService.js | 7 +++++++ src/main/webapp/assets/modules/common/popupEmail.html | 2 +- .../employer-dashboard/employerDashboardController.js | 9 +++++++-- 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/src/main/webapp/assets/modules/common/apiService.js b/src/main/webapp/assets/modules/common/apiService.js index 7acdb7d33..9f473205a 100644 --- a/src/main/webapp/assets/modules/common/apiService.js +++ b/src/main/webapp/assets/modules/common/apiService.js @@ -206,6 +206,13 @@ techlooper.factory("apiService", function ($rootScope, $location, jsonValue, $ht * */ getDailyChallengeRegistrantNames: function(challengeId, now) { return $http.get("user/challengeRegistrantNames/" + challengeId + "/" + now); + }, + + /** + * @see com.techlooper.controller.UserController.sendEmailToDailyChallengeRegistrants + * */ + sendEmailToDailyChallengeRegistrants: function(challengeId, now, emailContent) { + return $http.post("user/challengeRegistrantNames/sendMailToDaily/" + challengeId + "/" + now, emailContent); } }; diff --git a/src/main/webapp/assets/modules/common/popupEmail.html b/src/main/webapp/assets/modules/common/popupEmail.html index 8173ee6a6..8b35a3deb 100644 --- a/src/main/webapp/assets/modules/common/popupEmail.html +++ b/src/main/webapp/assets/modules/common/popupEmail.html @@ -14,7 +14,7 @@
- +
diff --git a/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js b/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js index 19ff6b6c4..315628e72 100644 --- a/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js +++ b/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js @@ -23,9 +23,12 @@ techlooper.controller('employerDashboardController', function ($scope, jsonValue $scope.composeEmail = { send: function() { + $scope.composeEmail.content = $('.summernote').code(); console.log($scope.composeEmail); - var content = $('.click2edit').code(); - console.log(content); + //apiService.sendEmailToDailyChallengeRegistrants($scope.composeEmail.challengeId, $scope.composeEmail.now, $scope.composeEmail) + // .finally(function() { + // $scope.composeEmail.cancel(); + // }); }, cancel: function() { $location.search({}); @@ -37,6 +40,8 @@ techlooper.controller('employerDashboardController', function ($scope, jsonValue if (param.a == "challenge-daily-mail-registrants") { var challengeId = param.challengeId; var now = param.currentDateTime; + $scope.composeEmail.challengeId = challengeId; + $scope.composeEmail.now = now; apiService.getDailyChallengeRegistrantNames(challengeId, now) .success(function (names) { $scope.composeEmail.names = names.join("; "); From b3594af992b7ffa179b749672e906d072423a47e Mon Sep 17 00:00:00 2001 From: johnsonpham Date: Thu, 1 Oct 2015 11:13:56 +0700 Subject: [PATCH 07/29] remove link comopse email --- .../assets/modules/employer-dashboard/employer-dashboard.html | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/webapp/assets/modules/employer-dashboard/employer-dashboard.html b/src/main/webapp/assets/modules/employer-dashboard/employer-dashboard.html index bec94b022..790153fd2 100644 --- a/src/main/webapp/assets/modules/employer-dashboard/employer-dashboard.html +++ b/src/main/webapp/assets/modules/employer-dashboard/employer-dashboard.html @@ -1,5 +1,4 @@
- Open Email Compose
From 6908dc05f3c8fcbb58163b5537e5b37d8890d194 Mon Sep 17 00:00:00 2001 From: johnsonpham Date: Thu, 1 Oct 2015 11:17:26 +0700 Subject: [PATCH 08/29] hide "modal-backdrop" affter cancel compose email --- .../modules/employer-dashboard/employerDashboardController.js | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js b/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js index 315628e72..7bcbf5da8 100644 --- a/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js +++ b/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js @@ -32,6 +32,7 @@ techlooper.controller('employerDashboardController', function ($scope, jsonValue }, cancel: function() { $location.search({}); + $('.modal-backdrop').remove(); } }; From 9a62dc0bac0cea777c1931b63438ff8874909d63 Mon Sep 17 00:00:00 2001 From: Phuong H Date: Thu, 1 Oct 2015 13:01:55 +0700 Subject: [PATCH 09/29] Send mail to daily contestants --- .../techlooper/config/CoreConfiguration.java | 7 + .../techlooper/controller/UserController.java | 12 +- .../com/techlooper/model/EmailContent.java | 12 + .../techlooper/service/ChallengeService.java | 7 +- .../com/techlooper/service/EmailService.java | 11 + .../service/impl/ChallengeServiceImpl.java | 1211 +++++++++-------- .../service/impl/EmailServiceImpl.java | 45 + .../employerDashboardController.js | 10 +- 8 files changed, 712 insertions(+), 603 deletions(-) create mode 100644 src/main/java/com/techlooper/service/EmailService.java create mode 100644 src/main/java/com/techlooper/service/impl/EmailServiceImpl.java diff --git a/src/main/java/com/techlooper/config/CoreConfiguration.java b/src/main/java/com/techlooper/config/CoreConfiguration.java index 648716873..5364ff4a3 100644 --- a/src/main/java/com/techlooper/config/CoreConfiguration.java +++ b/src/main/java/com/techlooper/config/CoreConfiguration.java @@ -504,6 +504,7 @@ public void setApplicationContext(ApplicationContext applicationContext) throws public MimeMessage fromTechlooperMailMessage(JavaMailSender mailSender) throws MessagingException, UnsupportedEncodingException { MimeMessage mailMessage = mailSender.createMimeMessage(); mailMessage.setFrom(new InternetAddress(mailTechlooperForm, "TechLooper", "UTF-8")); + mailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); return mailMessage; } @@ -513,4 +514,10 @@ private ClientHttpRequestFactory clientHttpRequestFactory() { factory.setConnectTimeout(5000); return factory; } + + @Bean + public Template dailyChallengeSummaryMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("challengeDailySummary.vi.ftl"); + return template; + } } \ No newline at end of file diff --git a/src/main/java/com/techlooper/controller/UserController.java b/src/main/java/com/techlooper/controller/UserController.java index e018729e3..c1e872d06 100644 --- a/src/main/java/com/techlooper/controller/UserController.java +++ b/src/main/java/com/techlooper/controller/UserController.java @@ -34,7 +34,6 @@ import java.util.Arrays; import java.util.Collection; import java.util.List; -import java.util.stream.Collector; import java.util.stream.Collectors; import static java.util.stream.Collectors.toList; @@ -380,7 +379,7 @@ public WebinarInfoDto joinWebinar(@RequestBody JoinBySocialDto 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) { + @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() @@ -391,5 +390,12 @@ public List getDailyChallengeRegistrantNames(HttpServletRequest request, return null; } - + @PreAuthorize("hasAuthority('EMPLOYER')") + @RequestMapping(value = "user/challengeRegistrantNames/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); + } + } } diff --git a/src/main/java/com/techlooper/model/EmailContent.java b/src/main/java/com/techlooper/model/EmailContent.java index 5e0bba349..eacb9133e 100644 --- a/src/main/java/com/techlooper/model/EmailContent.java +++ b/src/main/java/com/techlooper/model/EmailContent.java @@ -1,6 +1,8 @@ package com.techlooper.model; +import javax.mail.Address; import java.io.Serializable; +import java.util.Set; /** * Created by phuonghqh on 10/1/15. @@ -11,6 +13,16 @@ public class EmailContent implements Serializable { private String content; + private Address[] bcc; + + public Address[] getBcc() { + return bcc; + } + + public void setBcc(Address[] bcc) { + this.bcc = bcc; + } + public String getSubject() { return subject; } diff --git a/src/main/java/com/techlooper/service/ChallengeService.java b/src/main/java/com/techlooper/service/ChallengeService.java index a7fd4fb56..c01fcaf79 100644 --- a/src/main/java/com/techlooper/service/ChallengeService.java +++ b/src/main/java/com/techlooper/service/ChallengeService.java @@ -4,10 +4,7 @@ import com.techlooper.entity.ChallengeRegistrantDto; import com.techlooper.entity.ChallengeRegistrantEntity; import com.techlooper.entity.ChallengeSubmissionEntity; -import com.techlooper.model.ChallengeDetailDto; -import com.techlooper.model.ChallengeDto; -import com.techlooper.model.ChallengePhaseEnum; -import com.techlooper.model.TimePeriodEnum; +import com.techlooper.model.*; import freemarker.template.TemplateException; import javax.mail.MessagingException; @@ -85,4 +82,6 @@ List findChallengeSubmissionWithinPeriod( boolean isOwnerOfChallenge(String ownerEmail, Long challengeId); + boolean sendEmailToDailyChallengeRegistrants(String challengeOwner, Long challengeId, Long now, EmailContent emailContent); + } diff --git a/src/main/java/com/techlooper/service/EmailService.java b/src/main/java/com/techlooper/service/EmailService.java new file mode 100644 index 000000000..adc56a1de --- /dev/null +++ b/src/main/java/com/techlooper/service/EmailService.java @@ -0,0 +1,11 @@ +package com.techlooper.service; + +import com.techlooper.model.EmailContent; + +/** + * Created by phuonghqh on 10/1/15. + */ +public interface EmailService { + + boolean sendEmailWithBcc(EmailContent emailContent); +} diff --git a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java index b1c6421ba..eacd25308 100644 --- a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java @@ -9,6 +9,7 @@ import com.techlooper.repository.elasticsearch.ChallengeRepository; import com.techlooper.repository.elasticsearch.ChallengeSubmissionRepository; import com.techlooper.service.ChallengeService; +import com.techlooper.service.EmailService; import com.techlooper.util.DateTimeUtils; import freemarker.template.Template; import freemarker.template.TemplateException; @@ -61,257 +62,264 @@ @Service public class ChallengeServiceImpl implements ChallengeService { - private final static Logger LOGGER = LoggerFactory.getLogger(ChallengeServiceImpl.class); + private final static Logger LOGGER = LoggerFactory.getLogger(ChallengeServiceImpl.class); - @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; - 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 = DateTimeUtils.daysBetween(DateTimeUtils.currentDate(), challengeEntity.getRegistrationDateTime()) + 1; - } else if (challengePhase == ChallengePhaseEnum.IN_PROGRESS) { - numberOfDays = DateTimeUtils.daysBetween(DateTimeUtils.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 ChallengeDetailDto getChallengeDetail(Long challengeId) { - ChallengeEntity challengeEntity = challengeRepository.findOne(challengeId); - if (challengeEntity != null && !Boolean.TRUE.equals(challengeEntity.getExpired())) { - ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); - challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeId)); - return challengeDetailDto; - } - return null; - } - - 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) throws MessagingException, IOException, TemplateException { - Long challengeId = challengeRegistrantDto.getChallengeId(); - boolean isExist = checkIfChallengeRegistrantExist(challengeId, challengeRegistrantDto.getRegistrantEmail()); - - if (!isExist) { - ChallengeRegistrantEntity challengeRegistrantEntity = dozerMapper.map(challengeRegistrantDto, ChallengeRegistrantEntity.class); - ChallengeEntity challengeEntity = challengeRepository.findOne(challengeId); - sendApplicationEmailToContestant(challengeEntity, challengeRegistrantEntity); - sendApplicationEmailToEmployer(challengeEntity, challengeRegistrantEntity); - challengeRegistrantEntity.setMailSent(Boolean.TRUE); - challengeRegistrantEntity.setRegistrantId(new Date().getTime()); - challengeRegistrantRepository.save(challengeRegistrantEntity); - } + @Resource + private EmailService emailService; - return getNumberOfRegistrants(challengeId); - } - - public List listChallenges() { + 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 = DateTimeUtils.daysBetween(DateTimeUtils.currentDate(), challengeEntity.getRegistrationDateTime()) + 1; + } + else if (challengePhase == ChallengePhaseEnum.IN_PROGRESS) { + numberOfDays = DateTimeUtils.daysBetween(DateTimeUtils.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 ChallengeDetailDto getChallengeDetail(Long challengeId) { + ChallengeEntity challengeEntity = challengeRepository.findOne(challengeId); + if (challengeEntity != null && !Boolean.TRUE.equals(challengeEntity.getExpired())) { + ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); + challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeId)); + return challengeDetailDto; + } + return null; + } + + 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) throws MessagingException, IOException, TemplateException { + Long challengeId = challengeRegistrantDto.getChallengeId(); + boolean isExist = checkIfChallengeRegistrantExist(challengeId, challengeRegistrantDto.getRegistrantEmail()); + + if (!isExist) { + ChallengeRegistrantEntity challengeRegistrantEntity = dozerMapper.map(challengeRegistrantDto, ChallengeRegistrantEntity.class); + ChallengeEntity challengeEntity = challengeRepository.findOne(challengeId); + sendApplicationEmailToContestant(challengeEntity, challengeRegistrantEntity); + sendApplicationEmailToEmployer(challengeEntity, challengeRegistrantEntity); + challengeRegistrantEntity.setMailSent(Boolean.TRUE); + challengeRegistrantEntity.setRegistrantId(new Date().getTime()); + challengeRegistrantRepository.save(challengeRegistrantEntity); + } + + return getNumberOfRegistrants(challengeId); + } + + public List listChallenges() { // List challenges = new ArrayList<>(); // Iterator challengeIter = challengeRepository.findAll().iterator(); // while (challengeIter.hasNext()) { @@ -321,169 +329,174 @@ public List listChallenges() { // challenges.add(challengeDetailDto); // } // return sortChallengesByDescendingStartDate(challenges); - TermQueryBuilder notExpiredQuery = termQuery("expired", Boolean.TRUE); - Iterable challengeIterator = challengeRepository.search(boolQuery().mustNot(notExpiredQuery)); - ArrayList challenges = new ArrayList<>(); - challengeIterator.forEach(challengeEntity -> { - ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); - challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeEntity.getChallengeId())); - challenges.add(challengeDetailDto); - }); - return sortChallengesByDescendingStartDate(challenges); - } - - private void sendContestApplicationEmail(Template template, String mailSubject, Address[] recipientAddresses, - ChallengeEntity challengeEntity, ChallengeRegistrantEntity challengeRegistrantEntity, boolean hasReplyTo) - throws MessagingException, IOException, TemplateException { - postChallengeMailMessage.setRecipients(Message.RecipientType.TO, recipientAddresses); - - if (hasReplyTo) { - postChallengeMailMessage.setReplyTo(InternetAddress.parse(challengeRegistrantEntity.getRegistrantEmail())); - } else { - postChallengeMailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); + 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; } - - 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()); + else if (challenge1.getStartDateTime() == null) { + return 1; } - return InternetAddress.parse(StringUtils.join(emails, ',')); - } - - private List sortChallengesByDescendingStartDate(List challenges) { - SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); - return challenges.stream().sorted((challenge1, challenge2) -> { - try { - if (challenge2.getStartDateTime() == null) { - return -1; - } else if (challenge1.getStartDateTime() == null) { - return 1; - } - long challenge2StartDate = sdf.parse(challenge2.getStartDateTime()).getTime(); - long challenge1StartDate = sdf.parse(challenge1.getStartDateTime()).getTime(); - if (challenge2StartDate - challenge1StartDate > 0) { - return 1; - } else if (challenge2StartDate - challenge1StartDate < 0) { - return -1; - } else { - return 0; - } - } catch (ParseException e) { - return 0; - } - }).collect(Collectors.toList()); - } - - public boolean checkIfChallengeRegistrantExist(Long challengeId, String email) { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder(); - searchQueryBuilder.withQuery(boolQuery() - .must(matchPhraseQuery("registrantEmail", email)) - .must(termQuery("challengeId", challengeId)) - .must(termQuery("mailSent", true))); - - 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() { + 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(Collectors.toList()); + } + + public boolean checkIfChallengeRegistrantExist(Long challengeId, String email) { + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder(); + searchQueryBuilder.withQuery(boolQuery() + .must(matchPhraseQuery("registrantEmail", email)) + .must(termQuery("challengeId", challengeId)) + .must(termQuery("mailSent", true))); + + 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)); @@ -494,226 +507,242 @@ 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 challenges; - } - - public List listChallenges(String ownerEmail) { - MatchQueryBuilder authorEmailQuery = matchQuery("authorEmail", ownerEmail).minimumShouldMatch("100%"); - TermQueryBuilder notExpiredQuery = termQuery("expired", Boolean.TRUE); - Iterable challenges = challengeRepository.search(boolQuery().must(authorEmailQuery).mustNot(notExpiredQuery)); - ArrayList dtos = new ArrayList<>(); - challenges.forEach(challengeEntity -> { - ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); - challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeEntity.getChallengeId())); - dtos.add(challengeDetailDto); - }); - dozerMapper.map(challenges, dtos); - return dtos; - } - - 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 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 false; - } - - public ChallengeDto findChallengeById(Long id) { - return dozerMapper.map(challengeRepository.findOne(id), ChallengeDto.class); - } - - public Set findRegistrantsByOwner(String ownerEmail, Long challengeId) { - BoolQueryBuilder boolQueryBuilder = boolQuery(); - - if (StringUtils.isNotEmpty(ownerEmail)) { - boolQueryBuilder.must(matchQuery("authorEmail", ownerEmail).minimumShouldMatch("100%")); - } - - TermQueryBuilder challengeQuery = termQuery("challengeId", challengeId); - if (challengeId != null) { - boolQueryBuilder.must(challengeQuery); - } - - boolQueryBuilder.mustNot(termQuery("expired", Boolean.TRUE)); - Iterator challengeIterator = challengeRepository.search(boolQueryBuilder).iterator(); - Set registrantDtos = new HashSet<>(); - - if (challengeIterator.hasNext()) { - Iterator registrants = challengeRegistrantRepository.search(challengeQuery).iterator(); - registrants.forEachRemaining(registrant -> registrantDtos.add(dozerMapper.map(registrant, ChallengeRegistrantDto.class))); - } - - return registrantDtos; - } - - public ChallengeRegistrantDto saveRegistrant(String ownerEmail, ChallengeRegistrantDto challengeRegistrantDto) { - ChallengeEntity challenge = challengeRepository.findOne(challengeRegistrantDto.getChallengeId()); - if (ownerEmail.equalsIgnoreCase(challenge.getAuthorEmail())) { - ChallengeRegistrantEntity registrant = challengeRegistrantRepository.findOne(challengeRegistrantDto.getRegistrantId()); - challengeRegistrantDto.setRegistrantEmail(registrant.getRegistrantEmail()); - dozerMapper.map(challengeRegistrantDto, registrant); - registrant = challengeRegistrantRepository.save(registrant); - challengeRegistrantDto = dozerMapper.map(registrant, ChallengeRegistrantDto.class); + }); + } + return challenges; + } + + public List listChallenges(String ownerEmail) { + MatchQueryBuilder authorEmailQuery = matchQuery("authorEmail", ownerEmail).minimumShouldMatch("100%"); + TermQueryBuilder notExpiredQuery = termQuery("expired", Boolean.TRUE); + Iterable challenges = challengeRepository.search(boolQuery().must(authorEmailQuery).mustNot(notExpiredQuery)); + ArrayList dtos = new ArrayList<>(); + challenges.forEach(challengeEntity -> { + ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); + challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeEntity.getChallengeId())); + dtos.add(challengeDetailDto); + }); + dozerMapper.map(challenges, dtos); + return dtos; + } + + 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(String ownerEmail, Long challengeId) { + BoolQueryBuilder boolQueryBuilder = boolQuery(); + + if (StringUtils.isNotEmpty(ownerEmail)) { + boolQueryBuilder.must(matchQuery("authorEmail", ownerEmail).minimumShouldMatch("100%")); + } + + TermQueryBuilder challengeQuery = termQuery("challengeId", challengeId); + if (challengeId != null) { + boolQueryBuilder.must(challengeQuery); + } + + boolQueryBuilder.mustNot(termQuery("expired", Boolean.TRUE)); + Iterator challengeIterator = challengeRepository.search(boolQueryBuilder).iterator(); + Set registrantDtos = new HashSet<>(); + + if (challengeIterator.hasNext()) { + Iterator registrants = challengeRegistrantRepository.search(challengeQuery).iterator(); + registrants.forEachRemaining(registrant -> registrantDtos.add(dozerMapper.map(registrant, ChallengeRegistrantDto.class))); + } + + return registrantDtos; + } + + 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)); - searchQueryBuilder.withPageable(new PageRequest(0, 100)); - - List result = new ArrayList<>(); - Iterator iterator = challengeRegistrantRepository.search(searchQueryBuilder.build()).iterator(); - while (iterator.hasNext()) { - result.add(iterator.next()); - } - - 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)); - - Long pastTime = currentDateTime - period.getMiliseconds() > 0 ? currentDateTime - period.getMiliseconds() : 0; - boolQueryBuilder.must(rangeQuery("challengeSubmissionId").from(pastTime)); - searchQueryBuilder.withQuery(boolQueryBuilder); - searchQueryBuilder.withSort(fieldSort("challengeSubmissionId").order(SortOrder.DESC)); - searchQueryBuilder.withPageable(new PageRequest(0, 100)); - - List result = new ArrayList<>(); - Iterator iterator = challengeSubmissionRepository.search(searchQueryBuilder.build()).iterator(); - while (iterator.hasNext()) { - result.add(iterator.next()); - } - - return result; - } - - @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())); - - 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); + 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)); + searchQueryBuilder.withPageable(new PageRequest(0, 100)); + + List result = new ArrayList<>(); + Iterator iterator = challengeRegistrantRepository.search(searchQueryBuilder.build()).iterator(); + while (iterator.hasNext()) { + result.add(iterator.next()); + } + + 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)); + + Long pastTime = currentDateTime - period.getMiliseconds() > 0 ? currentDateTime - period.getMiliseconds() : 0; + boolQueryBuilder.must(rangeQuery("challengeSubmissionId").from(pastTime)); + searchQueryBuilder.withQuery(boolQueryBuilder); + searchQueryBuilder.withSort(fieldSort("challengeSubmissionId").order(SortOrder.DESC)); + searchQueryBuilder.withPageable(new PageRequest(0, 100)); + + List result = new ArrayList<>(); + Iterator iterator = challengeSubmissionRepository.search(searchQueryBuilder.build()).iterator(); + while (iterator.hasNext()) { + result.add(iterator.next()); + } + + return result; + } + + @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())); + + 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(Collectors.joining(",")); + try { + csvEmails += ",phuonghqh@gmail.com";//TODO remove this value because its used to test only + emailContent.setBcc(InternetAddress.parse(csvEmails)); + } + catch (AddressException e) { + LOGGER.debug("Can not parse email address", e); + return false; + } } + return emailService.sendEmailWithBcc(emailContent); + } } diff --git a/src/main/java/com/techlooper/service/impl/EmailServiceImpl.java b/src/main/java/com/techlooper/service/impl/EmailServiceImpl.java new file mode 100644 index 000000000..b3d412c1e --- /dev/null +++ b/src/main/java/com/techlooper/service/impl/EmailServiceImpl.java @@ -0,0 +1,45 @@ +package com.techlooper.service.impl; + +import com.techlooper.model.EmailContent; +import com.techlooper.service.EmailService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import javax.mail.Message; +import javax.mail.MessagingException; +import javax.mail.internet.MimeMessage; +import javax.mail.internet.MimeUtility; + +/** + * Created by phuonghqh on 10/1/15. + */ +@Service +public class EmailServiceImpl implements EmailService { + + private final Logger LOGGER = LoggerFactory.getLogger(EmailServiceImpl.class); + + @Resource + private JavaMailSender mailSender; + + @Resource + private MimeMessage fromTechlooperMailMessage; + + public boolean sendEmailWithBcc(EmailContent emailContent) { + try { + fromTechlooperMailMessage.setSubject(MimeUtility.encodeText(emailContent.getSubject(), "UTF-8", null)); + fromTechlooperMailMessage.setText(emailContent.getContent(), "UTF-8", "html"); + //InternetAddress.parse(StringUtils.join(emails, ',')) + fromTechlooperMailMessage.setRecipients(Message.RecipientType.BCC, emailContent.getBcc()); + fromTechlooperMailMessage.saveChanges(); + mailSender.send(fromTechlooperMailMessage); + } + catch (Exception e) { + LOGGER.error("Can not send email", e); + return false; + } + return true; + } +} diff --git a/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js b/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js index 7bcbf5da8..31545c291 100644 --- a/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js +++ b/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js @@ -24,11 +24,11 @@ techlooper.controller('employerDashboardController', function ($scope, jsonValue $scope.composeEmail = { send: function() { $scope.composeEmail.content = $('.summernote').code(); - console.log($scope.composeEmail); - //apiService.sendEmailToDailyChallengeRegistrants($scope.composeEmail.challengeId, $scope.composeEmail.now, $scope.composeEmail) - // .finally(function() { - // $scope.composeEmail.cancel(); - // }); + //console.log($scope.composeEmail); + apiService.sendEmailToDailyChallengeRegistrants($scope.composeEmail.challengeId, $scope.composeEmail.now, $scope.composeEmail) + .finally(function() { + $scope.composeEmail.cancel(); + }); }, cancel: function() { $location.search({}); From 4dac6da99eaa8f06e0833abe9798b5eed527867d Mon Sep 17 00:00:00 2001 From: Phuong H Date: Thu, 1 Oct 2015 13:58:37 +0700 Subject: [PATCH 10/29] Add email template to send all contestants --- .../techlooper/config/CoreConfiguration.java | 10 ++++++-- .../techlooper/controller/UserController.java | 2 ++ .../com/techlooper/model/EmailContent.java | 22 ++++++++++++++++ .../service/impl/EmailServiceImpl.java | 1 - src/main/webapp/assets/modules/_app.js | 25 ++----------------- .../interceptor/languageHttpInterceptor.js | 11 ++++++++ 6 files changed, 45 insertions(+), 26 deletions(-) create mode 100644 src/main/webapp/assets/modules/common/interceptor/languageHttpInterceptor.js diff --git a/src/main/java/com/techlooper/config/CoreConfiguration.java b/src/main/java/com/techlooper/config/CoreConfiguration.java index 5364ff4a3..d6eef533a 100644 --- a/src/main/java/com/techlooper/config/CoreConfiguration.java +++ b/src/main/java/com/techlooper/config/CoreConfiguration.java @@ -516,8 +516,14 @@ private ClientHttpRequestFactory clientHttpRequestFactory() { } @Bean - public Template dailyChallengeSummaryMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("challengeDailySummary.vi.ftl"); + public Template challengeEmployerMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("challengeEmployerEmail.en.ftl"); + return template; + } + + @Bean + public Template challengeEmployerMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("challengeEmployerEmail.vi.ftl"); return template; } } \ No newline at end of file diff --git a/src/main/java/com/techlooper/controller/UserController.java b/src/main/java/com/techlooper/controller/UserController.java index c1e872d06..d83f4dc0f 100644 --- a/src/main/java/com/techlooper/controller/UserController.java +++ b/src/main/java/com/techlooper/controller/UserController.java @@ -394,6 +394,8 @@ public List getDailyChallengeRegistrantNames(HttpServletRequest request, @RequestMapping(value = "user/challengeRegistrantNames/sendMailToDaily/{challengeId}/{now}", method = RequestMethod.POST) public void sendEmailToDailyChallengeRegistrants(HttpServletRequest request, HttpServletResponse response, @PathVariable Long challengeId, @PathVariable Long now, @RequestBody EmailContent emailContent) { + String lang = request.getParameter("lang"); + System.out.println(lang); if (!challengeService.sendEmailToDailyChallengeRegistrants(request.getRemoteUser(), challengeId, now, emailContent)) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } diff --git a/src/main/java/com/techlooper/model/EmailContent.java b/src/main/java/com/techlooper/model/EmailContent.java index eacb9133e..c3c5ef31c 100644 --- a/src/main/java/com/techlooper/model/EmailContent.java +++ b/src/main/java/com/techlooper/model/EmailContent.java @@ -1,5 +1,7 @@ package com.techlooper.model; +import freemarker.template.Template; + import javax.mail.Address; import java.io.Serializable; import java.util.Set; @@ -15,6 +17,26 @@ public class EmailContent implements Serializable { private Address[] bcc; + private Template template; + + private Language language; + + public Language getLanguage() { + return language; + } + + public void setLanguage(Language language) { + this.language = language; + } + + public Template getTemplate() { + return template; + } + + public void setTemplate(Template template) { + this.template = template; + } + public Address[] getBcc() { return bcc; } diff --git a/src/main/java/com/techlooper/service/impl/EmailServiceImpl.java b/src/main/java/com/techlooper/service/impl/EmailServiceImpl.java index b3d412c1e..976447f8c 100644 --- a/src/main/java/com/techlooper/service/impl/EmailServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/EmailServiceImpl.java @@ -31,7 +31,6 @@ public boolean sendEmailWithBcc(EmailContent emailContent) { try { fromTechlooperMailMessage.setSubject(MimeUtility.encodeText(emailContent.getSubject(), "UTF-8", null)); fromTechlooperMailMessage.setText(emailContent.getContent(), "UTF-8", "html"); - //InternetAddress.parse(StringUtils.join(emails, ',')) fromTechlooperMailMessage.setRecipients(Message.RecipientType.BCC, emailContent.getBcc()); fromTechlooperMailMessage.saveChanges(); mailSender.send(fromTechlooperMailMessage); diff --git a/src/main/webapp/assets/modules/_app.js b/src/main/webapp/assets/modules/_app.js index a58a470c2..cf39b0125 100644 --- a/src/main/webapp/assets/modules/_app.js +++ b/src/main/webapp/assets/modules/_app.js @@ -32,29 +32,8 @@ var techlooper = angular.module("Techlooper", [ ]); techlooper.config(["$routeProvider", "$translateProvider", "$authProvider", "localStorageServiceProvider", "$httpProvider", - function ($routeProvider, $translateProvider, $authProvider, localStorageServiceProvider, $httpProvider) { - $httpProvider.interceptors.push(function ($q, utils, jsonValue, $location, $rootScope) { - return { - request: function (request) { - return request || $q.when(request); - }, - - responseError: function (rejection) { - switch (rejection.status) { - //case 403: - // $rootScope.lastPath = $location.path(); - // $location.path("/login"); - // break; - - case 500: - case 404: - utils.sendNotification(jsonValue.notifications.serverError); - break; - } - return $q.reject(rejection); - } - }; - }); + function ($routeProvider, $translateProvider, $authProvider, localStorageServiceProvider, $httpProvider, languageHttpInterceptor) { + $httpProvider.interceptors.push(languageHttpInterceptor); localStorageServiceProvider .setPrefix('techlooper') diff --git a/src/main/webapp/assets/modules/common/interceptor/languageHttpInterceptor.js b/src/main/webapp/assets/modules/common/interceptor/languageHttpInterceptor.js new file mode 100644 index 000000000..230dfb9fe --- /dev/null +++ b/src/main/webapp/assets/modules/common/interceptor/languageHttpInterceptor.js @@ -0,0 +1,11 @@ +techlooper.factory('languageHttpInterceptor', function ($rootScope, jsonValue, $q, $translate) { + var instance = { + request: function (config) { + config.params = config.params || {}; + config.params.lang = $translate.use(); + return config || $q.when(config); + } + }; + + return instance; +}); \ No newline at end of file From abd915650f899b3881a03922edd33f0bd2dfad6d Mon Sep 17 00:00:00 2001 From: khoa-nd Date: Thu, 1 Oct 2015 14:24:04 +0700 Subject: [PATCH 11/29] Change action name for feedback link --- src/main/resources/template/challengeDailySummary.en.ftl | 2 +- src/main/resources/template/challengeDailySummary.vi.ftl | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/resources/template/challengeDailySummary.en.ftl b/src/main/resources/template/challengeDailySummary.en.ftl index 3effb3dd5..cc7aaa06b 100644 --- a/src/main/resources/template/challengeDailySummary.en.ftl +++ b/src/main/resources/template/challengeDailySummary.en.ftl @@ -333,7 +333,7 @@
Review - Feedback + Feedback
diff --git a/src/main/resources/template/challengeDailySummary.vi.ftl b/src/main/resources/template/challengeDailySummary.vi.ftl index bf5fdf81d..96b60cfa1 100644 --- a/src/main/resources/template/challengeDailySummary.vi.ftl +++ b/src/main/resources/template/challengeDailySummary.vi.ftl @@ -333,7 +333,7 @@
Xem Trước - Phản Hồi + Phản Hồi
From 96e81e417c15e3041a502d4e0c7e806004bdc13b Mon Sep 17 00:00:00 2001 From: johnsonpham Date: Thu, 1 Oct 2015 14:48:46 +0700 Subject: [PATCH 12/29] update style for milestone time line --- .../contest-detail/contest-detail.tem.html | 17 +++++--- .../webapp/assets/sass/contest-detail.sass | 42 +++++++++++++++---- 2 files changed, 45 insertions(+), 14 deletions(-) diff --git a/src/main/webapp/assets/modules/contest-detail/contest-detail.tem.html b/src/main/webapp/assets/modules/contest-detail/contest-detail.tem.html index c7b6b2120..7e255f4fc 100644 --- a/src/main/webapp/assets/modules/contest-detail/contest-detail.tem.html +++ b/src/main/webapp/assets/modules/contest-detail/contest-detail.tem.html @@ -80,29 +80,33 @@

ng-class="{'three-cols': contestDetail.timeline == 3, 'four-cols': contestDetail.timeline == 4, 'five-cols': contestDetail.timeline == 5}"> - {{contestDetail.startDateTime}} - {{contestDetail.registrationDateTime}} + + {{contestDetail.startDateTime}} + {{contestDetail.registrationDateTime}}
- 15/09/2015 + + 15/09/2015
- 15/09/2015 + + 15/09/2015
- 15/09/2015 + + 15/09/2015
@@ -113,7 +117,8 @@

ng-class="{'three-cols': contestDetail.timeline == 3, 'four-cols': contestDetail.timeline == 4, 'five-cols': contestDetail.timeline == 5}"> - {{contestDetail.submissionDateTime}} + + {{contestDetail.submissionDateTime}} diff --git a/src/main/webapp/assets/sass/contest-detail.sass b/src/main/webapp/assets/sass/contest-detail.sass index 9f4ed9eff..aca2e84a9 100644 --- a/src/main/webapp/assets/sass/contest-detail.sass +++ b/src/main/webapp/assets/sass/contest-detail.sass @@ -341,6 +341,7 @@ height: 20px border-right: 1px dotted #ccc padding-bottom: 0 + float: left span.date-right text-align: right font-weight: 300 @@ -349,7 +350,7 @@ clear: none float: right font-size: 12px - padding: 10px 2px 0 0 + padding: 0 2px 0 0 span.date-left text-align: left font-weight: 300 @@ -358,51 +359,76 @@ clear: none float: left font-size: 12px - padding: 10px 0 0 2px + padding: 0 + span.line-dot + height: 20px + width: 100% + display: inline-block + clear: both + float: left .phase-box.phase-registration color: #1ea185 padding-bottom: 0 span.line-color background-color: #1ea185 - span.date-right + span.line-dot border-right: 1px dotted #1ea185 - span.date-left border-left: 1px dotted #1ea185 + span.date-left + i + margin-left: -5px + span.date-right + margin-right: -7px .phase-box.phase-idea color: #9bba5c padding-bottom: 0 span.line-color background-color: #9bba5c span.date-right + i + margin-right: -7px + span.line-dot border-right: 1px dotted #9bba5c .phase-box.phase-uiux color: #f29b27 padding-bottom: 0 span.line-color background-color: #f29b27 - span.date-right + span.line-dot border-right: 1px dotted #f29b27 + span.date-right + i + margin-right: -7px .phase-box.phase-prototype color: #bd392f padding-bottom: 0 span.line-color background-color: #bd392f - span.date-right + span.line-dot border-right: 1px dotted #bd392f + span.date-right + i + margin-right: -7px .phase-box.phase-in-progress color: #257abb padding-bottom: 0 span.line-color background-color: #257abb - span.date-right + span.line-dot border-right: 1px dotted #257abb + span.date-right + i + margin-right: -7px .phase-box.phase-final-app color: #257abb padding-bottom: 0 span.line-color background-color: #257abb - span.date-right + span.line-dot border-right: 1px dotted #257abb + span.date-right + i + margin-right: -7px .phase-box.two-cols width: 50% From 7e1a5af37bdc9b0be72081ef23faee1eb7f9f647 Mon Sep 17 00:00:00 2001 From: johnsonpham Date: Thu, 1 Oct 2015 15:15:10 +0700 Subject: [PATCH 13/29] update translate and position of tooltips of milestone date line --- .../modules/post-contest/postContestTimeline.html | 12 ++++++------ .../post-contest/postContestTimelineDirective.js | 8 +++++++- .../assets/modules/translation/messages_en.json | 7 +++++-- .../assets/modules/translation/messages_vi.json | 7 +++++-- 4 files changed, 23 insertions(+), 11 deletions(-) diff --git a/src/main/webapp/assets/modules/post-contest/postContestTimeline.html b/src/main/webapp/assets/modules/post-contest/postContestTimeline.html index 3778e221a..5207ec22b 100644 --- a/src/main/webapp/assets/modules/post-contest/postContestTimeline.html +++ b/src/main/webapp/assets/modules/post-contest/postContestTimeline.html @@ -6,7 +6,7 @@
-
-

@@ -90,7 +90,7 @@

@@ -117,7 +117,7 @@

@@ -143,7 +143,7 @@

- *", "challengeRegisterTip": "Typically between 2-4 weeks after the challenge start date. After this date, the contest is officially in-progress and contestants are working on the challenge. It is up to you to accept more registrations at this stage.", - "challengeSubmit": "And Contestants Must Submit By: *", + "challengeSubmit": "And Contestants Must Submit Final App By:: *", "challengeSubmitTip": "Contest duration should not be longer than 8 weeks. This date officially ends the contest. All the contestants must submit their solutions by this date.", "userName": "Enter User Name/Email Address: *", "userNameEX": "Username / Example@vietnamworks.com", @@ -750,5 +750,8 @@ "finalDateGtRegisterDate": "Final submission day should be ahead of Register day at least 1 day.", "mailSubject": "Subject:", "mailTo": "To:", - "mailSend": "Send" + "mailSend": "Send", + "challengeIdeaTips": "This date officially ends the Idea phase of the contest. Contestants must propose their ideas to Contest Owner by this date. Once the Contest Owner approves the idea, contestant who proposed the idea will be selected to go to the next phase.", + "challengeUIUXTips": "This date officially ends the UI/UX phase of the contest. Contestants must propose their UI/UX mockups and/or Usability Test if required to Contest Owner by this date. Once the Contest Owner approves the mockup, contestant who submitted that mockup will be selected to go to the next phase.", + "challengePrototypeTips": "This date officially ends the Prototype phase of the contest. Contestants must submit their prototypes to Contest Owner by this date. Once the Contest Owner approves the prototype, contestant who submitted that prototype will be selected to go to the next phase." } \ 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 38d22b4c0..0106da55a 100644 --- a/src/main/webapp/assets/modules/translation/messages_vi.json +++ b/src/main/webapp/assets/modules/translation/messages_vi.json @@ -354,7 +354,7 @@ "challengeStartTip": "Đây là Ngày Bắt Đầu cuộc thi và cũng là ngày bắt đầu nhận đăng ký từ các thí sinh. Trong giai đoạn này, Nhà tổ chức cuộc thi sẽ vừa quảng bá cuộc thi vừa nhận thông tin các thí sinh tham gia.", "challengeRegister": "Thí Sinh Phải Đăng Ký Không Quá: *", "challengeRegisterTip": "Thông thường, Ngày Hết Hạn Đăng Ký sẽ sau Ngày Bắt Đầu khoảng từ 2 đến 4 tuần. Khi hết hạn đăng ký, cuộc thi sẽ chính thức diễn ra. Trong giai đoạn này, bạn vẫn có thể chấp nhận thêm các đăng ký mới.", - "challengeSubmit": "Và Thí Sinh Phải Gửi Kết Quả Không Quá: *", + "challengeSubmit": "Và Thí Sinh Phải Gửi Sản Phẩm Cuối Trước Ngày: *", "challengeSubmitTip": "Thời gian diễn ra của cuộc thi bình thường sẽ không quá 8 tuần. Ngày Hết Hạn Nộp Bài được xem là ngày kết thúc của cuộc thi. Mọi thí sinh phải nộp sản phẩm trước hạn nộp bài.", "userName": "Tên truy cập/Địa chỉ Email: *", "userNameEX": "Tên truy cập / example@vietnamworks.com", @@ -750,5 +750,8 @@ "finalApp": "Final App", "mailSubject": "Tiêu đề:", "mailTo": "Gửi tới:", - "mailSend": "Gửi Email" + "mailSend": "Gửi Email", + "challengeIdeaTips": "Đây là ngày kết thúc giai đoạn Ý Tưởng của cuộc thi và thí sinh phải đề xuất ý tưởng trước ngày này. Nhà Tổ Chức sẽ phân loại, đánh giá và sắp xếp các ý tưởng. Các thí sinh với ý tưởng xuất sắc sẽ được lựa chọn để vào tiếp vòng trong.", + "challengeUIUXTips":"Đây là ngày kết thúc giai đoạn UI/UX của cuộc thi và thí sinh phải nộp UI/UX mockup và/hay kết quả Kiểm Tra Khả Dụng (Usability Test) nếu được yêu cầu trước ngày này. Nhà Tổ Chức sẽ chịu trách nhiệm đánh giá UI/UX mockup và sẽ lựa chon các thí sinh với UI/UX mockup xuất sắc vào vòng tiếp theo.", + "challengePrototypeTips":"Đây là ngày kết thúc giai đoạn Prototype của cuộc thi và thí sinh phải nộp Prototype trước ngày này. Nhà Tổ Chức sẽ chịu trách nhiệm đánh giá Prototype và sẽ lựa chon các thí sinh với Prototype xuất sắc vào vòng tiếp theo." } From 08aa0fc7871b2b96fa84fad8f3bd462453fa488b Mon Sep 17 00:00:00 2001 From: Phuong H Date: Thu, 1 Oct 2015 15:21:34 +0700 Subject: [PATCH 14/29] Able to send mail to registrant from now --- .../techlooper/config/CoreConfiguration.java | 22 ++++++++-------- .../controller/ChallengeController.java | 12 ++++++++- .../techlooper/controller/UserController.java | 2 +- .../com/techlooper/model/EmailContent.java | 13 ---------- src/main/resources/local/logback.groovy | 9 ++++++- src/main/webapp/assets/modules/_app.js | 25 +++++++++++++++++-- .../assets/modules/common/apiService.js | 5 ++-- .../interceptor/languageHttpInterceptor.js | 11 -------- .../employerDashboardController.js | 22 +++------------- 9 files changed, 60 insertions(+), 61 deletions(-) delete mode 100644 src/main/webapp/assets/modules/common/interceptor/languageHttpInterceptor.js diff --git a/src/main/java/com/techlooper/config/CoreConfiguration.java b/src/main/java/com/techlooper/config/CoreConfiguration.java index d6eef533a..a8f343d27 100644 --- a/src/main/java/com/techlooper/config/CoreConfiguration.java +++ b/src/main/java/com/techlooper/config/CoreConfiguration.java @@ -515,15 +515,15 @@ private ClientHttpRequestFactory clientHttpRequestFactory() { return factory; } - @Bean - public Template challengeEmployerMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("challengeEmployerEmail.en.ftl"); - return template; - } - - @Bean - public Template challengeEmployerMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("challengeEmployerEmail.vi.ftl"); - return template; - } +// @Bean +// public Template challengeEmployerMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { +// Template template = freemakerConfig.getTemplate("challengeEmployerEmail.en.ftl"); +// return template; +// } +// +// @Bean +// public Template challengeEmployerMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { +// Template template = freemakerConfig.getTemplate("challengeEmployerEmail.vi.ftl"); +// return template; +// } } \ No newline at end of file diff --git a/src/main/java/com/techlooper/controller/ChallengeController.java b/src/main/java/com/techlooper/controller/ChallengeController.java index 30ff4be08..2dd10c9cb 100644 --- a/src/main/java/com/techlooper/controller/ChallengeController.java +++ b/src/main/java/com/techlooper/controller/ChallengeController.java @@ -2,9 +2,11 @@ import com.techlooper.entity.ChallengeEntity; import com.techlooper.entity.ChallengeRegistrantDto; +import com.techlooper.entity.ChallengeRegistrantEntity; import com.techlooper.entity.vnw.VnwCompany; import com.techlooper.entity.vnw.VnwUser; import com.techlooper.model.*; +import com.techlooper.repository.elasticsearch.ChallengeRegistrantRepository; import com.techlooper.service.ChallengeService; import com.techlooper.service.EmployerService; import com.techlooper.service.LeadAPIService; @@ -34,6 +36,9 @@ public class ChallengeController { @Resource private LeadAPIService leadAPIService; + @Resource + private ChallengeRegistrantRepository challengeRegistrantRepository; + @PreAuthorize("hasAuthority('EMPLOYER')") @RequestMapping(value = "/challenge/publish", method = RequestMethod.POST) public ChallengeResponse publishChallenge(@RequestBody ChallengeDto challengeDto, HttpServletRequest servletRequest) throws Exception { @@ -125,5 +130,10 @@ public ChallengeRegistrantDto saveRegistrant(@RequestBody ChallengeRegistrantDto return challengeService.saveRegistrant(request.getRemoteUser(), dto); } - + @PreAuthorize("hasAuthority('EMPLOYER')") + @RequestMapping(value = "challengeRegistrant/fullName/{registrantId}", method = RequestMethod.POST) + public String getChallengeRegistrant(@PathVariable Long registrantId) { + ChallengeRegistrantEntity registrantEntity = challengeRegistrantRepository.findOne(registrantId); + return registrantEntity.getRegistrantFirstName() + " " + registrantEntity.getRegistrantLastName(); + } } diff --git a/src/main/java/com/techlooper/controller/UserController.java b/src/main/java/com/techlooper/controller/UserController.java index d83f4dc0f..3470855d3 100644 --- a/src/main/java/com/techlooper/controller/UserController.java +++ b/src/main/java/com/techlooper/controller/UserController.java @@ -391,7 +391,7 @@ public List getDailyChallengeRegistrantNames(HttpServletRequest request, } @PreAuthorize("hasAuthority('EMPLOYER')") - @RequestMapping(value = "user/challengeRegistrantNames/sendMailToDaily/{challengeId}/{now}", method = RequestMethod.POST) + @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) { String lang = request.getParameter("lang"); diff --git a/src/main/java/com/techlooper/model/EmailContent.java b/src/main/java/com/techlooper/model/EmailContent.java index c3c5ef31c..d5e0b0d89 100644 --- a/src/main/java/com/techlooper/model/EmailContent.java +++ b/src/main/java/com/techlooper/model/EmailContent.java @@ -1,10 +1,7 @@ package com.techlooper.model; -import freemarker.template.Template; - import javax.mail.Address; import java.io.Serializable; -import java.util.Set; /** * Created by phuonghqh on 10/1/15. @@ -17,8 +14,6 @@ public class EmailContent implements Serializable { private Address[] bcc; - private Template template; - private Language language; public Language getLanguage() { @@ -29,14 +24,6 @@ public void setLanguage(Language language) { this.language = language; } - public Template getTemplate() { - return template; - } - - public void setTemplate(Template template) { - this.template = template; - } - public Address[] getBcc() { return bcc; } diff --git a/src/main/resources/local/logback.groovy b/src/main/resources/local/logback.groovy index a06613303..500e3fafb 100644 --- a/src/main/resources/local/logback.groovy +++ b/src/main/resources/local/logback.groovy @@ -5,6 +5,7 @@ import ch.qos.logback.core.rolling.RollingFileAppender import ch.qos.logback.core.rolling.TimeBasedRollingPolicy import static ch.qos.logback.classic.Level.ALL +import static ch.qos.logback.classic.Level.DEBUG import static ch.qos.logback.classic.Level.ERROR import static ch.qos.logback.classic.Level.OFF @@ -25,8 +26,14 @@ appender("ROOT_FILE", RollingFileAppender) { } } +appender("CONSOLE", ConsoleAppender) { + encoder(PatternLayoutEncoder) { + pattern = "%d{dd-MM-yyyy HH:mm:ss.SSS} %p [%t] %c{1}: %m%n" + } +} + logger("org.elasticsearch", ERROR) logger("org.hibernate", ERROR) logger("org.dozer", ERROR) -root(ALL, ["ROOT_FILE"]) \ No newline at end of file +root(DEBUG, ["CONSOLE"]) \ No newline at end of file diff --git a/src/main/webapp/assets/modules/_app.js b/src/main/webapp/assets/modules/_app.js index cf39b0125..a58a470c2 100644 --- a/src/main/webapp/assets/modules/_app.js +++ b/src/main/webapp/assets/modules/_app.js @@ -32,8 +32,29 @@ var techlooper = angular.module("Techlooper", [ ]); techlooper.config(["$routeProvider", "$translateProvider", "$authProvider", "localStorageServiceProvider", "$httpProvider", - function ($routeProvider, $translateProvider, $authProvider, localStorageServiceProvider, $httpProvider, languageHttpInterceptor) { - $httpProvider.interceptors.push(languageHttpInterceptor); + function ($routeProvider, $translateProvider, $authProvider, localStorageServiceProvider, $httpProvider) { + $httpProvider.interceptors.push(function ($q, utils, jsonValue, $location, $rootScope) { + return { + request: function (request) { + return request || $q.when(request); + }, + + responseError: function (rejection) { + switch (rejection.status) { + //case 403: + // $rootScope.lastPath = $location.path(); + // $location.path("/login"); + // break; + + case 500: + case 404: + utils.sendNotification(jsonValue.notifications.serverError); + break; + } + return $q.reject(rejection); + } + }; + }); localStorageServiceProvider .setPrefix('techlooper') diff --git a/src/main/webapp/assets/modules/common/apiService.js b/src/main/webapp/assets/modules/common/apiService.js index 9f473205a..8dd4fb9db 100644 --- a/src/main/webapp/assets/modules/common/apiService.js +++ b/src/main/webapp/assets/modules/common/apiService.js @@ -1,4 +1,4 @@ -techlooper.factory("apiService", function ($rootScope, $location, jsonValue, $http, localStorageService, utils) { +techlooper.factory("apiService", function ($rootScope, $location, jsonValue, $http, localStorageService, utils, $translate) { var instance = { login: function (techlooperKey) { @@ -212,7 +212,8 @@ techlooper.factory("apiService", function ($rootScope, $location, jsonValue, $ht * @see com.techlooper.controller.UserController.sendEmailToDailyChallengeRegistrants * */ sendEmailToDailyChallengeRegistrants: function(challengeId, now, emailContent) { - return $http.post("user/challengeRegistrantNames/sendMailToDaily/" + challengeId + "/" + now, emailContent); + emailContent.language = $translate.use(); + return $http.post("user/challenge/sendMailToDaily/" + challengeId + "/" + now, emailContent); } }; diff --git a/src/main/webapp/assets/modules/common/interceptor/languageHttpInterceptor.js b/src/main/webapp/assets/modules/common/interceptor/languageHttpInterceptor.js deleted file mode 100644 index 230dfb9fe..000000000 --- a/src/main/webapp/assets/modules/common/interceptor/languageHttpInterceptor.js +++ /dev/null @@ -1,11 +0,0 @@ -techlooper.factory('languageHttpInterceptor', function ($rootScope, jsonValue, $q, $translate) { - var instance = { - request: function (config) { - config.params = config.params || {}; - config.params.lang = $translate.use(); - return config || $q.when(config); - } - }; - - return instance; -}); \ No newline at end of file diff --git a/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js b/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js index 31545c291..1fcb216a8 100644 --- a/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js +++ b/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js @@ -1,23 +1,4 @@ techlooper.controller('employerDashboardController', function ($scope, jsonValue, utils, apiService, $location, $filter, $route) { - //$('.summernote').summernote(); - //var edit = function () { - //$('.summernote').summernote({ - // toolbar: [ - // ['fontname', ['fontname']], - // ['fontsize', ['fontsize']], - // ['style', ['bold', 'italic', 'underline', 'clear']], - // ['color', ['color']], - // ['para', ['ul', 'ol', 'paragraph']], - // ['height', ['height']], - // ['table', ['table']], - // ['insert', ['link']], - // ['misc', ['undo', 'redo', 'codeview', 'fullscreen']] - // ] - //}); - //var save = function () { - // var aHTML = $('.click2edit').code(); //save HTML If you need(aHTML: array). - // $('.click2edit').destroy(); - //}; utils.sendNotification(jsonValue.notifications.loading, $(window).height()); @@ -49,6 +30,9 @@ techlooper.controller('employerDashboardController', function ($scope, jsonValue $("#emailCompose").modal(); }); } + else if (param.a == "feedback-registrant") { + //TODO feedback email + } } apiService.getEmployerDashboardInfo() From 55c22f745874db6eecb9f07e59292c89269c2a4c Mon Sep 17 00:00:00 2001 From: johnsonpham Date: Thu, 1 Oct 2015 15:43:14 +0700 Subject: [PATCH 15/29] reset value for date input when uncheck --- .../modules/post-contest/postContestTimeline.html | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/main/webapp/assets/modules/post-contest/postContestTimeline.html b/src/main/webapp/assets/modules/post-contest/postContestTimeline.html index 5207ec22b..8c8a4455f 100644 --- a/src/main/webapp/assets/modules/post-contest/postContestTimeline.html +++ b/src/main/webapp/assets/modules/post-contest/postContestTimeline.html @@ -57,7 +57,9 @@

  • - +
    @@ -82,7 +84,9 @@

  • - +
    @@ -109,7 +113,9 @@

  • - +
    From 6e82b2ba23d589e42c76b0352490f5885cb8dab6 Mon Sep 17 00:00:00 2001 From: khoa-nd Date: Thu, 1 Oct 2015 16:00:07 +0700 Subject: [PATCH 16/29] Data binding email content in email template that is sent to registrants --- .../techlooper/config/CoreConfiguration.java | 916 ++++++------ .../com/techlooper/model/EmailContent.java | 10 +- .../com/techlooper/service/EmailService.java | 2 +- .../service/impl/ChallengeServiceImpl.java | 1227 ++++++++--------- .../service/impl/EmailServiceImpl.java | 56 +- .../template/challengeEmployerEmail.en.ftl | 16 +- .../template/challengeEmployerEmail.vi.ftl | 16 +- 7 files changed, 1115 insertions(+), 1128 deletions(-) diff --git a/src/main/java/com/techlooper/config/CoreConfiguration.java b/src/main/java/com/techlooper/config/CoreConfiguration.java index a8f343d27..abeb6db13 100644 --- a/src/main/java/com/techlooper/config/CoreConfiguration.java +++ b/src/main/java/com/techlooper/config/CoreConfiguration.java @@ -61,469 +61,469 @@ @Configuration @ComponentScan(basePackages = "com.techlooper") @PropertySources({ - @PropertySource("classpath:techlooper.properties"), - @PropertySource("classpath:secret.properties")}) + @PropertySource("classpath:techlooper.properties"), + @PropertySource("classpath:secret.properties")}) @EnableScheduling @EnableAspectJAutoProxy @EnableCaching(proxyTargetClass = true) public class CoreConfiguration implements ApplicationContextAware { - @Resource - private Environment environment; - - @Value("${mail.techlooper.form}") - private String mailTechlooperForm; + @Resource + private Environment environment; + + @Value("${mail.techlooper.form}") + private String mailTechlooperForm; - @Value("${mail.techlooper.reply_to}") - private String mailTechlooperReplyTo; + @Value("${mail.techlooper.reply_to}") + private String mailTechlooperReplyTo; - @Value("${mail.form}") - private String mailForm; - - @Value("${mail.reply_to}") - private String mailReplyTo; - - @Value("${mail.citibank.cc_promotion.to}") - private String mailCitibankCreditCardPromotionTo; - - @Value("${mail.citibank.cc_promotion.subject}") - private String mailCitibankCreditCardPromotionSubject; - - @Value("classpath:vnwConfig.json") - private org.springframework.core.io.Resource vnwConfigRes; - - @Value("classpath:google-auth/techLooper.p12") - private org.springframework.core.io.Resource googleApiAuthResource; - - private ApplicationContext applicationContext; - - @Bean - public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { - PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer(); - configurer.setFileEncoding("UTF-8"); - return configurer; - } - - @Bean - public CacheManager cacheManager() { - CompositeCacheManager manager = new CompositeCacheManager(); - manager.setCacheManagers(Arrays.asList( - new ConcurrentMapCacheManager("SOCIAL_CONFIG"), - new ConcurrentMapCacheManager("COMMON_TERM"), - new ConcurrentMapCacheManager("SKILL_CONFIG"))); - return manager; - } - - @Bean - public RestTemplate restTemplate() { - return new RestTemplate(clientHttpRequestFactory()); - } - - @Bean - public MultipartResolver multipartResolver() { - CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); - multipartResolver.setMaxUploadSize(500000); - return multipartResolver; - } - - @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"); - - } - }); - return dozerBeanMapper; - } - - @Bean - public TextEncryptor textEncryptor() { - BasicTextEncryptor textEncryptor = new BasicTextEncryptor(); - textEncryptor.setPassword(environment.getProperty("core.textEncryptor.password")); - return textEncryptor; - } - - @Bean - public JavaMailSender mailSender() { - JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); - mailSender.setHost("localhost"); - mailSender.setPort(25); - - Properties javaMailProperties = new Properties(); - javaMailProperties.put("mail.transport.protocol", "smtp"); - mailSender.setJavaMailProperties(javaMailProperties); - return mailSender; - } - - @Bean - public SimpleMailMessage citibankCreditCardPromotionMailMessage() { - SimpleMailMessage mailMessage = new SimpleMailMessage(); - mailMessage.setFrom(mailForm); - mailMessage.setTo(mailCitibankCreditCardPromotionTo); - mailMessage.setReplyTo(mailReplyTo); - mailMessage.setSubject(mailCitibankCreditCardPromotionSubject); - return mailMessage; - } - - @Bean - public freemarker.template.Configuration freemakerConfig() throws IOException, URISyntaxException { - freemarker.template.Configuration cfg = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_22); - cfg.setDirectoryForTemplateLoading(Paths.get(this.getClass().getClassLoader().getResource("/template").toURI()).toFile()); - cfg.setDefaultEncoding("UTF-8"); - cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); - return cfg; - } - - @Bean - public Template citibankCreditCardPromotionTemplate(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("citibankCreditCardPromotion.ftl"); - return template; - } - - @Bean - public Map locationMap() { - Map locations = new HashMap<>(); - locations.put(29L, "Ho Chi Minh"); - locations.put(24L, "Ha Noi"); - return locations; - } - - @Bean - public MimeMessage salaryReviewMailMessage(JavaMailSender mailSender) throws MessagingException, UnsupportedEncodingException { - MimeMessage mailMessage = mailSender.createMimeMessage(); - mailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); - mailMessage.setFrom(new InternetAddress(mailTechlooperForm, "TechLooper", "UTF-8")); - return mailMessage; - } - - @Bean - public MimeMessage getPromotedMailMessage(JavaMailSender mailSender) throws MessagingException, UnsupportedEncodingException { - MimeMessage mailMessage = mailSender.createMimeMessage(); - mailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); - mailMessage.setFrom(new InternetAddress(mailTechlooperForm, "TechLooper", "UTF-8")); - return mailMessage; - } - - @Bean - public MimeMessage postChallengeMailMessage(JavaMailSender mailSender) throws MessagingException, UnsupportedEncodingException { - MimeMessage mailMessage = mailSender.createMimeMessage(); - mailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); - mailMessage.setFrom(new InternetAddress(mailTechlooperForm, "TechLooper", "UTF-8")); - return mailMessage; - } - - @Bean - public MimeMessage applyJobMailMessage(JavaMailSender mailSender) throws MessagingException, UnsupportedEncodingException { - MimeMessage mailMessage = mailSender.createMimeMessage(); - mailMessage.setFrom(new InternetAddress(mailTechlooperForm, "TechLooper", "UTF-8")); - return mailMessage; - } - - @Bean - public MimeMessage jobAlertMailMessage(JavaMailSender mailSender) throws MessagingException, UnsupportedEncodingException { - MimeMessage mailMessage = mailSender.createMimeMessage(); - mailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); - mailMessage.setFrom(new InternetAddress(mailTechlooperForm, "TechLooper", "UTF-8")); - return mailMessage; - } - - @Bean - public MimeMessage alertEventOrganiserMailMessage(JavaMailSender mailSender) throws MessagingException, UnsupportedEncodingException { - MimeMessage mailMessage = mailSender.createMimeMessage(); - mailMessage.setFrom(new InternetAddress(mailTechlooperForm, "TechLooper", "UTF-8")); - return mailMessage; - } - - @Bean - public Template salaryReviewReportTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("salaryReviewReport.en.ftl"); - return template; - } - - @Bean - public Template salaryReviewReportTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("salaryReviewReport.vi.ftl"); - return template; - } - - @Bean - public Template getPromotedTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("getPromoted.en.ftl"); - return template; - } - - @Bean - public Template getPromotedTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("getPromoted.vi.ftl"); - return template; - } - - @Bean - public Template postChallengeMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("postChallenge.en.ftl"); - return template; - } - - @Bean - public Template notifyChallengeTimelineMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("notifyChallengeTimeline.vi.ftl"); - return template; - } - - @Bean - public Template notifyChallengeTimelineMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("notifyChallengeTimeline.en.ftl"); - return template; - } - - @Bean - public Template postChallengeUpdateMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("updateChallenge.en.ftl"); - return template; - } - - @Bean - public Template postChallengeMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("postChallenge.vi.ftl"); - return template; - } - - @Bean - public Template confirmUserJoinChallengeMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("confirmUserJoinChallenge.en.ftl"); - return template; - } - - @Bean - public Template confirmUserJoinChallengeMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("confirmUserJoinChallenge.vi.ftl"); - return template; - } - - @Bean - public Template alertEmployerChallengeMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("alertEmployerChallenge.en.ftl"); - return template; - } - - @Bean - public Template alertEmployerChallengeMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("alertEmployerChallenge.vi.ftl"); - return template; - } - - @Bean - public Template alertJobSeekerApplyJobMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("alertJobSeekerApplyJob.en.ftl"); - return template; - } - - @Bean - public Template alertJobSeekerApplyJobMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("alertJobSeekerApplyJob.vi.ftl"); - return template; - } - - @Bean - public Template alertEmployerApplyJobMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("alertEmployerApplyJob.en.ftl"); - return template; - } - - @Bean - public Template alertEmployerApplyJobMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("alertEmployerApplyJob.vi.ftl"); - return template; - } - - @Bean - public Template alertEmployerPostJobMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("alertEmployerPostJob.vi.ftl"); - return template; - } - - @Bean - public Template alertEmployerPostJobMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("alertEmployerPostJob.en.ftl"); - return template; - } - - @Bean - public Template alertTechloopiesPostJobMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("alertTechloopiesApplyJob.en.ftl"); - return template; - } - - @Bean - public Template jobAlertMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("jobAlert.en.ftl"); - return template; - } - - @Bean - public Template jobAlertMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("jobAlert.vi.ftl"); - return template; - } - - @Bean - public Template alertEventOrganiserMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("webinar.en.ftl"); - return template; - } - - @Bean - public Template alertEventOrganiserMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("webinar.vi.ftl"); - return template; - } - - @Bean - public Template onBoardingMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("onboarding.en.ftl"); - return template; - } - - @Bean - public Template onBoardingMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("onboarding.vi.ftl"); - return template; - } - - @Bean - public Template dailyChallengeSummaryMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("challengeDailySummary.en.ftl"); - return template; - } - - @Bean - public Template dailyChallengeSummaryMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { - Template template = freemakerConfig.getTemplate("challengeDailySummary.vi.ftl"); - return template; - } - - @Bean - public JsonNode vietnamworksConfiguration() throws IOException { - return new ObjectMapper().readTree(vnwConfigRes.getInputStream()); - } - - @Bean - @DependsOn("jsonConfigRepository") - public SocialConfig googleSocialConfig() { - return applicationContext.getBean(JsonConfigRepository.class).getSocialConfig().stream() - .filter(socialConfig -> socialConfig.getProvider() == SocialProvider.GOOGLE) - .findFirst().get(); - } - - @Bean - public Calendar googleCalendar() throws GeneralSecurityException, IOException { - JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance(); - HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport(); - SocialConfig googleConfig = googleSocialConfig(); - HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); - GoogleCredential credential = new GoogleCredential.Builder() - .setTransport(httpTransport) - .setJsonFactory(jsonFactory) - .setServiceAccountId(googleConfig.getServiceAccountEmail()) - .setServiceAccountPrivateKeyFromP12File(googleApiAuthResource.getFile()) - .setServiceAccountScopes(Collections.singleton(CalendarScopes.CALENDAR)) - .setServiceAccountUser(googleConfig.getCalendarOwner()) - .build(); - - return new Calendar.Builder(transport, jsonFactory, credential) - .setApplicationName("Techlooper").build(); - } - - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - this.applicationContext = applicationContext; - this.applicationContext.getEnvironment().acceptsProfiles(environment.getProperty("spring.profiles.active")); - } - - @Bean - public MimeMessage fromTechlooperMailMessage(JavaMailSender mailSender) throws MessagingException, UnsupportedEncodingException { - MimeMessage mailMessage = mailSender.createMimeMessage(); - mailMessage.setFrom(new InternetAddress(mailTechlooperForm, "TechLooper", "UTF-8")); - mailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); - return mailMessage; - } - - private ClientHttpRequestFactory clientHttpRequestFactory() { - HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); - factory.setReadTimeout(5000); - factory.setConnectTimeout(5000); - return factory; - } - -// @Bean -// public Template challengeEmployerMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { -// Template template = freemakerConfig.getTemplate("challengeEmployerEmail.en.ftl"); -// return template; -// } -// -// @Bean -// public Template challengeEmployerMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { -// Template template = freemakerConfig.getTemplate("challengeEmployerEmail.vi.ftl"); -// return template; -// } + @Value("${mail.form}") + private String mailForm; + + @Value("${mail.reply_to}") + private String mailReplyTo; + + @Value("${mail.citibank.cc_promotion.to}") + private String mailCitibankCreditCardPromotionTo; + + @Value("${mail.citibank.cc_promotion.subject}") + private String mailCitibankCreditCardPromotionSubject; + + @Value("classpath:vnwConfig.json") + private org.springframework.core.io.Resource vnwConfigRes; + + @Value("classpath:google-auth/techLooper.p12") + private org.springframework.core.io.Resource googleApiAuthResource; + + private ApplicationContext applicationContext; + + @Bean + public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { + PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer(); + configurer.setFileEncoding("UTF-8"); + return configurer; + } + + @Bean + public CacheManager cacheManager() { + CompositeCacheManager manager = new CompositeCacheManager(); + manager.setCacheManagers(Arrays.asList( + new ConcurrentMapCacheManager("SOCIAL_CONFIG"), + new ConcurrentMapCacheManager("COMMON_TERM"), + new ConcurrentMapCacheManager("SKILL_CONFIG"))); + return manager; + } + + @Bean + public RestTemplate restTemplate() { + return new RestTemplate(clientHttpRequestFactory()); + } + + @Bean + public MultipartResolver multipartResolver() { + CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); + multipartResolver.setMaxUploadSize(500000); + return multipartResolver; + } + + @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"); + + } + }); + return dozerBeanMapper; + } + + @Bean + public TextEncryptor textEncryptor() { + BasicTextEncryptor textEncryptor = new BasicTextEncryptor(); + textEncryptor.setPassword(environment.getProperty("core.textEncryptor.password")); + return textEncryptor; + } + + @Bean + public JavaMailSender mailSender() { + JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); + mailSender.setHost("localhost"); + mailSender.setPort(25); + + Properties javaMailProperties = new Properties(); + javaMailProperties.put("mail.transport.protocol", "smtp"); + mailSender.setJavaMailProperties(javaMailProperties); + return mailSender; + } + + @Bean + public SimpleMailMessage citibankCreditCardPromotionMailMessage() { + SimpleMailMessage mailMessage = new SimpleMailMessage(); + mailMessage.setFrom(mailForm); + mailMessage.setTo(mailCitibankCreditCardPromotionTo); + mailMessage.setReplyTo(mailReplyTo); + mailMessage.setSubject(mailCitibankCreditCardPromotionSubject); + return mailMessage; + } + + @Bean + public freemarker.template.Configuration freemakerConfig() throws IOException, URISyntaxException { + freemarker.template.Configuration cfg = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_22); + cfg.setDirectoryForTemplateLoading(Paths.get(this.getClass().getClassLoader().getResource("/template").toURI()).toFile()); + cfg.setDefaultEncoding("UTF-8"); + cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); + return cfg; + } + + @Bean + public Template citibankCreditCardPromotionTemplate(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("citibankCreditCardPromotion.ftl"); + return template; + } + + @Bean + public Map locationMap() { + Map locations = new HashMap<>(); + locations.put(29L, "Ho Chi Minh"); + locations.put(24L, "Ha Noi"); + return locations; + } + + @Bean + public MimeMessage salaryReviewMailMessage(JavaMailSender mailSender) throws MessagingException, UnsupportedEncodingException { + MimeMessage mailMessage = mailSender.createMimeMessage(); + mailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); + mailMessage.setFrom(new InternetAddress(mailTechlooperForm, "TechLooper", "UTF-8")); + return mailMessage; + } + + @Bean + public MimeMessage getPromotedMailMessage(JavaMailSender mailSender) throws MessagingException, UnsupportedEncodingException { + MimeMessage mailMessage = mailSender.createMimeMessage(); + mailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); + mailMessage.setFrom(new InternetAddress(mailTechlooperForm, "TechLooper", "UTF-8")); + return mailMessage; + } + + @Bean + public MimeMessage postChallengeMailMessage(JavaMailSender mailSender) throws MessagingException, UnsupportedEncodingException { + MimeMessage mailMessage = mailSender.createMimeMessage(); + mailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); + mailMessage.setFrom(new InternetAddress(mailTechlooperForm, "TechLooper", "UTF-8")); + return mailMessage; + } + + @Bean + public MimeMessage applyJobMailMessage(JavaMailSender mailSender) throws MessagingException, UnsupportedEncodingException { + MimeMessage mailMessage = mailSender.createMimeMessage(); + mailMessage.setFrom(new InternetAddress(mailTechlooperForm, "TechLooper", "UTF-8")); + return mailMessage; + } + + @Bean + public MimeMessage jobAlertMailMessage(JavaMailSender mailSender) throws MessagingException, UnsupportedEncodingException { + MimeMessage mailMessage = mailSender.createMimeMessage(); + mailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); + mailMessage.setFrom(new InternetAddress(mailTechlooperForm, "TechLooper", "UTF-8")); + return mailMessage; + } + + @Bean + public MimeMessage alertEventOrganiserMailMessage(JavaMailSender mailSender) throws MessagingException, UnsupportedEncodingException { + MimeMessage mailMessage = mailSender.createMimeMessage(); + mailMessage.setFrom(new InternetAddress(mailTechlooperForm, "TechLooper", "UTF-8")); + return mailMessage; + } + + @Bean + public Template salaryReviewReportTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("salaryReviewReport.en.ftl"); + return template; + } + + @Bean + public Template salaryReviewReportTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("salaryReviewReport.vi.ftl"); + return template; + } + + @Bean + public Template getPromotedTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("getPromoted.en.ftl"); + return template; + } + + @Bean + public Template getPromotedTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("getPromoted.vi.ftl"); + return template; + } + + @Bean + public Template postChallengeMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("postChallenge.en.ftl"); + return template; + } + + @Bean + public Template notifyChallengeTimelineMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("notifyChallengeTimeline.vi.ftl"); + return template; + } + + @Bean + public Template notifyChallengeTimelineMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("notifyChallengeTimeline.en.ftl"); + return template; + } + + @Bean + public Template postChallengeUpdateMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("updateChallenge.en.ftl"); + return template; + } + + @Bean + public Template postChallengeMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("postChallenge.vi.ftl"); + return template; + } + + @Bean + public Template confirmUserJoinChallengeMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("confirmUserJoinChallenge.en.ftl"); + return template; + } + + @Bean + public Template confirmUserJoinChallengeMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("confirmUserJoinChallenge.vi.ftl"); + return template; + } + + @Bean + public Template alertEmployerChallengeMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("alertEmployerChallenge.en.ftl"); + return template; + } + + @Bean + public Template alertEmployerChallengeMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("alertEmployerChallenge.vi.ftl"); + return template; + } + + @Bean + public Template alertJobSeekerApplyJobMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("alertJobSeekerApplyJob.en.ftl"); + return template; + } + + @Bean + public Template alertJobSeekerApplyJobMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("alertJobSeekerApplyJob.vi.ftl"); + return template; + } + + @Bean + public Template alertEmployerApplyJobMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("alertEmployerApplyJob.en.ftl"); + return template; + } + + @Bean + public Template alertEmployerApplyJobMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("alertEmployerApplyJob.vi.ftl"); + return template; + } + + @Bean + public Template alertEmployerPostJobMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("alertEmployerPostJob.vi.ftl"); + return template; + } + + @Bean + public Template alertEmployerPostJobMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("alertEmployerPostJob.en.ftl"); + return template; + } + + @Bean + public Template alertTechloopiesPostJobMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("alertTechloopiesApplyJob.en.ftl"); + return template; + } + + @Bean + public Template jobAlertMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("jobAlert.en.ftl"); + return template; + } + + @Bean + public Template jobAlertMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("jobAlert.vi.ftl"); + return template; + } + + @Bean + public Template alertEventOrganiserMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("webinar.en.ftl"); + return template; + } + + @Bean + public Template alertEventOrganiserMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("webinar.vi.ftl"); + return template; + } + + @Bean + public Template onBoardingMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("onboarding.en.ftl"); + return template; + } + + @Bean + public Template onBoardingMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("onboarding.vi.ftl"); + return template; + } + + @Bean + public Template dailyChallengeSummaryMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("challengeDailySummary.en.ftl"); + return template; + } + + @Bean + public Template dailyChallengeSummaryMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("challengeDailySummary.vi.ftl"); + return template; + } + + @Bean + public JsonNode vietnamworksConfiguration() throws IOException { + return new ObjectMapper().readTree(vnwConfigRes.getInputStream()); + } + + @Bean + @DependsOn("jsonConfigRepository") + public SocialConfig googleSocialConfig() { + return applicationContext.getBean(JsonConfigRepository.class).getSocialConfig().stream() + .filter(socialConfig -> socialConfig.getProvider() == SocialProvider.GOOGLE) + .findFirst().get(); + } + + @Bean + public Calendar googleCalendar() throws GeneralSecurityException, IOException { + JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance(); + HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport(); + SocialConfig googleConfig = googleSocialConfig(); + HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); + GoogleCredential credential = new GoogleCredential.Builder() + .setTransport(httpTransport) + .setJsonFactory(jsonFactory) + .setServiceAccountId(googleConfig.getServiceAccountEmail()) + .setServiceAccountPrivateKeyFromP12File(googleApiAuthResource.getFile()) + .setServiceAccountScopes(Collections.singleton(CalendarScopes.CALENDAR)) + .setServiceAccountUser(googleConfig.getCalendarOwner()) + .build(); + + return new Calendar.Builder(transport, jsonFactory, credential) + .setApplicationName("Techlooper").build(); + } + + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + this.applicationContext = applicationContext; + this.applicationContext.getEnvironment().acceptsProfiles(environment.getProperty("spring.profiles.active")); + } + + @Bean + public MimeMessage fromTechlooperMailMessage(JavaMailSender mailSender) throws MessagingException, UnsupportedEncodingException { + MimeMessage mailMessage = mailSender.createMimeMessage(); + mailMessage.setFrom(new InternetAddress(mailTechlooperForm, "TechLooper", "UTF-8")); + mailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); + return mailMessage; + } + + private ClientHttpRequestFactory clientHttpRequestFactory() { + HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); + factory.setReadTimeout(5000); + factory.setConnectTimeout(5000); + return factory; + } + + @Bean + public Template challengeEmployerMailTemplateEn(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("challengeEmployerEmail.en.ftl"); + return template; + } + + @Bean + public Template challengeEmployerMailTemplateVi(freemarker.template.Configuration freemakerConfig) throws IOException { + Template template = freemakerConfig.getTemplate("challengeEmployerEmail.vi.ftl"); + return template; + } } \ No newline at end of file diff --git a/src/main/java/com/techlooper/model/EmailContent.java b/src/main/java/com/techlooper/model/EmailContent.java index d5e0b0d89..45435e21a 100644 --- a/src/main/java/com/techlooper/model/EmailContent.java +++ b/src/main/java/com/techlooper/model/EmailContent.java @@ -12,7 +12,7 @@ public class EmailContent implements Serializable { private String content; - private Address[] bcc; + private Address[] recipients; private Language language; @@ -24,12 +24,12 @@ public void setLanguage(Language language) { this.language = language; } - public Address[] getBcc() { - return bcc; + public Address[] getRecipients() { + return recipients; } - public void setBcc(Address[] bcc) { - this.bcc = bcc; + public void setRecipients(Address[] recipients) { + this.recipients = recipients; } public String getSubject() { diff --git a/src/main/java/com/techlooper/service/EmailService.java b/src/main/java/com/techlooper/service/EmailService.java index adc56a1de..181b55bdb 100644 --- a/src/main/java/com/techlooper/service/EmailService.java +++ b/src/main/java/com/techlooper/service/EmailService.java @@ -7,5 +7,5 @@ */ public interface EmailService { - boolean sendEmailWithBcc(EmailContent emailContent); + boolean sendEmail(EmailContent emailContent); } diff --git a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java index eacd25308..bafb888e3 100644 --- a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java @@ -62,264 +62,260 @@ @Service public class ChallengeServiceImpl implements ChallengeService { - private final static Logger LOGGER = LoggerFactory.getLogger(ChallengeServiceImpl.class); + private final static Logger LOGGER = LoggerFactory.getLogger(ChallengeServiceImpl.class); - @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 = DateTimeUtils.daysBetween(DateTimeUtils.currentDate(), challengeEntity.getRegistrationDateTime()) + 1; - } - else if (challengePhase == ChallengePhaseEnum.IN_PROGRESS) { - numberOfDays = DateTimeUtils.daysBetween(DateTimeUtils.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 ChallengeDetailDto getChallengeDetail(Long challengeId) { - ChallengeEntity challengeEntity = challengeRepository.findOne(challengeId); - if (challengeEntity != null && !Boolean.TRUE.equals(challengeEntity.getExpired())) { - ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); - challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeId)); - return challengeDetailDto; - } - return null; - } - - 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) throws MessagingException, IOException, TemplateException { - Long challengeId = challengeRegistrantDto.getChallengeId(); - boolean isExist = checkIfChallengeRegistrantExist(challengeId, challengeRegistrantDto.getRegistrantEmail()); - - if (!isExist) { - ChallengeRegistrantEntity challengeRegistrantEntity = dozerMapper.map(challengeRegistrantDto, ChallengeRegistrantEntity.class); - ChallengeEntity challengeEntity = challengeRepository.findOne(challengeId); - sendApplicationEmailToContestant(challengeEntity, challengeRegistrantEntity); - sendApplicationEmailToEmployer(challengeEntity, challengeRegistrantEntity); - challengeRegistrantEntity.setMailSent(Boolean.TRUE); - challengeRegistrantEntity.setRegistrantId(new Date().getTime()); - challengeRegistrantRepository.save(challengeRegistrantEntity); - } - - return getNumberOfRegistrants(challengeId); - } - - public List listChallenges() { + 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 = DateTimeUtils.daysBetween(DateTimeUtils.currentDate(), challengeEntity.getRegistrationDateTime()) + 1; + } else if (challengePhase == ChallengePhaseEnum.IN_PROGRESS) { + numberOfDays = DateTimeUtils.daysBetween(DateTimeUtils.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 ChallengeDetailDto getChallengeDetail(Long challengeId) { + ChallengeEntity challengeEntity = challengeRepository.findOne(challengeId); + if (challengeEntity != null && !Boolean.TRUE.equals(challengeEntity.getExpired())) { + ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); + challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeId)); + return challengeDetailDto; + } + return null; + } + + 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) throws MessagingException, IOException, TemplateException { + Long challengeId = challengeRegistrantDto.getChallengeId(); + boolean isExist = checkIfChallengeRegistrantExist(challengeId, challengeRegistrantDto.getRegistrantEmail()); + + if (!isExist) { + ChallengeRegistrantEntity challengeRegistrantEntity = dozerMapper.map(challengeRegistrantDto, ChallengeRegistrantEntity.class); + ChallengeEntity challengeEntity = challengeRepository.findOne(challengeId); + sendApplicationEmailToContestant(challengeEntity, challengeRegistrantEntity); + sendApplicationEmailToEmployer(challengeEntity, challengeRegistrantEntity); + challengeRegistrantEntity.setMailSent(Boolean.TRUE); + challengeRegistrantEntity.setRegistrantId(new Date().getTime()); + challengeRegistrantRepository.save(challengeRegistrantEntity); + } + + return getNumberOfRegistrants(challengeId); + } + + public List listChallenges() { // List challenges = new ArrayList<>(); // Iterator challengeIter = challengeRepository.findAll().iterator(); // while (challengeIter.hasNext()) { @@ -329,174 +325,169 @@ public List listChallenges() { // challenges.add(challengeDetailDto); // } // return sortChallengesByDescendingStartDate(challenges); - TermQueryBuilder notExpiredQuery = termQuery("expired", Boolean.TRUE); - Iterable challengeIterator = challengeRepository.search(boolQuery().mustNot(notExpiredQuery)); - ArrayList challenges = new ArrayList<>(); - challengeIterator.forEach(challengeEntity -> { - ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); - challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeEntity.getChallengeId())); - challenges.add(challengeDetailDto); - }); - return sortChallengesByDescendingStartDate(challenges); - } - - private void sendContestApplicationEmail(Template template, String mailSubject, Address[] recipientAddresses, - ChallengeEntity challengeEntity, ChallengeRegistrantEntity challengeRegistrantEntity, boolean hasReplyTo) - throws MessagingException, IOException, TemplateException { - postChallengeMailMessage.setRecipients(Message.RecipientType.TO, recipientAddresses); - - if (hasReplyTo) { - postChallengeMailMessage.setReplyTo(InternetAddress.parse(challengeRegistrantEntity.getRegistrantEmail())); - } - 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; - } - 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; + TermQueryBuilder notExpiredQuery = termQuery("expired", Boolean.TRUE); + Iterable challengeIterator = challengeRepository.search(boolQuery().mustNot(notExpiredQuery)); + ArrayList challenges = new ArrayList<>(); + challengeIterator.forEach(challengeEntity -> { + ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); + challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeEntity.getChallengeId())); + challenges.add(challengeDetailDto); + }); + return sortChallengesByDescendingStartDate(challenges); + } + + private void sendContestApplicationEmail(Template template, String mailSubject, Address[] recipientAddresses, + ChallengeEntity challengeEntity, ChallengeRegistrantEntity challengeRegistrantEntity, boolean hasReplyTo) + throws MessagingException, IOException, TemplateException { + postChallengeMailMessage.setRecipients(Message.RecipientType.TO, recipientAddresses); + + if (hasReplyTo) { + postChallengeMailMessage.setReplyTo(InternetAddress.parse(challengeRegistrantEntity.getRegistrantEmail())); + } else { + postChallengeMailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); } - else { - return 0; + + StringWriter stringWriter = new StringWriter(); + Map templateModel = new HashMap<>(); + templateModel.put("webBaseUrl", webBaseUrl); + templateModel.put("challengeName", challengeEntity.getChallengeName()); + templateModel.put("businessRequirement", challengeEntity.getBusinessRequirement()); + templateModel.put("generalNote", challengeEntity.getGeneralNote()); + templateModel.put("technologies", StringUtils.join(challengeEntity.getTechnologies(), "
    ")); + templateModel.put("documents", challengeEntity.getDocuments()); + templateModel.put("deliverables", challengeEntity.getDeliverables()); + templateModel.put("receivedEmails", StringUtils.join(challengeEntity.getReceivedEmails(), "
    ")); + templateModel.put("reviewStyle", challengeEntity.getReviewStyle()); + templateModel.put("startDate", challengeEntity.getStartDateTime()); + templateModel.put("registrationDate", challengeEntity.getRegistrationDateTime()); + templateModel.put("submissionDate", challengeEntity.getSubmissionDateTime()); + templateModel.put("qualityIdea", challengeEntity.getQualityIdea()); + templateModel.put("firstPlaceReward", challengeEntity.getFirstPlaceReward() != null ? challengeEntity.getFirstPlaceReward() : 0); + templateModel.put("secondPlaceReward", challengeEntity.getSecondPlaceReward() != null ? challengeEntity.getSecondPlaceReward() : 0); + templateModel.put("thirdPlaceReward", challengeEntity.getThirdPlaceReward() != null ? challengeEntity.getThirdPlaceReward() : 0); + templateModel.put("challengeId", challengeEntity.getChallengeId().toString()); + templateModel.put("authorEmail", challengeEntity.getAuthorEmail()); + templateModel.put("challengeOverview", challengeEntity.getChallengeOverview()); + templateModel.put("firstName", challengeRegistrantEntity.getRegistrantFirstName()); + templateModel.put("lastName", challengeRegistrantEntity.getRegistrantLastName()); + templateModel.put("registrantEmail", challengeRegistrantEntity.getRegistrantEmail()); + templateModel.put("challengeNameAlias", challengeEntity.getChallengeName().replaceAll("\\W", "-")); + + template.process(templateModel, stringWriter); + postChallengeMailMessage.setSubject(MimeUtility.encodeText(mailSubject, "UTF-8", null)); + postChallengeMailMessage.setText(stringWriter.toString(), "UTF-8", "html"); + + stringWriter.flush(); + postChallengeMailMessage.saveChanges(); + mailSender.send(postChallengeMailMessage); + } + + private void sendPostChallengeEmail(ChallengeEntity challengeEntity, String mailSubject, + Address[] recipientAddresses, Template template) throws MessagingException, IOException, TemplateException { + postChallengeMailMessage.setRecipients(Message.RecipientType.TO, recipientAddresses); + postChallengeMailMessage.setReplyTo(InternetAddress.parse(mailTechlooperReplyTo)); + StringWriter stringWriter = new StringWriter(); + + Map templateModel = new HashMap<>(); + templateModel.put("webBaseUrl", webBaseUrl); + templateModel.put("challengeName", challengeEntity.getChallengeName()); + templateModel.put("businessRequirement", challengeEntity.getBusinessRequirement()); + templateModel.put("generalNote", challengeEntity.getGeneralNote()); + templateModel.put("technologies", StringUtils.join(challengeEntity.getTechnologies(), "
    ")); + templateModel.put("documents", challengeEntity.getDocuments()); + templateModel.put("deliverables", challengeEntity.getDeliverables()); + templateModel.put("receivedEmails", StringUtils.join(challengeEntity.getReceivedEmails(), "
    ")); + templateModel.put("reviewStyle", challengeEntity.getReviewStyle()); + templateModel.put("startDate", challengeEntity.getStartDateTime()); + templateModel.put("registrationDate", challengeEntity.getRegistrationDateTime()); + templateModel.put("submissionDate", challengeEntity.getSubmissionDateTime()); + templateModel.put("qualityIdea", challengeEntity.getQualityIdea()); + templateModel.put("firstPlaceReward", challengeEntity.getFirstPlaceReward() != null ? challengeEntity.getFirstPlaceReward() : 0); + templateModel.put("secondPlaceReward", challengeEntity.getSecondPlaceReward() != null ? challengeEntity.getSecondPlaceReward() : 0); + templateModel.put("thirdPlaceReward", challengeEntity.getThirdPlaceReward() != null ? challengeEntity.getThirdPlaceReward() : 0); + templateModel.put("challengeId", challengeEntity.getChallengeId().toString()); + templateModel.put("authorEmail", challengeEntity.getAuthorEmail()); + templateModel.put("challengeOverview", challengeEntity.getChallengeOverview()); + templateModel.put("challengeNameAlias", challengeEntity.getChallengeName().replaceAll("\\W", "-")); + + template.process(templateModel, stringWriter); + 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()); } - } - catch (ParseException e) { - return 0; - } - }).collect(Collectors.toList()); - } - - public boolean checkIfChallengeRegistrantExist(Long challengeId, String email) { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder(); - searchQueryBuilder.withQuery(boolQuery() - .must(matchPhraseQuery("registrantEmail", email)) - .must(termQuery("challengeId", challengeId)) - .must(termQuery("mailSent", true))); - - long total = challengeRegistrantRepository.search(searchQueryBuilder.build()).getTotalElements(); - return (total > 0); - } - - @Override - public Long getTotalNumberOfChallenges() { - return challengeRepository.count(); - } - - @Override - public Double getTotalAmountOfPrizeValues() { - NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withSearchType(SearchType.COUNT); - searchQueryBuilder.withQuery(matchAllQuery()); - - SumBuilder sumPrizeBuilder = sum("sumPrize").script("doc['firstPlaceReward'].value + doc['secondPlaceReward'].value + doc['thirdPlaceReward'].value"); - searchQueryBuilder.addAggregation(sumPrizeBuilder); - - Aggregations aggregations = elasticsearchTemplateUserImport.query(searchQueryBuilder.build(), SearchResponse::getAggregations); - Sum sumReponse = aggregations.get("sumPrize"); - return sumReponse != null ? sumReponse.getValue() : 0D; - } - - @Override - public Long getTotalNumberOfRegistrants() { - return challengeRegistrantRepository.count(); - } - - @Override - public ChallengeDetailDto getTheLatestChallenge() { + return InternetAddress.parse(StringUtils.join(emails, ',')); + } + + private List sortChallengesByDescendingStartDate(List challenges) { + SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); + return challenges.stream().sorted((challenge1, challenge2) -> { + try { + if (challenge2.getStartDateTime() == null) { + return -1; + } else if (challenge1.getStartDateTime() == null) { + return 1; + } + long challenge2StartDate = sdf.parse(challenge2.getStartDateTime()).getTime(); + long challenge1StartDate = sdf.parse(challenge1.getStartDateTime()).getTime(); + if (challenge2StartDate - challenge1StartDate > 0) { + return 1; + } else if (challenge2StartDate - challenge1StartDate < 0) { + return -1; + } else { + return 0; + } + } catch (ParseException e) { + return 0; + } + }).collect(Collectors.toList()); + } + + public boolean checkIfChallengeRegistrantExist(Long challengeId, String email) { + NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder(); + searchQueryBuilder.withQuery(boolQuery() + .must(matchPhraseQuery("registrantEmail", email)) + .must(termQuery("challengeId", challengeId)) + .must(termQuery("mailSent", true))); + + 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)); @@ -507,242 +498,240 @@ 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) { - MatchQueryBuilder authorEmailQuery = matchQuery("authorEmail", ownerEmail).minimumShouldMatch("100%"); - TermQueryBuilder notExpiredQuery = termQuery("expired", Boolean.TRUE); - Iterable challenges = challengeRepository.search(boolQuery().must(authorEmailQuery).mustNot(notExpiredQuery)); - ArrayList dtos = new ArrayList<>(); - challenges.forEach(challengeEntity -> { - ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); - challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeEntity.getChallengeId())); - dtos.add(challengeDetailDto); - }); - dozerMapper.map(challenges, dtos); - return dtos; - } - - 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(String ownerEmail, Long challengeId) { - BoolQueryBuilder boolQueryBuilder = boolQuery(); - - if (StringUtils.isNotEmpty(ownerEmail)) { - boolQueryBuilder.must(matchQuery("authorEmail", ownerEmail).minimumShouldMatch("100%")); - } - - TermQueryBuilder challengeQuery = termQuery("challengeId", challengeId); - if (challengeId != null) { - boolQueryBuilder.must(challengeQuery); - } - - boolQueryBuilder.mustNot(termQuery("expired", Boolean.TRUE)); - Iterator challengeIterator = challengeRepository.search(boolQueryBuilder).iterator(); - Set registrantDtos = new HashSet<>(); - - if (challengeIterator.hasNext()) { - Iterator registrants = challengeRegistrantRepository.search(challengeQuery).iterator(); - registrants.forEachRemaining(registrant -> registrantDtos.add(dozerMapper.map(registrant, ChallengeRegistrantDto.class))); - } - - return registrantDtos; - } - - 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 challenges; + } + + public List listChallenges(String ownerEmail) { + MatchQueryBuilder authorEmailQuery = matchQuery("authorEmail", ownerEmail).minimumShouldMatch("100%"); + TermQueryBuilder notExpiredQuery = termQuery("expired", Boolean.TRUE); + Iterable challenges = challengeRepository.search(boolQuery().must(authorEmailQuery).mustNot(notExpiredQuery)); + ArrayList dtos = new ArrayList<>(); + challenges.forEach(challengeEntity -> { + ChallengeDetailDto challengeDetailDto = dozerMapper.map(challengeEntity, ChallengeDetailDto.class); + challengeDetailDto.setNumberOfRegistrants(getNumberOfRegistrants(challengeEntity.getChallengeId())); + dtos.add(challengeDetailDto); + }); + dozerMapper.map(challenges, dtos); + return dtos; + } + + 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(); } - 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)); - searchQueryBuilder.withPageable(new PageRequest(0, 100)); - - List result = new ArrayList<>(); - Iterator iterator = challengeRegistrantRepository.search(searchQueryBuilder.build()).iterator(); - while (iterator.hasNext()) { - result.add(iterator.next()); - } - - 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)); - - Long pastTime = currentDateTime - period.getMiliseconds() > 0 ? currentDateTime - period.getMiliseconds() : 0; - boolQueryBuilder.must(rangeQuery("challengeSubmissionId").from(pastTime)); - searchQueryBuilder.withQuery(boolQueryBuilder); - searchQueryBuilder.withSort(fieldSort("challengeSubmissionId").order(SortOrder.DESC)); - searchQueryBuilder.withPageable(new PageRequest(0, 100)); - - List result = new ArrayList<>(); - Iterator iterator = challengeSubmissionRepository.search(searchQueryBuilder.build()).iterator(); - while (iterator.hasNext()) { - result.add(iterator.next()); - } - - return result; - } - - @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())); - - 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(Collectors.joining(",")); - try { - csvEmails += ",phuonghqh@gmail.com";//TODO remove this value because its used to test only - emailContent.setBcc(InternetAddress.parse(csvEmails)); - } - catch (AddressException e) { - LOGGER.debug("Can not parse email address", e); + + public boolean delete(Long id, String ownerEmail) { + ChallengeEntity challenge = challengeRepository.findOne(id); + if (challenge.getAuthorEmail().equalsIgnoreCase(ownerEmail)) { + challenge.setExpired(Boolean.TRUE); + challengeRepository.save(challenge); + return true; + } return false; - } } - return emailService.sendEmailWithBcc(emailContent); - } + + public ChallengeDto findChallengeById(Long id) { + return dozerMapper.map(challengeRepository.findOne(id), ChallengeDto.class); + } + + public Set findRegistrantsByOwner(String ownerEmail, Long challengeId) { + BoolQueryBuilder boolQueryBuilder = boolQuery(); + + if (StringUtils.isNotEmpty(ownerEmail)) { + boolQueryBuilder.must(matchQuery("authorEmail", ownerEmail).minimumShouldMatch("100%")); + } + + TermQueryBuilder challengeQuery = termQuery("challengeId", challengeId); + if (challengeId != null) { + boolQueryBuilder.must(challengeQuery); + } + + boolQueryBuilder.mustNot(termQuery("expired", Boolean.TRUE)); + Iterator challengeIterator = challengeRepository.search(boolQueryBuilder).iterator(); + Set registrantDtos = new HashSet<>(); + + if (challengeIterator.hasNext()) { + Iterator registrants = challengeRegistrantRepository.search(challengeQuery).iterator(); + registrants.forEachRemaining(registrant -> registrantDtos.add(dozerMapper.map(registrant, ChallengeRegistrantDto.class))); + } + + return registrantDtos; + } + + 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)); + searchQueryBuilder.withPageable(new PageRequest(0, 100)); + + List result = new ArrayList<>(); + Iterator iterator = challengeRegistrantRepository.search(searchQueryBuilder.build()).iterator(); + while (iterator.hasNext()) { + result.add(iterator.next()); + } + + 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)); + + Long pastTime = currentDateTime - period.getMiliseconds() > 0 ? currentDateTime - period.getMiliseconds() : 0; + boolQueryBuilder.must(rangeQuery("challengeSubmissionId").from(pastTime)); + searchQueryBuilder.withQuery(boolQueryBuilder); + searchQueryBuilder.withSort(fieldSort("challengeSubmissionId").order(SortOrder.DESC)); + searchQueryBuilder.withPageable(new PageRequest(0, 100)); + + List result = new ArrayList<>(); + Iterator iterator = challengeSubmissionRepository.search(searchQueryBuilder.build()).iterator(); + while (iterator.hasNext()) { + result.add(iterator.next()); + } + + return result; + } + + @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())); + + 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(Collectors.joining(",")); + try { + emailContent.setRecipients(InternetAddress.parse(csvEmails)); + } catch (AddressException e) { + LOGGER.debug("Can not parse email address", e); + return false; + } + } + return emailService.sendEmail(emailContent); + } } diff --git a/src/main/java/com/techlooper/service/impl/EmailServiceImpl.java b/src/main/java/com/techlooper/service/impl/EmailServiceImpl.java index 976447f8c..be8f0cfce 100644 --- a/src/main/java/com/techlooper/service/impl/EmailServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/EmailServiceImpl.java @@ -1,7 +1,9 @@ package com.techlooper.service.impl; import com.techlooper.model.EmailContent; +import com.techlooper.model.Language; import com.techlooper.service.EmailService; +import freemarker.template.Template; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.mail.javamail.JavaMailSender; @@ -9,9 +11,11 @@ import javax.annotation.Resource; import javax.mail.Message; -import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeUtility; +import java.io.StringWriter; +import java.util.HashMap; +import java.util.Map; /** * Created by phuonghqh on 10/1/15. @@ -19,26 +23,40 @@ @Service public class EmailServiceImpl implements EmailService { - private final Logger LOGGER = LoggerFactory.getLogger(EmailServiceImpl.class); + private final Logger LOGGER = LoggerFactory.getLogger(EmailServiceImpl.class); - @Resource - private JavaMailSender mailSender; + @Resource + private JavaMailSender mailSender; - @Resource - private MimeMessage fromTechlooperMailMessage; + @Resource + private MimeMessage fromTechlooperMailMessage; - public boolean sendEmailWithBcc(EmailContent emailContent) { - try { - fromTechlooperMailMessage.setSubject(MimeUtility.encodeText(emailContent.getSubject(), "UTF-8", null)); - fromTechlooperMailMessage.setText(emailContent.getContent(), "UTF-8", "html"); - fromTechlooperMailMessage.setRecipients(Message.RecipientType.BCC, emailContent.getBcc()); - fromTechlooperMailMessage.saveChanges(); - mailSender.send(fromTechlooperMailMessage); - } - catch (Exception e) { - LOGGER.error("Can not send email", e); - return false; + @Resource + private Template challengeEmployerMailTemplateEn; + + @Resource + private Template challengeEmployerMailTemplateVi; + + public boolean sendEmail(EmailContent emailContent) { + try { + fromTechlooperMailMessage.setSubject(MimeUtility.encodeText(emailContent.getSubject(), "UTF-8", null)); + + Template template = emailContent.getLanguage() == Language.vi ? challengeEmployerMailTemplateVi : + challengeEmployerMailTemplateEn; + + StringWriter stringWriter = new StringWriter(); + Map templateModel = new HashMap<>(); + templateModel.put("emailContent", emailContent.getContent()); + template.process(templateModel, stringWriter); + + fromTechlooperMailMessage.setText(stringWriter.toString(), "UTF-8", "html"); + fromTechlooperMailMessage.setRecipients(Message.RecipientType.TO, emailContent.getRecipients()); + fromTechlooperMailMessage.saveChanges(); + mailSender.send(fromTechlooperMailMessage); + } catch (Exception e) { + LOGGER.error("Can not send email", e); + return false; + } + return true; } - return true; - } } diff --git a/src/main/resources/template/challengeEmployerEmail.en.ftl b/src/main/resources/template/challengeEmployerEmail.en.ftl index 18b20b2fd..18eebcc51 100644 --- a/src/main/resources/template/challengeEmployerEmail.en.ftl +++ b/src/main/resources/template/challengeEmployerEmail.en.ftl @@ -116,12 +116,12 @@ @@ -161,22 +161,12 @@ - - - - - -
    -

    Hey thu.hoang@navigosgroup.com,

    -
    - -
    - email challenge container will be show here + ${emailContent}
    diff --git a/src/main/resources/template/challengeEmployerEmail.vi.ftl b/src/main/resources/template/challengeEmployerEmail.vi.ftl index 0af2c4f69..a875ca623 100644 --- a/src/main/resources/template/challengeEmployerEmail.vi.ftl +++ b/src/main/resources/template/challengeEmployerEmail.vi.ftl @@ -116,12 +116,12 @@ @@ -161,22 +161,12 @@ - - - - - -
    -

    Xin chào thu.hoang@navigosgroup.com,

    -
    - -
    - email challenge container will be show here + ${emailContent}
    From 025322447165168260bb13d3a252fd1881355937 Mon Sep 17 00:00:00 2001 From: Phuong H Date: Thu, 1 Oct 2015 16:00:36 +0700 Subject: [PATCH 17/29] Send feedback email --- .../controller/ChallengeController.java | 2 +- .../techlooper/controller/UserController.java | 11 +++++-- .../techlooper/service/ChallengeService.java | 2 ++ .../service/impl/ChallengeServiceImpl.java | 16 ++++++++++ .../assets/modules/common/apiService.js | 27 ++++++++++++---- .../employerDashboardController.js | 31 ++++++++++++++----- 6 files changed, 72 insertions(+), 17 deletions(-) diff --git a/src/main/java/com/techlooper/controller/ChallengeController.java b/src/main/java/com/techlooper/controller/ChallengeController.java index 2dd10c9cb..e1387de44 100644 --- a/src/main/java/com/techlooper/controller/ChallengeController.java +++ b/src/main/java/com/techlooper/controller/ChallengeController.java @@ -131,7 +131,7 @@ public ChallengeRegistrantDto saveRegistrant(@RequestBody ChallengeRegistrantDto } @PreAuthorize("hasAuthority('EMPLOYER')") - @RequestMapping(value = "challengeRegistrant/fullName/{registrantId}", method = RequestMethod.POST) + @RequestMapping(value = "challengeRegistrant/fullName/{registrantId}", method = RequestMethod.GET) public String getChallengeRegistrant(@PathVariable Long registrantId) { ChallengeRegistrantEntity registrantEntity = challengeRegistrantRepository.findOne(registrantId); return registrantEntity.getRegistrantFirstName() + " " + registrantEntity.getRegistrantLastName(); diff --git a/src/main/java/com/techlooper/controller/UserController.java b/src/main/java/com/techlooper/controller/UserController.java index 3470855d3..3ec542550 100644 --- a/src/main/java/com/techlooper/controller/UserController.java +++ b/src/main/java/com/techlooper/controller/UserController.java @@ -394,10 +394,17 @@ public List getDailyChallengeRegistrantNames(HttpServletRequest request, @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) { - String lang = request.getParameter("lang"); - System.out.println(lang); 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); + } + } } diff --git a/src/main/java/com/techlooper/service/ChallengeService.java b/src/main/java/com/techlooper/service/ChallengeService.java index c01fcaf79..76ebcd4ca 100644 --- a/src/main/java/com/techlooper/service/ChallengeService.java +++ b/src/main/java/com/techlooper/service/ChallengeService.java @@ -84,4 +84,6 @@ List findChallengeSubmissionWithinPeriod( boolean sendEmailToDailyChallengeRegistrants(String challengeOwner, Long challengeId, Long now, EmailContent emailContent); + boolean sendEmailToRegistrant(String challengeOwner, Long challengeId, Long registrantId, EmailContent emailContent); + } diff --git a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java index eacd25308..cf63d902d 100644 --- a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java @@ -745,4 +745,20 @@ public boolean sendEmailToDailyChallengeRegistrants(String challengeOwner, Long return emailService.sendEmailWithBcc(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 { + csvEmails += ",phuonghqh@gmail.com";//TODO remove this value because its used to test only + emailContent.setBcc(InternetAddress.parse(csvEmails)); + } + catch (AddressException e) { + LOGGER.debug("Can not parse email address", e); + return false; + } + } + return emailService.sendEmailWithBcc(emailContent); + } + } diff --git a/src/main/webapp/assets/modules/common/apiService.js b/src/main/webapp/assets/modules/common/apiService.js index 8dd4fb9db..2c3a5ecc5 100644 --- a/src/main/webapp/assets/modules/common/apiService.js +++ b/src/main/webapp/assets/modules/common/apiService.js @@ -176,44 +176,59 @@ techlooper.factory("apiService", function ($rootScope, $location, jsonValue, $ht /** * @see com.techlooper.controller.ChallengeController.deleteChallengeById * */ - deleteChallengeById: function(id) { + deleteChallengeById: function (id) { return $http.delete("challenge/" + id); }, /** * @see com.techlooper.controller.ChallengeController.findChallengeById * */ - findChallengeById: function(id) { + findChallengeById: function (id) { return $http.get("challenges/" + id); }, /** * @see com.techlooper.controller.ChallengeController.getRegistrantsById * */ - getChallengeRegistrants: function(challengeId) { + getChallengeRegistrants: function (challengeId) { return $http.get("challenges/" + challengeId + "/registrants"); }, /** * @see com.techlooper.controller.ChallengeController.saveRegistrant * */ - saveChallengeRegistrant: function(registrant) { + saveChallengeRegistrant: function (registrant) { return $http.post("challengeDetail/registrant", registrant); }, /** * @see com.techlooper.controller.UserController.getDailyChallengeRegistrantNames * */ - getDailyChallengeRegistrantNames: function(challengeId, now) { + getDailyChallengeRegistrantNames: function (challengeId, now) { return $http.get("user/challengeRegistrantNames/" + challengeId + "/" + now); }, /** * @see com.techlooper.controller.UserController.sendEmailToDailyChallengeRegistrants * */ - sendEmailToDailyChallengeRegistrants: function(challengeId, now, emailContent) { + sendEmailToDailyChallengeRegistrants: function (challengeId, now, emailContent) { emailContent.language = $translate.use(); return $http.post("user/challenge/sendMailToDaily/" + challengeId + "/" + now, emailContent); + }, + + /** + * @see com.techlooper.controller.ChallengeController.getChallengeRegistrant + * */ + getChallengeRegistrantFullName: function (challengeRegistrantId) { + return $http.get("challengeRegistrant/fullName/" + challengeRegistrantId, {transformResponse: function (d, h) {return d;}}); + }, + + /** + * @see com.techlooper.controller.UserController.sendFeedbackToRegistrant + * */ + sendFeedbackToRegistrant: function(challengeId, registrantId, emailContent) { + emailContent.language = $translate.use(); + return $http.post("user/challenge/feedback/" + challengeId + "/" + registrantId, emailContent); } }; diff --git a/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js b/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js index 1fcb216a8..862141873 100644 --- a/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js +++ b/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js @@ -3,15 +3,23 @@ techlooper.controller('employerDashboardController', function ($scope, jsonValue utils.sendNotification(jsonValue.notifications.loading, $(window).height()); $scope.composeEmail = { - send: function() { + send: function () { $scope.composeEmail.content = $('.summernote').code(); - //console.log($scope.composeEmail); - apiService.sendEmailToDailyChallengeRegistrants($scope.composeEmail.challengeId, $scope.composeEmail.now, $scope.composeEmail) - .finally(function() { - $scope.composeEmail.cancel(); - }); + + if ($scope.composeEmail.action == "challenge-daily-mail-registrants") { + apiService.sendEmailToDailyChallengeRegistrants($scope.composeEmail.challengeId, $scope.composeEmail.now, $scope.composeEmail) + .finally(function () { + $scope.composeEmail.cancel(); + }); + } + else if ($scope.composeEmail.action == "feedback-registrant") { + apiService.sendFeedbackToRegistrant($scope.composeEmail.challengeId, $scope.composeEmail.registrantId, $scope.composeEmail) + .finally(function () { + $scope.composeEmail.cancel(); + }); + } }, - cancel: function() { + cancel: function () { $location.search({}); $('.modal-backdrop').remove(); } @@ -19,6 +27,7 @@ techlooper.controller('employerDashboardController', function ($scope, jsonValue var param = $location.search(); if (!$.isEmptyObject(param)) { + $scope.composeEmail.action = param.a; if (param.a == "challenge-daily-mail-registrants") { var challengeId = param.challengeId; var now = param.currentDateTime; @@ -31,7 +40,13 @@ techlooper.controller('employerDashboardController', function ($scope, jsonValue }); } else if (param.a == "feedback-registrant") { - //TODO feedback email + $scope.composeEmail.challengeId = param.challengeId; + $scope.composeEmail.registrantId = param.registrantId; + apiService.getChallengeRegistrantFullName($scope.composeEmail.registrantId) + .success(function (fullname) { + $scope.composeEmail.names = fullname; + $("#emailCompose").modal(); + }); } } From a1b30141f572f95e44b020a4471a1a5d4ef1a9c0 Mon Sep 17 00:00:00 2001 From: Phuong H Date: Thu, 1 Oct 2015 16:07:43 +0700 Subject: [PATCH 18/29] Fix build fail , missing email model --- .../com/techlooper/service/impl/ChallengeServiceImpl.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java index 0431ed545..fb8cd13dc 100644 --- a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java @@ -740,14 +740,14 @@ public boolean sendEmailToRegistrant(String challengeOwner, Long challengeId, Lo String csvEmails = registrant.getRegistrantEmail(); try { csvEmails += ",phuonghqh@gmail.com";//TODO remove this value because its used to test only - emailContent.setBcc(InternetAddress.parse(csvEmails)); + emailContent.setRecipients(InternetAddress.parse(csvEmails)); } catch (AddressException e) { LOGGER.debug("Can not parse email address", e); return false; } } - return emailService.sendEmailWithBcc(emailContent); + return emailService.sendEmail(emailContent); } } From 422f34cd0ef17a6d46e0927aeae5112561a18a74 Mon Sep 17 00:00:00 2001 From: Phuong H Date: Thu, 1 Oct 2015 16:21:26 +0700 Subject: [PATCH 19/29] Remove require on submit milestone --- .../webapp/assets/modules/post-contest/postContestTimeline.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/webapp/assets/modules/post-contest/postContestTimeline.html b/src/main/webapp/assets/modules/post-contest/postContestTimeline.html index 8c8a4455f..8ab7bd36f 100644 --- a/src/main/webapp/assets/modules/post-contest/postContestTimeline.html +++ b/src/main/webapp/assets/modules/post-contest/postContestTimeline.html @@ -124,7 +124,7 @@

    placeholder="{{'ex' | translate}}{{state.status('ex-register-date')}}" name="prototypeSubmissionDate" ng-disabled="!prototypeChecked" data-toggle="tooltip" data-original-title="{{'challengePrototypeTips' | translate}}" - ng-model="contest.prototypeSubmissionDate" required> + ng-model="contest.prototypeSubmissionDate"> From d29619d3d28121cb2f5710f2b44b8b31ed2cb260 Mon Sep 17 00:00:00 2001 From: khoa-nd Date: Thu, 1 Oct 2015 16:22:55 +0700 Subject: [PATCH 20/29] Update mapping between Challenge Entity vs Challenge Dto --- src/main/java/com/techlooper/config/CoreConfiguration.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/techlooper/config/CoreConfiguration.java b/src/main/java/com/techlooper/config/CoreConfiguration.java index abeb6db13..902961791 100644 --- a/src/main/java/com/techlooper/config/CoreConfiguration.java +++ b/src/main/java/com/techlooper/config/CoreConfiguration.java @@ -190,7 +190,10 @@ protected void configure() { mapping(ChallengeEntity.class, ChallengeDto.class) .fields("startDateTime", "startDate") .fields("submissionDateTime", "submissionDate") - .fields("registrationDateTime", "registrationDate"); + .fields("registrationDateTime", "registrationDate") + .fields("ideaSubmissionDateTime", "ideaSubmissionDate") + .fields("uxSubmissionDateTime", "uxSubmissionDate") + .fields("prototypeSubmissionDateTime", "prototypeSubmissionDate"); } }); From 6600ff6ae9849ff501a54a909d171a02a68fafbf Mon Sep 17 00:00:00 2001 From: Phuong H Date: Thu, 1 Oct 2015 16:26:45 +0700 Subject: [PATCH 21/29] Remove ex email --- .../java/com/techlooper/service/impl/ChallengeServiceImpl.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java index fb8cd13dc..b341341fa 100644 --- a/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/ChallengeServiceImpl.java @@ -739,7 +739,6 @@ public boolean sendEmailToRegistrant(String challengeOwner, Long challengeId, Lo ChallengeRegistrantEntity registrant = challengeRegistrantRepository.findOne(registrantId); String csvEmails = registrant.getRegistrantEmail(); try { - csvEmails += ",phuonghqh@gmail.com";//TODO remove this value because its used to test only emailContent.setRecipients(InternetAddress.parse(csvEmails)); } catch (AddressException e) { From 2a927d3f2b2748af0699f4ab65e208ee2a1c9c34 Mon Sep 17 00:00:00 2001 From: johnsonpham Date: Thu, 1 Oct 2015 16:32:18 +0700 Subject: [PATCH 22/29] update validation for send email --- src/main/webapp/assets/modules/common/popupEmail.html | 8 ++------ .../employer-dashboard/employerDashboardController.js | 4 +++- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/src/main/webapp/assets/modules/common/popupEmail.html b/src/main/webapp/assets/modules/common/popupEmail.html index 8b35a3deb..875135968 100644 --- a/src/main/webapp/assets/modules/common/popupEmail.html +++ b/src/main/webapp/assets/modules/common/popupEmail.html @@ -20,15 +20,11 @@
    -
    - email container ....... ... -
    -
    -
    +
    diff --git a/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js b/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js index 1fcb216a8..e621cdb79 100644 --- a/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js +++ b/src/main/webapp/assets/modules/employer-dashboard/employerDashboardController.js @@ -5,7 +5,9 @@ techlooper.controller('employerDashboardController', function ($scope, jsonValue $scope.composeEmail = { send: function() { $scope.composeEmail.content = $('.summernote').code(); - //console.log($scope.composeEmail); + if($scope.composeEmail.content == '


    '){ + return; + } apiService.sendEmailToDailyChallengeRegistrants($scope.composeEmail.challengeId, $scope.composeEmail.now, $scope.composeEmail) .finally(function() { $scope.composeEmail.cancel(); From 2d367a2e1a442b59474bd532900fff5d3a90feae Mon Sep 17 00:00:00 2001 From: khoa-nd Date: Thu, 1 Oct 2015 16:35:27 +0700 Subject: [PATCH 23/29] Set email subject to default value [No Subject] --- .../java/com/techlooper/service/impl/EmailServiceImpl.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/techlooper/service/impl/EmailServiceImpl.java b/src/main/java/com/techlooper/service/impl/EmailServiceImpl.java index be8f0cfce..6b1d4ec65 100644 --- a/src/main/java/com/techlooper/service/impl/EmailServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/EmailServiceImpl.java @@ -4,6 +4,7 @@ import com.techlooper.model.Language; import com.techlooper.service.EmailService; import freemarker.template.Template; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.mail.javamail.JavaMailSender; @@ -39,7 +40,8 @@ public class EmailServiceImpl implements EmailService { public boolean sendEmail(EmailContent emailContent) { try { - fromTechlooperMailMessage.setSubject(MimeUtility.encodeText(emailContent.getSubject(), "UTF-8", null)); + String subject = StringUtils.isNotEmpty(emailContent.getSubject()) ? emailContent.getSubject() : "[No Subject]"; + fromTechlooperMailMessage.setSubject(MimeUtility.encodeText(subject, "UTF-8", null)); Template template = emailContent.getLanguage() == Language.vi ? challengeEmployerMailTemplateVi : challengeEmployerMailTemplateEn; From 300bfd738f0e2ab49d0f1693fe46ac6aca6ca580 Mon Sep 17 00:00:00 2001 From: johnsonpham Date: Thu, 1 Oct 2015 17:26:08 +0700 Subject: [PATCH 24/29] update translate and binding data for Challenge details page --- .../assets/modules/contest-detail/contest-detail.tem.html | 6 +++--- src/main/webapp/assets/modules/translation/messages_en.json | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/webapp/assets/modules/contest-detail/contest-detail.tem.html b/src/main/webapp/assets/modules/contest-detail/contest-detail.tem.html index 7e255f4fc..4bc9bcc11 100644 --- a/src/main/webapp/assets/modules/contest-detail/contest-detail.tem.html +++ b/src/main/webapp/assets/modules/contest-detail/contest-detail.tem.html @@ -90,7 +90,7 @@

    - 15/09/2015 + {{contestDetail.ideaSubmissionDateTime}}
    - 15/09/2015 + {{contestDetail.uxSubmissionDateTime}}
    - 15/09/2015 + {{contestDetail.prototypeSubmissionDateTime}}
    diff --git a/src/main/webapp/assets/modules/translation/messages_en.json b/src/main/webapp/assets/modules/translation/messages_en.json index 05fbdd646..aa907cb03 100644 --- a/src/main/webapp/assets/modules/translation/messages_en.json +++ b/src/main/webapp/assets/modules/translation/messages_en.json @@ -729,7 +729,7 @@ "disqualify": "Disqualify", "qualify": "Qualify", "qualifyConfirmation": "Are you sure to qualify this contestant again?", - "mileStones": "Mile Stones:", + "mileStones": "Milestones:", "pleaseSelectMileStone": "Please select milestones relevant to your contest.", "prototype": "Prototype", "idea": "Idea", From cdfef63cbb5f4f092f41bd832e6300fca6d7f957 Mon Sep 17 00:00:00 2001 From: khoa-nd Date: Thu, 1 Oct 2015 17:28:19 +0700 Subject: [PATCH 25/29] Add web base URL param --- .../java/com/techlooper/service/impl/EmailServiceImpl.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/main/java/com/techlooper/service/impl/EmailServiceImpl.java b/src/main/java/com/techlooper/service/impl/EmailServiceImpl.java index 6b1d4ec65..0e82dd19d 100644 --- a/src/main/java/com/techlooper/service/impl/EmailServiceImpl.java +++ b/src/main/java/com/techlooper/service/impl/EmailServiceImpl.java @@ -7,6 +7,7 @@ import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Service; @@ -38,6 +39,9 @@ public class EmailServiceImpl implements EmailService { @Resource private Template challengeEmployerMailTemplateVi; + @Value("${web.baseUrl}") + private String webBaseUrl; + public boolean sendEmail(EmailContent emailContent) { try { String subject = StringUtils.isNotEmpty(emailContent.getSubject()) ? emailContent.getSubject() : "[No Subject]"; @@ -48,6 +52,7 @@ public boolean sendEmail(EmailContent emailContent) { StringWriter stringWriter = new StringWriter(); Map templateModel = new HashMap<>(); + templateModel.put("webBaseUrl", webBaseUrl); templateModel.put("emailContent", emailContent.getContent()); template.process(templateModel, stringWriter); From 98f7881a4523d498eb734ee47cc3e6c7840fbbc1 Mon Sep 17 00:00:00 2001 From: johnsonpham Date: Thu, 1 Oct 2015 17:29:22 +0700 Subject: [PATCH 26/29] update css --- src/main/resources/template/challengeDailySummary.en.ftl | 4 ++-- src/main/resources/template/challengeDailySummary.vi.ftl | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/resources/template/challengeDailySummary.en.ftl b/src/main/resources/template/challengeDailySummary.en.ftl index cc7aaa06b..a2cb8cc67 100644 --- a/src/main/resources/template/challengeDailySummary.en.ftl +++ b/src/main/resources/template/challengeDailySummary.en.ftl @@ -322,13 +322,13 @@

    - +
    ${latestSubmission_index + 1} ${latestSubmission.registrantName}
    - +
    diff --git a/src/main/resources/template/challengeDailySummary.vi.ftl b/src/main/resources/template/challengeDailySummary.vi.ftl index 96b60cfa1..418b23c01 100644 --- a/src/main/resources/template/challengeDailySummary.vi.ftl +++ b/src/main/resources/template/challengeDailySummary.vi.ftl @@ -322,13 +322,13 @@
    Review
    - +
    ${latestSubmission_index + 1} ${latestSubmission.registrantName}
    - +
    From a6f31905c8a49bed9548dbad9febdd449548864b Mon Sep 17 00:00:00 2001 From: khoa-nd Date: Thu, 1 Oct 2015 17:34:35 +0700 Subject: [PATCH 27/29] Consider registrant id as a string instead of number --- src/main/resources/template/challengeDailySummary.en.ftl | 2 +- src/main/resources/template/challengeDailySummary.vi.ftl | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/resources/template/challengeDailySummary.en.ftl b/src/main/resources/template/challengeDailySummary.en.ftl index cc7aaa06b..7e31f9053 100644 --- a/src/main/resources/template/challengeDailySummary.en.ftl +++ b/src/main/resources/template/challengeDailySummary.en.ftl @@ -333,7 +333,7 @@
    Xem Trước Review - Feedback + Feedback
    diff --git a/src/main/resources/template/challengeDailySummary.vi.ftl b/src/main/resources/template/challengeDailySummary.vi.ftl index 96b60cfa1..f1e20e663 100644 --- a/src/main/resources/template/challengeDailySummary.vi.ftl +++ b/src/main/resources/template/challengeDailySummary.vi.ftl @@ -333,7 +333,7 @@
    Xem Trước - Phản Hồi + Phản Hồi
    From 71e25fa5239dcb4f13f7b87e59dd8d8774fa01ba Mon Sep 17 00:00:00 2001 From: Phuong H Date: Thu, 1 Oct 2015 17:40:34 +0700 Subject: [PATCH 28/29] Fix not redirect url from email --- src/main/webapp/assets/modules/_app.js | 2 +- .../loading-box/loadingBoxController.js | 23 +++++++++++++++++++ .../post-contest/postContestController.js | 3 +++ .../post-contest/postContestTimeline.html | 9 +++++--- 4 files changed, 33 insertions(+), 4 deletions(-) diff --git a/src/main/webapp/assets/modules/_app.js b/src/main/webapp/assets/modules/_app.js index a58a470c2..9655e461c 100644 --- a/src/main/webapp/assets/modules/_app.js +++ b/src/main/webapp/assets/modules/_app.js @@ -211,7 +211,7 @@ techlooper.config(["$routeProvider", "$translateProvider", "$authProvider", "loc .otherwise({ redirectTo: function (err, path, params) { if (!$.isEmptyObject(params)) { - return "/loading"; + return "/loading?" + $.param(params); } if (window.location.host.indexOf("hiring") >= 0) { diff --git a/src/main/webapp/assets/modules/loading-box/loadingBoxController.js b/src/main/webapp/assets/modules/loading-box/loadingBoxController.js index 8b3f17667..e0b343f06 100644 --- a/src/main/webapp/assets/modules/loading-box/loadingBoxController.js +++ b/src/main/webapp/assets/modules/loading-box/loadingBoxController.js @@ -10,5 +10,28 @@ techlooper.controller("loadingBoxController", function (utils, jsonValue, $scope return securityService.routeByRole(); } + var param = $location.search(); + if (!$.isEmptyObject(param)) { + switch (param.action) { + case "registerVnwUser": + localStorageService.set("lastName", param.lastName); + localStorageService.set("firstName", param.firstName); + localStorageService.set("email", param.email); + break; + + case "loginBySocial": + securityService.login(param.code, param.social, param.social); + break; + + case "redirectJA": + window.location.href = param.targetUrl; + break; + + case "cancel": + $location.url("/"); + break; + } + } + $location.url("/"); }); \ No newline at end of file diff --git a/src/main/webapp/assets/modules/post-contest/postContestController.js b/src/main/webapp/assets/modules/post-contest/postContestController.js index a84bb6745..208c2d296 100644 --- a/src/main/webapp/assets/modules/post-contest/postContestController.js +++ b/src/main/webapp/assets/modules/post-contest/postContestController.js @@ -256,5 +256,8 @@ techlooper.controller("postContestController", function ($scope, $http, jsonValu compareDate = compareDate.charAt(0).toUpperCase() + compareDate.substr(1); $scope.timelineForm && $scope.timelineForm.submissionDate.$setValidity("gt" + compareDate, valid); + if (!$scope.ideaChecked) delete $scope.contest.ideaSubmissionDate; + if (!$scope.uiuxChecked) delete $scope.contest.uxSubmissionDate; + if (!$scope.prototypeChecked) delete $scope.contest.prototypeSubmissionDate; }, true); }); \ No newline at end of file diff --git a/src/main/webapp/assets/modules/post-contest/postContestTimeline.html b/src/main/webapp/assets/modules/post-contest/postContestTimeline.html index 8ab7bd36f..5781ff4d6 100644 --- a/src/main/webapp/assets/modules/post-contest/postContestTimeline.html +++ b/src/main/webapp/assets/modules/post-contest/postContestTimeline.html @@ -68,7 +68,7 @@

    placeholder="{{'ex' | translate}}{{state.status('ex-register-date')}}" name="ideaSubmissionDate" ng-disabled="!ideaChecked" data-toggle="tooltip" data-original-title="{{'challengeIdeaTips' | translate}}" - ng-model="contest.ideaSubmissionDate"> + ng-model="contest.ideaSubmissionDate" ng-required="ideaChecked"> @@ -78,6 +78,7 @@

    +
    @@ -95,7 +96,7 @@

    name="uxSubmissionDate" ng-disabled="!uiuxChecked" placeholder="{{'ex' | translate}}{{state.status('ex-register-date')}}" data-toggle="tooltip" data-original-title="{{'challengeUIUXTips' | translate}}" - ng-model="contest.uxSubmissionDate"> + ng-model="contest.uxSubmissionDate" ng-required="uiuxChecked"> @@ -105,6 +106,7 @@

    +
    placeholder="{{'ex' | translate}}{{state.status('ex-register-date')}}" name="prototypeSubmissionDate" ng-disabled="!prototypeChecked" data-toggle="tooltip" data-original-title="{{'challengePrototypeTips' | translate}}" - ng-model="contest.prototypeSubmissionDate"> + ng-model="contest.prototypeSubmissionDate" ng-required="prototypeChecked"> @@ -134,6 +136,7 @@

    +
    Date: Thu, 1 Oct 2015 17:46:14 +0700 Subject: [PATCH 29/29] format number to string --- src/main/resources/template/challengeDailySummary.en.ftl | 2 +- src/main/resources/template/challengeDailySummary.vi.ftl | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/resources/template/challengeDailySummary.en.ftl b/src/main/resources/template/challengeDailySummary.en.ftl index f9bbbbe99..f4980475b 100644 --- a/src/main/resources/template/challengeDailySummary.en.ftl +++ b/src/main/resources/template/challengeDailySummary.en.ftl @@ -333,7 +333,7 @@
    Review - Feedback + Feedback
    diff --git a/src/main/resources/template/challengeDailySummary.vi.ftl b/src/main/resources/template/challengeDailySummary.vi.ftl index 666b6a53d..bfce94669 100644 --- a/src/main/resources/template/challengeDailySummary.vi.ftl +++ b/src/main/resources/template/challengeDailySummary.vi.ftl @@ -333,7 +333,7 @@
    Xem Trước - Phản Hồi + Phản Hồi