diff --git a/build.gradle b/build.gradle index 0edeb92..0373cfc 100644 --- a/build.gradle +++ b/build.gradle @@ -125,8 +125,11 @@ dependencies { compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.6.0' compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.6.0' + compile group: 'net.sourceforge.htmlunit', name: 'htmlunit', version: '2.35.0' testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test' - testCompile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '3.3.1' + compile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '3.3.1' + testCompile group: 'org.seleniumhq.selenium', name: 'selenium-support', version: '3.3.1' + testCompile group: 'com.google.guava', name: 'guava', version: '21.0' } \ No newline at end of file diff --git a/deploy/gdccloud/deploy.sh b/deploy/gdccloud/deploy.sh index 26604b7..50d3d5c 100644 --- a/deploy/gdccloud/deploy.sh +++ b/deploy/gdccloud/deploy.sh @@ -18,6 +18,6 @@ fi ssh $USERSERVER "cd /tmp && rm -rf $ARTIFACT_NAME*.jar && echo `date` 'killed' >> log_$ARTIFACT_NAME" scp build/libs/$ARTIFACT_NAME-0.1.0-SNAPSHOT.jar $USERSERVER:/tmp/$ARTIFACT_NAME-0.1.0-SNAPSHOT.jar -ssh $USERSERVER -f "cd /tmp/ && /opt/jdk1.8.0_192/bin/java -jar $ARTIFACT_NAME-0.1.0-SNAPSHOT.jar -Xms 512m -Xmx 1024m --server.port=8443 --server.http.port=8080 --ng-tracker.base-url=http://193.110.3.124:8080 >> /home/user/logfile_$ARTIFACT_NAME" & +ssh $USERSERVER -f "cd /tmp/ && /opt/jdk1.8.0_192/bin/java -jar $ARTIFACT_NAME-0.1.0-SNAPSHOT.jar -Xms 512m -Xmx 1024m --server.port=8443 --server.http.port=8080 --ng-tracker.base-url=http://193.110.3.124:8080 --ng-tracker.dev-mode=false --ng-tracker.driver-path=/home/user >> /home/user/logfile_$ARTIFACT_NAME" & sleep 10 echo "is deployed" \ No newline at end of file diff --git a/src/main/java/ru/ulstu/conference/controller/ConferenceController.java b/src/main/java/ru/ulstu/conference/controller/ConferenceController.java index a416345..f9a4bac 100644 --- a/src/main/java/ru/ulstu/conference/controller/ConferenceController.java +++ b/src/main/java/ru/ulstu/conference/controller/ConferenceController.java @@ -6,7 +6,6 @@ import org.springframework.ui.ModelMap; import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @@ -14,7 +13,6 @@ import ru.ulstu.conference.model.ConferenceDto; import ru.ulstu.conference.model.ConferenceFilterDto; import ru.ulstu.conference.model.ConferenceUser; import ru.ulstu.conference.service.ConferenceService; -import ru.ulstu.deadline.model.Deadline; import ru.ulstu.user.model.User; import springfox.documentation.annotations.ApiIgnore; @@ -23,9 +21,7 @@ import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.List; -import java.util.stream.Collectors; -import static org.springframework.util.StringUtils.isEmpty; import static ru.ulstu.core.controller.Navigation.CONFERENCES_PAGE; import static ru.ulstu.core.controller.Navigation.CONFERENCE_PAGE; import static ru.ulstu.core.controller.Navigation.REDIRECT_TO; @@ -57,6 +53,8 @@ public class ConferenceController { @GetMapping("/dashboard") public void getDashboard(ModelMap modelMap) { modelMap.put("conferences", conferenceService.findAllActiveDto()); + + conferenceService.setChartData(modelMap); // example } @GetMapping("/conference") @@ -68,30 +66,27 @@ public class ConferenceController { } } + @PostMapping(value = "/conferences", params = "deleteConference") + public String delete(@RequestParam("deleteConference") Integer conferenceId) throws IOException { + conferenceService.delete(conferenceId); + return String.format(REDIRECT_TO, CONFERENCES_PAGE); + } + @PostMapping(value = "/conference", params = "save") public String save(@Valid ConferenceDto conferenceDto, Errors errors) throws IOException { - filterEmptyDeadlines(conferenceDto); - if (errors.hasErrors()) { + if (!conferenceService.save(conferenceDto, errors)) { return CONFERENCE_PAGE; } - conferenceService.save(conferenceDto); - return String.format(REDIRECT_TO, CONFERENCES_PAGE); - - } - - @GetMapping("/delete/{conference-id}") - public String delete(@PathVariable("conference-id") Integer conferenceId) throws IOException { - conferenceService.delete(conferenceId); return String.format(REDIRECT_TO, CONFERENCES_PAGE); } @PostMapping(value = "/conference", params = "addDeadline") - public String addDeadline(@Valid ConferenceDto conferenceDto, Errors errors) { - filterEmptyDeadlines(conferenceDto); + public String addDeadline(@Valid ConferenceDto conferenceDto, Errors errors) throws IOException { + conferenceService.filterEmptyDeadlines(conferenceDto); if (errors.hasErrors()) { return CONFERENCE_PAGE; } - conferenceDto.getDeadlines().add(new Deadline()); + conferenceService.addDeadline(conferenceDto); return CONFERENCE_PAGE; } @@ -105,6 +100,16 @@ public class ConferenceController { return CONFERENCE_PAGE; } + @PostMapping(value = "/conference", params = "addPaper") + public String addPaper(@Valid ConferenceDto conferenceDto, Errors errors) throws IOException { + if (errors.hasErrors()) { + return CONFERENCE_PAGE; + } + conferenceService.addPaper(conferenceDto); + + return CONFERENCE_PAGE; + } + @PostMapping(value = "/conference", params = "removePaper") public String removePaper(@Valid ConferenceDto conferenceDto, Errors errors, @RequestParam(value = "removePaper") Integer paperIndex) throws IOException { @@ -124,6 +129,15 @@ public class ConferenceController { return CONFERENCE_PAGE; } + @PostMapping(value = "/conference", params = "pingConference") + public String ping(@Valid ConferenceDto conferenceDto, Errors errors) throws IOException { + if (errors.hasErrors()) { + return CONFERENCE_PAGE; + } + conferenceService.ping(conferenceDto); + return CONFERENCE_PAGE; + } + @ModelAttribute("allParticipation") public List getAllParticipation() { return conferenceService.getAllParticipations(); @@ -148,9 +162,4 @@ public class ConferenceController { return years; } - private void filterEmptyDeadlines(ConferenceDto conferenceDto) { - conferenceDto.setDeadlines(conferenceDto.getDeadlines().stream() - .filter(dto -> dto.getDate() != null || !isEmpty(dto.getDescription())) - .collect(Collectors.toList())); - } } diff --git a/src/main/java/ru/ulstu/conference/model/Conference.java b/src/main/java/ru/ulstu/conference/model/Conference.java index 9831a0e..d11901f 100644 --- a/src/main/java/ru/ulstu/conference/model/Conference.java +++ b/src/main/java/ru/ulstu/conference/model/Conference.java @@ -4,11 +4,16 @@ import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; import org.springframework.format.annotation.DateTimeFormat; import ru.ulstu.core.model.BaseEntity; +import ru.ulstu.core.model.EventSource; +import ru.ulstu.core.model.UserActivity; import ru.ulstu.deadline.model.Deadline; import ru.ulstu.paper.model.Paper; +import ru.ulstu.timeline.model.Event; +import ru.ulstu.user.model.User; import javax.persistence.CascadeType; import javax.persistence.Column; +import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; @@ -21,12 +26,17 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotBlank; import java.util.ArrayList; +import java.util.Comparator; import java.util.Date; import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; @Entity @Table(name = "conference") -public class Conference extends BaseEntity { +@DiscriminatorValue("CONFERENCE") +public class Conference extends BaseEntity implements UserActivity, EventSource { @NotBlank private String title; @@ -35,17 +45,17 @@ public class Conference extends BaseEntity { private String url; - private int ping; + private int ping = 0; @Column(name = "begin_date") @Temporal(TemporalType.TIMESTAMP) @DateTimeFormat(pattern = "yyyy-MM-dd") - private Date beginDate; + private Date beginDate = new Date(); @Column(name = "end_date") @Temporal(TemporalType.TIMESTAMP) @DateTimeFormat(pattern = "yyyy-MM-dd") - private Date endDate; + private Date endDate = new Date(); @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinColumn(name = "conference_id", unique = true) @@ -53,10 +63,11 @@ public class Conference extends BaseEntity { @OrderBy("date") private List deadlines = new ArrayList<>(); - @ManyToMany(fetch = FetchType.EAGER) + @ManyToMany(cascade = CascadeType.MERGE, fetch = FetchType.EAGER) @JoinTable(name = "paper_conference", joinColumns = {@JoinColumn(name = "conference_id")}, inverseJoinColumns = {@JoinColumn(name = "paper_id")}) + @Fetch(FetchMode.SUBSELECT) private List papers = new ArrayList<>(); @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @@ -68,6 +79,19 @@ public class Conference extends BaseEntity { return title; } + @Override + public List getRecipients() { + List list = new ArrayList<>(); + + getUsers().forEach(conferenceUser -> list.add(conferenceUser.getUser())); + return list; + } + + @Override + public void addObjectToEvent(Event event) { + event.setConference(this); + } + public void setTitle(String title) { this.title = title; } @@ -135,4 +159,18 @@ public class Conference extends BaseEntity { public void setUsers(List users) { this.users = users; } + + public Optional getNextDeadline() { + return deadlines + .stream() + .filter(deadline -> deadline.getDate() != null) + .sorted(Comparator.comparing(Deadline::getDate)) + .filter(d -> d.getDate().after(new Date())) + .findFirst(); + } + + @Override + public Set getActivityUsers() { + return getUsers().stream().map(ConferenceUser::getUser).collect(Collectors.toSet()); + } } diff --git a/src/main/java/ru/ulstu/conference/model/ConferenceDto.java b/src/main/java/ru/ulstu/conference/model/ConferenceDto.java index 6264f62..7246854 100644 --- a/src/main/java/ru/ulstu/conference/model/ConferenceDto.java +++ b/src/main/java/ru/ulstu/conference/model/ConferenceDto.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import org.springframework.format.annotation.DateTimeFormat; import ru.ulstu.core.model.BaseEntity; import ru.ulstu.deadline.model.Deadline; +import ru.ulstu.name.NameContainer; import ru.ulstu.paper.model.Paper; import javax.persistence.Temporal; @@ -14,10 +15,11 @@ import javax.validation.constraints.Size; import java.util.ArrayList; import java.util.Date; import java.util.List; +import java.util.Objects; import static ru.ulstu.core.util.StreamApiUtils.convert; -public class ConferenceDto { +public class ConferenceDto extends NameContainer { private final static String BEGIN_DATE = "Начало: "; private final static String END_DATE = "Конец: "; @@ -219,4 +221,33 @@ public class ConferenceDto { return BEGIN_DATE + beginDate.toString().split(" ")[0] + " " + END_DATE + endDate.toString().split(" ")[0]; } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ConferenceDto that = (ConferenceDto) o; + return ping == that.ping && + disabledTakePart == that.disabledTakePart && + Objects.equals(id, that.id) && + Objects.equals(title, that.title) && + Objects.equals(description, that.description) && + Objects.equals(url, that.url) && + Objects.equals(deadlines, that.deadlines) && + Objects.equals(removedDeadlineIds, that.removedDeadlineIds) && + Objects.equals(userIds, that.userIds) && + Objects.equals(paperIds, that.paperIds) && + Objects.equals(papers, that.papers) && + Objects.equals(notSelectedPapers, that.notSelectedPapers) && + Objects.equals(users, that.users); + } + + @Override + public int hashCode() { + return Objects.hash(id, title, description, url, ping, beginDate, endDate, deadlines, removedDeadlineIds, + userIds, paperIds, papers, notSelectedPapers, users, disabledTakePart); + } } diff --git a/src/main/java/ru/ulstu/conference/model/ConferenceFilterDto.java b/src/main/java/ru/ulstu/conference/model/ConferenceFilterDto.java index 8503b40..0649901 100644 --- a/src/main/java/ru/ulstu/conference/model/ConferenceFilterDto.java +++ b/src/main/java/ru/ulstu/conference/model/ConferenceFilterDto.java @@ -11,14 +11,14 @@ public class ConferenceFilterDto { public ConferenceFilterDto() { } - public ConferenceFilterDto(List conferenceDtos, Integer filterUserId, Integer year) { - this.conferences = conferenceDtos; + public ConferenceFilterDto(List conferences, Integer filterUserId, Integer year) { + this.conferences = conferences; this.filterUserId = filterUserId; this.year = year; } - public ConferenceFilterDto(List conferenceDtos) { - this(conferenceDtos, null, null); + public ConferenceFilterDto(List conferences) { + this(conferences, null, null); } public List getConferences() { diff --git a/src/main/java/ru/ulstu/conference/repository/ConferenceRepository.java b/src/main/java/ru/ulstu/conference/repository/ConferenceRepository.java index cb8a488..8f9e05f 100644 --- a/src/main/java/ru/ulstu/conference/repository/ConferenceRepository.java +++ b/src/main/java/ru/ulstu/conference/repository/ConferenceRepository.java @@ -1,19 +1,36 @@ package ru.ulstu.conference.repository; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import ru.ulstu.conference.model.Conference; +import ru.ulstu.name.BaseRepository; import ru.ulstu.user.model.User; import java.util.Date; import java.util.List; -public interface ConferenceRepository extends JpaRepository { +public interface ConferenceRepository extends JpaRepository, BaseRepository { @Query("SELECT c FROM Conference c LEFT JOIN c.users u WHERE (:user IS NULL OR u.user = :user) " + "AND (YEAR(c.beginDate) = :year OR :year IS NULL) ORDER BY begin_date DESC") List findByUserAndYear(@Param("user") User user, @Param("year") Integer year); @Query("SELECT c FROM Conference c WHERE c.beginDate > :date") List findAllActive(@Param("date") Date date); + + @Query("SELECT case when count(c) > 0 then true else false end FROM Conference c JOIN c.papers p WHERE p.id = :paperId") + boolean isPaperAttached(@Param("paperId") Integer paperId); + + @Modifying + @Query("UPDATE Conference c SET c.ping = (c.ping + 1) WHERE c.id = :id") + int updatePingConference(@Param("id") Integer id); + + @Override + @Query("SELECT title FROM Conference c WHERE (c.title = :name) AND (:id IS NULL OR c.id != :id) ") + String findByNameAndNotId(@Param("name") String name, @Param("id") Integer id); + + @Query("SELECT c FROM Conference c LEFT JOIN c.users u WHERE (:user IS NULL OR u.user = :user) " + + "AND (u.participation = 'INTRAMURAL') AND (c.beginDate <= CURRENT_DATE) AND (c.endDate >= CURRENT_DATE)") + Conference findActiveByUser(@Param("user") User user); } diff --git a/src/main/java/ru/ulstu/conference/service/ConferenceNotificationService.java b/src/main/java/ru/ulstu/conference/service/ConferenceNotificationService.java index ff9f69a..ddb8130 100644 --- a/src/main/java/ru/ulstu/conference/service/ConferenceNotificationService.java +++ b/src/main/java/ru/ulstu/conference/service/ConferenceNotificationService.java @@ -1,7 +1,113 @@ package ru.ulstu.conference.service; +import com.google.common.collect.ImmutableMap; import org.springframework.stereotype.Service; +import ru.ulstu.conference.model.Conference; +import ru.ulstu.core.util.DateUtils; +import ru.ulstu.ping.service.PingService; +import ru.ulstu.user.service.MailService; +import ru.ulstu.user.service.UserService; + +import java.util.Calendar; +import java.util.Date; +import java.util.List; +import java.util.Map; @Service public class ConferenceNotificationService { + + private final static int YESTERDAY = -1; + private final static int DAYS_TO_DEADLINE_NOTIFICATION = 7; + private final static String TEMPLATE_PING = "conferencePingNotification"; + private final static String TEMPLATE_DEADLINE = "conferenceDeadlineNotification"; + private final static String TEMPLATE_CREATE = "conferenceCreateNotification"; + private final static String TEMPLATE_UPDATE_DEADLINES = "conferenceUpdateDeadlinesNotification"; + private final static String TEMPLATE_UPDATE_DATES = "conferenceUpdateDatesNotification"; + + private final static String TITLE_PING = "Обратите внимание на конференцию: %s"; + private final static String TITLE_DEADLINE = "Приближается дедлайн конференции: %s"; + private final static String TITLE_CREATE = "Создана новая конференция: %s"; + private final static String TITLE_UPDATE_DEADLINES = "Изменения дедлайнов в конференции: %s"; + private final static String TITLE_UPDATE_DATES = "Изменение дат проведения конференции: %s"; + + private final MailService mailService; + private final UserService userService; + private final PingService pingService; + + public ConferenceNotificationService(MailService mailService, + UserService userService, + PingService pingService) { + this.mailService = mailService; + this.userService = userService; + this.pingService = pingService; + } + + public void sendDeadlineNotifications(List conferences) { + Date now = DateUtils.addDays(new Date(), DAYS_TO_DEADLINE_NOTIFICATION); + conferences + .stream() + .filter(conference -> needToSendDeadlineNotification(conference, now)) + .forEach(this::sendMessageDeadline); + } + + private boolean needToSendDeadlineNotification(Conference conference, Date compareDate) { + return (conference.getNextDeadline().isPresent()) + && conference.getNextDeadline().get().getDate().after(new Date()) + && conference.getNextDeadline().get().getDate().before(compareDate); + } + + private void sendMessageDeadline(Conference conference) { + Map variables = ImmutableMap.of("conference", conference); + sendForAllParticipants(variables, conference, TEMPLATE_DEADLINE, String.format(TITLE_DEADLINE, conference.getTitle())); + } + + public void sendCreateNotification(Conference conference) { + Map variables = ImmutableMap.of("conference", conference); + sendForAllUsers(variables, TEMPLATE_CREATE, String.format(TITLE_CREATE, conference.getTitle())); + } + + public void updateDeadlineNotification(Conference conference) { + Map variables = ImmutableMap.of("conference", conference); + sendForAllParticipants(variables, conference, TEMPLATE_UPDATE_DEADLINES, String.format(TITLE_UPDATE_DEADLINES, conference.getTitle())); + } + + public void updateConferencesDatesNotification(Conference conference, Date oldBeginDate, Date oldEndDate) { + Map variables = ImmutableMap.of("conference", conference, "oldBeginDate", oldBeginDate, "oldEndDate", oldEndDate); + sendForAllParticipants(variables, conference, TEMPLATE_UPDATE_DATES, String.format(TITLE_UPDATE_DATES, conference.getTitle())); + } + + private void sendForAllUsers(Map variables, String template, String title) { + userService.findAll().forEach(user -> mailService.sendEmailFromTemplate(variables, user, template, title)); + } + + private void sendForAllParticipants(Map variables, Conference conference, String template, String title) { + conference.getUsers().forEach(conferenceUser -> mailService.sendEmailFromTemplate(variables, conferenceUser.getUser(), template, title)); + } + + + public void sendPingNotifications(List conferences) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(new Date()); + calendar.add(Calendar.DAY_OF_MONTH, YESTERDAY); + conferences + .stream() + .filter(conference -> { + Integer pingCount = pingService.countPingYesterday(conference, calendar); + return needToSendPingNotification(conference, pingCount); + }) + .forEach(this::sendMessagePing); + } + + private boolean needToSendPingNotification(Conference conference, Integer pingCount) { + if (pingCount > 0) { + conference.setPing((Integer) pingCount); + return true; + } + return false; + } + + private void sendMessagePing(Conference conference) { + Map variables = ImmutableMap.of("conference", conference); + sendForAllParticipants(variables, conference, TEMPLATE_PING, String.format(TITLE_PING, conference.getTitle())); + } } diff --git a/src/main/java/ru/ulstu/conference/service/ConferenceScheduler.java b/src/main/java/ru/ulstu/conference/service/ConferenceScheduler.java new file mode 100644 index 0000000..6f8fe90 --- /dev/null +++ b/src/main/java/ru/ulstu/conference/service/ConferenceScheduler.java @@ -0,0 +1,37 @@ +package ru.ulstu.conference.service; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +@Service +public class ConferenceScheduler { + private final static boolean IS_DEADLINE_NOTIFICATION_BEFORE_WEEK = true; + + private final Logger log = LoggerFactory.getLogger(ConferenceScheduler.class); + + private final ConferenceNotificationService conferenceNotificationService; + private final ConferenceService conferenceService; + + public ConferenceScheduler(ConferenceNotificationService conferenceNotificationService, + ConferenceService conferenceService) { + this.conferenceNotificationService = conferenceNotificationService; + this.conferenceService = conferenceService; + } + + + @Scheduled(cron = "0 0 8 * * MON", zone = "Europe/Samara") + public void checkDeadlineBeforeWeek() { + log.debug("ConferenceScheduler.checkDeadlineBeforeWeek started"); + conferenceNotificationService.sendDeadlineNotifications(conferenceService.findAll()); + log.debug("ConferenceScheduler.checkDeadlineBeforeWeek finished"); + } + + @Scheduled(cron = "0 0 8 * * *", zone = "Europe/Samara") + public void checkNewPing() { + log.debug("ConferenceScheduler.checkPing started"); + conferenceNotificationService.sendPingNotifications(conferenceService.findAll()); + log.debug("ConferenceScheduler.checkPing finished"); + } +} diff --git a/src/main/java/ru/ulstu/conference/service/ConferenceService.java b/src/main/java/ru/ulstu/conference/service/ConferenceService.java index dfd0f8a..c605378 100644 --- a/src/main/java/ru/ulstu/conference/service/ConferenceService.java +++ b/src/main/java/ru/ulstu/conference/service/ConferenceService.java @@ -4,28 +4,36 @@ import org.apache.commons.lang3.StringUtils; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.ui.ModelMap; +import org.springframework.validation.Errors; import ru.ulstu.conference.model.Conference; import ru.ulstu.conference.model.ConferenceDto; import ru.ulstu.conference.model.ConferenceFilterDto; import ru.ulstu.conference.model.ConferenceUser; import ru.ulstu.conference.repository.ConferenceRepository; +import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.service.DeadlineService; +import ru.ulstu.name.BaseService; import ru.ulstu.paper.model.Paper; import ru.ulstu.paper.service.PaperService; +import ru.ulstu.ping.service.PingService; +import ru.ulstu.timeline.service.EventService; import ru.ulstu.user.model.User; import ru.ulstu.user.service.UserService; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.Date; import java.util.List; +import java.util.stream.Collectors; import static org.springframework.util.ObjectUtils.isEmpty; import static ru.ulstu.core.util.StreamApiUtils.convert; @Service -public class ConferenceService { +public class ConferenceService extends BaseService { private final static int MAX_DISPLAY_SIZE = 40; private final ConferenceRepository conferenceRepository; @@ -33,21 +41,31 @@ public class ConferenceService { private final DeadlineService deadlineService; private final PaperService paperService; private final UserService userService; + private final PingService pingService; + private final ConferenceNotificationService conferenceNotificationService; + private final EventService eventService; public ConferenceService(ConferenceRepository conferenceRepository, ConferenceUserService conferenceUserService, DeadlineService deadlineService, PaperService paperService, - UserService userService) { + UserService userService, + PingService pingService, + ConferenceNotificationService conferenceNotificationService, + EventService eventService) { + this.baseRepository = conferenceRepository; this.conferenceRepository = conferenceRepository; this.conferenceUserService = conferenceUserService; this.deadlineService = deadlineService; this.paperService = paperService; this.userService = userService; + this.pingService = pingService; + this.conferenceNotificationService = conferenceNotificationService; + this.eventService = eventService; } public ConferenceDto getExistConferenceById(Integer id) { - ConferenceDto conferenceDto = findOneDto(id); + ConferenceDto conferenceDto = new ConferenceDto(conferenceRepository.getOne(id)); conferenceDto.setNotSelectedPapers(getNotSelectPapers(conferenceDto.getPaperIds())); conferenceDto.setDisabledTakePart(isCurrentUserParticipant(conferenceDto.getUsers())); return conferenceDto; @@ -55,7 +73,7 @@ public class ConferenceService { public ConferenceDto getNewConference() { ConferenceDto conferenceDto = new ConferenceDto(); - conferenceDto.setNotSelectedPapers(getNotSelectPapers(new ArrayList())); + conferenceDto.setNotSelectedPapers(getNotSelectPapers(new ArrayList<>())); return conferenceDto; } @@ -70,58 +88,103 @@ public class ConferenceService { return conferences; } - public ConferenceDto findOneDto(Integer id) { - return new ConferenceDto(conferenceRepository.getOne(id)); - } + public boolean save(ConferenceDto conferenceDto, Errors errors) throws IOException { + conferenceDto.setName(conferenceDto.getTitle()); + filterEmptyDeadlines(conferenceDto); + checkEmptyFieldsOfDeadline(conferenceDto, errors); + checkEmptyFieldsOfDates(conferenceDto, errors); + checkUniqueName(conferenceDto, + errors, + conferenceDto.getId(), + "title", + "Конференция с таким именем уже существует"); + if (errors.hasErrors()) { + return false; + } - public void save(ConferenceDto conferenceDto) throws IOException { if (isEmpty(conferenceDto.getId())) { create(conferenceDto); } else { update(conferenceDto); } + + return true; } @Transactional - public Integer create(ConferenceDto conferenceDto) throws IOException { + public Conference create(ConferenceDto conferenceDto) throws IOException { Conference newConference = copyFromDto(new Conference(), conferenceDto); newConference = conferenceRepository.save(newConference); - return newConference.getId(); + conferenceNotificationService.sendCreateNotification(newConference); + eventService.createFromObject(newConference, Collections.emptyList(), false, "конференции"); + return newConference; } @Transactional - public Integer update(ConferenceDto conferenceDto) throws IOException { + public Conference update(ConferenceDto conferenceDto) throws IOException { Conference conference = conferenceRepository.getOne(conferenceDto.getId()); + List oldDeadlines = conference.getDeadlines().stream() + .map(this::copyDeadline) + .collect(Collectors.toList()); + Date oldBeginDate = conference.getBeginDate(); + Date oldEndDate = conference.getEndDate(); conferenceRepository.save(copyFromDto(conference, conferenceDto)); + eventService.updateConferenceDeadlines(conference); + sendNotificationAfterUpdateDeadlines(conference, oldDeadlines); + if (!conference.getBeginDate().equals(oldBeginDate) || !conference.getEndDate().equals(oldEndDate)) { + conferenceNotificationService.updateConferencesDatesNotification(conference, oldBeginDate, oldEndDate); + } conferenceDto.getRemovedDeadlineIds().forEach(deadlineService::remove); - return conference.getId(); + return conference; } @Transactional - public void delete(Integer conferenceId) { + public boolean delete(Integer conferenceId) { if (conferenceRepository.existsById(conferenceId)) { + eventService.removeConferencesEvent(conferenceRepository.getOne(conferenceId)); conferenceRepository.deleteById(conferenceId); + return true; } + return false; + } + + public ConferenceDto addDeadline(ConferenceDto conferenceDto) { + conferenceDto.getDeadlines().add(new Deadline()); + return conferenceDto; } - public void removeDeadline(ConferenceDto conferenceDto, Integer deadlineIndex) throws IOException { + + public ConferenceDto removeDeadline(ConferenceDto conferenceDto, Integer deadlineIndex) throws IOException { if (conferenceDto.getDeadlines().get(deadlineIndex).getId() != null) { conferenceDto.getRemovedDeadlineIds().add(conferenceDto.getDeadlines().get(deadlineIndex).getId()); } conferenceDto.getDeadlines().remove((int) deadlineIndex); + return conferenceDto; } - public void removePaper(ConferenceDto conferenceDto, Integer paperIndex) throws IOException { + public ConferenceDto addPaper(ConferenceDto conferenceDto) { + Paper paper = new Paper(); + paper.setTitle(userService.getCurrentUser().getLastName() + "_" + conferenceDto.getTitle() + "_" + (new Date()).getTime()); + paper.setStatus(Paper.PaperStatus.DRAFT); + conferenceDto.getPapers().add(paper); + return conferenceDto; + } + + public ConferenceDto removePaper(ConferenceDto conferenceDto, Integer paperIndex) throws IOException { Paper removedPaper = conferenceDto.getPapers().remove((int) paperIndex); - conferenceDto.getNotSelectedPapers().add(removedPaper); + if (removedPaper.getId() != null) { + conferenceDto.getNotSelectedPapers().add(removedPaper); + } + return conferenceDto; } - public void takePart(ConferenceDto conferenceDto) throws IOException { + public ConferenceDto takePart(ConferenceDto conferenceDto) throws IOException { conferenceDto.getUsers().add(new ConferenceUser(userService.getCurrentUser())); conferenceDto.setDisabledTakePart(true); + return conferenceDto; } - public List getNotSelectPapers(List paperIds) { + private List getNotSelectPapers(List paperIds) { return paperService.findAllNotSelect(paperIds); } @@ -141,21 +204,21 @@ public class ConferenceService { conference.setTitle(conferenceDto.getTitle()); conference.setDescription(conferenceDto.getDescription()); conference.setUrl(conferenceDto.getUrl()); - conference.setPing(0); conference.setBeginDate(conferenceDto.getBeginDate()); conference.setEndDate(conferenceDto.getEndDate()); - conference.setPapers(conferenceDto.getPapers()); + conference.getPapers().clear(); + conferenceDto.getPapers().forEach(paper -> conference.getPapers().add(paper.getId() != null ? paperService.findPaperById(paper.getId()) : paperService.create(paper))); conference.setDeadlines(deadlineService.saveOrCreate(conferenceDto.getDeadlines())); conference.setUsers(conferenceUserService.saveOrCreate(conferenceDto.getUsers())); if (conferenceDto.getPaperIds() != null && !conferenceDto.getPaperIds().isEmpty()) { conferenceDto.getPaperIds().forEach(paperId -> - conference.getPapers().add(paperService.findEntityById(paperId))); + conference.getPapers().add(paperService.findPaperById(paperId))); } return conference; } - public boolean isCurrentUserParticipant(List conferenceUsers) { + private boolean isCurrentUserParticipant(List conferenceUsers) { return conferenceUsers.stream().anyMatch(participant -> participant.getUser().equals(userService.getCurrentUser())); } @@ -170,7 +233,87 @@ public class ConferenceService { return convert(findAllActive(), ConferenceDto::new); } - public List findAllActive() { + private List findAllActive() { return conferenceRepository.findAllActive(new Date()); } + + public boolean isAttachedToConference(Integer paperId) { + return conferenceRepository.isPaperAttached(paperId); + } + + @Transactional + public void ping(ConferenceDto conferenceDto) throws IOException { + pingService.addPing(findOne(conferenceDto.getId())); + conferenceRepository.updatePingConference(conferenceDto.getId()); + } + + private Conference findOne(Integer conferenceId) { + return conferenceRepository.getOne(conferenceId); + } + + public void setChartData(ModelMap modelMap) { + //first, add the regional sales + Integer northeastSales = 17089; + Integer westSales = 10603; + Integer midwestSales = 5223; + Integer southSales = 10111; + + modelMap.addAttribute("northeastSales", northeastSales); + modelMap.addAttribute("southSales", southSales); + modelMap.addAttribute("midwestSales", midwestSales); + modelMap.addAttribute("westSales", westSales); + + //now add sales by lure type + List inshoreSales = Arrays.asList(4074, 3455, 4112); + List nearshoreSales = Arrays.asList(3222, 3011, 3788); + List offshoreSales = Arrays.asList(7811, 7098, 6455); + + modelMap.addAttribute("inshoreSales", inshoreSales); + modelMap.addAttribute("nearshoreSales", nearshoreSales); + modelMap.addAttribute("offshoreSales", offshoreSales); + } + + private void sendNotificationAfterUpdateDeadlines(Conference conference, List oldDeadlines) { + if (oldDeadlines.size() != conference.getDeadlines().size()) { + conferenceNotificationService.updateDeadlineNotification(conference); + return; + } + + if (conference.getDeadlines() + .stream() + .filter(deadline -> !oldDeadlines.contains(deadline)) + .count() > 0) { + conferenceNotificationService.updateDeadlineNotification(conference); + } + } + + private Deadline copyDeadline(Deadline oldDeadline) { + Deadline newDeadline = new Deadline(oldDeadline.getDate(), oldDeadline.getDescription()); + newDeadline.setId(oldDeadline.getId()); + return newDeadline; + } + + public void checkEmptyFieldsOfDeadline(ConferenceDto conferenceDto, Errors errors) { + for (Deadline deadline : conferenceDto.getDeadlines()) { + if (deadline.getDate() == null || deadline.getDescription().isEmpty()) { + errors.rejectValue("deadlines", "errorCode", "Все поля дедлайна должны быть заполнены"); + } + } + } + + private void checkEmptyFieldsOfDates(ConferenceDto conferenceDto, Errors errors) { + if (conferenceDto.getBeginDate() == null || conferenceDto.getEndDate() == null) { + errors.rejectValue("beginDate", "errorCode", "Даты должны быть заполнены"); + } + } + + public void filterEmptyDeadlines(ConferenceDto conferenceDto) { + conferenceDto.setDeadlines(conferenceDto.getDeadlines().stream() + .filter(dto -> dto.getDate() != null || !org.springframework.util.StringUtils.isEmpty(dto.getDescription())) + .collect(Collectors.toList())); + } + + public Conference getActiveConferenceByUser(User user) { + return conferenceRepository.findActiveByUser(user); + } } diff --git a/src/main/java/ru/ulstu/conference/service/ConferenceUserService.java b/src/main/java/ru/ulstu/conference/service/ConferenceUserService.java index 269e7df..bd1b719 100644 --- a/src/main/java/ru/ulstu/conference/service/ConferenceUserService.java +++ b/src/main/java/ru/ulstu/conference/service/ConferenceUserService.java @@ -43,6 +43,4 @@ public class ConferenceUserService { newUser = conferenceUserRepository.save(newUser); return newUser; } - - } diff --git a/src/main/java/ru/ulstu/configuration/ApplicationProperties.java b/src/main/java/ru/ulstu/configuration/ApplicationProperties.java index 0b09821..878e0b4 100644 --- a/src/main/java/ru/ulstu/configuration/ApplicationProperties.java +++ b/src/main/java/ru/ulstu/configuration/ApplicationProperties.java @@ -22,6 +22,10 @@ public class ApplicationProperties { private boolean checkRun; + private String debugEmail; + + private String driverPath; + public boolean isUseHttps() { return useHttps; } @@ -61,4 +65,20 @@ public class ApplicationProperties { public void setCheckRun(boolean checkRun) { this.checkRun = checkRun; } + + public String getDebugEmail() { + return debugEmail; + } + + public void setDebugEmail(String debugEmail) { + this.debugEmail = debugEmail; + } + + public String getDriverPath() { + return driverPath; + } + + public void setDriverPath(String driverPath) { + this.driverPath = driverPath; + } } diff --git a/src/main/java/ru/ulstu/configuration/Constants.java b/src/main/java/ru/ulstu/configuration/Constants.java index 0a2268a..77a9a4d 100644 --- a/src/main/java/ru/ulstu/configuration/Constants.java +++ b/src/main/java/ru/ulstu/configuration/Constants.java @@ -5,7 +5,11 @@ public class Constants { public static final String MAIL_ACTIVATE = "Account activation"; public static final String MAIL_RESET = "Password reset"; + public static final String MAIL_INVITE = "Account registration"; + public static final String MAIL_CHANGE_PASSWORD = "Password has been changed"; + public static final int MIN_PASSWORD_LENGTH = 6; + public static final int MAX_PASSWORD_LENGTH = 32; public static final String LOGIN_REGEX = "^[_'.@A-Za-z0-9-]*$"; @@ -17,4 +21,5 @@ public class Constants { public static final String PASSWORD_RESET_REQUEST_PAGE = "/resetRequest"; public static final String PASSWORD_RESET_PAGE = "/reset"; + public static final int RESET_KEY_LENGTH = 6; } \ No newline at end of file diff --git a/src/main/java/ru/ulstu/configuration/SecurityConfiguration.java b/src/main/java/ru/ulstu/configuration/SecurityConfiguration.java index 591fa0c..5eb7220 100644 --- a/src/main/java/ru/ulstu/configuration/SecurityConfiguration.java +++ b/src/main/java/ru/ulstu/configuration/SecurityConfiguration.java @@ -13,8 +13,10 @@ import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; +import ru.ulstu.core.model.AuthFailureHandler; import ru.ulstu.user.controller.UserController; import ru.ulstu.user.model.UserRoleConstants; import ru.ulstu.user.service.UserService; @@ -35,17 +37,20 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter { private final AuthenticationSuccessHandler authenticationSuccessHandler; private final LogoutSuccessHandler logoutSuccessHandler; private final ApplicationProperties applicationProperties; + private final AuthenticationFailureHandler authenticationFailureHandler; public SecurityConfiguration(UserService userService, BCryptPasswordEncoder bCryptPasswordEncoder, AuthenticationSuccessHandler authenticationSuccessHandler, LogoutSuccessHandler logoutSuccessHandler, - ApplicationProperties applicationProperties) { + ApplicationProperties applicationProperties, + AuthFailureHandler authenticationFailureHandler) { this.userService = userService; this.bCryptPasswordEncoder = bCryptPasswordEncoder; this.authenticationSuccessHandler = authenticationSuccessHandler; this.logoutSuccessHandler = logoutSuccessHandler; this.applicationProperties = applicationProperties; + this.authenticationFailureHandler = authenticationFailureHandler; } @Override @@ -66,6 +71,7 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter { .antMatchers(UserController.ACTIVATE_URL).permitAll() .antMatchers(Constants.PASSWORD_RESET_REQUEST_PAGE).permitAll() .antMatchers(Constants.PASSWORD_RESET_PAGE).permitAll() + .antMatchers("/users/block").permitAll() .antMatchers(UserController.URL + UserController.REGISTER_URL).permitAll() .antMatchers(UserController.URL + UserController.ACTIVATE_URL).permitAll() .antMatchers(UserController.URL + UserController.PASSWORD_RESET_REQUEST_URL).permitAll() @@ -76,6 +82,7 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter { .formLogin() .loginPage("/login") .successHandler(authenticationSuccessHandler) + .failureHandler(authenticationFailureHandler) .permitAll() .and() .logout() @@ -104,7 +111,8 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter { .antMatchers("/css/**") .antMatchers("/js/**") .antMatchers("/templates/**") - .antMatchers("/webjars/**"); + .antMatchers("/webjars/**") + .antMatchers("/img/**"); } @Autowired diff --git a/src/main/java/ru/ulstu/core/controller/AdviceController.java b/src/main/java/ru/ulstu/core/controller/AdviceController.java index 8238797..f89001a 100644 --- a/src/main/java/ru/ulstu/core/controller/AdviceController.java +++ b/src/main/java/ru/ulstu/core/controller/AdviceController.java @@ -20,6 +20,7 @@ import ru.ulstu.user.error.UserNotActivatedException; import ru.ulstu.user.error.UserNotFoundException; import ru.ulstu.user.error.UserPasswordsNotValidOrNotMatchException; import ru.ulstu.user.error.UserResetKeyError; +import ru.ulstu.user.error.UserSendingMailException; import ru.ulstu.user.service.UserService; import java.util.Set; @@ -34,9 +35,9 @@ public class AdviceController { this.userService = userService; } - @ModelAttribute("currentUser") - public String getCurrentUser() { - return userService.getCurrentUser().getUserAbbreviate(); + @ModelAttribute("flashMessage") + public String getFlashMessage() { + return null; } private Response handleException(ErrorConstants error) { @@ -107,4 +108,9 @@ public class AdviceController { public ResponseExtended handleUserIsUndeadException(Throwable e) { return handleException(ErrorConstants.USER_UNDEAD_ERROR, e.getMessage()); } + + @ExceptionHandler(UserSendingMailException.class) + public ResponseExtended handleUserSendingMailException(Throwable e) { + return handleException(ErrorConstants.USER_SENDING_MAIL_EXCEPTION, e.getMessage()); + } } diff --git a/src/main/java/ru/ulstu/core/model/AuthFailureHandler.java b/src/main/java/ru/ulstu/core/model/AuthFailureHandler.java new file mode 100644 index 0000000..8b6bd9d --- /dev/null +++ b/src/main/java/ru/ulstu/core/model/AuthFailureHandler.java @@ -0,0 +1,21 @@ +package ru.ulstu.core.model; + +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.authentication.AuthenticationFailureHandler; +import org.springframework.stereotype.Component; +import ru.ulstu.user.error.UserBlockedException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +@Component +public class AuthFailureHandler implements AuthenticationFailureHandler { + @Override + public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, + AuthenticationException ex) throws IOException { + if (ex.getClass() == UserBlockedException.class) { + response.sendRedirect("/users/block"); + } + } +} \ No newline at end of file diff --git a/src/main/java/ru/ulstu/core/model/ErrorConstants.java b/src/main/java/ru/ulstu/core/model/ErrorConstants.java index ad69b86..017725a 100644 --- a/src/main/java/ru/ulstu/core/model/ErrorConstants.java +++ b/src/main/java/ru/ulstu/core/model/ErrorConstants.java @@ -6,14 +6,15 @@ public enum ErrorConstants { VALIDATION_ERROR(2, "Validation error"), USER_ID_EXISTS(100, "New user can't have id"), USER_ACTIVATION_ERROR(101, "Invalid activation key"), - USER_EMAIL_EXISTS(102, "User with same email already exists"), - USER_LOGIN_EXISTS(103, "User with same login already exists"), - USER_PASSWORDS_NOT_VALID_OR_NOT_MATCH(104, "User passwords is not valid or not match"), - USER_NOT_FOUND(105, "User is not found"), + USER_EMAIL_EXISTS(102, "Пользователь с таким почтовым ящиком уже существует"), + USER_LOGIN_EXISTS(103, "Пользователь с таким логином уже существует"), + USER_PASSWORDS_NOT_VALID_OR_NOT_MATCH(104, "Пароли введены неверно"), + USER_NOT_FOUND(105, "Аккаунт не найден"), USER_NOT_ACTIVATED(106, "User is not activated"), - USER_RESET_ERROR(107, "Invalid reset key"), + USER_RESET_ERROR(107, "Некорректный ключ подтверждения"), USER_UNDEAD_ERROR(108, "Can't edit/delete that user"), - FILE_UPLOAD_ERROR(110, "File upload error"); + FILE_UPLOAD_ERROR(110, "File upload error"), + USER_SENDING_MAIL_EXCEPTION(111, "Во время отправки приглашения пользователю произошла ошибка"); private int code; private String message; diff --git a/src/main/java/ru/ulstu/core/model/EventSource.java b/src/main/java/ru/ulstu/core/model/EventSource.java new file mode 100644 index 0000000..32ffcf2 --- /dev/null +++ b/src/main/java/ru/ulstu/core/model/EventSource.java @@ -0,0 +1,17 @@ +package ru.ulstu.core.model; + +import ru.ulstu.deadline.model.Deadline; +import ru.ulstu.timeline.model.Event; +import ru.ulstu.user.model.User; + +import java.util.List; + +public interface EventSource { + List getDeadlines(); + + String getTitle(); + + List getRecipients(); + + void addObjectToEvent(Event event); +} diff --git a/src/main/java/ru/ulstu/core/model/UserActivity.java b/src/main/java/ru/ulstu/core/model/UserActivity.java new file mode 100644 index 0000000..f45819d --- /dev/null +++ b/src/main/java/ru/ulstu/core/model/UserActivity.java @@ -0,0 +1,11 @@ +package ru.ulstu.core.model; + +import ru.ulstu.user.model.User; + +import java.util.Set; + +public interface UserActivity { + String getTitle(); + + Set getActivityUsers(); +} diff --git a/src/main/java/ru/ulstu/core/model/UserContainer.java b/src/main/java/ru/ulstu/core/model/UserContainer.java deleted file mode 100644 index 7f83cd3..0000000 --- a/src/main/java/ru/ulstu/core/model/UserContainer.java +++ /dev/null @@ -1,9 +0,0 @@ -package ru.ulstu.core.model; - -import ru.ulstu.user.model.User; - -import java.util.Set; - -public interface UserContainer { - Set getUsers(); -} diff --git a/src/main/java/ru/ulstu/core/model/response/Response.java b/src/main/java/ru/ulstu/core/model/response/Response.java index 4722010..7c57168 100644 --- a/src/main/java/ru/ulstu/core/model/response/Response.java +++ b/src/main/java/ru/ulstu/core/model/response/Response.java @@ -11,6 +11,6 @@ public class Response extends ResponseEntity { } public Response(ErrorConstants error) { - super(new ControllerResponse(new ControllerResponseError<>(error, null)), HttpStatus.OK); + super(new ControllerResponse(new ControllerResponseError<>(error, null)), HttpStatus.BAD_REQUEST); } } diff --git a/src/main/java/ru/ulstu/core/model/response/ResponseExtended.java b/src/main/java/ru/ulstu/core/model/response/ResponseExtended.java index 1829622..568e9b5 100644 --- a/src/main/java/ru/ulstu/core/model/response/ResponseExtended.java +++ b/src/main/java/ru/ulstu/core/model/response/ResponseExtended.java @@ -7,6 +7,6 @@ import ru.ulstu.core.model.ErrorConstants; public class ResponseExtended extends ResponseEntity { public ResponseExtended(ErrorConstants error, E errorData) { - super(new ControllerResponse(new ControllerResponseError(error, errorData)), HttpStatus.OK); + super(new ControllerResponse(new ControllerResponseError(error, errorData)), HttpStatus.BAD_REQUEST); } } diff --git a/src/main/java/ru/ulstu/core/util/DateUtils.java b/src/main/java/ru/ulstu/core/util/DateUtils.java index 6122583..bbcc86b 100644 --- a/src/main/java/ru/ulstu/core/util/DateUtils.java +++ b/src/main/java/ru/ulstu/core/util/DateUtils.java @@ -16,7 +16,7 @@ public class DateUtils { public static Date clearTime(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); - calendar.set(Calendar.HOUR, 0); + calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); @@ -54,4 +54,10 @@ public class DateUtils { cal.add(Calendar.DAY_OF_MONTH, count); return cal.getTime(); } + + public static Date addYears(Date date, int count) { + Calendar cal = getCalendar(date); + cal.add(Calendar.YEAR, count); + return cal.getTime(); + } } diff --git a/src/main/java/ru/ulstu/deadline/model/Deadline.java b/src/main/java/ru/ulstu/deadline/model/Deadline.java index 404e5c8..d0564a0 100644 --- a/src/main/java/ru/ulstu/deadline/model/Deadline.java +++ b/src/main/java/ru/ulstu/deadline/model/Deadline.java @@ -4,21 +4,31 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import org.springframework.format.annotation.DateTimeFormat; import ru.ulstu.core.model.BaseEntity; +import ru.ulstu.user.model.User; import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.OneToMany; import javax.persistence.Temporal; import javax.persistence.TemporalType; import java.util.Date; +import java.util.List; +import java.util.Objects; @Entity public class Deadline extends BaseEntity { private String description; - @Temporal(value = TemporalType.TIMESTAMP) + @Temporal(value = TemporalType.DATE) @DateTimeFormat(pattern = "yyyy-MM-dd") private Date date; + @OneToMany(targetEntity = User.class, fetch = FetchType.EAGER) + private List executors; + + private Boolean done; + public Deadline() { } @@ -27,13 +37,24 @@ public class Deadline extends BaseEntity { this.description = description; } + public Deadline(Date deadlineDate, String description, List executors, Boolean done) { + this.date = deadlineDate; + this.description = description; + this.executors = executors; + this.done = done; + } + @JsonCreator public Deadline(@JsonProperty("id") Integer id, @JsonProperty("description") String description, - @JsonProperty("date") Date date) { + @JsonProperty("date") Date date, + @JsonProperty("executors") List executors, + @JsonProperty("done") Boolean done) { this.setId(id); this.description = description; this.date = date; + this.executors = executors; + this.done = done; } public String getDescription() { @@ -51,4 +72,49 @@ public class Deadline extends BaseEntity { public void setDate(Date date) { this.date = date; } + + public List getExecutors() { + return executors; + } + + public void setExecutors(List executors) { + this.executors = executors; + } + + public Boolean getDone() { + return done; + } + + public void setDone(Boolean done) { + this.done = done; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + if (!super.equals(o)) { + return false; + } + Deadline deadline = (Deadline) o; + if (getId() == null && deadline.getId() == null && + description == null && deadline.description == null && + date == null && deadline.date == null) { + return true; + } + return getId().equals(deadline.getId()) && + description.equals(deadline.description) && + date.equals(deadline.date) && + executors.equals(deadline.executors) && + done.equals(deadline.done); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), description, date, executors, done); + } } diff --git a/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java b/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java index f26c572..652f01d 100644 --- a/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java +++ b/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java @@ -2,8 +2,14 @@ package ru.ulstu.deadline.repository; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import ru.ulstu.deadline.model.Deadline; +import java.util.Date; + public interface DeadlineRepository extends JpaRepository { + @Query("SELECT d.date FROM Grant g JOIN g.deadlines d WHERE (g.id = :id) AND (d.date = :date)") + Date findByGrantIdAndDate(@Param("id") Integer grantId, @Param("date") Date date); } diff --git a/src/main/java/ru/ulstu/deadline/service/DeadlineService.java b/src/main/java/ru/ulstu/deadline/service/DeadlineService.java index cb80bfe..4bd3b0c 100644 --- a/src/main/java/ru/ulstu/deadline/service/DeadlineService.java +++ b/src/main/java/ru/ulstu/deadline/service/DeadlineService.java @@ -5,6 +5,7 @@ import org.springframework.transaction.annotation.Transactional; import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.repository.DeadlineRepository; +import java.util.Date; import java.util.List; import java.util.stream.Collectors; @@ -29,6 +30,8 @@ public class DeadlineService { Deadline updateDeadline = deadlineRepository.getOne(deadline.getId()); updateDeadline.setDate(deadline.getDate()); updateDeadline.setDescription(deadline.getDescription()); + updateDeadline.setExecutors(deadline.getExecutors()); + updateDeadline.setDone(deadline.getDone()); deadlineRepository.save(updateDeadline); return updateDeadline; } @@ -38,6 +41,8 @@ public class DeadlineService { Deadline newDeadline = new Deadline(); newDeadline.setDate(deadline.getDate()); newDeadline.setDescription(deadline.getDescription()); + newDeadline.setExecutors(deadline.getExecutors()); + newDeadline.setDone(deadline.getDone()); newDeadline = deadlineRepository.save(newDeadline); return newDeadline; } @@ -46,4 +51,8 @@ public class DeadlineService { public void remove(Integer deadlineId) { deadlineRepository.deleteById(deadlineId); } + + public Date findByGrantIdAndDate(Integer id, Date date) { + return deadlineRepository.findByGrantIdAndDate(id, date); + } } diff --git a/src/main/java/ru/ulstu/grant/controller/GrantController.java b/src/main/java/ru/ulstu/grant/controller/GrantController.java index a0bb916..48dee8e 100644 --- a/src/main/java/ru/ulstu/grant/controller/GrantController.java +++ b/src/main/java/ru/ulstu/grant/controller/GrantController.java @@ -9,19 +9,19 @@ import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; import ru.ulstu.deadline.model.Deadline; import ru.ulstu.grant.model.Grant; import ru.ulstu.grant.model.GrantDto; import ru.ulstu.grant.service.GrantService; +import ru.ulstu.paper.model.PaperDto; import ru.ulstu.user.model.User; import springfox.documentation.annotations.ApiIgnore; import javax.validation.Valid; import java.io.IOException; import java.util.List; -import java.util.stream.Collectors; -import static org.springframework.util.StringUtils.isEmpty; import static ru.ulstu.core.controller.Navigation.GRANTS_PAGE; import static ru.ulstu.core.controller.Navigation.GRANT_PAGE; import static ru.ulstu.core.controller.Navigation.REDIRECT_TO; @@ -44,13 +44,15 @@ public class GrantController { @GetMapping("/dashboard") public void getDashboard(ModelMap modelMap) { - modelMap.put("grants", grantService.findAllDto()); + modelMap.put("grants", grantService.findAllActiveDto()); } @GetMapping("/grant") public void getGrant(ModelMap modelMap, @RequestParam(value = "id") Integer id) { if (id != null && id > 0) { - modelMap.put("grantDto", grantService.findOneDto(id)); + GrantDto grantDto = grantService.getExistGrantById(id); + attachPaper(grantDto); + modelMap.put("grantDto", grantDto); } else { modelMap.put("grantDto", new GrantDto()); } @@ -59,17 +61,9 @@ public class GrantController { @PostMapping(value = "/grant", params = "save") public String save(@Valid GrantDto grantDto, Errors errors) throws IOException { - filterEmptyDeadlines(grantDto); - if (grantDto.getDeadlines().isEmpty()) { - errors.rejectValue("deadlines", "errorCode", "Не может быть пусто"); - } - if (grantDto.getLeaderId().equals(-1)) { - errors.rejectValue("leaderId", "errorCode", "Укажите руководителя"); - } - if (errors.hasErrors()) { + if (!grantService.save(grantDto, errors)) { return GRANT_PAGE; } - grantService.save(grantDto); return String.format(REDIRECT_TO, GRANTS_PAGE); } @@ -78,9 +72,15 @@ public class GrantController { return GRANT_PAGE; } + @PostMapping(value = "/grant", params = "attachPaper") + public String attachPaper(GrantDto grantDto) { + grantService.attachPaper(grantDto); + return GRANT_PAGE; + } + @PostMapping(value = "/grant", params = "addDeadline") public String addDeadline(@Valid GrantDto grantDto, Errors errors) { - filterEmptyDeadlines(grantDto); + grantService.filterEmptyDeadlines(grantDto); if (errors.hasErrors()) { return GRANT_PAGE; } @@ -88,6 +88,13 @@ public class GrantController { return GRANT_PAGE; } + @PostMapping(value = "/grant", params = "removeDeadline") + public String removeDeadline(GrantDto grantDto, + @RequestParam(value = "removeDeadline") Integer deadlineId) { + grantService.removeDeadline(grantDto, deadlineId); + return GRANT_PAGE; + } + @PostMapping(value = "/grant", params = "createProject") public String createProject(@Valid GrantDto grantDto, Errors errors) throws IOException { if (errors.hasErrors()) { @@ -113,9 +120,14 @@ public class GrantController { return grantService.getGrantAuthors(grantDto); } - private void filterEmptyDeadlines(GrantDto grantDto) { - grantDto.setDeadlines(grantDto.getDeadlines().stream() - .filter(dto -> dto.getDate() != null || !isEmpty(dto.getDescription())) - .collect(Collectors.toList())); + @ModelAttribute("allPapers") + public List getAllPapers() { + return grantService.getAllUncompletedPapers(); + } + + @ResponseBody + @PostMapping(value = "/ping") + public void ping(@RequestParam("grantId") int grantId) throws IOException { + grantService.ping(grantId); } } diff --git a/src/main/java/ru/ulstu/grant/controller/GrantRestController.java b/src/main/java/ru/ulstu/grant/controller/GrantRestController.java new file mode 100644 index 0000000..9b90a4d --- /dev/null +++ b/src/main/java/ru/ulstu/grant/controller/GrantRestController.java @@ -0,0 +1,29 @@ +package ru.ulstu.grant.controller; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import ru.ulstu.configuration.Constants; +import ru.ulstu.grant.service.GrantService; + +import java.io.IOException; +import java.text.ParseException; + +import static ru.ulstu.paper.controller.PaperRestController.URL; + +@RestController +@RequestMapping(URL) +public class GrantRestController { + public static final String URL = Constants.API_1_0 + "grants"; + + private final GrantService grantService; + + public GrantRestController(GrantService grantService) { + this.grantService = grantService; + } + + @GetMapping("/grab") + public void grab() throws IOException, ParseException { + grantService.createFromKias(); + } +} diff --git a/src/main/java/ru/ulstu/grant/model/Grant.java b/src/main/java/ru/ulstu/grant/model/Grant.java index 30d9fb3..becee63 100644 --- a/src/main/java/ru/ulstu/grant/model/Grant.java +++ b/src/main/java/ru/ulstu/grant/model/Grant.java @@ -1,18 +1,25 @@ package ru.ulstu.grant.model; +import org.hibernate.annotations.Fetch; +import org.hibernate.annotations.FetchMode; import ru.ulstu.core.model.BaseEntity; -import ru.ulstu.core.model.UserContainer; +import ru.ulstu.core.model.EventSource; +import ru.ulstu.core.model.UserActivity; import ru.ulstu.deadline.model.Deadline; import ru.ulstu.file.model.FileData; +import ru.ulstu.paper.model.Paper; import ru.ulstu.project.model.Project; +import ru.ulstu.timeline.model.Event; import ru.ulstu.user.model.User; import javax.persistence.CascadeType; +import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; @@ -21,6 +28,7 @@ import javax.persistence.Table; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.util.ArrayList; +import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashSet; @@ -30,7 +38,8 @@ import java.util.Set; @Entity @Table(name = "grants") -public class Grant extends BaseEntity implements UserContainer { +@DiscriminatorValue("GRANT") +public class Grant extends BaseEntity implements UserActivity, EventSource { public enum GrantStatus { APPLICATION("Заявка"), ON_COMPETITION("Отправлен на конкурс"), @@ -38,7 +47,8 @@ public class Grant extends BaseEntity implements UserContainer { IN_WORK("В работе"), COMPLETED("Завершен"), FAILED("Провалены сроки"), - LOADED_FROM_KIAS("Загружен автоматически"); + LOADED_FROM_KIAS("Загружен автоматически"), + SKIPPED("Не интересует"); private String statusName; @@ -57,19 +67,17 @@ public class Grant extends BaseEntity implements UserContainer { @Enumerated(value = EnumType.STRING) private GrantStatus status = GrantStatus.APPLICATION; - @OneToMany(cascade = CascadeType.ALL) + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinColumn(name = "grant_id") @OrderBy("date") private List deadlines = new ArrayList<>(); - //Описание гранта - @NotNull private String comment; - //Заявка на грант - @ManyToOne - @JoinColumn(name = "file_id") - private FileData application; + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) + @JoinColumn(name = "grant_id", unique = true) + @Fetch(FetchMode.SUBSELECT) + private List files = new ArrayList<>(); @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "project_id") @@ -83,6 +91,17 @@ public class Grant extends BaseEntity implements UserContainer { @JoinColumn(name = "leader_id") private User leader; + @ManyToMany(fetch = FetchType.EAGER) + @JoinTable(name = "grants_papers", + joinColumns = {@JoinColumn(name = "grant_id")}, + inverseJoinColumns = {@JoinColumn(name = "paper_id")}) + @Fetch(FetchMode.SUBSELECT) + private List papers = new ArrayList<>(); + + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) + @JoinColumn(name = "grant_id") + private List events = new ArrayList<>(); + public GrantStatus getStatus() { return status; } @@ -107,18 +126,28 @@ public class Grant extends BaseEntity implements UserContainer { this.comment = comment; } - public FileData getApplication() { - return application; + public List getFiles() { + return files; } - public void setApplication(FileData application) { - this.application = application; + public void setFiles(List files) { + this.files = files; } public String getTitle() { return title; } + @Override + public List getRecipients() { + return authors != null ? new ArrayList<>(authors) : Collections.emptyList(); + } + + @Override + public void addObjectToEvent(Event event) { + event.setGrant(this); + } + public void setTitle(String title) { this.title = title; } @@ -140,7 +169,7 @@ public class Grant extends BaseEntity implements UserContainer { } @Override - public Set getUsers() { + public Set getActivityUsers() { return getAuthors(); } @@ -152,6 +181,22 @@ public class Grant extends BaseEntity implements UserContainer { this.leader = leader; } + public List getPapers() { + return papers; + } + + public void setPapers(List papers) { + this.papers = papers; + } + + public List getEvents() { + return events; + } + + public void setEvents(List events) { + this.events = events; + } + public Optional getNextDeadline() { return deadlines .stream() diff --git a/src/main/java/ru/ulstu/grant/model/GrantDto.java b/src/main/java/ru/ulstu/grant/model/GrantDto.java index d836dfb..541dae8 100644 --- a/src/main/java/ru/ulstu/grant/model/GrantDto.java +++ b/src/main/java/ru/ulstu/grant/model/GrantDto.java @@ -4,18 +4,22 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import org.apache.commons.lang3.StringUtils; import ru.ulstu.deadline.model.Deadline; +import ru.ulstu.file.model.FileDataDto; +import ru.ulstu.name.NameContainer; +import ru.ulstu.paper.model.PaperDto; import ru.ulstu.project.model.ProjectDto; import ru.ulstu.user.model.UserDto; import javax.validation.constraints.NotEmpty; import java.util.ArrayList; +import java.util.Date; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import static ru.ulstu.core.util.StreamApiUtils.convert; -public class GrantDto { +public class GrantDto extends NameContainer { private final static int MAX_AUTHORS_LENGTH = 60; private Integer id; @@ -24,7 +28,7 @@ public class GrantDto { private Grant.GrantStatus status; private List deadlines = new ArrayList<>(); private String comment; - private String applicationFileName; + private List files = new ArrayList<>(); private ProjectDto project; private Set authorIds; private Set authors; @@ -32,6 +36,11 @@ public class GrantDto { private boolean wasLeader; private boolean hasAge; private boolean hasDegree; + private boolean hasBAKPapers; + private boolean hasScopusPapers; + private List paperIds = new ArrayList<>(); + private List papers = new ArrayList<>(); + private List removedDeadlineIds = new ArrayList<>(); public GrantDto() { deadlines.add(new Deadline()); @@ -43,25 +52,31 @@ public class GrantDto { @JsonProperty("status") Grant.GrantStatus status, @JsonProperty("deadlines") List deadlines, @JsonProperty("comment") String comment, + @JsonProperty("files") List files, @JsonProperty("project") ProjectDto project, @JsonProperty("authorIds") Set authorIds, @JsonProperty("authors") Set authors, - @JsonProperty("leader") Integer leaderId, + @JsonProperty("leaderId") Integer leaderId, @JsonProperty("wasLeader") boolean wasLeader, @JsonProperty("hasAge") boolean hasAge, - @JsonProperty("hasDegree") boolean hasDegree) { + @JsonProperty("hasDegree") boolean hasDegree, + @JsonProperty("paperIds") List paperIds, + @JsonProperty("papers") List papers) { this.id = id; this.title = title; this.status = status; this.deadlines = deadlines; this.comment = comment; - this.applicationFileName = null; + this.files = files; this.project = project; + this.authorIds = authorIds; this.authors = authors; this.leaderId = leaderId; this.wasLeader = wasLeader; this.hasAge = hasAge; this.hasDegree = hasDegree; + this.paperIds = paperIds; + this.papers = papers; } public GrantDto(Grant grant) { @@ -70,14 +85,22 @@ public class GrantDto { this.status = grant.getStatus(); this.deadlines = grant.getDeadlines(); this.comment = grant.getComment(); + this.files = convert(grant.getFiles(), FileDataDto::new); this.project = grant.getProject() == null ? null : new ProjectDto(grant.getProject()); - this.applicationFileName = grant.getApplication() == null ? null : grant.getApplication().getName(); this.authorIds = convert(grant.getAuthors(), user -> user.getId()); this.authors = convert(grant.getAuthors(), UserDto::new); this.leaderId = grant.getLeader().getId(); this.wasLeader = false; this.hasAge = false; this.hasDegree = false; + this.paperIds = convert(grant.getPapers(), paper -> paper.getId()); + this.papers = convert(grant.getPapers(), PaperDto::new); + } + + public GrantDto(String grantTitle, Date deadLineDate) { + this.title = grantTitle; + deadlines.add(new Deadline(deadLineDate, "Окончание приёма заявок")); + status = Grant.GrantStatus.LOADED_FROM_KIAS; } public Integer getId() { @@ -120,20 +143,20 @@ public class GrantDto { this.comment = comment; } - public ProjectDto getProject() { - return project; + public List getFiles() { + return files; } - public void setProject(ProjectDto project) { - this.project = project; + public void setFiles(List files) { + this.files = files; } - public String getApplicationFileName() { - return applicationFileName; + public ProjectDto getProject() { + return project; } - public void setApplicationFileName(String applicationFileName) { - this.applicationFileName = applicationFileName; + public void setProject(ProjectDto project) { + this.project = project; } public Set getAuthorIds() { @@ -190,4 +213,44 @@ public class GrantDto { public void setHasDegree(boolean hasDegree) { this.hasDegree = hasDegree; } + + public List getPaperIds() { + return paperIds; + } + + public void setPaperIds(List paperIds) { + this.paperIds = paperIds; + } + + public List getPapers() { + return papers; + } + + public void setPapers(List papers) { + this.papers = papers; + } + + public List getRemovedDeadlineIds() { + return removedDeadlineIds; + } + + public void setRemovedDeadlineIds(List removedDeadlineIds) { + this.removedDeadlineIds = removedDeadlineIds; + } + + public boolean isHasBAKPapers() { + return hasBAKPapers; + } + + public void setHasBAKPapers(boolean hasBAKPapers) { + this.hasBAKPapers = hasBAKPapers; + } + + public boolean isHasScopusPapers() { + return hasScopusPapers; + } + + public void setHasScopusPapers(boolean hasScopusPapers) { + this.hasScopusPapers = hasScopusPapers; + } } diff --git a/src/main/java/ru/ulstu/grant/page/KiasPage.java b/src/main/java/ru/ulstu/grant/page/KiasPage.java new file mode 100644 index 0000000..49d54a0 --- /dev/null +++ b/src/main/java/ru/ulstu/grant/page/KiasPage.java @@ -0,0 +1,55 @@ +package ru.ulstu.grant.page; + +import com.gargoylesoftware.htmlunit.html.DomNode; +import com.gargoylesoftware.htmlunit.html.HtmlElement; +import com.gargoylesoftware.htmlunit.html.HtmlPage; +import com.gargoylesoftware.htmlunit.html.HtmlTableRow; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + +public class KiasPage { + private final static String KIAS_GRANT_DATE_FORMAT = "dd.MM.yyyy HH:mm"; + private final HtmlPage page; + + public KiasPage(HtmlPage page) { + this.page = page; + } + + public boolean goToNextPage() { + try { + HtmlElement nextPageLink = page.getHtmlElementById("js-ctrlNext"); + if (nextPageLink.isDisplayed()) { + nextPageLink.click(); + return true; + } + } finally { + return false; + } + } + + public List getPageOfGrants() { + return page.getByXPath("/html/body/div[2]/div/div[2]/main/div[1]/table/tbody/tr"); + } + + public String getGrantTitle(DomNode grant) { + return ((DomNode) grant.getFirstByXPath("td[2]")).getTextContent() + " " + + ((DomNode) grant.getFirstByXPath("td[@class='tertiary']/a")).getTextContent(); + } + + public Date parseDeadLineDate(DomNode grantElement) throws ParseException { + String deadlineDate = getFirstDeadline(grantElement); //10.06.2019 23:59 + SimpleDateFormat formatter = new SimpleDateFormat(KIAS_GRANT_DATE_FORMAT); + return formatter.parse(deadlineDate); + } + + private String getFirstDeadline(DomNode grantElement) { + return ((DomNode) grantElement.getFirstByXPath("td[5]")).getTextContent(); + } + + public boolean isTableRowGrantLine(DomNode grantElement) { + return !((HtmlTableRow) grantElement).getAttribute("class").contains("pagerSavedHeightSpacer"); + } +} diff --git a/src/main/java/ru/ulstu/grant/repository/GrantRepository.java b/src/main/java/ru/ulstu/grant/repository/GrantRepository.java index 44c2cc0..50fad13 100644 --- a/src/main/java/ru/ulstu/grant/repository/GrantRepository.java +++ b/src/main/java/ru/ulstu/grant/repository/GrantRepository.java @@ -1,11 +1,25 @@ package ru.ulstu.grant.repository; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import ru.ulstu.grant.model.Grant; +import ru.ulstu.name.BaseRepository; import java.util.List; -public interface GrantRepository extends JpaRepository { +public interface GrantRepository extends JpaRepository, BaseRepository { List findByStatus(Grant.GrantStatus status); + + Grant findByTitle(String title); + + Grant findGrantById(Integer grantId); + + @Override + @Query("SELECT title FROM Grant g WHERE (g.title = :name) AND (:id IS NULL OR g.id != :id) ") + String findByNameAndNotId(@Param("name") String name, @Param("id") Integer id); + + @Query("SELECT g FROM Grant g WHERE (g.status <> 'SKIPPED') AND (g.status <> 'COMPLETED')") + List findAllActive(); } diff --git a/src/main/java/ru/ulstu/grant/service/GrantNotificationService.java b/src/main/java/ru/ulstu/grant/service/GrantNotificationService.java new file mode 100644 index 0000000..677b38f --- /dev/null +++ b/src/main/java/ru/ulstu/grant/service/GrantNotificationService.java @@ -0,0 +1,73 @@ +package ru.ulstu.grant.service; + +import com.google.common.collect.ImmutableMap; +import org.springframework.stereotype.Service; +import ru.ulstu.core.util.DateUtils; +import ru.ulstu.grant.model.Grant; +import ru.ulstu.user.model.User; +import ru.ulstu.user.service.MailService; + +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Set; + +@Service +public class GrantNotificationService { + private final static int DAYS_TO_DEADLINE_NOTIFICATION = 7; + private final static String TEMPLATE_DEADLINE = "grantDeadlineNotification"; + private final static String TEMPLATE_CREATE = "grantCreateNotification"; + private final static String TEMPLATE_AUTHORS_CHANGED = "grantAuthorsChangeNotification"; + private final static String TEMPLATE_LEADER_CHANGED = "grantLeaderChangeNotification"; + + private final static String TITLE_DEADLINE = "Приближается дедлайн гранта: %s"; + private final static String TITLE_CREATE = "Создан грант: %s"; + private final static String TITLE_AUTHORS_CHANGED = "Изменился состав рабочей группы гранта: %s"; + private final static String TITLE_LEADER_CHANGED = "Изменился руководитель гранта: %s"; + + private final MailService mailService; + + public GrantNotificationService(MailService mailService) { + this.mailService = mailService; + } + + public void sendDeadlineNotifications(List grants, boolean isDeadlineBeforeWeek) { + Date now = DateUtils.addDays(new Date(), DAYS_TO_DEADLINE_NOTIFICATION); + grants.stream() + .filter(grant -> needToSendDeadlineNotification(grant, now, isDeadlineBeforeWeek)) + .forEach(grant -> sendMessageDeadline(grant)); + } + + private boolean needToSendDeadlineNotification(Grant grant, Date compareDate, boolean isDeadlineBeforeWeek) { + return (grant.getNextDeadline().isPresent()) + && (compareDate.before(grant.getNextDeadline().get().getDate()) && isDeadlineBeforeWeek + || compareDate.after(grant.getNextDeadline().get().getDate()) && !isDeadlineBeforeWeek) + && grant.getNextDeadline().get().getDate().after(new Date()); + } + + private void sendMessageDeadline(Grant grant) { + Map variables = ImmutableMap.of("grant", grant); + sendForAllAuthors(variables, grant, TEMPLATE_DEADLINE, String.format(TITLE_DEADLINE, grant.getTitle())); + } + + public void sendCreateNotification(Grant grant) { + Map variables = ImmutableMap.of("grant", grant); + sendForAllAuthors(variables, grant, TEMPLATE_CREATE, String.format(TITLE_CREATE, grant.getTitle())); + } + + public void sendAuthorsChangeNotification(Grant grant, Set oldAuthors) { + Map variables = ImmutableMap.of("grant", grant, "oldAuthors", oldAuthors); + sendForAllAuthors(variables, grant, TEMPLATE_AUTHORS_CHANGED, String.format(TITLE_AUTHORS_CHANGED, grant.getTitle())); + } + + public void sendLeaderChangeNotification(Grant grant, User oldLeader) { + Map variables = ImmutableMap.of("grant", grant, "oldLeader", oldLeader); + sendForAllAuthors(variables, grant, TEMPLATE_LEADER_CHANGED, String.format(TITLE_LEADER_CHANGED, grant.getTitle())); + } + + private void sendForAllAuthors(Map variables, Grant grant, String template, String title) { + Set allAuthors = grant.getAuthors(); + allAuthors.forEach(author -> mailService.sendEmailFromTemplate(variables, author, template, title)); + mailService.sendEmailFromTemplate(variables, grant.getLeader(), template, title); + } +} diff --git a/src/main/java/ru/ulstu/grant/service/GrantScheduler.java b/src/main/java/ru/ulstu/grant/service/GrantScheduler.java new file mode 100644 index 0000000..d026911 --- /dev/null +++ b/src/main/java/ru/ulstu/grant/service/GrantScheduler.java @@ -0,0 +1,44 @@ +package ru.ulstu.grant.service; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.text.ParseException; + +@Service +public class GrantScheduler { + private final static boolean IS_DEADLINE_NOTIFICATION_BEFORE_WEEK = true; + + private final Logger log = LoggerFactory.getLogger(GrantScheduler.class); + + private final GrantNotificationService grantNotificationService; + private final GrantService grantService; + + public GrantScheduler(GrantNotificationService grantNotificationService, + GrantService grantService) { + this.grantNotificationService = grantNotificationService; + this.grantService = grantService; + } + + + @Scheduled(cron = "0 0 8 * * MON", zone = "Europe/Samara") + public void checkDeadlineBeforeWeek() { + log.debug("GrantScheduler.checkDeadlineBeforeWeek started"); + grantNotificationService.sendDeadlineNotifications(grantService.findAllActive(), IS_DEADLINE_NOTIFICATION_BEFORE_WEEK); + log.debug("GrantScheduler.checkDeadlineBeforeWeek finished"); + } + + @Scheduled(cron = "0 0 8 * * ?", zone = "Europe/Samara") + public void loadGrantsFromKias() { + log.debug("GrantScheduler.loadGrantsFromKias started"); + try { + grantService.createFromKias(); + } catch (ParseException | IOException e) { + e.printStackTrace(); + } + log.debug("GrantScheduler.loadGrantsFromKias finished"); + } +} diff --git a/src/main/java/ru/ulstu/grant/service/GrantService.java b/src/main/java/ru/ulstu/grant/service/GrantService.java index a6e255f..6a81aa4 100644 --- a/src/main/java/ru/ulstu/grant/service/GrantService.java +++ b/src/main/java/ru/ulstu/grant/service/GrantService.java @@ -1,50 +1,86 @@ package ru.ulstu.grant.service; import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.Errors; +import ru.ulstu.core.util.DateUtils; import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.service.DeadlineService; +import ru.ulstu.file.model.FileDataDto; import ru.ulstu.file.service.FileService; import ru.ulstu.grant.model.Grant; import ru.ulstu.grant.model.GrantDto; import ru.ulstu.grant.repository.GrantRepository; -import ru.ulstu.project.model.Project; +import ru.ulstu.name.BaseService; +import ru.ulstu.paper.model.Paper; +import ru.ulstu.paper.model.PaperDto; +import ru.ulstu.paper.service.PaperService; +import ru.ulstu.ping.service.PingService; import ru.ulstu.project.model.ProjectDto; import ru.ulstu.project.service.ProjectService; +import ru.ulstu.timeline.service.EventService; import ru.ulstu.user.model.User; import ru.ulstu.user.service.UserService; import java.io.IOException; +import java.text.ParseException; import java.util.Arrays; +import java.util.Collections; import java.util.Date; +import java.util.HashSet; import java.util.List; +import java.util.Set; import java.util.stream.Collectors; +import static java.util.stream.Collectors.toList; import static org.springframework.util.ObjectUtils.isEmpty; import static ru.ulstu.core.util.StreamApiUtils.convert; import static ru.ulstu.grant.model.Grant.GrantStatus.APPLICATION; @Service -public class GrantService { - private final static int MAX_DISPLAY_SIZE = 40; +public class GrantService extends BaseService { + private final Logger log = LoggerFactory.getLogger(GrantService.class); private final GrantRepository grantRepository; private final ProjectService projectService; private final DeadlineService deadlineService; private final FileService fileService; private final UserService userService; + private final PaperService paperService; + private final EventService eventService; + private final GrantNotificationService grantNotificationService; + private final KiasService kiasService; + private final PingService pingService; public GrantService(GrantRepository grantRepository, FileService fileService, DeadlineService deadlineService, ProjectService projectService, - UserService userService) { + UserService userService, + PaperService paperService, + EventService eventService, + GrantNotificationService grantNotificationService, + KiasService kiasService, + PingService pingService) { this.grantRepository = grantRepository; + this.kiasService = kiasService; + this.baseRepository = grantRepository; this.fileService = fileService; this.deadlineService = deadlineService; this.projectService = projectService; this.userService = userService; + this.paperService = paperService; + this.eventService = eventService; + this.grantNotificationService = grantNotificationService; + this.pingService = pingService; + } + + public GrantDto getExistGrantById(Integer id) { + GrantDto grantDto = new GrantDto(findById(id)); + return grantDto; } public List findAll() { @@ -52,20 +88,16 @@ public class GrantService { } public List findAllDto() { - List grants = convert(findAll(), GrantDto::new); - grants.forEach(grantDto -> grantDto.setTitle(StringUtils.abbreviate(grantDto.getTitle(), MAX_DISPLAY_SIZE))); - return grants; - } - - public GrantDto findOneDto(Integer id) { - return new GrantDto(grantRepository.getOne(id)); + return convert(findAll(), GrantDto::new); } @Transactional - public Integer create(GrantDto grantDto) throws IOException { + public Grant create(GrantDto grantDto) throws IOException { Grant newGrant = copyFromDto(new Grant(), grantDto); newGrant = grantRepository.save(newGrant); - return newGrant.getId(); + eventService.createFromObject(newGrant, Collections.emptyList(), false, "гранта"); + grantNotificationService.sendCreateNotification(newGrant); + return newGrant; } private Grant copyFromDto(Grant grant, GrantDto grantDto) throws IOException { @@ -76,8 +108,10 @@ public class GrantService { grant.setProject(projectService.findById(grantDto.getProject().getId())); } grant.setDeadlines(deadlineService.saveOrCreate(grantDto.getDeadlines())); - if (grantDto.getApplicationFileName() != null) { - grant.setApplication(fileService.createFileFromTmp(grantDto.getApplicationFileName())); + if (!grant.getFiles().isEmpty()) { + grant.setFiles(fileService.saveOrCreate(grantDto.getFiles().stream() + .filter(f -> !f.isDeleted()) + .collect(toList()))); } grant.getAuthors().clear(); if (grantDto.getAuthorIds() != null && !grantDto.getAuthorIds().isEmpty()) { @@ -86,9 +120,14 @@ public class GrantService { if (grantDto.getLeaderId() != null) { grant.setLeader(userService.findById(grantDto.getLeaderId())); } + grant.getPapers().clear(); + if (grantDto.getPaperIds() != null && !grantDto.getPaperIds().isEmpty()) { + grantDto.getPaperIds().forEach(paperIds -> grant.getPapers().add(paperService.findPaperById(paperIds))); + } return grant; } + public void createProject(GrantDto grantDto) throws IOException { grantDto.setProject( new ProjectDto(projectService.save(new ProjectDto(grantDto.getTitle())))); @@ -96,65 +135,208 @@ public class GrantService { @Transactional public Integer update(GrantDto grantDto) throws IOException { - Grant grant = grantRepository.getOne(grantDto.getId()); - Grant.GrantStatus oldStatus = grant.getStatus(); - if (grantDto.getApplicationFileName() != null && grant.getApplication() != null) { - fileService.deleteFile(grant.getApplication()); + Grant grant = findById(grantDto.getId()); + Set oldAuthors = new HashSet<>(grant.getAuthors()); + User oldLeader = grant.getLeader(); + for (FileDataDto file : grantDto.getFiles().stream() + .filter(f -> f.isDeleted() && f.getId() != null) + .collect(toList())) { + fileService.delete(file.getId()); } + grantDto.getRemovedDeadlineIds().forEach(deadlineService::remove); grantRepository.save(copyFromDto(grant, grantDto)); + + grant.getAuthors().forEach(author -> { + if (!oldAuthors.contains(author)) { + grantNotificationService.sendAuthorsChangeNotification(grant, oldAuthors); + } + }); + oldAuthors.forEach(oldAuthor -> { + if (!grant.getAuthors().contains(oldAuthor)) { + grantNotificationService.sendAuthorsChangeNotification(grant, oldAuthors); + } + }); + if (grant.getLeader() != oldLeader) { + grantNotificationService.sendLeaderChangeNotification(grant, oldLeader); + } + eventService.updateGrantDeadlines(grant); return grant.getId(); } @Transactional - public void delete(Integer grantId) throws IOException { - Grant grant = grantRepository.getOne(grantId); - if (grant.getApplication() != null) { - fileService.deleteFile(grant.getApplication()); + public boolean delete(Integer grantId) throws IOException { + Grant grant = findById(grantId); + if (grant != null) { + grantRepository.delete(grant); + return true; } - grantRepository.delete(grant); + return false; } public List getGrantStatuses() { return Arrays.asList(Grant.GrantStatus.values()); } - @Transactional - public Grant create(String title, Project projectId, Date deadlineDate, User user) { - Grant grant = new Grant(); - grant.setTitle(title); - grant.setComment("Комментарий к гранту 1"); - grant.setProject(projectId); - grant.setStatus(APPLICATION); - grant.getDeadlines().add(new Deadline(deadlineDate, "первый дедлайн")); - grant.getAuthors().add(user); - grant.setLeader(user); - grant = grantRepository.save(grant); - return grant; - } - - public void save(GrantDto grantDto) throws IOException { + public boolean save(GrantDto grantDto, Errors errors) throws IOException { + grantDto.setName(grantDto.getTitle()); + filterEmptyDeadlines(grantDto); + checkEmptyDeadlines(grantDto, errors); + checkEmptyLeader(grantDto, errors); + checkUniqueName(grantDto, errors, grantDto.getId(), "title", "Грант с таким именем уже существует"); + if (errors.hasErrors()) { + return false; + } if (isEmpty(grantDto.getId())) { create(grantDto); } else { update(grantDto); } + return true; + } + + public boolean saveFromKias(GrantDto grantDto) throws IOException { + grantDto.setName(grantDto.getTitle()); + String title = checkUniqueName(grantDto, grantDto.getId()); //проверка уникальности имени + if (title != null) { + Grant grantFromDB = grantRepository.findByTitle(title); //грант с таким же названием из бд + if (checkSameDeadline(grantDto, grantFromDB.getId())) { //если дедайны тоже совпадают + return false; + } else { //иначе грант уже был в системе, но в другом году, поэтому надо создать + create(grantDto); + return true; + } + } else { //иначе такого гранта ещё нет, поэтому надо создать + create(grantDto); + return true; + } + } + + private void checkEmptyLeader(GrantDto grantDto, Errors errors) { + if (grantDto.getLeaderId().equals(-1)) { + errors.rejectValue("leaderId", "errorCode", "Укажите руководителя"); + } + } + + private void checkEmptyDeadlines(GrantDto grantDto, Errors errors) { + if (grantDto.getDeadlines().isEmpty()) { + errors.rejectValue("deadlines", "errorCode", "Не может быть пусто"); + } + } + + private boolean checkSameDeadline(GrantDto grantDto, Integer id) { + Date date = DateUtils.clearTime(grantDto.getDeadlines().get(0).getDate()); //дата с сайта киас + Date foundGrantDate = DateUtils.clearTime(deadlineService.findByGrantIdAndDate(id, date)); + return foundGrantDate != null && foundGrantDate.compareTo(date) == 0; } public List getGrantAuthors(GrantDto grantDto) { List filteredUsers = userService.filterByAgeAndDegree(grantDto.isHasAge(), grantDto.isHasDegree()); if (grantDto.isWasLeader()) { - filteredUsers = filteredUsers - .stream() - .filter(getCompletedGrantLeaders()::contains) - .collect(Collectors.toList()); + filteredUsers = checkContains(filteredUsers, getCompletedGrantLeaders()); + } + if (grantDto.isHasBAKPapers()) { + filteredUsers = checkContains(filteredUsers, getBAKAuthors()); + } + if (grantDto.isHasScopusPapers()) { + filteredUsers = checkContains(filteredUsers, getScopusAuthors()); } return filteredUsers; } + private List checkContains(List filteredUsers, List checkUsers) { + return filteredUsers.stream() + .filter(checkUsers::contains) + .collect(toList()); + } + private List getCompletedGrantLeaders() { return grantRepository.findByStatus(Grant.GrantStatus.COMPLETED) .stream() .map(Grant::getLeader) - .collect(Collectors.toList()); + .collect(toList()); + } + + public List getGrantPapers(List paperIds) { + return paperService.findAllSelect(paperIds); + } + + public List getAllUncompletedPapers() { + return paperService.findAllNotCompleted(); + } + + public List attachPaper(GrantDto grantDto) { + if (!grantDto.getPaperIds().isEmpty()) { + grantDto.getPapers().clear(); + grantDto.setPapers(getGrantPapers(grantDto.getPaperIds())); + } else { + grantDto.getPapers().clear(); + } + return grantDto.getPapers(); + } + + public GrantDto removeDeadline(GrantDto grantDto, Integer deadlineId) { + if (grantDto.getDeadlines().get(deadlineId).getId() != null) { + grantDto.getRemovedDeadlineIds().add(grantDto.getDeadlines().get(deadlineId).getId()); + } + grantDto.getDeadlines().remove((int) deadlineId); + return grantDto; + } + + private List getCompletedPapersAuthors(Paper.PaperType type) { + List papers = paperService.findAllCompletedByType(type); + return papers.stream() + .filter(paper -> paper.getAuthors() != null) + .flatMap(paper -> paper.getAuthors().stream()) + .collect(toList()); + } + + private List getBAKAuthors() { + return getCompletedPapersAuthors(Paper.PaperType.VAK) + .stream() + .distinct() + .collect(toList()); + } + + private List getScopusAuthors() { + List authors = getCompletedPapersAuthors(Paper.PaperType.SCOPUS); + return authors + .stream() + .filter(author -> Collections.frequency(authors, author) > 3) + .collect(toList()); + } + + public List filterEmptyDeadlines(GrantDto grantDto) { + grantDto.setDeadlines(grantDto.getDeadlines().stream() + .filter(dto -> dto.getDate() != null || !StringUtils.isEmpty(dto.getDescription())) + .collect(Collectors.toList())); + return grantDto.getDeadlines(); + } + + @Transactional + public void createFromKias() throws IOException, ParseException { + for (GrantDto grantDto : kiasService.getNewGrantsDto()) { + if (saveFromKias(grantDto)) { + log.debug("GrantScheduler.loadGrantsFromKias new grant was loaded"); + } else { + log.debug("GrantScheduler.loadGrantsFromKias grant wasn't loaded, cause it's already exists"); + } + } + } + + public List findAllActiveDto() { + return convert(findAllActive(), GrantDto::new); + } + + public List findAllActive() { + return grantRepository.findAllActive(); + } + + public Grant findById(Integer id) { + return grantRepository.getOne(id); + } + + @Transactional + public void ping(int grantId) throws IOException { + pingService.addPing(findById(grantId)); } } diff --git a/src/main/java/ru/ulstu/grant/service/KiasService.java b/src/main/java/ru/ulstu/grant/service/KiasService.java new file mode 100644 index 0000000..b5ddd36 --- /dev/null +++ b/src/main/java/ru/ulstu/grant/service/KiasService.java @@ -0,0 +1,73 @@ +package ru.ulstu.grant.service; + +import com.gargoylesoftware.htmlunit.WebClient; +import com.gargoylesoftware.htmlunit.html.DomNode; +import com.gargoylesoftware.htmlunit.html.HtmlPage; +import org.springframework.stereotype.Service; +import ru.ulstu.configuration.ApplicationProperties; +import ru.ulstu.grant.model.GrantDto; +import ru.ulstu.grant.page.KiasPage; +import ru.ulstu.user.service.UserService; + +import java.io.IOException; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.List; + +@Service +public class KiasService { + private final static String BASE_URL = "https://www.rfbr.ru/rffi/ru/contest_search?CONTEST_STATUS_ID=%s&CONTEST_TYPE=%s&CONTEST_YEAR=%s"; + private final static String CONTEST_STATUS_ID = "1"; + private final static String CONTEST_TYPE = "-1"; + + private final UserService userService; + private final ApplicationProperties applicationProperties; + + public KiasService(UserService userService, + ApplicationProperties applicationProperties) { + this.userService = userService; + this.applicationProperties = applicationProperties; + } + + public List getNewGrantsDto() throws ParseException, IOException { + Integer leaderId = userService.findOneByLoginIgnoreCase("admin").getId(); + List grants = new ArrayList<>(); + try (final WebClient webClient = new WebClient()) { + for (Integer year : generateGrantYears()) { + final HtmlPage page = webClient.getPage(String.format(BASE_URL, CONTEST_STATUS_ID, CONTEST_TYPE, year)); + grants.addAll(getKiasGrants(page)); + } + } + grants.forEach(grantDto -> grantDto.setLeaderId(leaderId)); + return grants; + } + + public List getKiasGrants(HtmlPage page) throws ParseException { + List newGrants = new ArrayList<>(); + KiasPage kiasPage = new KiasPage(page); + do { + newGrants.addAll(getGrantsFromPage(kiasPage)); + } while (kiasPage.goToNextPage()); //проверка существования следующей страницы с грантами + return newGrants; + } + + private List getGrantsFromPage(KiasPage kiasPage) throws ParseException { + List grants = new ArrayList<>(); + for (DomNode grantElement : kiasPage.getPageOfGrants()) { + if (kiasPage.isTableRowGrantLine(grantElement)) { + GrantDto grantDto = new GrantDto( + kiasPage.getGrantTitle(grantElement), + kiasPage.parseDeadLineDate(grantElement)); + grants.add(grantDto); + } + } + return grants; + } + + private List generateGrantYears() { + return Arrays.asList(Calendar.getInstance().get(Calendar.YEAR), + Calendar.getInstance().get(Calendar.YEAR) + 1); + } +} diff --git a/src/main/java/ru/ulstu/name/BaseRepository.java b/src/main/java/ru/ulstu/name/BaseRepository.java new file mode 100644 index 0000000..b691ea2 --- /dev/null +++ b/src/main/java/ru/ulstu/name/BaseRepository.java @@ -0,0 +1,7 @@ +package ru.ulstu.name; + +import org.springframework.data.repository.query.Param; + +public interface BaseRepository { + String findByNameAndNotId(@Param("name") String name, @Param("id") Integer id); +} diff --git a/src/main/java/ru/ulstu/name/BaseService.java b/src/main/java/ru/ulstu/name/BaseService.java new file mode 100644 index 0000000..fd63cbf --- /dev/null +++ b/src/main/java/ru/ulstu/name/BaseService.java @@ -0,0 +1,23 @@ +package ru.ulstu.name; + +import org.springframework.stereotype.Service; +import org.springframework.validation.Errors; + +@Service +public abstract class BaseService { + + public BaseRepository baseRepository; + + public void checkUniqueName(NameContainer nameContainer, Errors errors, Integer id, String checkField, String errorMessage) { + if (nameContainer.getName().equals(baseRepository.findByNameAndNotId(nameContainer.getName(), id))) { + errors.rejectValue(checkField, "errorCode", errorMessage); + } + } + + public String checkUniqueName(NameContainer nameContainer, Integer id) { + if (nameContainer.getName().equals(baseRepository.findByNameAndNotId(nameContainer.getName(), id))) { + return baseRepository.findByNameAndNotId(nameContainer.getName(), id); + } + return null; + } +} diff --git a/src/main/java/ru/ulstu/name/NameContainer.java b/src/main/java/ru/ulstu/name/NameContainer.java new file mode 100644 index 0000000..4339fb2 --- /dev/null +++ b/src/main/java/ru/ulstu/name/NameContainer.java @@ -0,0 +1,14 @@ +package ru.ulstu.name; + +public abstract class NameContainer { + + private String name = ""; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/src/main/java/ru/ulstu/paper/controller/PaperController.java b/src/main/java/ru/ulstu/paper/controller/PaperController.java index e11e4d9..29da57d 100644 --- a/src/main/java/ru/ulstu/paper/controller/PaperController.java +++ b/src/main/java/ru/ulstu/paper/controller/PaperController.java @@ -8,14 +8,16 @@ import org.springframework.ui.ModelMap; import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; +import ru.ulstu.conference.service.ConferenceService; import ru.ulstu.deadline.model.Deadline; +import ru.ulstu.paper.model.AutoCompleteData; import ru.ulstu.paper.model.Paper; import ru.ulstu.paper.model.PaperDto; -import ru.ulstu.paper.model.PaperFilterDto; +import ru.ulstu.paper.model.PaperListDto; +import ru.ulstu.paper.model.ReferenceDto; import ru.ulstu.paper.service.LatexService; import ru.ulstu.paper.service.PaperService; import ru.ulstu.user.model.User; @@ -38,23 +40,34 @@ import static org.springframework.util.StringUtils.isEmpty; @ApiIgnore public class PaperController { private final PaperService paperService; + private final ConferenceService conferenceService; private final LatexService latexService; - public PaperController(PaperService paperService, LatexService latexService) { + public PaperController(PaperService paperService, + ConferenceService conferenceService, + LatexService latexService) { this.paperService = paperService; + this.conferenceService = conferenceService; this.latexService = latexService; } @GetMapping("/papers") public void getPapers(ModelMap modelMap) { - modelMap.put("filteredPapers", new PaperFilterDto(paperService.findAllDto(), null, null)); + modelMap.put("filteredPapers", new PaperListDto(paperService.findAllDto(), null, null)); } @PostMapping("/papers") - public void filterPapers(@Valid PaperFilterDto paperFilterDto, ModelMap modelMap) { - modelMap.put("filteredPapers", new PaperFilterDto(paperService.filter(paperFilterDto), - paperFilterDto.getFilterAuthorId(), - paperFilterDto.getYear())); + public void listPapers(@Valid PaperListDto paperListDto, ModelMap modelMap) { + if (paperListDto.getPaperDeleteId() != null) { + if (conferenceService.isAttachedToConference(paperListDto.getPaperDeleteId())) { + modelMap.put("flashMessage", "Статью нельзя удалить, она прикреплена к конференции"); + } else { + paperService.delete(paperListDto.getPaperDeleteId()); + } + } + modelMap.put("filteredPapers", new PaperListDto(paperService.filter(paperListDto), + paperListDto.getFilterAuthorId(), + paperListDto.getYear())); } @GetMapping("/dashboard") @@ -94,10 +107,13 @@ public class PaperController { return "/papers/paper"; } - @GetMapping("/delete/{paper-id}") - public String delete(@PathVariable("paper-id") Integer paperId) throws IOException { - paperService.delete(paperId); - return "redirect:/papers/papers"; + @PostMapping(value = "/paper", params = "addReference") + public String addReference(@Valid PaperDto paperDto, Errors errors) { + if (errors.hasErrors()) { + return "/papers/paper"; + } + paperDto.getReferences().add(new ReferenceDto()); + return "/papers/paper"; } @ModelAttribute("allStatuses") @@ -124,6 +140,16 @@ public class PaperController { return years; } + @ModelAttribute("allFormatStandards") + public List getFormatStandards() { + return paperService.getFormatStandards(); + } + + @ModelAttribute("allReferenceTypes") + public List getReferenceTypes() { + return paperService.getReferenceTypes(); + } + @PostMapping("/generatePdf") public ResponseEntity getPdfFile(PaperDto paper) throws IOException, InterruptedException { HttpHeaders headers = new HttpHeaders(); @@ -132,6 +158,16 @@ public class PaperController { return new ResponseEntity<>(latexService.generatePdfFromLatexFile(paper), headers, HttpStatus.OK); } + @PostMapping("/getFormattedReferences") + public ResponseEntity getFormattedReferences(PaperDto paperDto) { + return new ResponseEntity<>(paperService.getFormattedReferences(paperDto), new HttpHeaders(), HttpStatus.OK); + } + + @ModelAttribute("autocompleteData") + public AutoCompleteData getAutocompleteData() { + return paperService.getAutoCompleteData(); + } + private void filterEmptyDeadlines(PaperDto paperDto) { paperDto.setDeadlines(paperDto.getDeadlines().stream() .filter(dto -> dto.getDate() != null || !isEmpty(dto.getDescription())) diff --git a/src/main/java/ru/ulstu/paper/controller/PaperRestController.java b/src/main/java/ru/ulstu/paper/controller/PaperRestController.java index 2bd8384..7c0d9c5 100644 --- a/src/main/java/ru/ulstu/paper/controller/PaperRestController.java +++ b/src/main/java/ru/ulstu/paper/controller/PaperRestController.java @@ -7,11 +7,13 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import ru.ulstu.configuration.Constants; import ru.ulstu.core.model.response.Response; import ru.ulstu.paper.model.PaperDto; -import ru.ulstu.paper.model.PaperFilterDto; +import ru.ulstu.paper.model.PaperListDto; +import ru.ulstu.paper.model.ReferenceDto; import ru.ulstu.paper.service.PaperService; import javax.validation.Valid; @@ -58,12 +60,22 @@ public class PaperRestController { } @PostMapping("/filter") - public Response> filter(@RequestBody @Valid PaperFilterDto paperFilterDto) throws IOException { - return new Response<>(paperService.filter(paperFilterDto)); + public Response> filter(@RequestBody @Valid PaperListDto paperListDto) throws IOException { + return new Response<>(paperService.filter(paperListDto)); } @GetMapping("formatted-list") public Response> getFormattedPaperList() { return new Response<>(paperService.getFormattedPaperList()); } + + @PostMapping("/getFormattedReference") + public Response getFormattedReference(@RequestBody @Valid ReferenceDto referenceDto) { + return new Response<>(paperService.getFormattedReference(referenceDto)); + } + + @PostMapping(value = "/ping") + public void ping(@RequestParam("paperId") int paperId) throws IOException { + paperService.ping(paperId); + } } diff --git a/src/main/java/ru/ulstu/paper/error/PaperConferenceRelationExistException.java b/src/main/java/ru/ulstu/paper/error/PaperConferenceRelationExistException.java new file mode 100644 index 0000000..ddb3b5e --- /dev/null +++ b/src/main/java/ru/ulstu/paper/error/PaperConferenceRelationExistException.java @@ -0,0 +1,7 @@ +package ru.ulstu.paper.error; + +public class PaperConferenceRelationExistException extends RuntimeException { + public PaperConferenceRelationExistException(String message) { + super(message); + } +} diff --git a/src/main/java/ru/ulstu/paper/model/AutoCompleteData.java b/src/main/java/ru/ulstu/paper/model/AutoCompleteData.java new file mode 100644 index 0000000..91c3bf4 --- /dev/null +++ b/src/main/java/ru/ulstu/paper/model/AutoCompleteData.java @@ -0,0 +1,43 @@ +package ru.ulstu.paper.model; + +import java.util.ArrayList; +import java.util.List; + +public class AutoCompleteData { + private List authors = new ArrayList<>(); + private List publicationTitles = new ArrayList<>(); + private List publishers = new ArrayList<>(); + private List journalOrCollectionTitles = new ArrayList<>(); + + public List getAuthors() { + return authors; + } + + public void setAuthors(List authors) { + this.authors = authors; + } + + public List getPublicationTitles() { + return publicationTitles; + } + + public void setPublicationTitles(List publicationTitles) { + this.publicationTitles = publicationTitles; + } + + public List getPublishers() { + return publishers; + } + + public void setPublishers(List publishers) { + this.publishers = publishers; + } + + public List getJournalOrCollectionTitles() { + return journalOrCollectionTitles; + } + + public void setJournalOrCollectionTitles(List journalOrCollectionTitles) { + this.journalOrCollectionTitles = journalOrCollectionTitles; + } +} diff --git a/src/main/java/ru/ulstu/paper/model/Paper.java b/src/main/java/ru/ulstu/paper/model/Paper.java index 4f77826..79f5d3b 100644 --- a/src/main/java/ru/ulstu/paper/model/Paper.java +++ b/src/main/java/ru/ulstu/paper/model/Paper.java @@ -2,15 +2,19 @@ package ru.ulstu.paper.model; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; +import ru.ulstu.conference.model.Conference; import ru.ulstu.core.model.BaseEntity; -import ru.ulstu.core.model.UserContainer; +import ru.ulstu.core.model.EventSource; +import ru.ulstu.core.model.UserActivity; import ru.ulstu.deadline.model.Deadline; import ru.ulstu.file.model.FileData; +import ru.ulstu.grant.model.Grant; import ru.ulstu.timeline.model.Event; import ru.ulstu.user.model.User; import javax.persistence.CascadeType; import javax.persistence.Column; +import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; @@ -27,11 +31,13 @@ import java.util.Comparator; import java.util.Date; import java.util.HashSet; import java.util.List; +import java.util.Objects; import java.util.Optional; import java.util.Set; @Entity -public class Paper extends BaseEntity implements UserContainer { +@DiscriminatorValue("PAPER") +public class Paper extends BaseEntity implements UserActivity, EventSource { public enum PaperStatus { ATTENTION("Обратить внимание"), ON_PREPARATION("На подготовке"), @@ -114,6 +120,17 @@ public class Paper extends BaseEntity implements UserContainer { @Column(name = "latex_text") private String latexText; + @ManyToMany(mappedBy = "papers") + private List conferences; + + @ManyToMany(mappedBy = "papers") + private List grants; + + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @JoinColumn(name = "paper_id", unique = true) + @Fetch(FetchMode.SUBSELECT) + private List references = new ArrayList<>(); + public PaperStatus getStatus() { return status; } @@ -182,6 +199,16 @@ public class Paper extends BaseEntity implements UserContainer { return title; } + @Override + public List getRecipients() { + return new ArrayList(authors); + } + + @Override + public void addObjectToEvent(Event event) { + event.setPaper(this); + } + public void setTitle(String title) { this.title = title; } @@ -218,11 +245,35 @@ public class Paper extends BaseEntity implements UserContainer { this.latexText = latexText; } + public List getConferences() { + return conferences; + } + + public void setConferences(List conferences) { + this.conferences = conferences; + } + + public List getGrants() { + return grants; + } + + public void setGrants(List grants) { + this.grants = grants; + } + @Override - public Set getUsers() { + public Set getActivityUsers() { return getAuthors(); } + public List getReferences() { + return references; + } + + public void setReferences(List references) { + this.references = references; + } + public Optional getNextDeadline() { return deadlines .stream() @@ -240,4 +291,36 @@ public class Paper extends BaseEntity implements UserContainer { .findAny() .isPresent(); } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + if (!super.equals(o)) { + return false; + } + Paper paper = (Paper) o; + return Objects.equals(title, paper.title) && + status == paper.status && + type == paper.type && + Objects.equals(deadlines, paper.deadlines) && + Objects.equals(comment, paper.comment) && + Objects.equals(url, paper.url) && + Objects.equals(locked, paper.locked) && + Objects.equals(events, paper.events) && + Objects.equals(files, paper.files) && + Objects.equals(authors, paper.authors) && + Objects.equals(latexText, paper.latexText) && + Objects.equals(conferences, paper.conferences) && + Objects.equals(grants, paper.grants); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), title, status, type, createDate, updateDate, deadlines, comment, url, locked, events, files, authors, latexText, conferences, grants); + } } diff --git a/src/main/java/ru/ulstu/paper/model/PaperDto.java b/src/main/java/ru/ulstu/paper/model/PaperDto.java index 9ed60e7..cc44af5 100644 --- a/src/main/java/ru/ulstu/paper/model/PaperDto.java +++ b/src/main/java/ru/ulstu/paper/model/PaperDto.java @@ -38,6 +38,8 @@ public class PaperDto { private Set authors; private Integer filterAuthorId; private String latexText; + private List references = new ArrayList<>(); + private ReferenceDto.FormatStandard formatStandard = ReferenceDto.FormatStandard.GOST; public PaperDto() { deadlines.add(new Deadline()); @@ -57,7 +59,9 @@ public class PaperDto { @JsonProperty("locked") Boolean locked, @JsonProperty("files") List files, @JsonProperty("authorIds") Set authorIds, - @JsonProperty("authors") Set authors) { + @JsonProperty("authors") Set authors, + @JsonProperty("references") List references, + @JsonProperty("formatStandard") ReferenceDto.FormatStandard formatStandard) { this.id = id; this.title = title; this.status = status; @@ -71,6 +75,8 @@ public class PaperDto { this.locked = locked; this.files = files; this.authors = authors; + this.references = references; + this.formatStandard = formatStandard; } public PaperDto(Paper paper) { @@ -88,6 +94,7 @@ public class PaperDto { this.files = convert(paper.getFiles(), FileDataDto::new); this.authorIds = convert(paper.getAuthors(), user -> user.getId()); this.authors = convert(paper.getAuthors(), UserDto::new); + this.references = convert(paper.getReferences(), ReferenceDto::new); } public Integer getId() { @@ -216,4 +223,20 @@ public class PaperDto { public void setFilterAuthorId(Integer filterAuthorId) { this.filterAuthorId = filterAuthorId; } + + public List getReferences() { + return references; + } + + public void setReferences(List references) { + this.references = references; + } + + public ReferenceDto.FormatStandard getFormatStandard() { + return formatStandard; + } + + public void setFormatStandard(ReferenceDto.FormatStandard formatStandard) { + this.formatStandard = formatStandard; + } } diff --git a/src/main/java/ru/ulstu/paper/model/PaperFilterDto.java b/src/main/java/ru/ulstu/paper/model/PaperListDto.java similarity index 67% rename from src/main/java/ru/ulstu/paper/model/PaperFilterDto.java rename to src/main/java/ru/ulstu/paper/model/PaperListDto.java index f7aef29..871047a 100644 --- a/src/main/java/ru/ulstu/paper/model/PaperFilterDto.java +++ b/src/main/java/ru/ulstu/paper/model/PaperListDto.java @@ -2,15 +2,16 @@ package ru.ulstu.paper.model; import java.util.List; -public class PaperFilterDto { +public class PaperListDto { private List papers; private Integer filterAuthorId; + private Integer paperDeleteId; private Integer year; - public PaperFilterDto() { + public PaperListDto() { } - public PaperFilterDto(List paperDtos, Integer filterAuthorId, Integer year) { + public PaperListDto(List paperDtos, Integer filterAuthorId, Integer year) { this.papers = paperDtos; this.filterAuthorId = filterAuthorId; this.year = year; @@ -39,4 +40,12 @@ public class PaperFilterDto { public void setYear(Integer year) { this.year = year; } + + public Integer getPaperDeleteId() { + return paperDeleteId; + } + + public void setPaperDeleteId(Integer paperDeleteId) { + this.paperDeleteId = paperDeleteId; + } } diff --git a/src/main/java/ru/ulstu/paper/model/Reference.java b/src/main/java/ru/ulstu/paper/model/Reference.java new file mode 100644 index 0000000..289cdc1 --- /dev/null +++ b/src/main/java/ru/ulstu/paper/model/Reference.java @@ -0,0 +1,88 @@ +package ru.ulstu.paper.model; + +import ru.ulstu.core.model.BaseEntity; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; + +@Entity +public class Reference extends BaseEntity { + + private String authors; + + @Column(name = "publication_title") + private String publicationTitle; + + @Column(name = "publication_year") + private Integer publicationYear; + + private String publisher; + + private String pages; + + @Column(name = "journal_or_collection_title") + private String journalOrCollectionTitle; + + @Enumerated(value = EnumType.STRING) + @Column(name = "reference_type") + private ReferenceDto.ReferenceType referenceType = ReferenceDto.ReferenceType.ARTICLE; + + public String getAuthors() { + return authors; + } + + public void setAuthors(String authors) { + this.authors = authors; + } + + public String getPublicationTitle() { + return publicationTitle; + } + + public void setPublicationTitle(String publicationTitle) { + this.publicationTitle = publicationTitle; + } + + public Integer getPublicationYear() { + return publicationYear; + } + + public void setPublicationYear(Integer publicationYear) { + this.publicationYear = publicationYear; + } + + public String getPublisher() { + return publisher; + } + + public void setPublisher(String publisher) { + this.publisher = publisher; + } + + public String getPages() { + return pages; + } + + public void setPages(String pages) { + this.pages = pages; + } + + public String getJournalOrCollectionTitle() { + return journalOrCollectionTitle; + } + + public void setJournalOrCollectionTitle(String journalOrCollectionTitle) { + this.journalOrCollectionTitle = journalOrCollectionTitle; + } + + public ReferenceDto.ReferenceType getReferenceType() { + return referenceType; + } + + public void setReferenceType(ReferenceDto.ReferenceType referenceType) { + this.referenceType = referenceType; + } + +} diff --git a/src/main/java/ru/ulstu/paper/model/ReferenceDto.java b/src/main/java/ru/ulstu/paper/model/ReferenceDto.java new file mode 100644 index 0000000..1705e08 --- /dev/null +++ b/src/main/java/ru/ulstu/paper/model/ReferenceDto.java @@ -0,0 +1,166 @@ +package ru.ulstu.paper.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class ReferenceDto { + public enum ReferenceType { + ARTICLE("Статья"), + BOOK("Книга"); + + private String typeName; + + ReferenceType(String name) { + this.typeName = name; + } + + public String getTypeName() { + return typeName; + } + } + + public enum FormatStandard { + GOST("ГОСТ"), + SPRINGER("Springer"); + + private String standardName; + + FormatStandard(String name) { + this.standardName = name; + } + + public String getStandardName() { + return standardName; + } + } + + private Integer id; + private String authors; + private String publicationTitle; + private Integer publicationYear; + private String publisher; + private String pages; + private String journalOrCollectionTitle; + private ReferenceType referenceType; + private FormatStandard formatStandard; + private boolean deleted; + + @JsonCreator + public ReferenceDto( + @JsonProperty("id") Integer id, + @JsonProperty("authors") String authors, + @JsonProperty("publicationTitle") String publicationTitle, + @JsonProperty("publicationYear") Integer publicationYear, + @JsonProperty("publisher") String publisher, + @JsonProperty("pages") String pages, + @JsonProperty("journalOrCollectionTitle") String journalOrCollectionTitle, + @JsonProperty("referenceType") ReferenceType referenceType, + @JsonProperty("formatStandard") FormatStandard formatStandard, + @JsonProperty("isDeleted") boolean deleted) { + this.id = id; + this.authors = authors; + this.publicationTitle = publicationTitle; + this.publicationYear = publicationYear; + this.publisher = publisher; + this.pages = pages; + this.journalOrCollectionTitle = journalOrCollectionTitle; + this.referenceType = referenceType; + this.formatStandard = formatStandard; + this.deleted = deleted; + } + + public ReferenceDto(Reference reference) { + this.id = reference.getId(); + this.authors = reference.getAuthors(); + this.publicationTitle = reference.getPublicationTitle(); + this.publicationYear = reference.getPublicationYear(); + this.publisher = reference.getPublisher(); + this.pages = reference.getPages(); + this.journalOrCollectionTitle = reference.getJournalOrCollectionTitle(); + this.referenceType = reference.getReferenceType(); + } + + public ReferenceDto() { + referenceType = ReferenceType.ARTICLE; + } + + public String getAuthors() { + return authors; + } + + public void setAuthors(String authors) { + this.authors = authors; + } + + public String getPublicationTitle() { + return publicationTitle; + } + + public void setPublicationTitle(String publicationTitle) { + this.publicationTitle = publicationTitle; + } + + public Integer getPublicationYear() { + return publicationYear; + } + + public void setPublicationYear(Integer publicationYear) { + this.publicationYear = publicationYear; + } + + public String getPublisher() { + return publisher; + } + + public void setPublisher(String publisher) { + this.publisher = publisher; + } + + public String getPages() { + return pages; + } + + public void setPages(String pages) { + this.pages = pages; + } + + public String getJournalOrCollectionTitle() { + return journalOrCollectionTitle; + } + + public void setJournalOrCollectionTitle(String journalOrCollectionTitle) { + this.journalOrCollectionTitle = journalOrCollectionTitle; + } + + public ReferenceType getReferenceType() { + return referenceType; + } + + public void setReferenceType(ReferenceType referenceType) { + this.referenceType = referenceType; + } + + public FormatStandard getFormatStandard() { + return formatStandard; + } + + public void setFormatStandard(FormatStandard formatStandard) { + this.formatStandard = formatStandard; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public boolean getDeleted() { + return deleted; + } + + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } +} diff --git a/src/main/java/ru/ulstu/paper/repository/PaperRepository.java b/src/main/java/ru/ulstu/paper/repository/PaperRepository.java index 343e9e2..42d3703 100644 --- a/src/main/java/ru/ulstu/paper/repository/PaperRepository.java +++ b/src/main/java/ru/ulstu/paper/repository/PaperRepository.java @@ -14,4 +14,14 @@ public interface PaperRepository extends JpaRepository { List filter(@Param("author") User author, @Param("year") Integer year); List findByIdNotIn(List paperIds); + + List findAllByIdIn(List paperIds); + + List findByTypeAndStatus(Paper.PaperType type, Paper.PaperStatus status); + + List findByStatusNot(Paper.PaperStatus status); + + List findByConferencesIsNullAndStatusNot(Paper.PaperStatus status); + + List findByIdNotInAndConferencesIsNullAndStatusNot(List paperIds, Paper.PaperStatus status); } diff --git a/src/main/java/ru/ulstu/paper/repository/ReferenceRepository.java b/src/main/java/ru/ulstu/paper/repository/ReferenceRepository.java new file mode 100644 index 0000000..942a5b8 --- /dev/null +++ b/src/main/java/ru/ulstu/paper/repository/ReferenceRepository.java @@ -0,0 +1,23 @@ +package ru.ulstu.paper.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import ru.ulstu.paper.model.Reference; + +import java.util.List; + +public interface ReferenceRepository extends JpaRepository { + void deleteById(Integer id); + + @Query("SELECT DISTINCT r.authors FROM Reference r") + List findDistinctAuthors(); + + @Query("SELECT DISTINCT r.publicationTitle FROM Reference r") + List findDistinctPublicationTitles(); + + @Query("SELECT DISTINCT r.publisher FROM Reference r") + List findDistinctPublishers(); + + @Query("SELECT DISTINCT r.journalOrCollectionTitle FROM Reference r where r.journalOrCollectionTitle <> ''") + List findDistinctJournalOrCollectionTitles(); +} diff --git a/src/main/java/ru/ulstu/paper/service/LatexService.java b/src/main/java/ru/ulstu/paper/service/LatexService.java index 82dd1ba..9892e35 100644 --- a/src/main/java/ru/ulstu/paper/service/LatexService.java +++ b/src/main/java/ru/ulstu/paper/service/LatexService.java @@ -42,8 +42,9 @@ public class LatexService { InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream()); try (BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) { - while ((bufferedReader.readLine()) != null) { - // + String line = bufferedReader.readLine(); + while (line != null) { + line = bufferedReader.readLine(); } } diff --git a/src/main/java/ru/ulstu/paper/service/PaperService.java b/src/main/java/ru/ulstu/paper/service/PaperService.java index 33344a5..1a1e2cb 100644 --- a/src/main/java/ru/ulstu/paper/service/PaperService.java +++ b/src/main/java/ru/ulstu/paper/service/PaperService.java @@ -7,15 +7,21 @@ import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.service.DeadlineService; import ru.ulstu.file.model.FileDataDto; import ru.ulstu.file.service.FileService; +import ru.ulstu.paper.model.AutoCompleteData; import ru.ulstu.paper.model.Paper; import ru.ulstu.paper.model.PaperDto; -import ru.ulstu.paper.model.PaperFilterDto; +import ru.ulstu.paper.model.PaperListDto; +import ru.ulstu.paper.model.Reference; +import ru.ulstu.paper.model.ReferenceDto; import ru.ulstu.paper.repository.PaperRepository; +import ru.ulstu.paper.repository.ReferenceRepository; +import ru.ulstu.ping.service.PingService; import ru.ulstu.timeline.service.EventService; import ru.ulstu.user.model.User; import ru.ulstu.user.service.UserService; import java.io.IOException; +import java.text.MessageFormat; import java.util.Arrays; import java.util.Date; import java.util.HashSet; @@ -32,8 +38,12 @@ import static ru.ulstu.paper.model.Paper.PaperStatus.DRAFT; import static ru.ulstu.paper.model.Paper.PaperStatus.FAILED; import static ru.ulstu.paper.model.Paper.PaperStatus.ON_PREPARATION; import static ru.ulstu.paper.model.Paper.PaperType.OTHER; +import static ru.ulstu.paper.model.ReferenceDto.FormatStandard.GOST; +import static ru.ulstu.paper.model.ReferenceDto.ReferenceType.ARTICLE; +import static ru.ulstu.paper.model.ReferenceDto.ReferenceType.BOOK; @Service +@Transactional public class PaperService { private final static int MAX_DISPLAY_SIZE = 40; private final static String PAPER_FORMATTED_TEMPLATE = "%s %s"; @@ -44,19 +54,25 @@ public class PaperService { private final DeadlineService deadlineService; private final FileService fileService; private final EventService eventService; + private final ReferenceRepository referenceRepository; + private final PingService pingService; public PaperService(PaperRepository paperRepository, + ReferenceRepository referenceRepository, FileService fileService, PaperNotificationService paperNotificationService, UserService userService, DeadlineService deadlineService, - EventService eventService) { + EventService eventService, + PingService pingService) { this.paperRepository = paperRepository; + this.referenceRepository = referenceRepository; this.fileService = fileService; this.paperNotificationService = paperNotificationService; this.userService = userService; this.deadlineService = deadlineService; this.eventService = eventService; + this.pingService = pingService; } public List findAll() { @@ -93,6 +109,14 @@ public class PaperService { return newPaper.getId(); } + @Transactional + public Paper create(Paper paper) { + Paper newPaper = paperRepository.save(paper); + paperNotificationService.sendCreateNotification(newPaper); + eventService.createFromPaper(newPaper); + return newPaper; + } + private Paper copyFromDto(Paper paper, PaperDto paperDto) throws IOException { paper.setComment(paperDto.getComment()); paper.setUrl(paperDto.getUrl()); @@ -104,6 +128,7 @@ public class PaperService { paper.setTitle(paperDto.getTitle()); paper.setUpdateDate(new Date()); paper.setDeadlines(deadlineService.saveOrCreate(paperDto.getDeadlines())); + paper.setReferences(saveOrCreateReferences(paperDto.getReferences())); paper.setFiles(fileService.saveOrCreate(paperDto.getFiles().stream() .filter(f -> !f.isDeleted()) .collect(toList()))); @@ -114,6 +139,41 @@ public class PaperService { return paper; } + public List saveOrCreateReferences(List references) { + return references + .stream() + .filter(reference -> !reference.getDeleted()) + .map(reference -> reference.getId() != null ? updateReference(reference) : createReference(reference)) + .collect(Collectors.toList()); + } + + @Transactional + public Reference updateReference(ReferenceDto referenceDto) { + Reference updateReference = referenceRepository.getOne(referenceDto.getId()); + copyFromDto(updateReference, referenceDto); + referenceRepository.save(updateReference); + return updateReference; + } + + @Transactional + public Reference createReference(ReferenceDto referenceDto) { + Reference newReference = new Reference(); + copyFromDto(newReference, referenceDto); + newReference = referenceRepository.save(newReference); + return newReference; + } + + private Reference copyFromDto(Reference reference, ReferenceDto referenceDto) { + reference.setAuthors(referenceDto.getAuthors()); + reference.setJournalOrCollectionTitle(referenceDto.getJournalOrCollectionTitle()); + reference.setPages(referenceDto.getPages()); + reference.setPublicationTitle(referenceDto.getPublicationTitle()); + reference.setPublicationYear(referenceDto.getPublicationYear()); + reference.setPublisher(referenceDto.getPublisher()); + reference.setReferenceType(referenceDto.getReferenceType()); + return reference; + } + @Transactional public Integer update(PaperDto paperDto) throws IOException { Paper paper = paperRepository.getOne(paperDto.getId()); @@ -126,6 +186,11 @@ public class PaperService { fileService.delete(file.getId()); } paperRepository.save(copyFromDto(paper, paperDto)); + for (ReferenceDto referenceDto : paperDto.getReferences().stream() + .filter(f -> f.getDeleted() && f.getId() != null) + .collect(toList())) { + referenceRepository.deleteById(referenceDto.getId()); + } eventService.updatePaperDeadlines(paper); paper.getAuthors().forEach(author -> { @@ -142,7 +207,7 @@ public class PaperService { } @Transactional - public void delete(Integer paperId) throws IOException { + public void delete(Integer paperId) { Paper paper = paperRepository.getOne(paperId); paperRepository.delete(paper); } @@ -155,6 +220,14 @@ public class PaperService { return Arrays.asList(Paper.PaperType.values()); } + public List getFormatStandards() { + return Arrays.asList(ReferenceDto.FormatStandard.values()); + } + + public List getReferenceTypes() { + return Arrays.asList(ReferenceDto.ReferenceType.values()); + } + @Transactional public Paper create(String title, User user, Date deadlineDate) { Paper paper = new Paper(); @@ -173,7 +246,7 @@ public class PaperService { return paper; } - public List filter(PaperFilterDto filterDto) { + public List filter(PaperListDto filterDto) { return convert(sortPapers(paperRepository.filter( filterDto.getFilterAuthorId() == null ? null : userService.findById(filterDto.getFilterAuthorId()), filterDto.getYear())), PaperDto::new); @@ -223,17 +296,24 @@ public class PaperService { return new PaperDto(paperRepository.getOne(paperId)); } - public Paper findEntityById(Integer paperId) { + public Paper findPaperById(Integer paperId) { return paperRepository.getOne(paperId); } public List findAllNotSelect(List paperIds) { if (!paperIds.isEmpty()) { - return sortPapers(paperRepository.findByIdNotIn(paperIds)); + return sortPapers(paperRepository.findByIdNotInAndConferencesIsNullAndStatusNot(paperIds, COMPLETED)); } else { - return sortPapers(paperRepository.findAll()); + return sortPapers(paperRepository.findByConferencesIsNullAndStatusNot(COMPLETED)); } + } + public List findAllNotCompleted() { + return convert(paperRepository.findByStatusNot(COMPLETED), PaperDto::new); + } + + public List findAllSelect(List paperIds) { + return convert(paperRepository.findAllByIdIn(paperIds), PaperDto::new); } public List getPaperAuthors() { @@ -260,4 +340,59 @@ public class PaperService { .map(User::getUserAbbreviate) .collect(Collectors.joining(", ")); } + + public String getFormattedReference(ReferenceDto referenceDto) { + return referenceDto.getFormatStandard() == GOST + ? getGostReference(referenceDto) + : getSpringerReference(referenceDto); + } + + public String getFormattedReferences(PaperDto paperDto) { + return String.join("\r\n", paperDto.getReferences() + .stream() + .filter(r -> !r.getDeleted()) + .map(r -> { + r.setFormatStandard(paperDto.getFormatStandard()); + return getFormattedReference(r); + }) + .collect(Collectors.toList())); + } + + public String getGostReference(ReferenceDto referenceDto) { + return MessageFormat.format(referenceDto.getReferenceType() == BOOK ? "{0} {1} - {2}{3}. - {4}с." : "{0} {1}{5} {2}{3}. С. {4}.", + referenceDto.getAuthors(), + referenceDto.getPublicationTitle(), + StringUtils.isEmpty(referenceDto.getPublisher()) ? "" : referenceDto.getPublisher() + ", ", + referenceDto.getPublicationYear() != null ? referenceDto.getPublicationYear().toString() : "", + referenceDto.getPages(), + StringUtils.isEmpty(referenceDto.getJournalOrCollectionTitle()) ? "." : " // " + referenceDto.getJournalOrCollectionTitle() + "."); + } + + public String getSpringerReference(ReferenceDto referenceDto) { + return MessageFormat.format("{0} ({1}) {2}.{3} {4}pp {5}", + referenceDto.getAuthors(), + referenceDto.getPublicationYear() != null ? referenceDto.getPublicationYear().toString() : "", + referenceDto.getPublicationTitle(), + referenceDto.getReferenceType() == ARTICLE ? " " + referenceDto.getJournalOrCollectionTitle() + "," : "", + StringUtils.isEmpty(referenceDto.getPublisher()) ? "" : referenceDto.getPublisher() + ", ", + referenceDto.getPages()); + } + + public List findAllCompletedByType(Paper.PaperType type) { + return paperRepository.findByTypeAndStatus(type, Paper.PaperStatus.COMPLETED); + } + + public AutoCompleteData getAutoCompleteData() { + AutoCompleteData autoCompleteData = new AutoCompleteData(); + autoCompleteData.setAuthors(referenceRepository.findDistinctAuthors()); + autoCompleteData.setJournalOrCollectionTitles(referenceRepository.findDistinctJournalOrCollectionTitles()); + autoCompleteData.setPublicationTitles(referenceRepository.findDistinctPublicationTitles()); + autoCompleteData.setPublishers(referenceRepository.findDistinctPublishers()); + return autoCompleteData; + } + + @Transactional + public void ping(int paperId) throws IOException { + pingService.addPing(findPaperById(paperId)); + } } diff --git a/src/main/java/ru/ulstu/ping/model/Ping.java b/src/main/java/ru/ulstu/ping/model/Ping.java new file mode 100644 index 0000000..7118c22 --- /dev/null +++ b/src/main/java/ru/ulstu/ping/model/Ping.java @@ -0,0 +1,86 @@ +package ru.ulstu.ping.model; + +import org.hibernate.annotations.Any; +import org.hibernate.annotations.AnyMetaDef; +import org.hibernate.annotations.MetaValue; +import org.springframework.format.annotation.DateTimeFormat; +import ru.ulstu.conference.model.Conference; +import ru.ulstu.core.model.BaseEntity; +import ru.ulstu.core.model.UserActivity; +import ru.ulstu.grant.model.Grant; +import ru.ulstu.paper.model.Paper; +import ru.ulstu.project.model.Project; +import ru.ulstu.user.model.User; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; +import java.util.Date; + +@Entity +@Table(name = "ping") +public class Ping extends BaseEntity { + @Temporal(value = TemporalType.TIMESTAMP) + @DateTimeFormat(pattern = "yyyy-MM-dd") + private Date date; + + @ManyToOne(optional = false) + @JoinColumn(name = "users_id") + private User user; + + @Column(name = "activity_type", insertable = false, updatable = false) + private String activityType; + + @Any( + metaColumn = @Column(name = "activity_type"), + fetch = FetchType.LAZY + ) + @AnyMetaDef( + idType = "integer", metaType = "string", + metaValues = { + @MetaValue(targetEntity = Conference.class, value = "CONFERENCE"), + @MetaValue(targetEntity = Paper.class, value = "PAPER"), + @MetaValue(targetEntity = Project.class, value = "PROJECT"), + @MetaValue(targetEntity = Grant.class, value = "GRANT") + } + ) + @JoinColumn(name = "activity_id") + private UserActivity activity; + + public Ping() { + } + + public Ping(Date date, User user) { + this.date = date; + this.user = user; + } + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public UserActivity getActivity() { + return this.activity; + } + + public void setActivity(UserActivity activity) { + this.activity = activity; + } +} diff --git a/src/main/java/ru/ulstu/ping/model/PingInfo.java b/src/main/java/ru/ulstu/ping/model/PingInfo.java new file mode 100644 index 0000000..e8b943b --- /dev/null +++ b/src/main/java/ru/ulstu/ping/model/PingInfo.java @@ -0,0 +1,35 @@ +package ru.ulstu.ping.model; + +import ru.ulstu.user.model.User; + +import java.util.ArrayList; +import java.util.List; + +public class PingInfo { + private User user; + private List pings = new ArrayList<>(); + + public PingInfo(User user) { + this.user = user; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public List getPings() { + return pings; + } + + public void setPings(List pings) { + this.pings = pings; + } + + public void addPing(Ping ping) { + this.pings.add(ping); + } +} diff --git a/src/main/java/ru/ulstu/ping/repository/PingRepository.java b/src/main/java/ru/ulstu/ping/repository/PingRepository.java new file mode 100644 index 0000000..cec24e7 --- /dev/null +++ b/src/main/java/ru/ulstu/ping/repository/PingRepository.java @@ -0,0 +1,22 @@ +package ru.ulstu.ping.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import ru.ulstu.conference.model.Conference; +import ru.ulstu.ping.model.Ping; + +import java.util.Date; +import java.util.List; + +public interface PingRepository extends JpaRepository { + + @Query("SELECT count(*) FROM Ping p WHERE (DAY(p.date) = :day) AND (MONTH(p.date) = :month) AND (YEAR(p.date) = :year) AND (p.activityType = 'conference') AND (p.activity = :conference)") + long countByConferenceAndDate(@Param("conference") Conference conference, @Param("day") Integer day, @Param("month") Integer month, @Param("year") Integer year); + + @Query("SELECT p FROM Ping p WHERE (:activity = '' OR p.activityType = :activity)") + List getPings(@Param("activity") String activity); + + @Query("SELECT p FROM Ping p WHERE (:dateFrom < date)") + List findByDate(@Param("dateFrom") Date dateFrom); +} diff --git a/src/main/java/ru/ulstu/ping/service/PingScheduler.java b/src/main/java/ru/ulstu/ping/service/PingScheduler.java new file mode 100644 index 0000000..ca8724d --- /dev/null +++ b/src/main/java/ru/ulstu/ping/service/PingScheduler.java @@ -0,0 +1,58 @@ +package ru.ulstu.ping.service; + +import com.google.common.collect.ImmutableMap; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; +import ru.ulstu.core.model.UserActivity; +import ru.ulstu.ping.model.Ping; +import ru.ulstu.ping.model.PingInfo; +import ru.ulstu.ping.repository.PingRepository; +import ru.ulstu.user.model.User; +import ru.ulstu.user.service.MailService; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +@Service +public class PingScheduler { + private final Logger log = LoggerFactory.getLogger(PingScheduler.class); + private final PingRepository pingRepository; + private final MailService mailService; + private final static String PING_MAIL_SUBJECT = "Ping статистика"; + + public PingScheduler(PingRepository pingRepository, MailService mailService) { + this.pingRepository = pingRepository; + this.mailService = mailService; + } + + + @Scheduled(cron = "0 0 * * 1 ?") + public void sendPingsInfo() { + log.debug("Scheduler.sendPingsInfo started"); + + List pingInfos = new ArrayList<>(); + + for (Ping ping : pingRepository.findByDate(java.sql.Date.valueOf(LocalDate.now().minusWeeks(1)))) { + UserActivity pingActivity = ping.getActivity(); + Set users = pingActivity.getActivityUsers(); + + for (User user : users) { + PingInfo userPing = pingInfos.stream().filter(u -> u.getUser() == user).findFirst().orElse(null); + if (userPing == null) { + userPing = new PingInfo(user); + pingInfos.add(userPing); + } + userPing.addPing(ping); + } + } + + for (PingInfo pingInfo : pingInfos) { + mailService.sendEmailFromTemplate(ImmutableMap.of("pings", pingInfo.getPings()), + pingInfo.getUser(), "pingsInfoWeekEmail", PING_MAIL_SUBJECT); + } + } +} diff --git a/src/main/java/ru/ulstu/ping/service/PingService.java b/src/main/java/ru/ulstu/ping/service/PingService.java new file mode 100644 index 0000000..e1c0035 --- /dev/null +++ b/src/main/java/ru/ulstu/ping/service/PingService.java @@ -0,0 +1,45 @@ +package ru.ulstu.ping.service; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import ru.ulstu.conference.model.Conference; +import ru.ulstu.core.model.UserActivity; +import ru.ulstu.ping.model.Ping; +import ru.ulstu.ping.repository.PingRepository; +import ru.ulstu.user.service.UserService; + +import java.io.IOException; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +@Service +public class PingService { + private final PingRepository pingRepository; + private final UserService userService; + private final PingScheduler pingScheduler; + + public PingService(PingRepository pingRepository, + UserService userService, + PingScheduler pingScheduler) { + this.pingRepository = pingRepository; + this.userService = userService; + this.pingScheduler = pingScheduler; + } + + @Transactional + public Ping addPing(UserActivity activity) throws IOException { + Ping newPing = new Ping(new Date(), userService.getCurrentUser()); + newPing.setActivity(activity); + return pingRepository.save(newPing); + } + + public Integer countPingYesterday(Conference conference, Calendar calendar) { + return Math.toIntExact(pingRepository.countByConferenceAndDate(conference, calendar.get(Calendar.DAY_OF_MONTH), + calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.YEAR))); + } + + public List getPings(String activity) { + return pingRepository.getPings(activity); + } +} diff --git a/src/main/java/ru/ulstu/project/controller/ProjectController.java b/src/main/java/ru/ulstu/project/controller/ProjectController.java index affdaec..09438fd 100644 --- a/src/main/java/ru/ulstu/project/controller/ProjectController.java +++ b/src/main/java/ru/ulstu/project/controller/ProjectController.java @@ -5,13 +5,17 @@ import org.springframework.ui.ModelMap; import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; import ru.ulstu.deadline.model.Deadline; +import ru.ulstu.grant.model.GrantDto; import ru.ulstu.project.model.Project; import ru.ulstu.project.model.ProjectDto; import ru.ulstu.project.service.ProjectService; +import ru.ulstu.user.model.User; import springfox.documentation.annotations.ApiIgnore; import javax.validation.Valid; @@ -44,6 +48,8 @@ public class ProjectController { @GetMapping("/project") public void getProject(ModelMap modelMap, @RequestParam(value = "id") Integer id) { if (id != null && id > 0) { + ProjectDto projectDto = projectService.findOneDto(id); + attachGrant(projectDto); modelMap.put("projectDto", projectService.findOneDto(id)); } else { modelMap.put("projectDto", new ProjectDto()); @@ -68,6 +74,12 @@ public class ProjectController { return String.format("redirect:%s", "/projects/projects"); } + @PostMapping(value = "/project", params = "attachGrant") + public String attachGrant(ProjectDto projectDto) { + projectService.attachGrant(projectDto); + return "/projects/project"; + } + @PostMapping(value = "/project", params = "addDeadline") public String addDeadline(@Valid ProjectDto projectDto, Errors errors) { filterEmptyDeadlines(projectDto); @@ -78,9 +90,38 @@ public class ProjectController { return "/projects/project"; } + @PostMapping(value = "/project", params = "removeDeadline") + public String removeDeadline(ProjectDto projectDto, + @RequestParam(value = "removeDeadline") Integer deadlineId) { + projectService.removeDeadline(projectDto, deadlineId); + return "/projects/project"; + } + + @GetMapping("/delete/{project-id}") + public String delete(@PathVariable("project-id") Integer projectId) throws IOException { + projectService.delete(projectId); + return String.format("redirect:%s", "/projects/projects"); + } + + @ModelAttribute("allExecutors") + public List getAllExecutors(ProjectDto projectDto) { + return projectService.getProjectExecutors(projectDto); + } + + @ModelAttribute("allGrants") + public List getAllGrants() { + return projectService.getAllGrants(); + } + private void filterEmptyDeadlines(ProjectDto projectDto) { projectDto.setDeadlines(projectDto.getDeadlines().stream() .filter(dto -> dto.getDate() != null || !isEmpty(dto.getDescription())) .collect(Collectors.toList())); } + + @ResponseBody + @PostMapping(value = "/ping") + public void ping(@RequestParam("projectId") int projectId) throws IOException { + projectService.ping(projectId); + } } diff --git a/src/main/java/ru/ulstu/project/model/Project.java b/src/main/java/ru/ulstu/project/model/Project.java index 5b9da69..25a7382 100644 --- a/src/main/java/ru/ulstu/project/model/Project.java +++ b/src/main/java/ru/ulstu/project/model/Project.java @@ -1,30 +1,45 @@ package ru.ulstu.project.model; +import org.hibernate.annotations.Fetch; +import org.hibernate.annotations.FetchMode; import ru.ulstu.core.model.BaseEntity; +import ru.ulstu.core.model.EventSource; +import ru.ulstu.core.model.UserActivity; import ru.ulstu.deadline.model.Deadline; import ru.ulstu.file.model.FileData; import ru.ulstu.grant.model.Grant; +import ru.ulstu.timeline.model.Event; +import ru.ulstu.user.model.User; import javax.persistence.CascadeType; +import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; +import javax.persistence.FetchType; import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; import java.util.List; +import java.util.Set; @Entity -public class Project extends BaseEntity { +@DiscriminatorValue("PROJECT") +public class Project extends BaseEntity implements UserActivity, EventSource { + public enum ProjectStatus { - APPLICATION("Заявка"), - ON_COMPETITION("Отправлен на конкурс"), - SUCCESSFUL_PASSAGE("Успешное прохождение"), + TECHNICAL_TASK("Техническое задание"), + OPEN("Открыт"), IN_WORK("В работе"), - COMPLETED("Завершен"), + CERTIFICATE_ISSUED("Оформление свидетельства"), + CLOSED("Закрыт"), FAILED("Провалены сроки"); private String statusName; @@ -42,7 +57,7 @@ public class Project extends BaseEntity { private String title; @Enumerated(value = EnumType.STRING) - private ProjectStatus status = ProjectStatus.APPLICATION; + private ProjectStatus status = ProjectStatus.TECHNICAL_TASK; @NotNull private String description; @@ -58,14 +73,39 @@ public class Project extends BaseEntity { @NotNull private String repository; - @ManyToOne - @JoinColumn(name = "file_id") - private FileData application; + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @JoinColumn(name = "project_id", unique = true) + @Fetch(FetchMode.SUBSELECT) + private List files = new ArrayList<>(); + + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) + @JoinColumn(name = "project_id") + private List events = new ArrayList<>(); + + @ManyToMany(fetch = FetchType.LAZY) + private List executors = new ArrayList<>(); + + @ManyToMany(fetch = FetchType.LAZY) + @JoinTable(name = "project_grants", + joinColumns = {@JoinColumn(name = "project_id")}, + inverseJoinColumns = {@JoinColumn(name = "grants_id")}) + @Fetch(FetchMode.SUBSELECT) + private List grants = new ArrayList<>(); public String getTitle() { return title; } + @Override + public List getRecipients() { + return executors != null ? new ArrayList<>(executors) : Collections.emptyList(); + } + + @Override + public void addObjectToEvent(Event event) { + event.setProject(this); + } + public void setTitle(String title) { this.title = title; } @@ -110,11 +150,44 @@ public class Project extends BaseEntity { this.deadlines = deadlines; } - public FileData getApplication() { - return application; + public List getFiles() { + return files; + } + + public void setFiles(List files) { + this.files = files; + } + + public List getEvents() { + return events; + } + + public void setEvents(List events) { + this.events = events; + } + + public List getExecutors() { + return executors; + } + + public void setExecutors(List executors) { + this.executors = executors; + } + + public Set getUsers() { + return new HashSet<>(getExecutors()); + } + + @Override + public Set getActivityUsers() { + return new HashSet<>(); + } + + public List getGrants() { + return grants; } - public void setApplication(FileData application) { - this.application = application; + public void setGrants(List grants) { + this.grants = grants; } } diff --git a/src/main/java/ru/ulstu/project/model/ProjectDto.java b/src/main/java/ru/ulstu/project/model/ProjectDto.java index d9e60ab..d5a8345 100644 --- a/src/main/java/ru/ulstu/project/model/ProjectDto.java +++ b/src/main/java/ru/ulstu/project/model/ProjectDto.java @@ -2,12 +2,21 @@ package ru.ulstu.project.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; +import org.thymeleaf.util.StringUtils; import ru.ulstu.deadline.model.Deadline; +import ru.ulstu.file.model.FileDataDto; import ru.ulstu.grant.model.GrantDto; +import ru.ulstu.user.model.User; +import ru.ulstu.user.model.UserDto; import javax.validation.constraints.NotEmpty; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import static ru.ulstu.core.util.StreamApiUtils.convert; public class ProjectDto { private Integer id; @@ -19,7 +28,14 @@ public class ProjectDto { private List deadlines = new ArrayList<>(); private GrantDto grant; private String repository; - private String applicationFileName; + private List files = new ArrayList<>(); + private List removedDeadlineIds = new ArrayList<>(); + private Set executorIds; + private List executors; + private List grantIds; + private List grants; + + private final static int MAX_EXECUTORS_LENGTH = 40; public ProjectDto() { } @@ -35,7 +51,12 @@ public class ProjectDto { @JsonProperty("description") String description, @JsonProperty("grant") GrantDto grant, @JsonProperty("repository") String repository, - @JsonProperty("deadlines") List deadlines) { + @JsonProperty("files") List files, + @JsonProperty("deadlines") List deadlines, + @JsonProperty("executorIds") Set executorIds, + @JsonProperty("executors") List executors, + @JsonProperty("grantIds") List grantIds, + @JsonProperty("grants") List grants) { this.id = id; this.title = title; this.status = status; @@ -43,19 +64,28 @@ public class ProjectDto { this.grant = grant; this.repository = repository; this.deadlines = deadlines; - this.applicationFileName = null; + this.files = files; + this.executorIds = executorIds; + this.executors = executors; + this.grantIds = grantIds; + this.grants = grants; } public ProjectDto(Project project) { + Set users = new HashSet(project.getExecutors()); this.id = project.getId(); this.title = project.getTitle(); this.status = project.getStatus(); this.description = project.getDescription(); - this.applicationFileName = project.getApplication() == null ? null : project.getApplication().getName(); + this.files = convert(project.getFiles(), FileDataDto::new); this.grant = project.getGrant() == null ? null : new GrantDto(project.getGrant()); this.repository = project.getRepository(); this.deadlines = project.getDeadlines(); + this.executorIds = convert(users, user -> user.getId()); + this.executors = convert(project.getExecutors(), UserDto::new); + this.grantIds = convert(project.getGrants(), grant -> grant.getId()); + this.grants = convert(project.getGrants(), GrantDto::new); } public Integer getId() { @@ -114,11 +144,58 @@ public class ProjectDto { this.deadlines = deadlines; } - public String getApplicationFileName() { - return applicationFileName; + public List getFiles() { + return files; + } + + public void setFiles(List files) { + this.files = files; + } + + public List getRemovedDeadlineIds() { + return removedDeadlineIds; + } + + public void setRemovedDeadlineIds(List removedDeadlineIds) { + this.removedDeadlineIds = removedDeadlineIds; + } + + public Set getExecutorIds() { + return executorIds; + } + + public void setExecutorIds(Set executorIds) { + this.executorIds = executorIds; + } + + public List getExecutors() { + return executors; + } + + public void setExecutors(List executors) { + this.executors = executors; + } + + public String getExecutorsString() { + return StringUtils.abbreviate(executors + .stream() + .map(executor -> executor.getLastName()) + .collect(Collectors.joining(", ")), MAX_EXECUTORS_LENGTH); + } + + public List getGrantIds() { + return grantIds; + } + + public void setGrantIds(List grantIds) { + this.grantIds = grantIds; + } + + public List getGrants() { + return grants; } - public void setApplicationFileName(String applicationFileName) { - this.applicationFileName = applicationFileName; + public void setGrants(List grants) { + this.grants = grants; } } diff --git a/src/main/java/ru/ulstu/project/service/ProjectService.java b/src/main/java/ru/ulstu/project/service/ProjectService.java index 115f5ae..7ce4861 100644 --- a/src/main/java/ru/ulstu/project/service/ProjectService.java +++ b/src/main/java/ru/ulstu/project/service/ProjectService.java @@ -4,19 +4,27 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.thymeleaf.util.StringUtils; import ru.ulstu.deadline.service.DeadlineService; +import ru.ulstu.file.model.FileDataDto; import ru.ulstu.file.service.FileService; +import ru.ulstu.grant.model.GrantDto; import ru.ulstu.grant.repository.GrantRepository; +import ru.ulstu.ping.service.PingService; import ru.ulstu.project.model.Project; import ru.ulstu.project.model.ProjectDto; import ru.ulstu.project.repository.ProjectRepository; +import ru.ulstu.timeline.service.EventService; +import ru.ulstu.user.model.User; +import ru.ulstu.user.service.UserService; import java.io.IOException; import java.util.Arrays; +import java.util.Collections; import java.util.List; +import static java.util.stream.Collectors.toList; import static org.springframework.util.ObjectUtils.isEmpty; import static ru.ulstu.core.util.StreamApiUtils.convert; -import static ru.ulstu.project.model.Project.ProjectStatus.APPLICATION; +import static ru.ulstu.project.model.Project.ProjectStatus.TECHNICAL_TASK; @Service public class ProjectService { @@ -26,15 +34,24 @@ public class ProjectService { private final DeadlineService deadlineService; private final GrantRepository grantRepository; private final FileService fileService; + private final EventService eventService; + private final UserService userService; + private final PingService pingService; public ProjectService(ProjectRepository projectRepository, DeadlineService deadlineService, GrantRepository grantRepository, - FileService fileService) { + FileService fileService, + EventService eventService, + UserService userService, + PingService pingService) { this.projectRepository = projectRepository; this.deadlineService = deadlineService; this.grantRepository = grantRepository; this.fileService = fileService; + this.eventService = eventService; + this.userService = userService; + this.pingService = pingService; } public List findAll() { @@ -59,20 +76,48 @@ public class ProjectService { public Project create(ProjectDto projectDto) throws IOException { Project newProject = copyFromDto(new Project(), projectDto); newProject = projectRepository.save(newProject); + eventService.createFromObject(newProject, Collections.emptyList(), false, "проекта"); return newProject; } + @Transactional + public Project update(ProjectDto projectDto) throws IOException { + Project project = projectRepository.getOne(projectDto.getId()); + projectRepository.save(copyFromDto(project, projectDto)); + eventService.updateProjectDeadlines(project); + for (FileDataDto file : projectDto.getFiles().stream() + .filter(f -> f.isDeleted() && f.getId() != null) + .collect(toList())) { + fileService.delete(file.getId()); + } + return project; + } + + @Transactional + public boolean delete(Integer projectId) throws IOException { + if (projectRepository.existsById(projectId)) { + Project project = projectRepository.getOne(projectId); + projectRepository.delete(project); + return true; + } + return false; + } + private Project copyFromDto(Project project, ProjectDto projectDto) throws IOException { project.setDescription(projectDto.getDescription()); - project.setStatus(projectDto.getStatus() == null ? APPLICATION : projectDto.getStatus()); + project.setStatus(projectDto.getStatus() == null ? TECHNICAL_TASK : projectDto.getStatus()); project.setTitle(projectDto.getTitle()); if (projectDto.getGrant() != null && projectDto.getGrant().getId() != null) { project.setGrant(grantRepository.getOne(projectDto.getGrant().getId())); } project.setRepository(projectDto.getRepository()); project.setDeadlines(deadlineService.saveOrCreate(projectDto.getDeadlines())); - if (projectDto.getApplicationFileName() != null) { - project.setApplication(fileService.createFileFromTmp(projectDto.getApplicationFileName())); + project.setFiles(fileService.saveOrCreate(projectDto.getFiles().stream() + .filter(f -> !f.isDeleted()) + .collect(toList()))); + project.getGrants().clear(); + if (projectDto.getGrantIds() != null && !projectDto.getGrantIds().isEmpty()) { + projectDto.getGrantIds().forEach(grantIds -> project.getGrants().add(grantRepository.findGrantById(grantIds))); } return project; } @@ -85,12 +130,44 @@ public class ProjectService { } } - private Project update(ProjectDto projectDto) { - throw new RuntimeException("not implemented yet"); + public ProjectDto removeDeadline(ProjectDto projectDto, Integer deadlineId) { + if (deadlineId != null) { + projectDto.getRemovedDeadlineIds().add(deadlineId); + } + projectDto.getDeadlines().remove((int) deadlineId); + return projectDto; } public Project findById(Integer id) { return projectRepository.getOne(id); } + public List getProjectExecutors(ProjectDto projectDto) { + List users = userService.findAll(); + return users; + } + + @Transactional + public void ping(int projectId) throws IOException { + pingService.addPing(findById(projectId)); + } + + public List getAllGrants() { + List grants = convert(grantRepository.findAll(), GrantDto::new); + return grants; + } + + public List getProjectGrants(List grantIds) { + return convert(grantRepository.findAllById(grantIds), GrantDto::new); + } + + public void attachGrant(ProjectDto projectDto) { + if (!projectDto.getGrantIds().isEmpty()) { + projectDto.getGrants().clear(); + projectDto.setGrants(getProjectGrants(projectDto.getGrantIds())); + } else { + projectDto.getGrants().clear(); + } + } + } diff --git a/src/main/java/ru/ulstu/strategy/api/EntityCreateStrategy.java b/src/main/java/ru/ulstu/strategy/api/EntityCreateStrategy.java index 8449e10..8a14399 100644 --- a/src/main/java/ru/ulstu/strategy/api/EntityCreateStrategy.java +++ b/src/main/java/ru/ulstu/strategy/api/EntityCreateStrategy.java @@ -1,21 +1,21 @@ package ru.ulstu.strategy.api; -import ru.ulstu.core.model.UserContainer; +import ru.ulstu.core.model.UserActivity; import ru.ulstu.user.model.User; import java.util.List; import java.util.stream.Collectors; -public abstract class EntityCreateStrategy { +public abstract class EntityCreateStrategy { protected abstract List getActiveEntities(); protected abstract void createEntity(User user); - protected void createDefaultEntityIfNeed(List allUsers, List entities) { + protected void createDefaultEntityIfNeed(List allUsers, List entities) { allUsers.forEach(user -> { if (entities .stream() - .filter(entity -> entity.getUsers().contains(user)) + .filter(entity -> entity.getActivityUsers().contains(user)) .collect(Collectors.toSet()).isEmpty()) { createEntity(user); } diff --git a/src/main/java/ru/ulstu/students/controller/TaskController.java b/src/main/java/ru/ulstu/students/controller/TaskController.java index 50cb052..5d0f4e8 100644 --- a/src/main/java/ru/ulstu/students/controller/TaskController.java +++ b/src/main/java/ru/ulstu/students/controller/TaskController.java @@ -5,13 +5,16 @@ import org.springframework.ui.ModelMap; import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import ru.ulstu.deadline.model.Deadline; import ru.ulstu.students.model.Task; import ru.ulstu.students.model.TaskDto; +import ru.ulstu.students.model.TaskFilterDto; import ru.ulstu.students.service.TaskService; +import ru.ulstu.tags.model.Tag; import springfox.documentation.annotations.ApiIgnore; import javax.validation.Valid; @@ -35,16 +38,16 @@ public class TaskController { this.taskService = taskService; } - @GetMapping("/tasks") - public void getTasks(ModelMap modelMap) { - modelMap.put("tasks", taskService.findAllDto()); - } - @GetMapping("/dashboard") public void getDashboard(ModelMap modelMap) { modelMap.put("tasks", taskService.findAllDto()); } + @GetMapping("/tasks") + public void getTask(ModelMap modelMap) { + modelMap.put("filteredTasks", new TaskFilterDto(taskService.findAllDto(), null, null, null)); + } + @GetMapping("/task") public void getTask(ModelMap modelMap, @RequestParam(value = "id") Integer id) { if (id != null && id > 0) { @@ -54,6 +57,14 @@ public class TaskController { } } + @PostMapping("/tasks") + public void filterTasks(@Valid TaskFilterDto taskFilterDto, ModelMap modelMap) { + modelMap.put("filteredTasks", new TaskFilterDto(taskService.filter(taskFilterDto), + taskFilterDto.getStatus(), + taskFilterDto.getTag(), + taskFilterDto.getOrder())); + } + @PostMapping(value = "/task", params = "save") public String save(@Valid TaskDto taskDto, Errors errors) throws IOException { filterEmptyDeadlines(taskDto); @@ -77,11 +88,23 @@ public class TaskController { return TASK_PAGE; } + @GetMapping("/delete/{task-id}") + public String delete(@PathVariable("task-id") Integer taskId) throws IOException { + taskService.delete(taskId); + return String.format(REDIRECT_TO, TASKS_PAGE); + } + + @ModelAttribute("allStatuses") public List getTaskStatuses() { return taskService.getTaskStatuses(); } + @ModelAttribute("allTags") + public List getTags() { + return taskService.getTags(); + } + private void filterEmptyDeadlines(TaskDto taskDto) { taskDto.setDeadlines(taskDto.getDeadlines().stream() .filter(dto -> dto.getDate() != null || !isEmpty(dto.getDescription())) diff --git a/src/main/java/ru/ulstu/students/model/Scheduler.java b/src/main/java/ru/ulstu/students/model/Scheduler.java new file mode 100644 index 0000000..67005b1 --- /dev/null +++ b/src/main/java/ru/ulstu/students/model/Scheduler.java @@ -0,0 +1,49 @@ +package ru.ulstu.students.model; + +import org.springframework.format.annotation.DateTimeFormat; +import ru.ulstu.core.model.BaseEntity; + +import javax.persistence.Entity; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; +import java.util.Date; + +@Entity +@Table(name = "scheduler") +public class Scheduler extends BaseEntity { + + @OneToOne(optional = false) + @JoinColumn(name = "task_id") + private Task task; + + @Temporal(value = TemporalType.TIMESTAMP) + @DateTimeFormat(pattern = "yyyy-MM-dd") + private Date date; + + public Scheduler() { + } + + public Scheduler(Task task, Date date) { + this.task = task; + this.date = date; + } + + public Task getTask() { + return task; + } + + public void setTask(Task task) { + this.task = task; + } + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } +} diff --git a/src/main/java/ru/ulstu/students/model/Task.java b/src/main/java/ru/ulstu/students/model/Task.java index 5646ef3..9043387 100644 --- a/src/main/java/ru/ulstu/students/model/Task.java +++ b/src/main/java/ru/ulstu/students/model/Task.java @@ -3,8 +3,12 @@ package ru.ulstu.students.model; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; import ru.ulstu.core.model.BaseEntity; +import ru.ulstu.core.model.EventSource; import ru.ulstu.deadline.model.Deadline; import ru.ulstu.tags.model.Tag; +import ru.ulstu.timeline.model.Event; +import ru.ulstu.user.model.User; +import ru.ulstu.user.service.UserService; import javax.persistence.CascadeType; import javax.persistence.Column; @@ -19,13 +23,15 @@ import javax.persistence.OneToMany; import javax.persistence.OrderBy; import javax.persistence.Temporal; import javax.persistence.TemporalType; +import javax.persistence.Transient; import javax.validation.constraints.NotBlank; import java.util.ArrayList; +import java.util.Collections; import java.util.Date; import java.util.List; @Entity -public class Task extends BaseEntity { +public class Task extends BaseEntity implements EventSource { public enum TaskStatus { IN_WORK("В работе"), @@ -49,8 +55,19 @@ public class Task extends BaseEntity { private String description; + @Transient + private UserService userService; + + public Task() { + + } + + public Task(UserService userService) { + this.userService = userService; + } + @Enumerated(value = EnumType.STRING) - private ru.ulstu.students.model.Task.TaskStatus status = TaskStatus.IN_WORK; + private TaskStatus status = TaskStatus.IN_WORK; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinColumn(name = "task_id", unique = true) @@ -67,6 +84,7 @@ public class Task extends BaseEntity { private Date updateDate = new Date(); @ManyToMany(fetch = FetchType.EAGER) + @Fetch(FetchMode.SUBSELECT) @JoinTable(name = "task_tags", joinColumns = {@JoinColumn(name = "task_id")}, inverseJoinColumns = {@JoinColumn(name = "tag_id")}) @@ -76,6 +94,16 @@ public class Task extends BaseEntity { return title; } + @Override + public List getRecipients() { + return Collections.emptyList(); + } + + @Override + public void addObjectToEvent(Event event) { + event.setTask(this); + } + public void setTitle(String title) { this.title = title; } @@ -127,4 +155,5 @@ public class Task extends BaseEntity { public void setTags(List tags) { this.tags = tags; } + } diff --git a/src/main/java/ru/ulstu/students/model/TaskDto.java b/src/main/java/ru/ulstu/students/model/TaskDto.java index 5071dab..24ad204 100644 --- a/src/main/java/ru/ulstu/students/model/TaskDto.java +++ b/src/main/java/ru/ulstu/students/model/TaskDto.java @@ -10,6 +10,7 @@ import javax.validation.constraints.NotEmpty; import java.util.ArrayList; import java.util.Date; import java.util.List; +import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; @@ -26,7 +27,7 @@ public class TaskDto { private Date createDate; private Date updateDate; private Set tagIds; - private List tags; + private List tags = new ArrayList<>(); public TaskDto() { deadlines.add(new Deadline()); @@ -135,6 +136,29 @@ public class TaskDto { this.tags = tags; } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TaskDto taskDto = (TaskDto) o; + return Objects.equals(id, taskDto.id) && + Objects.equals(title, taskDto.title) && + Objects.equals(description, taskDto.description) && + status == taskDto.status && + Objects.equals(deadlines, taskDto.deadlines) && + Objects.equals(tagIds, taskDto.tagIds) && + Objects.equals(tags, taskDto.tags); + } + + @Override + public int hashCode() { + return Objects.hash(id, title, description, status, deadlines, createDate, updateDate, tagIds, tags); + } + public String getTagsString() { return StringUtils.abbreviate(tags .stream() diff --git a/src/main/java/ru/ulstu/students/model/TaskFilterDto.java b/src/main/java/ru/ulstu/students/model/TaskFilterDto.java new file mode 100644 index 0000000..21bd5ac --- /dev/null +++ b/src/main/java/ru/ulstu/students/model/TaskFilterDto.java @@ -0,0 +1,54 @@ +package ru.ulstu.students.model; + +import java.util.List; + +public class TaskFilterDto { + + private List tasks; + private Task.TaskStatus status; + private Integer tagId; + private String order; + + public TaskFilterDto(List tasks, Task.TaskStatus status, Integer tagId, String order) { + this.tasks = tasks; + this.status = status; + this.tagId = tagId; + this.order = order; + } + + public TaskFilterDto() { + + } + + public List getTasks() { + return tasks; + } + + public void setTasks(List tasks) { + this.tasks = tasks; + } + + public Task.TaskStatus getStatus() { + return status; + } + + public void setStatus(Task.TaskStatus status) { + this.status = status; + } + + public Integer getTag() { + return tagId; + } + + public void setTag(Integer tagId) { + this.tagId = tagId; + } + + public String getOrder() { + return order; + } + + public void setOrder(String order) { + this.order = order; + } +} diff --git a/src/main/java/ru/ulstu/students/repository/SchedulerRepository.java b/src/main/java/ru/ulstu/students/repository/SchedulerRepository.java new file mode 100644 index 0000000..7481692 --- /dev/null +++ b/src/main/java/ru/ulstu/students/repository/SchedulerRepository.java @@ -0,0 +1,11 @@ +package ru.ulstu.students.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import ru.ulstu.students.model.Scheduler; +import ru.ulstu.students.model.Task; + +public interface SchedulerRepository extends JpaRepository { + + Scheduler findOneByTask(Task task); + +} diff --git a/src/main/java/ru/ulstu/students/repository/TaskRepository.java b/src/main/java/ru/ulstu/students/repository/TaskRepository.java index 6f48d1f..af277d1 100644 --- a/src/main/java/ru/ulstu/students/repository/TaskRepository.java +++ b/src/main/java/ru/ulstu/students/repository/TaskRepository.java @@ -1,7 +1,27 @@ package ru.ulstu.students.repository; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import ru.ulstu.students.model.Task; +import ru.ulstu.tags.model.Tag; + +import java.util.Date; +import java.util.List; public interface TaskRepository extends JpaRepository { + + @Query("SELECT t FROM Task t WHERE (t.status = :status OR :status IS NULL) AND (:tag IS NULL OR :tag MEMBER OF t.tags) ORDER BY create_date DESC") + List filterNew(@Param("status") Task.TaskStatus status, @Param("tag") Tag tag); + + @Query("SELECT t FROM Task t WHERE (t.status = :status OR :status IS NULL) AND (:tag IS NULL OR :tag MEMBER OF t.tags) ORDER BY create_date ASC") + List filterOld(@Param("status") Task.TaskStatus status, @Param("tag") Tag tag); + + @Query("SELECT t FROM Task t WHERE(:tag IS NULL OR :tag MEMBER OF t.tags) ORDER BY create_date DESC") + List findByTag(@Param("tag") Tag tag); + + @Query("SELECT t FROM Task t WHERE (t.createDate >= :date) ORDER BY create_date DESC") + List findAllYear(@Param("date") Date date); + + } diff --git a/src/main/java/ru/ulstu/students/service/SchedulerService.java b/src/main/java/ru/ulstu/students/service/SchedulerService.java new file mode 100644 index 0000000..b192130 --- /dev/null +++ b/src/main/java/ru/ulstu/students/service/SchedulerService.java @@ -0,0 +1,116 @@ +package ru.ulstu.students.service; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import ru.ulstu.students.model.Scheduler; +import ru.ulstu.students.model.Task; +import ru.ulstu.students.repository.SchedulerRepository; +import ru.ulstu.tags.model.Tag; + +import java.util.Date; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +@Service +public class SchedulerService { + + private final TaskService taskService; + private final SchedulerRepository schedulerRepository; + + public SchedulerService(TaskService taskService, SchedulerRepository schedulerRepository) { + this.taskService = taskService; + this.schedulerRepository = schedulerRepository; + } + + + private void save(Tag tag) { + List taskList = taskService.findTasksByTag(tag); + create(taskList.get(0)); + } + + + @Transactional + private Scheduler create(Task task) { + Scheduler scheduler = new Scheduler(task, task.getDeadlines().get(task.getDeadlines().size() - 1).getDate()); + return schedulerRepository.save(scheduler); + } + + @Transactional + private void delete(Integer schedulerId) { + if (schedulerRepository.existsById(schedulerId)) { + schedulerRepository.deleteById(schedulerId); + } + } + + public void checkPlanToday() { + List schedulerList = schedulerRepository.findAll(); + if (!schedulerList.isEmpty()) { + doTodayPlanIfNeed(schedulerList); + schedulerList = schedulerRepository.findAll(); + } + checkNewPlan(schedulerList); + } + + private void checkNewPlan(List schedulerList) { + Set tags = taskService.checkRepeatingTags(true); + Set newTags = null; + if (!schedulerList.isEmpty()) { + newTags = checkNewTags(tags, schedulerList); + } else { + if (!tags.isEmpty()) { + newTags = tags; + } + } + + if (newTags != null) { + newTags.forEach(tag -> { + if (!hasNewTag(tag, schedulerList)) { + save(tag); + Task task = taskService.findTasksByTag(tag).get(0); + schedulerList.add(new Scheduler(task, task.getDeadlines().get(task.getDeadlines().size() - 1).getDate())); + } + }); + } + } + + private boolean hasNewTag(Tag tag, List schedulerList) { + + return schedulerList + .stream() + .anyMatch(scheduler -> scheduler.getTask().getTags().contains(tag)); + + } + + + private Set checkNewTags(Set tags, List schedulerList) { + Set newTags = tags + .stream() + .filter(tag -> schedulerList + .stream() + .anyMatch(scheduler -> + !scheduler.getTask().getTags().contains(tag))) + .collect(Collectors.toSet()); + if (!newTags.isEmpty()) { + return newTags; + } + return null; + } + + private void doTodayPlanIfNeed(List schedulerList) { + List plan = schedulerList + .stream() + .filter(scheduler -> scheduler.getDate().before(new Date())) + .collect(Collectors.toList()); + doToday(plan); + } + + private void doToday(List plan) { + plan.forEach(scheduler -> { + taskService.createPeriodTask(scheduler); + delete(scheduler.getId()); + }); + } + + +} diff --git a/src/main/java/ru/ulstu/students/service/TaskGenerationService.java b/src/main/java/ru/ulstu/students/service/TaskGenerationService.java new file mode 100644 index 0000000..1c04c20 --- /dev/null +++ b/src/main/java/ru/ulstu/students/service/TaskGenerationService.java @@ -0,0 +1,32 @@ +package ru.ulstu.students.service; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +@Service +public class TaskGenerationService { + + private final Logger log = LoggerFactory.getLogger(TaskGenerationService.class); + private final TaskService taskService; + private final SchedulerService schedulerService; + + public TaskGenerationService(TaskService taskService, SchedulerService schedulerService) { + + this.taskService = taskService; + this.schedulerService = schedulerService; + } + + @Scheduled(cron = "0 0 0 * * ?", zone = "Europe/Samara") + public void generateTasks() { + log.debug("SchedulerService.checkPlanToday started"); + schedulerService.checkPlanToday(); + log.debug("SchedulerService.checkPlanToday finished"); + + log.debug("TaskService.generateYearTasks started"); + taskService.generateYearTasks(); + log.debug("TaskService.generateYearTasks finished"); + } + +} diff --git a/src/main/java/ru/ulstu/students/service/TaskService.java b/src/main/java/ru/ulstu/students/service/TaskService.java index dac6ef5..a9b2505 100644 --- a/src/main/java/ru/ulstu/students/service/TaskService.java +++ b/src/main/java/ru/ulstu/students/service/TaskService.java @@ -1,18 +1,33 @@ package ru.ulstu.students.service; import org.apache.commons.lang3.StringUtils; +import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import ru.ulstu.core.util.DateUtils; +import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.service.DeadlineService; +import ru.ulstu.students.model.Scheduler; import ru.ulstu.students.model.Task; import ru.ulstu.students.model.TaskDto; +import ru.ulstu.students.model.TaskFilterDto; +import ru.ulstu.students.repository.SchedulerRepository; import ru.ulstu.students.repository.TaskRepository; +import ru.ulstu.tags.model.Tag; import ru.ulstu.tags.service.TagService; +import ru.ulstu.timeline.service.EventService; import java.io.IOException; +import java.util.ArrayList; import java.util.Arrays; +import java.util.Calendar; +import java.util.Collections; import java.util.Date; import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.stream.Collectors; import static org.springframework.util.ObjectUtils.isEmpty; import static ru.ulstu.core.util.StreamApiUtils.convert; @@ -24,18 +39,23 @@ public class TaskService { private final static int MAX_DISPLAY_SIZE = 40; private final TaskRepository taskRepository; + private final SchedulerRepository schedulerRepository; private final DeadlineService deadlineService; private final TagService tagService; + private final EventService eventService; - public TaskService(TaskRepository grantRepository, - DeadlineService deadlineService, TagService tagService) { - this.taskRepository = grantRepository; + + public TaskService(TaskRepository taskRepository, + DeadlineService deadlineService, TagService tagService, SchedulerRepository schedulerRepository, EventService eventService) { + this.taskRepository = taskRepository; this.deadlineService = deadlineService; this.tagService = tagService; + this.eventService = eventService; + this.schedulerRepository = schedulerRepository; } public List findAll() { - return taskRepository.findAll(); + return taskRepository.findAll(new Sort(Sort.Direction.DESC, "createDate")); } public List findAllDto() { @@ -48,10 +68,23 @@ public class TaskService { return new TaskDto(taskRepository.getOne(id)); } + public List filter(TaskFilterDto filterDto) { + if (filterDto.getOrder().compareTo("new") == 0) { + return convert(taskRepository.filterNew( + filterDto.getStatus(), + filterDto.getTag() == null ? null : tagService.findById(filterDto.getTag())), TaskDto::new); + } else { + return convert(taskRepository.filterOld( + filterDto.getStatus(), + filterDto.getTag() == null ? null : tagService.findById(filterDto.getTag())), TaskDto::new); + } + } + @Transactional public Integer create(TaskDto taskDto) throws IOException { Task newTask = copyFromDto(new Task(), taskDto); newTask = taskRepository.save(newTask); + eventService.createFromObject(newTask, Collections.emptyList(), true, "задачи"); return newTask.getId(); } @@ -71,13 +104,23 @@ public class TaskService { public Integer update(TaskDto taskDto) throws IOException { Task task = taskRepository.getOne(taskDto.getId()); taskRepository.save(copyFromDto(task, taskDto)); + eventService.updateTaskDeadlines(task); return task.getId(); } @Transactional - public void delete(Integer taskId) throws IOException { - Task task = taskRepository.getOne(taskId); - taskRepository.delete(task); + public boolean delete(Integer taskId) throws IOException { + if (taskRepository.existsById(taskId)) { + Task scheduleTask = taskRepository.getOne(taskId); + Scheduler sch = schedulerRepository.findOneByTask(scheduleTask); + if (sch != null) { + schedulerRepository.deleteById(sch.getId()); + } + taskRepository.deleteById(taskId); + return true; + } + return false; + } public void save(TaskDto taskDto) throws IOException { @@ -88,8 +131,128 @@ public class TaskService { } } + private void copyMainPart(Task newTask, Task task) { + newTask.setTitle(task.getTitle()); + newTask.setTags(tagService.saveOrCreate(task.getTags())); + newTask.setCreateDate(new Date()); + newTask.setStatus(Task.TaskStatus.LOADED_FROM_KIAS); + } + + private Task copyTaskWithNewDates(Task task) { + Task newTask = new Task(); + copyMainPart(newTask, task); + Calendar cal1 = DateUtils.getCalendar(newTask.getCreateDate()); + Calendar cal2 = DateUtils.getCalendar(task.getCreateDate()); + Integer interval = cal1.get(Calendar.DAY_OF_YEAR) - cal2.get(Calendar.DAY_OF_YEAR); + newTask.setDeadlines(newDatesDeadlines(task.getDeadlines(), interval)); + return newTask; + } + + private List newDatesDeadlines(List deadlines, Integer interval) { + return deadlines + .stream() + .map(deadline -> { + Deadline newDeadline = new Deadline(); + Date newDate = DateUtils.addDays(deadline.getDate(), interval); + newDeadline.setDescription(deadline.getDescription()); + newDeadline.setDate(newDate); + return deadlineService.create(newDeadline); + }).collect(Collectors.toList()); + } + + private Task copyTaskWithNewYear(Task task) { + Task newTask = new Task(); + copyMainPart(newTask, task); + newTask.setDeadlines(newYearDeadlines(task.getDeadlines())); + return newTask; + } + + private List newYearDeadlines(List deadlines) { + return deadlines + .stream() + .map(deadline -> { + Deadline newDeadline = new Deadline(); + newDeadline.setDescription(deadline.getDescription()); + newDeadline.setDate(DateUtils.addYears(deadline.getDate(), 1)); + return deadlineService.create(newDeadline); + }).collect(Collectors.toList()); + } + + private boolean equalsDate(Task task) { + Calendar taskDate = DateUtils.getCalendar(task.getCreateDate()); + Calendar nowDate = DateUtils.getCalendar(new Date()); + return (taskDate.get(Calendar.DAY_OF_MONTH) == nowDate.get(Calendar.DAY_OF_MONTH) && + taskDate.get(Calendar.MONTH) + 1 == nowDate.get(Calendar.MONTH) + 1 && + taskDate.get(Calendar.YEAR) + 1 == nowDate.get(Calendar.YEAR)); + } + + @Transactional + public List generateYearTasks() { + Set tags = checkRepeatingTags(false); + List tasks = new ArrayList<>(); + tags.forEach(tag -> { + Task singleTask = findTasksByTag(tag).get(0); + if (equalsDate(singleTask)) { + if (!tasks.contains(singleTask)) { + tasks.add(singleTask); + } + } + }); + if (tasks != null) { + tasks.forEach(task -> { + Task newTask = copyTaskWithNewYear(task); + taskRepository.save(newTask); + }); + return tasks; + } + return null; + } + + + @Transactional + public Set checkRepeatingTags(Boolean createPeriodTask) { //param: false = year task; true = period task + Map tagsCount = new TreeMap<>(); + List tags = tagService.getTags(); + List tasks = taskRepository.findAllYear(DateUtils.clearTime(DateUtils.addYears(new Date(), -1))); + tags.forEach(tag -> + tagsCount.put(tag, tasks + .stream() + .filter(task -> task.getTags().contains(tag)) + .count())); + if (!createPeriodTask) { + return tagsCount + .entrySet() + .stream() + .filter(tagLongEntry -> tagLongEntry.getValue() == 1) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)) + .keySet(); + } else { + return tagsCount + .entrySet() + .stream() + .filter(tagLongEntry -> tagLongEntry.getValue() >= 2) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)) + .keySet(); + } + + } + public List getTaskStatuses() { return Arrays.asList(Task.TaskStatus.values()); } + public List getTags() { + return tagService.getTags(); + } + + public List findTasksByTag(Tag tag) { + return taskRepository.findByTag(tag); + } + + @Transactional + public Task createPeriodTask(Scheduler scheduler) { + Task newTask = copyTaskWithNewDates(scheduler.getTask()); + taskRepository.save(newTask); + return newTask; + } } diff --git a/src/main/java/ru/ulstu/tags/model/Tag.java b/src/main/java/ru/ulstu/tags/model/Tag.java index 460e9b0..023cfb4 100644 --- a/src/main/java/ru/ulstu/tags/model/Tag.java +++ b/src/main/java/ru/ulstu/tags/model/Tag.java @@ -9,6 +9,7 @@ import javax.persistence.Entity; import javax.persistence.Table; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Size; +import java.util.Objects; @Entity @Table(name = "tag") @@ -41,4 +42,21 @@ public class Tag extends BaseEntity { public void setTagName(String tagName) { this.tagName = tagName; } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return tagName.equals(tag.tagName); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), tagName); + } } diff --git a/src/main/java/ru/ulstu/tags/service/TagService.java b/src/main/java/ru/ulstu/tags/service/TagService.java index ad5d227..b84d492 100644 --- a/src/main/java/ru/ulstu/tags/service/TagService.java +++ b/src/main/java/ru/ulstu/tags/service/TagService.java @@ -50,4 +50,12 @@ public class TagService { return newTag; } + public List getTags() { + return tagRepository.findAll(); + } + + public Tag findById(Integer tagId) { + return tagRepository.getOne(tagId); + } + } diff --git a/src/main/java/ru/ulstu/timeline/model/Event.java b/src/main/java/ru/ulstu/timeline/model/Event.java index f8fd179..2f714a3 100644 --- a/src/main/java/ru/ulstu/timeline/model/Event.java +++ b/src/main/java/ru/ulstu/timeline/model/Event.java @@ -1,7 +1,11 @@ package ru.ulstu.timeline.model; +import ru.ulstu.conference.model.Conference; import ru.ulstu.core.model.BaseEntity; +import ru.ulstu.grant.model.Grant; import ru.ulstu.paper.model.Paper; +import ru.ulstu.project.model.Project; +import ru.ulstu.students.model.Task; import ru.ulstu.user.model.User; import javax.persistence.CascadeType; @@ -18,6 +22,7 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; +import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -61,8 +66,8 @@ public class Event extends BaseEntity { private String description; - @ManyToMany(fetch = FetchType.EAGER) - private List recipients; + @ManyToMany(fetch = FetchType.LAZY) + private List recipients = new ArrayList<>(); @ManyToOne @JoinColumn(name = "child_id") @@ -76,6 +81,22 @@ public class Event extends BaseEntity { @JoinColumn(name = "paper_id") private Paper paper; + @ManyToOne + @JoinColumn(name = "conference_id") + private Conference conference; + + @ManyToOne + @JoinColumn(name = "grant_id") + private Grant grant; + + @ManyToOne + @JoinColumn(name = "project_id") + private Project project; + + @ManyToOne + @JoinColumn(name = "task_id") + private Task task; + public String getTitle() { return title; } @@ -163,4 +184,36 @@ public class Event extends BaseEntity { public void setPaper(Paper paper) { this.paper = paper; } + + public Conference getConference() { + return conference; + } + + public void setConference(Conference conference) { + this.conference = conference; + } + + public Grant getGrant() { + return grant; + } + + public void setGrant(Grant grant) { + this.grant = grant; + } + + public Project getProject() { + return project; + } + + public void setProject(Project project) { + this.project = project; + } + + public Task getTask() { + return task; + } + + public void setTask(Task task) { + this.task = task; + } } diff --git a/src/main/java/ru/ulstu/timeline/model/EventDto.java b/src/main/java/ru/ulstu/timeline/model/EventDto.java index 17e4623..7c3a836 100644 --- a/src/main/java/ru/ulstu/timeline/model/EventDto.java +++ b/src/main/java/ru/ulstu/timeline/model/EventDto.java @@ -2,10 +2,14 @@ package ru.ulstu.timeline.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; -import javax.validation.constraints.NotBlank; +import ru.ulstu.conference.model.ConferenceDto; +import ru.ulstu.grant.model.GrantDto; import ru.ulstu.paper.model.PaperDto; +import ru.ulstu.project.model.ProjectDto; +import ru.ulstu.students.model.TaskDto; import ru.ulstu.user.model.UserDto; +import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.util.Date; import java.util.List; @@ -25,6 +29,10 @@ public class EventDto { private final String description; private final List recipients; private PaperDto paperDto; + private ConferenceDto conferenceDto; + private GrantDto grantDto; + private ProjectDto projectDto; + private TaskDto taskDto; @JsonCreator public EventDto(@JsonProperty("id") Integer id, @@ -36,7 +44,11 @@ public class EventDto { @JsonProperty("updateDate") Date updateDate, @JsonProperty("description") String description, @JsonProperty("paperDto") PaperDto paperDto, - @JsonProperty("recipients") List recipients) { + @JsonProperty("recipients") List recipients, + @JsonProperty("conferenceDto") ConferenceDto conferenceDto, + @JsonProperty("grantDto") GrantDto grantDto, + @JsonProperty("projectDto") ProjectDto projectDto, + @JsonProperty("taskDto") TaskDto taskDto) { this.id = id; this.title = title; this.period = period; @@ -47,6 +59,10 @@ public class EventDto { this.description = description; this.recipients = recipients; this.paperDto = paperDto; + this.conferenceDto = conferenceDto; + this.grantDto = grantDto; + this.projectDto = projectDto; + this.taskDto = taskDto; } public EventDto(Event event) { @@ -58,8 +74,22 @@ public class EventDto { this.createDate = event.getCreateDate(); this.updateDate = event.getUpdateDate(); this.description = event.getDescription(); - this.paperDto = new PaperDto(event.getPaper()); this.recipients = convert(event.getRecipients(), UserDto::new); + if (paperDto != null) { + this.paperDto = new PaperDto(event.getPaper()); + } + if (conferenceDto != null) { + this.conferenceDto = new ConferenceDto(event.getConference()); + } + if (grantDto != null) { + this.grantDto = new GrantDto(event.getGrant()); + } + if (projectDto != null) { + this.projectDto = new ProjectDto(event.getProject()); + } + if (taskDto != null) { + this.taskDto = new TaskDto(event.getTask()); + } } public Integer getId() { @@ -105,4 +135,36 @@ public class EventDto { public void setPaperDto(PaperDto paperDto) { this.paperDto = paperDto; } + + public ConferenceDto getConferenceDto() { + return conferenceDto; + } + + public void setConferenceDto(ConferenceDto conferenceDto) { + this.conferenceDto = conferenceDto; + } + + public GrantDto getGrantDto() { + return grantDto; + } + + public void setGrantDto(GrantDto grantDto) { + this.grantDto = grantDto; + } + + public ProjectDto getProjectDto() { + return projectDto; + } + + public void setProjectDto(ProjectDto projectDto) { + this.projectDto = projectDto; + } + + public TaskDto getTaskDto() { + return taskDto; + } + + public void setTaskDto(TaskDto taskDto) { + this.taskDto = taskDto; + } } diff --git a/src/main/java/ru/ulstu/timeline/repository/EventRepository.java b/src/main/java/ru/ulstu/timeline/repository/EventRepository.java index eb5c08b..15e1355 100644 --- a/src/main/java/ru/ulstu/timeline/repository/EventRepository.java +++ b/src/main/java/ru/ulstu/timeline/repository/EventRepository.java @@ -2,7 +2,11 @@ package ru.ulstu.timeline.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; +import ru.ulstu.conference.model.Conference; +import ru.ulstu.grant.model.Grant; import ru.ulstu.paper.model.Paper; +import ru.ulstu.project.model.Project; +import ru.ulstu.students.model.Task; import ru.ulstu.timeline.model.Event; import java.util.List; @@ -15,4 +19,12 @@ public interface EventRepository extends JpaRepository { List findAllFuture(); List findAllByPaper(Paper paper); + + List findAllByConference(Conference conference); + + List findAllByGrant(Grant grant); + + List findAllByProject(Project project); + + List findAllByTask(Task task); } diff --git a/src/main/java/ru/ulstu/timeline/service/EventService.java b/src/main/java/ru/ulstu/timeline/service/EventService.java index a1f54f5..552b17c 100644 --- a/src/main/java/ru/ulstu/timeline/service/EventService.java +++ b/src/main/java/ru/ulstu/timeline/service/EventService.java @@ -4,8 +4,13 @@ import org.apache.commons.lang3.time.DateUtils; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import ru.ulstu.conference.model.Conference; +import ru.ulstu.core.model.EventSource; import ru.ulstu.deadline.model.Deadline; +import ru.ulstu.grant.model.Grant; import ru.ulstu.paper.model.Paper; +import ru.ulstu.project.model.Project; +import ru.ulstu.students.model.Task; import ru.ulstu.timeline.model.Event; import ru.ulstu.timeline.model.EventDto; import ru.ulstu.timeline.model.Timeline; @@ -13,7 +18,7 @@ import ru.ulstu.timeline.repository.EventRepository; import ru.ulstu.user.model.UserDto; import ru.ulstu.user.service.UserService; -import java.util.ArrayList; +import java.util.Collections; import java.util.Date; import java.util.List; import java.util.stream.Collectors; @@ -100,33 +105,40 @@ public class EventService { } public void createFromPaper(Paper newPaper) { + createFromObject(newPaper, Collections.emptyList(), false, "статьи"); + } + + public void createFromObject(EventSource eventSource, List events, Boolean addCurrentUser, String suffix) { List timelines = timelineService.findAll(); Timeline timeline = timelines.isEmpty() ? new Timeline() : timelines.get(0); - for (Deadline deadline : newPaper.getDeadlines() + timeline.getEvents().removeAll(events); + for (Deadline deadline : eventSource.getDeadlines() .stream() .filter(d -> d.getDate().after(new Date()) || DateUtils.isSameDay(d.getDate(), new Date())) .collect(Collectors.toList())) { Event newEvent = new Event(); - newEvent.setTitle("Дедлайн статьи"); + newEvent.setTitle("Дедлайн " + suffix); newEvent.setStatus(Event.EventStatus.NEW); newEvent.setExecuteDate(deadline.getDate()); newEvent.setCreateDate(new Date()); newEvent.setUpdateDate(new Date()); - newEvent.setDescription("Дедлайн '" + deadline.getDescription() + "' cтатьи '" + newPaper.getTitle() + "'"); - newEvent.setRecipients(new ArrayList(newPaper.getAuthors())); - newEvent.setPaper(newPaper); - eventRepository.save(newEvent); - - timeline.getEvents().add(newEvent); - timelineService.save(timeline); + newEvent.setDescription("Дедлайн '" + deadline.getDescription() + "' " + suffix + " '" + + eventSource.getTitle() + "'"); + if (addCurrentUser) { + newEvent.getRecipients().add(userService.getCurrentUser()); + } + newEvent.setRecipients(eventSource.getRecipients()); + eventSource.addObjectToEvent(newEvent); + timeline.getEvents().add(eventRepository.save(newEvent)); } + timelineService.save(timeline); } public void updatePaperDeadlines(Paper paper) { - eventRepository.deleteAll(eventRepository.findAllByPaper(paper)); - - createFromPaper(paper); + List foundEvents = eventRepository.findAllByPaper(paper); + eventRepository.deleteAll(foundEvents); + createFromObject(paper, foundEvents, false, "статьи"); } public List findByCurrentDate() { @@ -140,4 +152,29 @@ public class EventService { public List findAllFutureDto() { return convert(findAllFuture(), EventDto::new); } -} + + public void updateConferenceDeadlines(Conference conference) { + eventRepository.deleteAll(eventRepository.findAllByConference(conference)); + createFromObject(conference, Collections.emptyList(), false, "конференции"); + } + + public void updateGrantDeadlines(Grant grant) { + eventRepository.deleteAll(eventRepository.findAllByGrant(grant)); + createFromObject(grant, Collections.emptyList(), false, "гранта"); + } + + public void updateProjectDeadlines(Project project) { + eventRepository.deleteAll(eventRepository.findAllByProject(project)); + createFromObject(project, Collections.emptyList(), false, "проекта"); + } + + public void removeConferencesEvent(Conference conference) { + List eventList = eventRepository.findAllByConference(conference); + eventList.forEach(event -> eventRepository.deleteById(event.getId())); + } + + public void updateTaskDeadlines(Task task) { + eventRepository.deleteAll(eventRepository.findAllByTask(task)); + createFromObject(task, Collections.emptyList(), true, "задачи"); + } +} \ No newline at end of file diff --git a/src/main/java/ru/ulstu/user/controller/UserController.java b/src/main/java/ru/ulstu/user/controller/UserController.java index d7db909..d080d54 100644 --- a/src/main/java/ru/ulstu/user/controller/UserController.java +++ b/src/main/java/ru/ulstu/user/controller/UserController.java @@ -19,6 +19,7 @@ import ru.ulstu.odin.controller.OdinController; import ru.ulstu.odin.model.OdinMetadata; import ru.ulstu.odin.model.OdinVoid; import ru.ulstu.odin.service.OdinService; +import ru.ulstu.user.model.User; import ru.ulstu.user.model.UserDto; import ru.ulstu.user.model.UserListDto; import ru.ulstu.user.model.UserResetPasswordDto; @@ -28,7 +29,10 @@ import ru.ulstu.user.model.UserSessionListDto; import ru.ulstu.user.service.UserService; import ru.ulstu.user.service.UserSessionService; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; import javax.validation.Valid; +import java.util.Map; import static ru.ulstu.user.controller.UserController.URL; @@ -141,30 +145,39 @@ public class UserController extends OdinController { return new Response<>(userService.activateUser(activationKey)); } - // TODO: add page for user edit (user-profile) - @PostMapping("/change-information") - public Response changeInformation(@Valid @RequestBody UserDto userDto) { - log.debug("REST: UserController.changeInformation( {} )", userDto.getLogin()); - return new Response<>(userService.updateUserInformation(userDto)); + @PostMapping(PASSWORD_RESET_REQUEST_URL) + public void requestPasswordReset(@RequestParam("email") String email) { + log.debug("REST: UserController.requestPasswordReset( {} )", email); + userService.requestUserPasswordReset(email); } - // TODO: add page for user password change (user-profile) - @PostMapping("/change-password") - public Response changePassword(@Valid @RequestBody UserDto userDto) { - log.debug("REST: UserController.changePassword( {} )", userDto.getLogin()); - return new Response<>(userService.changeUserPassword(userDto)); + @PostMapping(PASSWORD_RESET_URL) + public Response finishPasswordReset(@RequestBody UserResetPasswordDto userResetPasswordDto) { + log.debug("REST: UserController.requestPasswordReset( {} )", userResetPasswordDto.getResetKey()); + return new Response<>(userService.completeUserPasswordReset(userResetPasswordDto)); } - @PostMapping(PASSWORD_RESET_REQUEST_URL) - public Response requestPasswordReset(@RequestParam("email") String email) { - log.debug("REST: UserController.requestPasswordReset( {} )", email); - return new Response<>(userService.requestUserPasswordReset(email)); + @PostMapping("/changePassword") + public void changePassword(@RequestBody Map payload, HttpServletRequest request) { + HttpSession session = request.getSession(false); + final String sessionId = session.getAttribute(Constants.SESSION_ID_ATTR).toString(); + User user = userSessionService.getUserBySessionId(sessionId); + userService.changeUserPassword(user, payload); } - @PostMapping(PASSWORD_RESET_URL) - public Response finishPasswordReset(@RequestParam("key") String key, - @RequestBody UserResetPasswordDto userResetPasswordDto) { - log.debug("REST: UserController.requestPasswordReset( {} )", key); - return new Response<>(userService.completeUserPasswordReset(key, userResetPasswordDto)); + @PostMapping("/invite") + public void inviteUser(@RequestParam("email") String email) { + userService.inviteUser(email); + } + + @GetMapping("/activities/pings") + public Response> getActivitesStats(@RequestParam(value = "userId", required = false) Integer userId, + @RequestParam(value = "activity", required = false) String activity) { + return new Response<>(userService.getActivitiesPings(userId, activity)); + } + + @PostMapping("/block") + public void blockUser(@RequestParam("userId") Integer userId) { + userService.blockUser(userId); } } diff --git a/src/main/java/ru/ulstu/user/controller/UserMvcController.java b/src/main/java/ru/ulstu/user/controller/UserMvcController.java new file mode 100644 index 0000000..bf84176 --- /dev/null +++ b/src/main/java/ru/ulstu/user/controller/UserMvcController.java @@ -0,0 +1,81 @@ +package ru.ulstu.user.controller; + +import com.google.common.collect.ImmutableMap; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import ru.ulstu.configuration.Constants; +import ru.ulstu.odin.controller.OdinController; +import ru.ulstu.user.model.User; +import ru.ulstu.user.model.UserDto; +import ru.ulstu.user.model.UserListDto; +import ru.ulstu.user.service.UserService; +import ru.ulstu.user.service.UserSessionService; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import java.util.List; +import java.util.Map; + +@Controller +@RequestMapping(value = "/users") +public class UserMvcController extends OdinController { + + private final Logger log = LoggerFactory.getLogger(UserMvcController.class); + + private final UserService userService; + private final UserSessionService userSessionService; + + public UserMvcController(UserService userService, + UserSessionService userSessionService) { + super(UserListDto.class, UserDto.class); + this.userService = userService; + this.userSessionService = userSessionService; + } + + @GetMapping("/profile") + public void getUserProfile(ModelMap modelMap, HttpServletRequest request) { + HttpSession session = request.getSession(false); + final String sessionId = session.getAttribute(Constants.SESSION_ID_ATTR).toString(); + modelMap.addAttribute("userDto", new UserDto(userSessionService.getUserBySessionId(sessionId))); + } + + @PostMapping("/profile") + public void updateUserProfile(ModelMap modelMap, HttpServletRequest request, UserDto userDto) { + HttpSession session = request.getSession(false); + final String sessionId = session.getAttribute(Constants.SESSION_ID_ATTR).toString(); + User user = userSessionService.getUserBySessionId(sessionId); + modelMap.addAttribute("userDto", userService.updateUserInformation(user, userDto)); + } + + @GetMapping("/dashboard") + public void getUsersDashboard(ModelMap modelMap) { + modelMap.addAllAttributes(userService.getUsersInfo()); + } + + @ModelAttribute("allUsers") + public List getAllUsers() { + return userService.findAll(); + } + + @ModelAttribute("allActivities") + public Map getAllActivites() { + return ImmutableMap.of("PAPER", "Статьи", + "GRANT", "Гранты", + "PROJECT", "Проекты", + "CONFERENCE", "Конференции"); + } + + @GetMapping("/pings") + public void getPings() { + } + + @GetMapping("/block") + public void getBlock() { + } +} diff --git a/src/main/java/ru/ulstu/user/error/UserBlockedException.java b/src/main/java/ru/ulstu/user/error/UserBlockedException.java new file mode 100644 index 0000000..23b9b3a --- /dev/null +++ b/src/main/java/ru/ulstu/user/error/UserBlockedException.java @@ -0,0 +1,9 @@ +package ru.ulstu.user.error; + +import org.springframework.security.core.AuthenticationException; + +public class UserBlockedException extends AuthenticationException { + public UserBlockedException(String message) { + super(message); + } +} diff --git a/src/main/java/ru/ulstu/user/error/UserPasswordsNotValidOrNotMatchException.java b/src/main/java/ru/ulstu/user/error/UserPasswordsNotValidOrNotMatchException.java index 088f999..3edc1fa 100644 --- a/src/main/java/ru/ulstu/user/error/UserPasswordsNotValidOrNotMatchException.java +++ b/src/main/java/ru/ulstu/user/error/UserPasswordsNotValidOrNotMatchException.java @@ -1,6 +1,7 @@ package ru.ulstu.user.error; public class UserPasswordsNotValidOrNotMatchException extends RuntimeException { - public UserPasswordsNotValidOrNotMatchException() { + public UserPasswordsNotValidOrNotMatchException(String message) { + super(message); } } diff --git a/src/main/java/ru/ulstu/user/error/UserSendingMailException.java b/src/main/java/ru/ulstu/user/error/UserSendingMailException.java new file mode 100644 index 0000000..576e834 --- /dev/null +++ b/src/main/java/ru/ulstu/user/error/UserSendingMailException.java @@ -0,0 +1,7 @@ +package ru.ulstu.user.error; + +public class UserSendingMailException extends RuntimeException { + public UserSendingMailException(String message) { + super(message); + } +} diff --git a/src/main/java/ru/ulstu/user/model/User.java b/src/main/java/ru/ulstu/user/model/User.java index fcfd88e..6507534 100644 --- a/src/main/java/ru/ulstu/user/model/User.java +++ b/src/main/java/ru/ulstu/user/model/User.java @@ -11,6 +11,7 @@ import javax.persistence.Enumerated; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; +import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; @@ -26,7 +27,7 @@ import java.util.Set; @Entity @Table(name = "users") public class User extends BaseEntity { - private final static String USER_ABBREVIATE_TEMPLATE = "%s %s%s"; + private final static String USER_ABBREVIATE_TEMPLATE = "%s %s %s"; @NotNull @Pattern(regexp = Constants.LOGIN_REGEX) @@ -91,6 +92,10 @@ public class User extends BaseEntity { @Temporal(TemporalType.TIMESTAMP) private Date birthDate; + @ManyToOne() + @JoinColumn(name = "blocker_id") + private User blocker; + public enum UserDegree { CANDIDATE("Кандидат технических наук"), DOCTOR("Доктор технических наук"); @@ -229,10 +234,18 @@ public class User extends BaseEntity { this.degree = degree; } + public User getBlocker() { + return blocker; + } + + public void setBlocker(User blocker) { + this.blocker = blocker; + } + public String getUserAbbreviate() { return String.format(USER_ABBREVIATE_TEMPLATE, lastName == null ? "" : lastName, - firstName == null ? "" : firstName.substring(0, 1) + ".", - patronymic == null ? "" : patronymic.substring(0, 1) + "."); + firstName == null ? "" : firstName.substring(0, 1), + patronymic == null ? "" : patronymic.substring(0, 1)); } } diff --git a/src/main/java/ru/ulstu/user/model/UserInfoNow.java b/src/main/java/ru/ulstu/user/model/UserInfoNow.java new file mode 100644 index 0000000..7d69c56 --- /dev/null +++ b/src/main/java/ru/ulstu/user/model/UserInfoNow.java @@ -0,0 +1,50 @@ +package ru.ulstu.user.model; + +import ru.ulstu.conference.model.Conference; +import ru.ulstu.utils.timetable.model.Lesson; + +public class UserInfoNow { + private Lesson lesson; + private Conference conference; + private User user; + private boolean isOnline; + + public UserInfoNow(Lesson lesson, Conference conference, User user, boolean isOnline) { + this.lesson = lesson; + this.conference = conference; + this.user = user; + this.isOnline = isOnline; + } + + public Lesson getLesson() { + return lesson; + } + + public void setLesson(Lesson lesson) { + this.lesson = lesson; + } + + public Conference getConference() { + return conference; + } + + public void setConference(Conference conference) { + this.conference = conference; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public boolean isOnline() { + return isOnline; + } + + public void setOnline(boolean online) { + isOnline = online; + } +} diff --git a/src/main/java/ru/ulstu/user/model/UserResetPasswordDto.java b/src/main/java/ru/ulstu/user/model/UserResetPasswordDto.java index 6da2813..58e76ff 100644 --- a/src/main/java/ru/ulstu/user/model/UserResetPasswordDto.java +++ b/src/main/java/ru/ulstu/user/model/UserResetPasswordDto.java @@ -14,6 +14,10 @@ public class UserResetPasswordDto { @Size(min = Constants.MIN_PASSWORD_LENGTH, max = 50) private String passwordConfirm; + @NotEmpty + @Size(min = Constants.RESET_KEY_LENGTH) + private String resetKey; + public String getPassword() { return password; } @@ -25,4 +29,8 @@ public class UserResetPasswordDto { public boolean isPasswordsValid() { return Objects.equals(password, passwordConfirm); } + + public String getResetKey() { + return resetKey; + } } diff --git a/src/main/java/ru/ulstu/user/repository/UserSessionRepository.java b/src/main/java/ru/ulstu/user/repository/UserSessionRepository.java index b922e4f..5319245 100644 --- a/src/main/java/ru/ulstu/user/repository/UserSessionRepository.java +++ b/src/main/java/ru/ulstu/user/repository/UserSessionRepository.java @@ -1,6 +1,7 @@ package ru.ulstu.user.repository; import org.springframework.data.jpa.repository.JpaRepository; +import ru.ulstu.user.model.User; import ru.ulstu.user.model.UserSession; import java.util.Date; @@ -10,4 +11,6 @@ public interface UserSessionRepository extends JpaRepository findAllByLogoutTimeIsNullAndLoginTimeBefore(Date date); + + List findAllByUserAndLogoutTimeIsNullAndLoginTimeBefore(User user, Date date); } diff --git a/src/main/java/ru/ulstu/user/service/MailService.java b/src/main/java/ru/ulstu/user/service/MailService.java index 77be5e7..7c83bfb 100644 --- a/src/main/java/ru/ulstu/user/service/MailService.java +++ b/src/main/java/ru/ulstu/user/service/MailService.java @@ -1,8 +1,10 @@ package ru.ulstu.user.service; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.autoconfigure.mail.MailProperties; +import org.springframework.mail.MailException; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.scheduling.annotation.Async; @@ -13,6 +15,7 @@ import ru.ulstu.configuration.ApplicationProperties; import ru.ulstu.configuration.Constants; import ru.ulstu.user.model.User; +import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.nio.charset.StandardCharsets; import java.util.Map; @@ -36,23 +39,23 @@ public class MailService { } @Async - public void sendEmail(String to, String subject, String content) { + public void sendEmail(String to, String subject, String content) throws MessagingException, MailException { log.debug("Send email to '{}' with subject '{}'", to, subject); MimeMessage mimeMessage = javaMailSender.createMimeMessage(); - try { - MimeMessageHelper message = new MimeMessageHelper(mimeMessage, false, StandardCharsets.UTF_8.name()); - message.setTo(to); - message.setFrom(mailProperties.getUsername()); - message.setSubject(subject); - message.setText(content, true); - javaMailSender.send(mimeMessage); - log.debug("Sent email to User '{}'", to); - } catch (Exception e) { - if (log.isDebugEnabled()) { - log.warn("Email could not be sent to user '{}'", to, e); - } else { - log.warn("Email could not be sent to user '{}': {}", to, e.getMessage()); - } + MimeMessageHelper message = new MimeMessageHelper(mimeMessage, false, StandardCharsets.UTF_8.name()); + message.setTo(to); + message.setFrom(mailProperties.getUsername()); + message.setSubject(subject); + message.setText(content, true); + modifyForDebug(message, subject); + javaMailSender.send(mimeMessage); + log.debug("Sent email to User '{}'", to); + } + + private void modifyForDebug(MimeMessageHelper message, String originalSubject) throws MessagingException { + if (!StringUtils.isEmpty(applicationProperties.getDebugEmail())) { + message.setTo(applicationProperties.getDebugEmail()); + message.setSubject("To " + applicationProperties.getDebugEmail() + "; " + originalSubject); } } @@ -62,7 +65,17 @@ public class MailService { context.setVariable(USER, user); context.setVariable(BASE_URL, applicationProperties.getBaseUrl()); String content = templateEngine.process(templateName, context); - sendEmail(user.getEmail(), subject, content); + try { + sendEmail(user.getEmail(), subject, content); + } catch ( + Exception e) { + if (log.isDebugEnabled()) { + log.warn("Email could not be sent to user '{}'", user.getEmail(), e); + } else { + log.warn("Email could not be sent to user '{}': {}", user.getEmail(), e.getMessage()); + } + } + } //Todo: выделить сервис нотификаций @@ -73,7 +86,26 @@ public class MailService { context.setVariable(USER, user); context.setVariable(BASE_URL, applicationProperties.getBaseUrl()); String content = templateEngine.process(templateName, context); - sendEmail(user.getEmail(), subject, content); + try { + sendEmail(user.getEmail(), subject, content); + } catch ( + Exception e) { + if (log.isDebugEnabled()) { + log.warn("Email could not be sent to user '{}'", user.getEmail(), e); + } else { + log.warn("Email could not be sent to user '{}': {}", user.getEmail(), e.getMessage()); + } + } + } + + @Async + public void sendEmailFromTemplate(Map variables, String templateName, String subject, String email) + throws MessagingException { + Context context = new Context(); + variables.entrySet().forEach(entry -> context.setVariable(entry.getKey(), entry.getValue())); + context.setVariable(BASE_URL, applicationProperties.getBaseUrl()); + String content = templateEngine.process(templateName, context); + sendEmail(email, subject, content); } @Async @@ -81,8 +113,16 @@ public class MailService { sendEmailFromTemplate(user, "activationEmail", Constants.MAIL_ACTIVATE); } - @Async - public void sendPasswordResetMail(User user) { + public void sendPasswordResetMail(User user) throws MessagingException, MailException { sendEmailFromTemplate(user, "passwordResetEmail", Constants.MAIL_RESET); } + + public void sendInviteMail(Map variables, String email) throws MessagingException, MailException { + sendEmailFromTemplate(variables, "userInviteEmail", Constants.MAIL_INVITE, email); + } + + @Async + public void sendChangePasswordMail(User user) { + sendEmailFromTemplate(user, "passwordChangeEmail", Constants.MAIL_CHANGE_PASSWORD); + } } diff --git a/src/main/java/ru/ulstu/user/service/UserService.java b/src/main/java/ru/ulstu/user/service/UserService.java index f92d2e3..8bad06e 100644 --- a/src/main/java/ru/ulstu/user/service/UserService.java +++ b/src/main/java/ru/ulstu/user/service/UserService.java @@ -1,9 +1,12 @@ package ru.ulstu.user.service; +import com.google.common.collect.ImmutableMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.Lazy; import org.springframework.data.domain.Page; import org.springframework.data.domain.Sort; +import org.springframework.mail.MailException; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; @@ -12,12 +15,17 @@ import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; +import ru.ulstu.conference.service.ConferenceService; import ru.ulstu.configuration.ApplicationProperties; import ru.ulstu.core.error.EntityIdIsNullException; import ru.ulstu.core.jpa.OffsetablePageRequest; import ru.ulstu.core.model.BaseEntity; +import ru.ulstu.core.model.UserActivity; import ru.ulstu.core.model.response.PageableItems; +import ru.ulstu.ping.model.Ping; +import ru.ulstu.ping.service.PingService; import ru.ulstu.user.error.UserActivationError; +import ru.ulstu.user.error.UserBlockedException; import ru.ulstu.user.error.UserEmailExistsException; import ru.ulstu.user.error.UserIdExistsException; import ru.ulstu.user.error.UserIsUndeadException; @@ -26,8 +34,10 @@ import ru.ulstu.user.error.UserNotActivatedException; import ru.ulstu.user.error.UserNotFoundException; import ru.ulstu.user.error.UserPasswordsNotValidOrNotMatchException; import ru.ulstu.user.error.UserResetKeyError; +import ru.ulstu.user.error.UserSendingMailException; import ru.ulstu.user.model.User; import ru.ulstu.user.model.UserDto; +import ru.ulstu.user.model.UserInfoNow; import ru.ulstu.user.model.UserListDto; import ru.ulstu.user.model.UserResetPasswordDto; import ru.ulstu.user.model.UserRole; @@ -36,11 +46,19 @@ import ru.ulstu.user.model.UserRoleDto; import ru.ulstu.user.repository.UserRepository; import ru.ulstu.user.repository.UserRoleRepository; import ru.ulstu.user.util.UserUtils; +import ru.ulstu.utils.timetable.TimetableService; +import ru.ulstu.utils.timetable.errors.TimetableClientException; +import ru.ulstu.utils.timetable.model.Lesson; +import javax.mail.MessagingException; +import java.text.ParseException; +import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; @@ -49,6 +67,8 @@ import java.util.stream.Collectors; @Service @Transactional public class UserService implements UserDetailsService { + private static final String INVITE_USER_EXCEPTION = "Во время отправки приглашения произошла ошибка"; + private final Logger log = LoggerFactory.getLogger(UserService.class); private final UserRepository userRepository; private final PasswordEncoder passwordEncoder; @@ -56,19 +76,30 @@ public class UserService implements UserDetailsService { private final UserMapper userMapper; private final MailService mailService; private final ApplicationProperties applicationProperties; + private final TimetableService timetableService; + private final ConferenceService conferenceService; + private final UserSessionService userSessionService; + private final PingService pingService; public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder, UserRoleRepository userRoleRepository, UserMapper userMapper, MailService mailService, - ApplicationProperties applicationProperties) { + ApplicationProperties applicationProperties, + @Lazy PingService pingService, + @Lazy ConferenceService conferenceRepository, + @Lazy UserSessionService userSessionService) throws ParseException { this.userRepository = userRepository; this.passwordEncoder = passwordEncoder; this.userRoleRepository = userRoleRepository; this.userMapper = userMapper; this.mailService = mailService; this.applicationProperties = applicationProperties; + this.conferenceService = conferenceRepository; + this.timetableService = new TimetableService(); + this.userSessionService = userSessionService; + this.pingService = pingService; } private User getUserByEmail(String email) { @@ -123,7 +154,7 @@ public class UserService implements UserDetailsService { throw new UserEmailExistsException(userDto.getEmail()); } if (!userDto.isPasswordsValid()) { - throw new UserPasswordsNotValidOrNotMatchException(); + throw new UserPasswordsNotValidOrNotMatchException(""); } User user = userMapper.userDtoToUserEntity(userDto); user.setActivated(false); @@ -193,10 +224,10 @@ public class UserService implements UserDetailsService { : roles); if (!StringUtils.isEmpty(userDto.getOldPassword())) { if (!userDto.isPasswordsValid() || !userDto.isOldPasswordValid()) { - throw new UserPasswordsNotValidOrNotMatchException(); + throw new UserPasswordsNotValidOrNotMatchException(""); } if (!passwordEncoder.matches(userDto.getOldPassword(), user.getPassword())) { - throw new UserPasswordsNotValidOrNotMatchException(); + throw new UserPasswordsNotValidOrNotMatchException(""); } user.setPassword(passwordEncoder.encode(userDto.getPassword())); log.debug("Changed password for User: {}", user.getLogin()); @@ -206,46 +237,28 @@ public class UserService implements UserDetailsService { return userMapper.userEntityToUserDto(user); } - public UserDto updateUserInformation(UserDto userDto) { - if (userDto.getId() == null) { - throw new EntityIdIsNullException(); - } - if (!Objects.equals( - Optional.ofNullable(getUserByEmail(userDto.getEmail())) - .map(BaseEntity::getId).orElse(userDto.getId()), - userDto.getId())) { - throw new UserEmailExistsException(userDto.getEmail()); - } - User user = userRepository.getOne(userDto.getId()); - if (user == null) { - throw new UserNotFoundException(userDto.getId().toString()); - } - user.setFirstName(userDto.getFirstName()); - user.setLastName(userDto.getLastName()); - user.setEmail(userDto.getEmail()); + public UserDto updateUserInformation(User user, UserDto updateUser) { + user.setFirstName(updateUser.getFirstName()); + user.setLastName(updateUser.getLastName()); + user.setEmail(updateUser.getEmail()); + user.setLogin(updateUser.getLogin()); user = userRepository.save(user); log.debug("Updated Information for User: {}", user.getLogin()); return userMapper.userEntityToUserDto(user); } - public UserDto changeUserPassword(UserDto userDto) { - if (userDto.getId() == null) { - throw new EntityIdIsNullException(); - } - if (!userDto.isPasswordsValid() || !userDto.isOldPasswordValid()) { - throw new UserPasswordsNotValidOrNotMatchException(); - } - final String login = UserUtils.getCurrentUserLogin(SecurityContextHolder.getContext()); - final User user = userRepository.findOneByLoginIgnoreCase(login); - if (user == null) { - throw new UserNotFoundException(login); + public void changeUserPassword(User user, Map payload) { + if (!payload.get("password").equals(payload.get("confirmPassword"))) { + throw new UserPasswordsNotValidOrNotMatchException(""); } - if (!passwordEncoder.matches(userDto.getOldPassword(), user.getPassword())) { - throw new UserPasswordsNotValidOrNotMatchException(); + if (!passwordEncoder.matches(payload.get("oldPassword"), user.getPassword())) { + throw new UserPasswordsNotValidOrNotMatchException("Старый пароль введен неправильно"); } - user.setPassword(passwordEncoder.encode(userDto.getPassword())); + user.setPassword(passwordEncoder.encode(payload.get("password"))); log.debug("Changed password for User: {}", user.getLogin()); - return userMapper.userEntityToUserDto(userRepository.save(user)); + userRepository.save(user); + + mailService.sendChangePasswordMail(user); } public boolean requestUserPasswordReset(String email) { @@ -259,23 +272,30 @@ public class UserService implements UserDetailsService { user.setResetKey(UserUtils.generateResetKey()); user.setResetDate(new Date()); user = userRepository.save(user); - mailService.sendPasswordResetMail(user); + try { + mailService.sendPasswordResetMail(user); + } catch (MessagingException | MailException e) { + throw new UserSendingMailException(email); + } log.debug("Created Reset Password Request for User: {}", user.getLogin()); return true; } - public boolean completeUserPasswordReset(String key, UserResetPasswordDto userResetPasswordDto) { + public boolean completeUserPasswordReset(UserResetPasswordDto userResetPasswordDto) { if (!userResetPasswordDto.isPasswordsValid()) { - throw new UserPasswordsNotValidOrNotMatchException(); + throw new UserPasswordsNotValidOrNotMatchException("Пароли не совпадают"); } - User user = userRepository.findOneByResetKey(key); + User user = userRepository.findOneByResetKey(userResetPasswordDto.getResetKey()); if (user == null) { - throw new UserResetKeyError(key); + throw new UserResetKeyError(userResetPasswordDto.getResetKey()); } user.setPassword(passwordEncoder.encode(userResetPasswordDto.getPassword())); user.setResetKey(null); user.setResetDate(null); user = userRepository.save(user); + + mailService.sendChangePasswordMail(user); + log.debug("Reset Password for User: {}", user.getLogin()); return true; } @@ -302,6 +322,9 @@ public class UserService implements UserDetailsService { if (!user.getActivated()) { throw new UserNotActivatedException(); } + if (user.getBlocker() != null) { + throw new UserBlockedException(String.format("Вы заблокированы пользователем %s", user.getBlocker().getUserAbbreviate())); + } return new org.springframework.security.core.userdetails.User(user.getLogin(), user.getPassword(), Optional.ofNullable(user.getRoles()).orElse(Collections.emptySet()).stream() @@ -329,4 +352,84 @@ public class UserService implements UserDetailsService { public List filterByAgeAndDegree(boolean hasDegree, boolean hasAge) { return userRepository.filterByAgeAndDegree(hasDegree, hasAge); } + + public void inviteUser(String email) throws UserSendingMailException { + if (userRepository.findOneByEmailIgnoreCase(email) != null) { + throw new UserEmailExistsException(email); + } + + String password = UserUtils.generatePassword(); + + User user = new User(); + user.setPassword(passwordEncoder.encode(password)); + user.setLogin(email); + user.setEmail(email); + user.setFirstName("user"); + user.setLastName("user"); + user.setActivated(true); + userRepository.save(user); + + Map variables = ImmutableMap.of("password", password, "email", email); + try { + mailService.sendInviteMail(variables, email); + } catch (MessagingException | MailException e) { + throw new UserSendingMailException(email); + } + } + + public User findOneByLoginIgnoreCase(String login) { + return userRepository.findOneByLoginIgnoreCase(login); + } + + public Map getUsersInfo() { + List usersInfoNow = new ArrayList<>(); + String err = ""; + + for (User user : userRepository.findAll()) { + Lesson lesson = null; + try { + lesson = timetableService.getCurrentLesson(user.getUserAbbreviate()); + } catch (TimetableClientException e) { + err = "Не удалось загрузить расписание"; + } + usersInfoNow.add(new UserInfoNow( + lesson, + conferenceService.getActiveConferenceByUser(user), + user, + userSessionService.isOnline(user)) + ); + } + return ImmutableMap.of("users", usersInfoNow, "error", err); + } + + public Map getActivitiesPings(Integer userId, + String activityName) { + User user = null; + if (userId != null) { + user = findById(userId); + } + Map activitiesPings = new HashMap<>(); + + for (Ping ping : pingService.getPings(activityName)) { + UserActivity activity = ping.getActivity(); + + if (user != null && !activity.getActivityUsers().contains(user)) { + continue; + } + + if (activitiesPings.containsKey(activity.getTitle())) { + activitiesPings.put(activity.getTitle(), activitiesPings.get(activity.getTitle()) + 1); + } else { + activitiesPings.put(activity.getTitle(), 1); + } + + } + return activitiesPings; + } + + public void blockUser(int userId) { + User userToBlock = findById(userId); + userToBlock.setBlocker(getCurrentUser()); + userRepository.save(userToBlock); + } } diff --git a/src/main/java/ru/ulstu/user/service/UserSessionService.java b/src/main/java/ru/ulstu/user/service/UserSessionService.java index 0d985cd..17a7f5b 100644 --- a/src/main/java/ru/ulstu/user/service/UserSessionService.java +++ b/src/main/java/ru/ulstu/user/service/UserSessionService.java @@ -14,6 +14,8 @@ import ru.ulstu.user.model.UserSession; import ru.ulstu.user.model.UserSessionListDto; import ru.ulstu.user.repository.UserSessionRepository; +import java.util.Date; + import static ru.ulstu.core.util.StreamApiUtils.convert; @Service @@ -54,4 +56,12 @@ public class UserSessionService { userSessionRepository.save(userSession); log.debug("User session {} closed", sessionId); } + + public User getUserBySessionId(String sessionId) { + return userSessionRepository.findOneBySessionId(sessionId).getUser(); + } + + public boolean isOnline(User user) { + return !userSessionRepository.findAllByUserAndLogoutTimeIsNullAndLoginTimeBefore(user, new Date()).isEmpty(); + } } diff --git a/src/main/java/ru/ulstu/user/util/UserUtils.java b/src/main/java/ru/ulstu/user/util/UserUtils.java index 8524c74..090240b 100644 --- a/src/main/java/ru/ulstu/user/util/UserUtils.java +++ b/src/main/java/ru/ulstu/user/util/UserUtils.java @@ -3,8 +3,8 @@ package ru.ulstu.user.util; import org.apache.commons.lang3.RandomStringUtils; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; +import ru.ulstu.configuration.Constants; public class UserUtils { private static final int DEF_COUNT = 20; @@ -32,4 +32,8 @@ public class UserUtils { } return null; } + + public static String generatePassword() { + return RandomStringUtils.randomAscii(Constants.MIN_PASSWORD_LENGTH, Constants.MAX_PASSWORD_LENGTH); + } } diff --git a/src/main/java/ru/ulstu/utils/timetable/TimetableService.java b/src/main/java/ru/ulstu/utils/timetable/TimetableService.java new file mode 100644 index 0000000..78a1c66 --- /dev/null +++ b/src/main/java/ru/ulstu/utils/timetable/TimetableService.java @@ -0,0 +1,98 @@ +package ru.ulstu.utils.timetable; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; +import ru.ulstu.core.util.DateUtils; +import ru.ulstu.utils.timetable.errors.TimetableClientException; +import ru.ulstu.utils.timetable.model.Lesson; +import ru.ulstu.utils.timetable.model.TimetableResponse; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +public class TimetableService { + private static final String TIMETABLE_URL = "http://timetable.athene.tech/api/1.0/timetable?filter=%s"; + private SimpleDateFormat lessonTimeFormat = new SimpleDateFormat("hh:mm"); + + private long[] lessonsStarts = new long[]{ + lessonTimeFormat.parse("8:00:00").getTime(), + lessonTimeFormat.parse("9:40:00").getTime(), + lessonTimeFormat.parse("11:30:00").getTime(), + lessonTimeFormat.parse("13:10:00").getTime(), + lessonTimeFormat.parse("14:50:00").getTime(), + lessonTimeFormat.parse("16:30:00").getTime(), + lessonTimeFormat.parse("18:10:00").getTime(), + }; + + public TimetableService() throws ParseException { + } + + private int getCurrentDay() { + Calendar calendar = Calendar.getInstance(); + int day = calendar.get(Calendar.DAY_OF_WEEK); + return (day + 5) % 7; + } + + private int getCurrentLessonNumber() { + long lessonDuration = 90 * 60000; + Date now = new Date(); + long timeNow = now.getTime() % (24 * 60 * 60 * 1000L); + + for (int i = 0; i < lessonsStarts.length; i++) { + if (timeNow > lessonsStarts[i] && timeNow < lessonsStarts[i] + lessonDuration) { + return i; + } + } + return -1; + } + + private int getCurrentWeek() { + Date currentDate = Calendar.getInstance().getTime(); + currentDate = DateUtils.clearTime(currentDate); + + Calendar firstJan = Calendar.getInstance(); + firstJan.set(Calendar.MONTH, 0); + firstJan.set(Calendar.DAY_OF_MONTH, 1); + + return (int) Math.round(Math.ceil((((currentDate.getTime() - firstJan.getTime().getTime()) / 86400000) + + DateUtils.addDays(firstJan.getTime(), 1).getTime() / 7) % 2)); + } + + private TimetableResponse getTimetableForUser(String userFIO) throws RestClientException { + RestTemplate restTemplate = new RestTemplate(); + return restTemplate.getForObject(String.format(TIMETABLE_URL, userFIO), TimetableResponse.class); + } + + public Lesson getCurrentLesson(String userFio) { + TimetableResponse response; + try { + response = getTimetableForUser(userFio); + } catch (RestClientException e) { + e.printStackTrace(); + throw new TimetableClientException(userFio); + } + + int lessonNumber = getCurrentLessonNumber(); + if (lessonNumber < 0) { + return null; + } + + List lessons = response + .getResponse() + .getWeeks() + .get(getCurrentWeek()) + .getDays() + .get(getCurrentDay()) + .getLessons() + .get(lessonNumber); + + if (lessons.size() == 0) { + return null; + } + return new ObjectMapper().convertValue(lessons.get(0), Lesson.class); + } +} diff --git a/src/main/java/ru/ulstu/utils/timetable/errors/TimetableClientException.java b/src/main/java/ru/ulstu/utils/timetable/errors/TimetableClientException.java new file mode 100644 index 0000000..4723bda --- /dev/null +++ b/src/main/java/ru/ulstu/utils/timetable/errors/TimetableClientException.java @@ -0,0 +1,7 @@ +package ru.ulstu.utils.timetable.errors; + +public class TimetableClientException extends RuntimeException { + public TimetableClientException(String message) { + super(message); + } +} diff --git a/src/main/java/ru/ulstu/utils/timetable/model/Day.java b/src/main/java/ru/ulstu/utils/timetable/model/Day.java new file mode 100644 index 0000000..211165d --- /dev/null +++ b/src/main/java/ru/ulstu/utils/timetable/model/Day.java @@ -0,0 +1,28 @@ +package ru.ulstu.utils.timetable.model; + +import java.util.ArrayList; +import java.util.List; + + +public class Day { + + private Integer day; + private List> lessons = new ArrayList<>(); + + public Integer getDay() { + return day; + } + + public void setDay(Integer day) { + this.day = day; + } + + public List> getLessons() { + return lessons; + } + + public void setLessons(List> lessons) { + this.lessons = lessons; + } +} + diff --git a/src/main/java/ru/ulstu/utils/timetable/model/Lesson.java b/src/main/java/ru/ulstu/utils/timetable/model/Lesson.java new file mode 100644 index 0000000..9c855bd --- /dev/null +++ b/src/main/java/ru/ulstu/utils/timetable/model/Lesson.java @@ -0,0 +1,24 @@ +package ru.ulstu.utils.timetable.model; + +public class Lesson { + private String group; + private String nameOfLesson; + private String teacher; + private String room; + + public String getGroup() { + return group; + } + + public String getNameOfLesson() { + return nameOfLesson; + } + + public String getTeacher() { + return teacher; + } + + public String getRoom() { + return room; + } +} diff --git a/src/main/java/ru/ulstu/utils/timetable/model/Response.java b/src/main/java/ru/ulstu/utils/timetable/model/Response.java new file mode 100644 index 0000000..dfd3a84 --- /dev/null +++ b/src/main/java/ru/ulstu/utils/timetable/model/Response.java @@ -0,0 +1,17 @@ +package ru.ulstu.utils.timetable.model; + +import java.util.ArrayList; +import java.util.List; + +public class Response { + + private List weeks = new ArrayList<>(); + + public List getWeeks() { + return weeks; + } + + public void setWeeks(List weeks) { + this.weeks = weeks; + } +} diff --git a/src/main/java/ru/ulstu/utils/timetable/model/TimetableResponse.java b/src/main/java/ru/ulstu/utils/timetable/model/TimetableResponse.java new file mode 100644 index 0000000..118c979 --- /dev/null +++ b/src/main/java/ru/ulstu/utils/timetable/model/TimetableResponse.java @@ -0,0 +1,22 @@ +package ru.ulstu.utils.timetable.model; + +public class TimetableResponse { + private Response response; + private String error; + + public Response getResponse() { + return response; + } + + public void setResponse(Response response) { + this.response = response; + } + + public String getError() { + return error; + } + + public void setError(String error) { + this.error = error; + } +} diff --git a/src/main/java/ru/ulstu/utils/timetable/model/Week.java b/src/main/java/ru/ulstu/utils/timetable/model/Week.java new file mode 100644 index 0000000..8ea76ea --- /dev/null +++ b/src/main/java/ru/ulstu/utils/timetable/model/Week.java @@ -0,0 +1,18 @@ +package ru.ulstu.utils.timetable.model; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +public class Week implements Serializable { + + private List days = new ArrayList<>(); + + public List getDays() { + return days; + } + + public void setDays(List days) { + this.days = days; + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 75c8ef9..1949a5b 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -12,6 +12,8 @@ server.ssl.key-store-password=secret server.ssl.key-password=password # Log settings (TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF) logging.level.ru.ulstu=DEBUG +#HtmlUnit +logging.level.com.gargoylesoftware.htmlunit=ERROR # Mail Settings spring.mail.host=smtp.yandex.ru spring.mail.port=465 @@ -34,5 +36,7 @@ spring.liquibase.enabled=true ng-tracker.base-url=http://127.0.0.1:8080 ng-tracker.undead-user-login=admin ng-tracker.dev-mode=true +ng-tracker.debug_email= ng-tracker.use-https=false -ng-tracker.check-run=false \ No newline at end of file +ng-tracker.check-run=false +ng-tracker.driver-path= diff --git a/src/main/resources/db/changelog-20190419_000000-schema.xml b/src/main/resources/db/changelog-20190419_000000-schema.xml new file mode 100644 index 0000000..b56f322 --- /dev/null +++ b/src/main/resources/db/changelog-20190419_000000-schema.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + diff --git a/src/main/resources/db/changelog-20190424_000000-schema.xml b/src/main/resources/db/changelog-20190424_000000-schema.xml new file mode 100644 index 0000000..d61b38a --- /dev/null +++ b/src/main/resources/db/changelog-20190424_000000-schema.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/db/changelog-20190426_000000-schema.xml b/src/main/resources/db/changelog-20190426_000000-schema.xml new file mode 100644 index 0000000..5304032 --- /dev/null +++ b/src/main/resources/db/changelog-20190426_000000-schema.xml @@ -0,0 +1,13 @@ + + + + + + + + + diff --git a/src/main/resources/db/changelog-20190430_000000-schema.xml b/src/main/resources/db/changelog-20190430_000000-schema.xml new file mode 100644 index 0000000..58a3bc5 --- /dev/null +++ b/src/main/resources/db/changelog-20190430_000000-schema.xml @@ -0,0 +1,11 @@ + + + + + + + + + diff --git a/src/main/resources/db/changelog-20190505_000000-schema.xml b/src/main/resources/db/changelog-20190505_000000-schema.xml new file mode 100644 index 0000000..ad56dac --- /dev/null +++ b/src/main/resources/db/changelog-20190505_000000-schema.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + diff --git a/src/main/resources/db/changelog-20190505_000001-schema.xml b/src/main/resources/db/changelog-20190505_000001-schema.xml new file mode 100644 index 0000000..1148d3a --- /dev/null +++ b/src/main/resources/db/changelog-20190505_000001-schema.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/db/changelog-20190506_000000-schema.xml b/src/main/resources/db/changelog-20190506_000000-schema.xml new file mode 100644 index 0000000..cd5a59b --- /dev/null +++ b/src/main/resources/db/changelog-20190506_000000-schema.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + diff --git a/src/main/resources/db/changelog-20190506_000001-schema.xml b/src/main/resources/db/changelog-20190506_000001-schema.xml new file mode 100644 index 0000000..e28d009 --- /dev/null +++ b/src/main/resources/db/changelog-20190506_000001-schema.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + diff --git a/src/main/resources/db/changelog-20190507_000000-schema.xml b/src/main/resources/db/changelog-20190507_000000-schema.xml new file mode 100644 index 0000000..0cdb99b --- /dev/null +++ b/src/main/resources/db/changelog-20190507_000000-schema.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/src/main/resources/db/changelog-20190507_000001-schema.xml b/src/main/resources/db/changelog-20190507_000001-schema.xml new file mode 100644 index 0000000..c320eba --- /dev/null +++ b/src/main/resources/db/changelog-20190507_000001-schema.xml @@ -0,0 +1,14 @@ + + + + + update grants + set leader_id = + (select u.id + from users u + where u.last_name = 'Романов' AND u.first_name = 'Антон'); + + + diff --git a/src/main/resources/db/changelog-20190507_000002-schema.xml b/src/main/resources/db/changelog-20190507_000002-schema.xml new file mode 100644 index 0000000..c756bf6 --- /dev/null +++ b/src/main/resources/db/changelog-20190507_000002-schema.xml @@ -0,0 +1,13 @@ + + + + + + + + + diff --git a/src/main/resources/db/changelog-20190511_000000-schema.xml b/src/main/resources/db/changelog-20190511_000000-schema.xml new file mode 100644 index 0000000..62e914f --- /dev/null +++ b/src/main/resources/db/changelog-20190511_000000-schema.xml @@ -0,0 +1,13 @@ + + + + + + + + + diff --git a/src/main/resources/db/changelog-20190517_000001-schema.xml b/src/main/resources/db/changelog-20190517_000001-schema.xml new file mode 100644 index 0000000..73c6435 --- /dev/null +++ b/src/main/resources/db/changelog-20190517_000001-schema.xml @@ -0,0 +1,14 @@ + + + + + + + diff --git a/src/main/resources/db/changelog-20190520_000000-schema.xml b/src/main/resources/db/changelog-20190520_000000-schema.xml new file mode 100644 index 0000000..69cdad0 --- /dev/null +++ b/src/main/resources/db/changelog-20190520_000000-schema.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/src/main/resources/db/changelog-20190523_000000-schema.xml b/src/main/resources/db/changelog-20190523_000000-schema.xml new file mode 100644 index 0000000..aca880f --- /dev/null +++ b/src/main/resources/db/changelog-20190523_000000-schema.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/db/changelog-20190528_000000-schema.xml b/src/main/resources/db/changelog-20190528_000000-schema.xml new file mode 100644 index 0000000..02ba642 --- /dev/null +++ b/src/main/resources/db/changelog-20190528_000000-schema.xml @@ -0,0 +1,11 @@ + + + + + + diff --git a/src/main/resources/db/changelog-20190528_000002-schema.xml b/src/main/resources/db/changelog-20190528_000002-schema.xml new file mode 100644 index 0000000..a4e2032 --- /dev/null +++ b/src/main/resources/db/changelog-20190528_000002-schema.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + diff --git a/src/main/resources/db/changelog-20190529_000000-schema.xml b/src/main/resources/db/changelog-20190529_000000-schema.xml new file mode 100644 index 0000000..40079ff --- /dev/null +++ b/src/main/resources/db/changelog-20190529_000000-schema.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + diff --git a/src/main/resources/db/changelog-20190529_000001-schema.xml b/src/main/resources/db/changelog-20190529_000001-schema.xml new file mode 100644 index 0000000..0b6548b --- /dev/null +++ b/src/main/resources/db/changelog-20190529_000001-schema.xml @@ -0,0 +1,13 @@ + + + + + + + + + diff --git a/src/main/resources/db/changelog-20190601_000001-schema.xml b/src/main/resources/db/changelog-20190601_000001-schema.xml new file mode 100644 index 0000000..409bde4 --- /dev/null +++ b/src/main/resources/db/changelog-20190601_000001-schema.xml @@ -0,0 +1,10 @@ + + + + + + + + diff --git a/src/main/resources/db/changelog-20190605_000000-schema.xml b/src/main/resources/db/changelog-20190605_000000-schema.xml new file mode 100644 index 0000000..3863268 --- /dev/null +++ b/src/main/resources/db/changelog-20190605_000000-schema.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/db/changelog-20190607_000002-schema.xml b/src/main/resources/db/changelog-20190607_000002-schema.xml new file mode 100644 index 0000000..9531c87 --- /dev/null +++ b/src/main/resources/db/changelog-20190607_000002-schema.xml @@ -0,0 +1,12 @@ + + + + + + + + + diff --git a/src/main/resources/db/changelog-master.xml b/src/main/resources/db/changelog-master.xml index dfe3cfc..39d79cb 100644 --- a/src/main/resources/db/changelog-master.xml +++ b/src/main/resources/db/changelog-master.xml @@ -30,7 +30,29 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/drivers/chromedriver b/src/main/resources/drivers/chromedriver old mode 100644 new mode 100755 diff --git a/src/main/resources/drivers/geckodriver b/src/main/resources/drivers/geckodriver old mode 100644 new mode 100755 diff --git a/src/main/resources/mail_templates/conferenceCreateNotification.html b/src/main/resources/mail_templates/conferenceCreateNotification.html new file mode 100644 index 0000000..055e85d --- /dev/null +++ b/src/main/resources/mail_templates/conferenceCreateNotification.html @@ -0,0 +1,30 @@ + + + + Уведомление о создании конференции + + + + +

+ Уважаемый(ая) Ivan Ivanov +

+

+ Была создана новая конференция: " + Title". +
+ Спешите принять участие! +

+

+ Даты проведения: + + - + . +

+

+ Regards, +
+ NG-tracker. +

+ + \ No newline at end of file diff --git a/src/main/resources/mail_templates/conferenceDeadlineNotification.html b/src/main/resources/mail_templates/conferenceDeadlineNotification.html new file mode 100644 index 0000000..77c89b1 --- /dev/null +++ b/src/main/resources/mail_templates/conferenceDeadlineNotification.html @@ -0,0 +1,29 @@ + + + + Уведомление о дедлайне конференции + + + + +

+ Уважаемый(ая) Ivan Ivanov +

+

+ Приближается дедлайн конференции " + Title". +

+

+ Срок исполнения: . +

+ +

+ Примечание: . +

+

+ Regards, +
+ NG-tracker. +

+ + diff --git a/src/main/resources/mail_templates/conferencePingNotification.html b/src/main/resources/mail_templates/conferencePingNotification.html new file mode 100644 index 0000000..a80a3f2 --- /dev/null +++ b/src/main/resources/mail_templates/conferencePingNotification.html @@ -0,0 +1,25 @@ + + + + Обратите внимание на конференциию + + + + +

+ Уважаемый(ая) Ivan Ivanov +

+

+ Конференция " + Title" была пропингована + раз. +
+ Обратите внимание. +

+

+ Regards, +
+ NG-tracker. +

+ + \ No newline at end of file diff --git a/src/main/resources/mail_templates/conferenceUpdateDatesNotification.html b/src/main/resources/mail_templates/conferenceUpdateDatesNotification.html new file mode 100644 index 0000000..479336f --- /dev/null +++ b/src/main/resources/mail_templates/conferenceUpdateDatesNotification.html @@ -0,0 +1,31 @@ + + + + Уведомление об изменении дат проведения конференции + + + + +

+ Уважаемый(ая) Ivan Ivanov +

+

+ Даты проведения конференции " + Title" изменились с
+ "oldBeginDate" + - + "oldEndDate" +
+ + на
+ "" + - + "". +

+

+ Regards, +
+ NG-tracker. +

+ + \ No newline at end of file diff --git a/src/main/resources/mail_templates/conferenceUpdateDeadlinesNotification.html b/src/main/resources/mail_templates/conferenceUpdateDeadlinesNotification.html new file mode 100644 index 0000000..f010fb8 --- /dev/null +++ b/src/main/resources/mail_templates/conferenceUpdateDeadlinesNotification.html @@ -0,0 +1,24 @@ + + + + Уведомление об изменении дедлайнов конференции + + + + +

+ Уважаемый(ая) Ivan Ivanov +

+

+ Дедлайны конференции " + Title" притерпели изменения. +
+ Ознакомтесь с изменениями. +

+

+ Regards, +
+ NG-tracker. +

+ + \ No newline at end of file diff --git a/src/main/resources/mail_templates/grantAuthorsChangeNotification.html b/src/main/resources/mail_templates/grantAuthorsChangeNotification.html new file mode 100644 index 0000000..2bae4fe --- /dev/null +++ b/src/main/resources/mail_templates/grantAuthorsChangeNotification.html @@ -0,0 +1,24 @@ + + + + Уведомление об изменении состава рабочей группы + + + + +

+ Уважаемый(ая) Ivan Ivanov +

+

+ Состав рабочей группы гранта "Title" сменился с + " oldAuthors" + на " newAuthors". +

+

+ Regards, +
+ NG-tracker. +

+ + diff --git a/src/main/resources/mail_templates/grantCreateNotification.html b/src/main/resources/mail_templates/grantCreateNotification.html new file mode 100644 index 0000000..69736cd --- /dev/null +++ b/src/main/resources/mail_templates/grantCreateNotification.html @@ -0,0 +1,28 @@ + + + + Уведомление о создании гранта + + + + +

+ Уважаемый(ая) Ivan Ivanov +

+

+ Был добавлен новый грант: " + Title". +
+

+

+ Руководитель гранта: + + Leader. +

+

+ Regards, +
+ NG-tracker. +

+ + \ No newline at end of file diff --git a/src/main/resources/mail_templates/grantDeadlineNotification.html b/src/main/resources/mail_templates/grantDeadlineNotification.html new file mode 100644 index 0000000..190ef67 --- /dev/null +++ b/src/main/resources/mail_templates/grantDeadlineNotification.html @@ -0,0 +1,28 @@ + + + + Уведомление о дедлайне гранта + + + + +

+ Уважаемый(ая) Ivan Ivanov +

+

+ Приближается дедлайн гранта "Title". +

+

+ Срок исполнения: Date. +

+

+ Примечание: Description. +

+

+ Regards, +
+ NG-tracker. +

+ + diff --git a/src/main/resources/mail_templates/grantLeaderChangeNotification.html b/src/main/resources/mail_templates/grantLeaderChangeNotification.html new file mode 100644 index 0000000..c6a37e0 --- /dev/null +++ b/src/main/resources/mail_templates/grantLeaderChangeNotification.html @@ -0,0 +1,24 @@ + + + + Уведомление об изменении руководителя гранта + + + + +

+ Уважаемый(ая) Ivan Ivanov +

+

+ Руководитель гранта "Title" сменился с + "oldLeader" + на "newLeader". +

+

+ Regards, +
+ NG-tracker. +

+ + diff --git a/src/main/resources/mail_templates/paperCreateNotification.html b/src/main/resources/mail_templates/paperCreateNotification.html index 2758143..82362bd 100644 --- a/src/main/resources/mail_templates/paperCreateNotification.html +++ b/src/main/resources/mail_templates/paperCreateNotification.html @@ -12,9 +12,11 @@

Вам нужно поработать над статьей "Title".

-

- Срок исполнения: . -

+
+

+ Срок исполнения: . +

+

Regards,
diff --git a/src/main/resources/mail_templates/passwordChangeEmail.html b/src/main/resources/mail_templates/passwordChangeEmail.html new file mode 100644 index 0000000..ec15a36 --- /dev/null +++ b/src/main/resources/mail_templates/passwordChangeEmail.html @@ -0,0 +1,21 @@ + + + + Password reset + + + + +

+ Dear Ivan Ivanov +

+

+ Your password has been changed. +

+

+ Regards, +
+ Balance Team. +

+ + diff --git a/src/main/resources/mail_templates/passwordResetEmail.html b/src/main/resources/mail_templates/passwordResetEmail.html index a1034d4..99e4f77 100644 --- a/src/main/resources/mail_templates/passwordResetEmail.html +++ b/src/main/resources/mail_templates/passwordResetEmail.html @@ -1,23 +1,19 @@ - Password reset + Восстановление пароля

- Dear Ivan Ivanov + Дорогой Ivan Ivanov

- For your account a password reset was requested, please click on the URL below to + Ваш ключ для восстановления пароля

- Reset Link -

-

- Regards, + С уважением,
Balance Team.

diff --git a/src/main/resources/mail_templates/pingsInfoWeekEmail.html b/src/main/resources/mail_templates/pingsInfoWeekEmail.html new file mode 100644 index 0000000..180ef3b --- /dev/null +++ b/src/main/resources/mail_templates/pingsInfoWeekEmail.html @@ -0,0 +1,23 @@ + + + + Уведомление о создании статьи + + + + +

+ Уважаемый(ая) Ivan Ivanov +

+

+ Вы были отмечены в следующих задачах: +

+

+

+

+ Regards, +
+ NG-tracker. +

+ + diff --git a/src/main/resources/mail_templates/userInviteEmail.html b/src/main/resources/mail_templates/userInviteEmail.html new file mode 100644 index 0000000..bb0ba38 --- /dev/null +++ b/src/main/resources/mail_templates/userInviteEmail.html @@ -0,0 +1,21 @@ + + + + Account activation + + + + +

+ Аккаунт в системе NG-Tracker был создан.
+ Данные для входа:
+ Логин -
+ Пароль - +

+

+ Regards, +
+ Balance Team. +

+ + diff --git a/src/main/resources/public/css/agency.css b/src/main/resources/public/css/agency.css index fb3ec24..82a36d2 100644 --- a/src/main/resources/public/css/agency.css +++ b/src/main/resources/public/css/agency.css @@ -782,6 +782,10 @@ ul.social-buttons li a:active, ul.social-buttons li a:focus, ul.social-buttons l margin: 5px; } +.small-icon { + width: 16px; +} + /* --------------------------------------------------- FEEDBACK STYLE ----------------------------------------------------- */ diff --git a/src/main/resources/public/css/base.css b/src/main/resources/public/css/base.css new file mode 100644 index 0000000..59da321 --- /dev/null +++ b/src/main/resources/public/css/base.css @@ -0,0 +1,3 @@ +.loader { + padding-left: 50% +} \ No newline at end of file diff --git a/src/main/resources/public/css/conference.css b/src/main/resources/public/css/conference.css index 8cebd1d..7a4784b 100644 --- a/src/main/resources/public/css/conference.css +++ b/src/main/resources/public/css/conference.css @@ -2,11 +2,15 @@ body { min-width: 400px; } -.conference-row .col:hover { - background-color: #f3f3f3; +.conference-row .d-flex:hover { + background-color: #f1f1f1; border-radius: .25rem; } +.conference-row .d-flex:hover .icon-delete { + visibility: visible; +} + .filter-option-inner-inner { color: white; } @@ -15,8 +19,34 @@ body { margin-bottom: 10px; } -.conference-row .col .text-decoration { +.conference-row .d-flex .text-decoration { text-decoration: none; + margin: 0; +} + +.conference-row .d-flex .text-decoration:nth-child(1) { + margin-left: 5px; +} + +.conference-row .d-flex .text-decoration span.h6.float-left.m-2 { + max-width: 470px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.conference-row .d-flex .icon-delete { + width: 29px; + height: 29px; + margin: auto; + border: none; + visibility: hidden; + background-color: transparent; +} + + +.conference-row .d-flex { + margin: 0 15px; } @@ -62,13 +92,17 @@ body { padding: 0.5rem 1.75em 0.5rem 0.5em; display: inline-block; background: transparent url("https://cdn3.iconfinder.com/data/icons/faticons/32/arrow-down-01-16.png") no-repeat right 7px center; - + cursor: pointer; } .member select:nth-child(4) { border-right: 1px solid #ced4da; } +.member select:hover { + background-color: #f1f1f1; +} + .member-name { padding: .75rem 1.25rem; @@ -78,6 +112,16 @@ body { border-right: 1px solid #ced4da; } +#ping-button[disabled=disabled] { + background-color: #ced4da; + border-color: #c2c5c7; +} + +#ping-button[disabled=disabled]:hover { + background-color: #737475 !important; + border-color: #5d5e5f !important; +} + #take-part[disabled=disabled] { background-color: #ced4da; border-color: #c2c5c7; @@ -103,13 +147,34 @@ body { .paper-name { flex: 1; + overflow: hidden; +} + +.paper-name:hover { + background-color: #f1f1f1; } .paper-name span { - margin: 6px 15px; + margin: 7px 10px; display: inline-block; } +.paper-name span:nth-child(1) { + margin: 3px 0px 3px 10px; + float: left; +} + +.paper-name span:nth-child(2) { + max-width: 326px; + white-space: nowrap; +} + +.dropdown-menu { + max-width: 445px; +} + + + .icon { width: 38px; height: 38px; @@ -118,14 +183,14 @@ body { } .icon-delete { - background-color: #f44; + background-color: #ff7272; background-image: url(/img/conference/delete.png); background-repeat: round; color: transparent !important; } .icon-delete:hover { - background-color: #ff2929; + background-color: #ff0000 !important; transition: background-color .15s ease-in-out; } @@ -154,6 +219,22 @@ body { float: right; } +.note-1 { + background-color: #bfffce; +} + +.note-2 { + background-color: #eaffb4; +} + +.note-3 { + background-color: #fff69f; +} + +.note-4 { + background-color: #ff9973; +} + @media (max-width: 1199px) and (min-width: 768px) { .paper-control { display: block!important; diff --git a/src/main/resources/public/css/grant.css b/src/main/resources/public/css/grant.css index 1073cdf..d4c7976 100644 --- a/src/main/resources/public/css/grant.css +++ b/src/main/resources/public/css/grant.css @@ -9,4 +9,35 @@ .div-deadline-description { padding-left: 5px; padding-right: 5px; +} + +.div-view-paper { + margin-top: 6px; +} + +.div-selected-papers { + border: 0px; + padding-left: 12px; +} + +.icon-paper { + height: 22px; + width: 22px; + margin: 3px; +} + +.btn-delete-deadline { + color: black; +} + +.div-file-name { + padding-top: 6px; +} + +.div-loader { + margin-bottom: 5px; +} + +.div-row-file { + margin-bottom: 2px; } \ No newline at end of file diff --git a/src/main/resources/public/css/paper.css b/src/main/resources/public/css/paper.css index 824209f..b4b3f85 100644 --- a/src/main/resources/public/css/paper.css +++ b/src/main/resources/public/css/paper.css @@ -6,4 +6,35 @@ .nav-tabs { margin-bottom: 20px; +} + +#nav-references label, #nav-references select, #nav-references input { + display: inline-block; + vertical-align: middle; +} + +#nav-references .collapse-heading { + border: 1px solid #ddd; + border-radius: 4px; + padding: 5px 15px; + background-color: #efefef; +} + +#nav-references .collapse-heading a { + text-decoration: none; +} + +#nav-references a:hover { + text-decoration: none; +} + +#nav-references #formattedReferencesArea { + height: 150px; +} + +.ui-autocomplete { + max-height: 200px; + max-width: 400px; + overflow-y: scroll; + overflow-x: hidden; } \ No newline at end of file diff --git a/src/main/resources/public/css/project.css b/src/main/resources/public/css/project.css new file mode 100644 index 0000000..24e12ea --- /dev/null +++ b/src/main/resources/public/css/project.css @@ -0,0 +1,5 @@ +.div-deadline-done { + width: 60%; + height: 100%; + float: right; +} \ No newline at end of file diff --git a/src/main/resources/public/css/tasks.css b/src/main/resources/public/css/tasks.css index 14718de..709756e 100644 --- a/src/main/resources/public/css/tasks.css +++ b/src/main/resources/public/css/tasks.css @@ -13,6 +13,21 @@ cursor: text; } +.filter .bootstrap-select { + margin-bottom: 10px; +} + +.filter-option-inner-inner { + font-size: 12px; + text-transform: uppercase; + font-weight: normal; + line-height: 25px; +} + +.sorting .bootstrap-select { + margin-bottom: 10px; +} + .input-tag-name { border: none; box-shadow: none; @@ -24,6 +39,66 @@ max-width: inherit; } +.tag-info { + font-size: 10px; + color: white; + padding: 5px 15px; + background-color: black; + display: none; + margin-left: 5px; + border-radius: 5px; + opacity: 0.8; + font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; +} + +.fa-question-circle { + + font-size: 15px; + color: #212529; + cursor: pointer; +} + +.fa-question-circle:hover .tag-info { + display: inline-block; + +} + +.task-row { + + position: relative; +} + +.task-row .col:hover { + + background-color: #f8f9fa; + +} + +.task-row .col > a { + display: block; + text-decoration: none; +} + +.task-row .col:hover .remove-task { + + visibility: visible; + +} + +.remove-task { + visibility: hidden; + position: absolute; + right: -20px; + top: 50%; + transform: translate(-50%, -50%); + padding: 0 20px; +} + +.remove-task:hover { + + background-color: #ebebeb; +} + .tag { display: inline-block; padding: .2em .6em .3em; diff --git a/src/main/resources/public/img/main/ajax-loader.gif b/src/main/resources/public/img/main/ajax-loader.gif new file mode 100644 index 0000000..f2a1bc0 Binary files /dev/null and b/src/main/resources/public/img/main/ajax-loader.gif differ diff --git a/src/main/resources/public/js/conference.js b/src/main/resources/public/js/conference.js index 8335f54..37c7403 100644 --- a/src/main/resources/public/js/conference.js +++ b/src/main/resources/public/js/conference.js @@ -1,7 +1,6 @@ $(document).ready(function () { - - $('a[data-confirm]').click(function (ev) { - var href = $(this).attr('href'); + $('input[data-confirm]').click(function (ev) { + var value = $(this).attr('value'); if (!$('#dataConfirmModal').length) { $('#modalDelete').append('\n' + ' \n' + ' \n' + @@ -22,8 +21,9 @@ $(document).ready(function () { ' '); } $('#dataConfirmModal').find('#myModalLabel').text($(this).attr('data-confirm')); - $('#dataConfirmOK').attr('href', href); + $('#deleteConference').attr('value', value); $('#dataConfirmModal').modal({show: true}); return false; }); + }); diff --git a/src/main/resources/public/js/core.js b/src/main/resources/public/js/core.js index 58e68f4..23ed621 100644 --- a/src/main/resources/public/js/core.js +++ b/src/main/resources/public/js/core.js @@ -4,6 +4,7 @@ var urlFileUpload = "/api/1.0/files/uploadTmpFile"; var urlFileDownload = "/api/1.0/files/download/"; var urlPdfGenerating = "/papers/generatePdf"; +var urlReferencesFormatting = "/papers/getFormattedReferences"; var urlFileDownloadTmp = "/api/1.0/files/download-tmp/"; /* exported MessageTypesEnum */ @@ -224,3 +225,19 @@ function getUrlVar(key) { var result = new RegExp(key + "=([^&]*)", "i").exec(window.location.search); return result && decodeURIComponent(result[1]) || ""; } + +function sendPing(field, url) { + id = document.getElementById(field).value + + $.ajax({ + url: url + `?${field}=` + id, + contentType: "application/json; charset=utf-8", + method: "POST", + success: function () { + showFeedbackMessage("Ping был отправлен", MessageTypesEnum.SUCCESS) + }, + error: function (errorData) { + showFeedbackMessage(errorData.responseJSON.error.message, MessageTypesEnum.WARNING) + } + }) +} \ No newline at end of file diff --git a/src/main/resources/public/js/grants.js b/src/main/resources/public/js/grants.js index c33b4df..40c3e4f 100644 --- a/src/main/resources/public/js/grants.js +++ b/src/main/resources/public/js/grants.js @@ -3,7 +3,7 @@ $(document).ready(function () { $(".grant-row").mouseenter(function (event) { var grantRow = $(event.target).closest(".grant-row"); $(grantRow).css("background-color", "#f8f9fa"); - $(grantRow).find(".remove-paper").removeClass("d-none"); + $(grantRow).find(".remove-grant").removeClass("d-none"); }); $(".grant-row").mouseleave(function (event) { diff --git a/src/main/resources/public/js/papers.js b/src/main/resources/public/js/papers.js index 78d3120..7a937ba 100644 --- a/src/main/resources/public/js/papers.js +++ b/src/main/resources/public/js/papers.js @@ -13,7 +13,8 @@ $(document).ready(function () { }); $('a[data-confirm]').click(function(ev) { - var href = $(this).attr('href'); + var id = $(this).parent().parent().find('.id-class').val(); + if (!$('#dataConfirmModal').length) { $('#modalDelete').append(''); } $('#dataConfirmModal').find('#myModalLabel').text($(this).attr('data-confirm')); - $('#dataConfirmOK').attr('href', href); + $('#dataConfirmOK').click(function () { + $("#paperDeleteId").val(id); + $('form').submit(); + }); $('#dataConfirmModal').modal({show:true}); return false; }); diff --git a/src/main/resources/public/js/projects.js b/src/main/resources/public/js/projects.js new file mode 100644 index 0000000..114beb4 --- /dev/null +++ b/src/main/resources/public/js/projects.js @@ -0,0 +1,42 @@ +/*\n' + + ' \n' + + ' '); + } + $('#dataConfirmModal').find('#myModalLabel').text($(this).attr('data-confirm')); + $('#dataConfirmOK').attr('href', href); + $('#dataConfirmModal').modal({show: true}); + return false; + }); +}); +/*]]>*/ \ No newline at end of file diff --git a/src/main/resources/public/js/tasks.js b/src/main/resources/public/js/tasks.js index 6ee3537..ebff7e2 100644 --- a/src/main/resources/public/js/tasks.js +++ b/src/main/resources/public/js/tasks.js @@ -19,8 +19,16 @@ $(document).ready(function () { $("#input-tag").keyup(function (event) { - if (event.keyCode == 13 || event.keyCode == 188) { + if (event.keyCode == 13) { var tagNumber = $("#tags .tag").length; + if (tagNumber > 0) { + tagNumber = $("#tags .tag").last() + .children('input') + .attr("name") + .split(']')[0] + .split('[')[1]; + tagNumber++; + } var tagName = $.trim($(this).val()); var addTag = true; // проверка, добавлен ли этот тег @@ -70,17 +78,17 @@ $(document).ready(function () { }); $("span[data-role=remove]").click(removeTag); - $(".task-row").mouseenter(function (event) { - var taskRow = $(event.target).closest(".task-row"); - $(taskRow).css("background-color", "#f8f9fa"); - $(taskRow).find(".remove-task").removeClass("d-none"); - - }); - $(".task-row").mouseleave(function (event) { - var taskRow = $(event.target).closest(".task-row"); - $(taskRow).css("background-color", "white"); - $(taskRow).closest(".task-row").find(".remove-task").addClass("d-none"); - }); +// $(".task-row").mouseenter(function (event) { +// var taskRow = $(event.target).closest(".task-row"); +// $(taskRow).css("background-color", "#f8f9fa"); +// $(taskRow).find(".remove-task").removeClass("d-none"); +// +// }); +// $(".task-row").mouseleave(function (event) { +// var taskRow = $(event.target).closest(".task-row"); +// $(taskRow).css("background-color", "white"); +// $(taskRow).closest(".task-row").find(".remove-task").addClass("d-none"); +// }); $('a[data-confirm]').click(function(ev) { var href = $(this).attr('href'); @@ -90,7 +98,7 @@ $(document).ready(function () { ' +

Incorrect title

@@ -93,6 +103,10 @@ +

Incorrect date

+

@@ -121,7 +135,10 @@
-
+
+
-
+ + + + + + + Имя статьи + + + th:unless="*{papers[__${rowStat.index}__].id !=null}"> + Имя статьи - @@ -156,7 +185,7 @@
diff --git a/src/main/resources/templates/conferences/conferences.html b/src/main/resources/templates/conferences/conferences.html index 3b8d6a1..3204bf0 100644 --- a/src/main/resources/templates/conferences/conferences.html +++ b/src/main/resources/templates/conferences/conferences.html @@ -8,7 +8,9 @@
-
+ +
@@ -18,9 +20,12 @@

+
+

+
- +
diff --git a/src/main/resources/templates/conferences/dashboard.html b/src/main/resources/templates/conferences/dashboard.html index cb4f2c0..5e3e97f 100644 --- a/src/main/resources/templates/conferences/dashboard.html +++ b/src/main/resources/templates/conferences/dashboard.html @@ -4,6 +4,7 @@ layout:decorator="default" xmlns:th=""> +
@@ -21,8 +22,128 @@
+
+ + + + + + + + + + + + + + + + + + + +
+
\ No newline at end of file diff --git a/src/main/resources/templates/conferences/fragments/confDashboardFragment.html b/src/main/resources/templates/conferences/fragments/confDashboardFragment.html index 17f4aa6..5aabef2 100644 --- a/src/main/resources/templates/conferences/fragments/confDashboardFragment.html +++ b/src/main/resources/templates/conferences/fragments/confDashboardFragment.html @@ -4,12 +4,13 @@ -
+
-
- -
-
+

diff --git a/src/main/resources/templates/conferences/fragments/confLineFragment.html b/src/main/resources/templates/conferences/fragments/confLineFragment.html index 7d948d4..21b4191 100644 --- a/src/main/resources/templates/conferences/fragments/confLineFragment.html +++ b/src/main/resources/templates/conferences/fragments/confLineFragment.html @@ -5,16 +5,15 @@
- diff --git a/src/main/resources/templates/conferences/fragments/confNavigationFragment.html b/src/main/resources/templates/conferences/fragments/confNavigationFragment.html index 7e67365..7bf9d27 100644 --- a/src/main/resources/templates/conferences/fragments/confNavigationFragment.html +++ b/src/main/resources/templates/conferences/fragments/confNavigationFragment.html @@ -21,7 +21,7 @@
- Новая конференцию + Новая конференция
diff --git a/src/main/resources/templates/default.html b/src/main/resources/templates/default.html index 00e2c0f..daf359a 100644 --- a/src/main/resources/templates/default.html +++ b/src/main/resources/templates/default.html @@ -55,18 +55,31 @@ Сайт кафедры -
+
+
diff --git a/src/main/resources/templates/grants/fragments/grantFilesListFragment.html b/src/main/resources/templates/grants/fragments/grantFilesListFragment.html new file mode 100644 index 0000000..2547c80 --- /dev/null +++ b/src/main/resources/templates/grants/fragments/grantFilesListFragment.html @@ -0,0 +1,37 @@ + + + + + + +
+ + +
+ + + + +
+ + +
+
+ + + +
+
+
+
+
+ + \ No newline at end of file diff --git a/src/main/resources/templates/grants/fragments/grantLineFragment.html b/src/main/resources/templates/grants/fragments/grantLineFragment.html index dda0e8d..86ae1cf 100644 --- a/src/main/resources/templates/grants/fragments/grantLineFragment.html +++ b/src/main/resources/templates/grants/fragments/grantLineFragment.html @@ -8,11 +8,18 @@
- + + + + + - diff --git a/src/main/resources/templates/grants/fragments/grantStatusFragment.html b/src/main/resources/templates/grants/fragments/grantStatusFragment.html index 569f5ee..bf866d2 100644 --- a/src/main/resources/templates/grants/fragments/grantStatusFragment.html +++ b/src/main/resources/templates/grants/fragments/grantStatusFragment.html @@ -25,7 +25,7 @@
- + \ No newline at end of file diff --git a/src/main/resources/templates/grants/grant.html b/src/main/resources/templates/grants/grant.html index 832ed56..ad19553 100644 --- a/src/main/resources/templates/grants/grant.html +++ b/src/main/resources/templates/grants/grant.html @@ -5,6 +5,7 @@ +
@@ -23,7 +24,7 @@ th:object="${grantDto}">
- +
-
+ +
- - +

-
- +
+
-
+
+
+
-
@@ -107,14 +115,16 @@
- +
- +
@@ -143,9 +153,9 @@
- + + +
+ + +
+
+
+
+
+
+
+
+ +
+ +
@@ -172,7 +215,8 @@ type="submit"> Сохранить -
@@ -190,18 +234,101 @@ new FileLoader({ div: "loader", url: urlFileUpload, - maxSize: 1.5, - extensions: ["doc", "docx", "xls", "jpg", "pdf", "txt", "png"], + maxSize: -1, + extensions: [], callback: function (response) { showFeedbackMessage("Файл успешно загружен"); console.debug(response); + addNewFile(response); } }); $('.selectpicker').selectpicker(); }); + /*]]>*/ + function addNewFile(fileDto) { + var fileNumber = $("#files-list div.row").length; + + var newFileRow = $("
") + .attr("id", 'files' + fileNumber) + .addClass("row div-row-file"); + + var idInput = $("") + .attr("type", "hidden") + .attr("id", "files" + fileNumber + ".id") + .attr("value", '') + .attr("name", "files[" + fileNumber + "].id"); + newFileRow.append(idInput); + + var flagInput = $("") + .attr("type", "hidden") + .attr("id", "files" + fileNumber + ".deleted") + .attr("value", "false") + .attr("name", "files[" + fileNumber + "].deleted"); + newFileRow.append(flagInput); + + var nameInput = $("") + .attr("type", "hidden") + .attr("id", "files" + fileNumber + ".name") + .attr("value", fileDto.fileName) + .attr("name", "files[" + fileNumber + "].name"); + newFileRow.append(nameInput); + + var tmpFileNameInput = $("") + .attr("type", "hidden") + .attr("id", "files" + fileNumber + ".tmpFileName") + .attr("value", fileDto.tmpFileName) + .attr("name", "files[" + fileNumber + "].tmpFileName"); + newFileRow.append(tmpFileNameInput); + + var nameDiv = $("
") + .addClass("col-10 div-file-name") + .append($("").text(fileDto.fileName) + .attr("href", 'javascript:void(0)') + .attr("onclick", "downloadFile('" + fileDto.tmpFileName + "',null,'" + fileDto.fileName + "')")); + newFileRow.append(nameDiv); + var nextDiv = $("
") + .addClass("col-2"); + var nextA = $("") + .addClass("btn btn-danger float-right") + .attr("onclick", "$('#files" + fileNumber + "\\\\.deleted').val('true'); $('#files" + fileNumber + "').hide();") + .append(($("").attr("aria-hidden", "true")).append($("").addClass("fa fa-times"))) + ; + nextDiv.append(nextA) + newFileRow.append(nextDiv); + $("#files-list").append(newFileRow); + } + + function downloadFile(tmpName, fileId, downloadName) { + let xhr = new XMLHttpRequest(); + if (fileId != null) xhr.open('GET', urlFileDownload + fileId); + if (tmpName != null) xhr.open('GET', urlFileDownloadTmp + tmpName); + xhr.responseType = 'blob'; + + var formData = new FormData(); + if (fileId != null) formData.append("file-id", fileId); + if (tmpName != null) formData.append("tmp-file-name", tmpName); + + xhr.send(formData); + + xhr.onload = function () { + if (this.status == 200) { + console.debug(this.response); + var blob = new Blob([this.response], {type: '*'}); + let a = document.createElement("a"); + a.style = "display: none"; + document.body.appendChild(a); + let url = window.URL.createObjectURL(blob); + a.href = url; + a.download = downloadName; + a.click(); + window.URL.revokeObjectURL(url); + } else { + } + } + } + @@ -31,12 +35,15 @@ href="#nav-main" role="tab" aria-controls="nav-main" aria-selected="true">Статья Latex + References
@@ -198,7 +330,7 @@
@@ -379,6 +511,64 @@ } } + function getFormattedReferences() { + + var formData = new FormData(document.forms.paperform); + var xhr = new XMLHttpRequest(); + xhr.open("POST", urlReferencesFormatting); + console.log(formData); + xhr.send(formData); + + xhr.onload = function () { + if (this.status == 200) { + console.debug(this.response); + $('#formattedReferencesArea').val(this.response); + + } else { + showFeedbackMessage("Ошибка при форматировании списка литературы", MessageTypesEnum.DANGER); + } + } + } + + + +
diff --git a/src/main/resources/templates/papers/papers.html b/src/main/resources/templates/papers/papers.html index 2f2ac42..f4eb06b 100644 --- a/src/main/resources/templates/papers/papers.html +++ b/src/main/resources/templates/papers/papers.html @@ -7,7 +7,8 @@
- +
@@ -17,7 +18,11 @@
+
+
+

+
@@ -43,7 +48,7 @@
-
+
diff --git a/src/main/resources/templates/projects/dashboard.html b/src/main/resources/templates/projects/dashboard.html index c48b035..0eafb4a 100644 --- a/src/main/resources/templates/projects/dashboard.html +++ b/src/main/resources/templates/projects/dashboard.html @@ -17,6 +17,7 @@
+
diff --git a/src/main/resources/templates/projects/fragments/projectDashboardFragment.html b/src/main/resources/templates/projects/fragments/projectDashboardFragment.html index 1f66c4f..027dce7 100644 --- a/src/main/resources/templates/projects/fragments/projectDashboardFragment.html +++ b/src/main/resources/templates/projects/fragments/projectDashboardFragment.html @@ -11,7 +11,6 @@
title -

status

diff --git a/src/main/resources/templates/projects/fragments/projectFilesListFragment.html b/src/main/resources/templates/projects/fragments/projectFilesListFragment.html new file mode 100644 index 0000000..0e803d9 --- /dev/null +++ b/src/main/resources/templates/projects/fragments/projectFilesListFragment.html @@ -0,0 +1,40 @@ + + + + + + + +
+ + +
+ + + + +
+ + + +
+
+ + +
+
+
+
+ + + + + \ No newline at end of file diff --git a/src/main/resources/templates/projects/fragments/projectLineFragment.html b/src/main/resources/templates/projects/fragments/projectLineFragment.html index 3605273..43bdfb9 100644 --- a/src/main/resources/templates/projects/fragments/projectLineFragment.html +++ b/src/main/resources/templates/projects/fragments/projectLineFragment.html @@ -12,6 +12,10 @@ + + +
diff --git a/src/main/resources/templates/projects/fragments/projectStatusFragment.html b/src/main/resources/templates/projects/fragments/projectStatusFragment.html index e5da374..bf0d3f6 100644 --- a/src/main/resources/templates/projects/fragments/projectStatusFragment.html +++ b/src/main/resources/templates/projects/fragments/projectStatusFragment.html @@ -4,21 +4,21 @@ - + -
+
-
+
-
+
-
+
-
+
diff --git a/src/main/resources/templates/projects/project.html b/src/main/resources/templates/projects/project.html index dc3fa6d..b8999a5 100644 --- a/src/main/resources/templates/projects/project.html +++ b/src/main/resources/templates/projects/project.html @@ -3,7 +3,7 @@ xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorator="default" xmlns:th="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/html"> - + @@ -24,7 +24,7 @@ th:object="${projectDto}">
- +
- -
- + +
+
+ +
-
@@ -71,7 +77,8 @@
-
+
+
+
+ +
+
+ +

Incorrect title

@@ -98,12 +121,25 @@ value="Добавить дедлайн"/>
+
+ + +
+ +
+
+
+ +
@@ -133,17 +169,119 @@ new FileLoader({ div: "loader", url: urlFileUpload, - maxSize: 2, - extensions: ["doc", "docx", "xls", "jpg", "png", "pdf", "txt"], + maxSize: -1, + extensions: [], callback: function (response) { showFeedbackMessage("Файл успешно загружен"); console.debug(response); + + addNewFile(response, $("#files-list")); } }); $('.selectpicker').selectpicker(); }); + + function sendPing() { + id = document.getElementById("projectId").value + + $.ajax({ + url: "/projects/ping?projectId=" + id, + contentType: "application/json; charset=utf-8", + method: "POST", + success: function () { + showFeedbackMessage("Ping был отправлен", MessageTypesEnum.SUCCESS) + }, + error: function (errorData) { + showFeedbackMessage(errorData.responseJSON.error.message, MessageTypesEnum.WARNING) + } + }) + } /*]]>*/ + function addNewFile(fileDto, listElement) { + var fileNumber = $('.files-list div.row').length; + + var newFileRow = $("
") + .attr("id", 'files' + fileNumber) + .addClass("row"); + + var idInput = $("") + .attr("type", "hidden") + .attr("id", "files" + fileNumber + ".id") + .attr("value", '') + .attr("name", "files[" + fileNumber + "].id"); + newFileRow.append(idInput); + + var flagInput = $("") + .attr("type", "hidden") + .attr("id", "files" + fileNumber + ".deleted") + .attr("value", "false") + .attr("name", "files[" + fileNumber + "].deleted"); + newFileRow.append(flagInput); + + var nameInput = $("") + .attr("type", "hidden") + .attr("id", "files" + fileNumber + ".name") + .attr("value", fileDto.fileName) + .attr("name", "files[" + fileNumber + "].name"); + newFileRow.append(nameInput); + + var tmpFileNameInput = $("") + .attr("type", "hidden") + .attr("id", "files" + fileNumber + ".tmpFileName") + .attr("value", fileDto.tmpFileName) + .attr("name", "files[" + fileNumber + "].tmpFileName"); + newFileRow.append(tmpFileNameInput); + + var nextDiv = $("
") + .addClass("col-2"); + + var nextA = $("") + .addClass("btn btn-danger float-right") + .attr("onclick", "$('#files" + fileNumber + "\\\\.deleted').val('true'); $('#files" + fileNumber + "').hide();") + .append(($("").attr("aria-hidden", "true")).append($("").addClass("fa fa-times"))) + ; + nextDiv.append(nextA) + newFileRow.append(nextDiv); + var nameDiv = $("
") + .addClass("col-10") + .append($("").text(fileDto.fileName) + .attr("href", 'javascript:void(0)') + .attr("onclick", "downloadFile('" + fileDto.tmpFileName + "',null,'" + fileDto.fileName + "')")); + newFileRow.append(nameDiv); + + listElement.append(newFileRow); + + } + + function downloadFile(tmpName, fileId, downloadName) { + let xhr = new XMLHttpRequest(); + if (fileId != null) xhr.open('GET', urlFileDownload + fileId); + if (tmpName != null) xhr.open('GET', urlFileDownloadTmp + tmpName); + xhr.responseType = 'blob'; + + var formData = new FormData(); + if (fileId != null) formData.append("file-id", fileId); + if (tmpName != null) formData.append("tmp-file-name", tmpName); + + xhr.send(formData); + + xhr.onload = function () { + if (this.status == 200) { + console.debug(this.response); + var blob = new Blob([this.response], {type: '*'}); + let a = document.createElement("a"); + a.style = "display: none"; + document.body.appendChild(a); + let url = window.URL.createObjectURL(blob); + a.href = url; + a.download = downloadName; + a.click(); + window.URL.revokeObjectURL(url); + } else { + } + } + }
diff --git a/src/main/resources/templates/projects/projects.html b/src/main/resources/templates/projects/projects.html index fd19383..de334f8 100644 --- a/src/main/resources/templates/projects/projects.html +++ b/src/main/resources/templates/projects/projects.html @@ -24,10 +24,13 @@
+
+
+
diff --git a/src/main/resources/templates/resetRequest.html b/src/main/resources/templates/resetRequest.html index ef960f4..d340151 100644 --- a/src/main/resources/templates/resetRequest.html +++ b/src/main/resources/templates/resetRequest.html @@ -1,57 +1,60 @@ + +
-
-
-
-
- -
- -
- - Вернуться к странице входа - +
+
+ +
+
+
+
+ +
+
+ +
+
+ +
+
+ +
+ + + + +
-
-
+
+
- - - \ No newline at end of file diff --git a/src/main/resources/templates/students/dashboard.html b/src/main/resources/templates/students/dashboard.html index c0c2f0e..1f930cd 100644 --- a/src/main/resources/templates/students/dashboard.html +++ b/src/main/resources/templates/students/dashboard.html @@ -14,10 +14,10 @@

-
- - - + +
+ +
diff --git a/src/main/resources/templates/students/fragments/taskLineFragment.html b/src/main/resources/templates/students/fragments/taskLineFragment.html index baad17e..210863d 100644 --- a/src/main/resources/templates/students/fragments/taskLineFragment.html +++ b/src/main/resources/templates/students/fragments/taskLineFragment.html @@ -6,15 +6,15 @@ diff --git a/src/main/resources/templates/students/fragments/taskStatusFragment.html b/src/main/resources/templates/students/fragments/taskStatusFragment.html index 77fd529..d8ef4f4 100644 --- a/src/main/resources/templates/students/fragments/taskStatusFragment.html +++ b/src/main/resources/templates/students/fragments/taskStatusFragment.html @@ -6,9 +6,6 @@ - - -
diff --git a/src/main/resources/templates/students/task.html b/src/main/resources/templates/students/task.html index 968c7a0..3642221 100644 --- a/src/main/resources/templates/students/task.html +++ b/src/main/resources/templates/students/task.html @@ -52,7 +52,7 @@
- +
diff --git a/src/main/resources/templates/students/tasks.html b/src/main/resources/templates/students/tasks.html index b1177d8..72c4194 100644 --- a/src/main/resources/templates/students/tasks.html +++ b/src/main/resources/templates/students/tasks.html @@ -7,7 +7,7 @@
-
+
@@ -20,27 +20,43 @@
- +
+
+
Сортировать:
+ +
Фильтр:
- + -
diff --git a/src/main/resources/templates/users/block.html b/src/main/resources/templates/users/block.html new file mode 100644 index 0000000..3b27494 --- /dev/null +++ b/src/main/resources/templates/users/block.html @@ -0,0 +1,21 @@ + + + + + +
+
+
+
+
+

Ваш аккаунт заблокирован

+

Вернуться на страницу авторизации

+
+
+
+
+
+ + \ No newline at end of file diff --git a/src/main/resources/templates/users/changePassword.html b/src/main/resources/templates/users/changePassword.html new file mode 100644 index 0000000..37d9e7e --- /dev/null +++ b/src/main/resources/templates/users/changePassword.html @@ -0,0 +1,32 @@ + + + + + + \ No newline at end of file diff --git a/src/main/resources/templates/users/dashboard.html b/src/main/resources/templates/users/dashboard.html new file mode 100644 index 0000000..3e3f13c --- /dev/null +++ b/src/main/resources/templates/users/dashboard.html @@ -0,0 +1,36 @@ + + + + + + +
+
+
+
+

Пользователи

+
+
+

teste

+
+
+ +
+ +
+
+
+ +
+ + \ No newline at end of file diff --git a/src/main/resources/templates/users/fragments/userDashboardFragment.html b/src/main/resources/templates/users/fragments/userDashboardFragment.html new file mode 100644 index 0000000..795c6ff --- /dev/null +++ b/src/main/resources/templates/users/fragments/userDashboardFragment.html @@ -0,0 +1,24 @@ + + + + + + +
+
+
+ +

+
+

+
+

+
+

Онлайн

+ +
+
+
+ + \ No newline at end of file diff --git a/src/main/resources/templates/users/inviteModal.html b/src/main/resources/templates/users/inviteModal.html new file mode 100644 index 0000000..3b02eef --- /dev/null +++ b/src/main/resources/templates/users/inviteModal.html @@ -0,0 +1,26 @@ + + + + + + \ No newline at end of file diff --git a/src/main/resources/templates/users/pings.html b/src/main/resources/templates/users/pings.html new file mode 100644 index 0000000..1e9f6c2 --- /dev/null +++ b/src/main/resources/templates/users/pings.html @@ -0,0 +1,53 @@ + + + + + + + + + + + + +
+
+
+
+
+

Ping активности

+
+
+
+
+
Фильтр:
+ +
+ +
+
+
+
+ +
+
+ + diff --git a/src/main/resources/templates/users/profile.html b/src/main/resources/templates/users/profile.html new file mode 100644 index 0000000..f59587d --- /dev/null +++ b/src/main/resources/templates/users/profile.html @@ -0,0 +1,75 @@ + + + + + + + + +
+
+
+
+
+

Личный кабинет

+
+
+
+
+
+ + +
+ + +

Incorrect firstName

+

+
+
+ + +

Incorrect lastName

+

+
+
+ + +

Incorrect email

+

+
+
+ + +

Incorrect email

+

+
+
+ +
+ +
+
+
+
+
+ + diff --git a/src/test/java/ConferenceTest.java b/src/test/java/ConferenceTest.java new file mode 100644 index 0000000..3fae34b --- /dev/null +++ b/src/test/java/ConferenceTest.java @@ -0,0 +1,230 @@ +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Iterables; +import conference.ConferencePage; +import conference.ConferencesDashboardPage; +import conference.ConferencesPage; +import core.PageObject; +import core.TestTemplate; +import org.junit.Assert; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.MethodSorters; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import ru.ulstu.NgTrackerApplication; +import ru.ulstu.configuration.ApplicationProperties; + +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Map; + +@RunWith(SpringRunner.class) +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@SpringBootTest(classes = NgTrackerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +public class ConferenceTest extends TestTemplate { + private final Map> navigationHolder = ImmutableMap.of( + new ConferencesPage(), Arrays.asList("КОНФЕРЕНЦИИ", "/conferences/conferences"), + new ConferencePage(), Arrays.asList("РЕДАКТИРОВАНИЕ КОНФЕРЕНЦИИ", "/conferences/conference?id=0"), + new ConferencesDashboardPage(), Arrays.asList("АКТУАЛЬНЫЕ КОНФЕРЕНЦИИ", "/conferences/dashboard") + ); + + @Autowired + private ApplicationProperties applicationProperties; + + @Test + public void testACreateNewConference() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 1); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + ConferencePage conferencePage = (ConferencePage) getContext().initPage(page.getKey()); + ConferencesPage conferencesPage = (ConferencesPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 0).getKey()); + + String newConferenceName = "test " + (new Date()).getTime(); + conferencePage.setName(newConferenceName); + conferencePage.clickSaveBut(); + + Assert.assertTrue(conferencesPage.checkNameInList(newConferenceName)); + } + + @Test + public void testBChangeConferenceNameAndSave() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + ConferencesPage conferencesPage = (ConferencesPage) getContext().initPage(page.getKey()); + ConferencePage conferencePage = (ConferencePage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey()); + + conferencesPage.getFirstConference(); + String newConferenceName = "test " + (new Date()).getTime(); + conferencePage.clearName(); + conferencePage.setName(newConferenceName); + conferencePage.clickSaveBut(); + + Assert.assertTrue(conferencesPage.checkNameInList(newConferenceName)); + } + + @Test + public void testCAddDeadlineAndSave() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + ConferencesPage conferencesPage = (ConferencesPage) getContext().initPage(page.getKey()); + ConferencePage conferencePage = (ConferencePage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey()); + + conferencesPage.getFirstConference(); + String conferenceId = conferencePage.getId(); + Integer deadlineCount = conferencePage.getDeadlineCount(); + + String description = "test"; + String date = "09.09.2019"; + String dateValue = "2019-09-09"; + conferencePage.clickAddDeadlineBut(); + conferencePage.setDeadlineDescription(description, deadlineCount); + conferencePage.setDeadlineDate(date, deadlineCount); + conferencePage.clickSaveBut(); + + getContext().goTo(applicationProperties.getBaseUrl() + String.format("/conferences/conference?id=%s", conferenceId)); + + Assert.assertTrue(conferencePage.checkDeadline(description, dateValue)); + } + + @Test + public void testDTakePartAndSave() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + ConferencesPage conferencesPage = (ConferencesPage) getContext().initPage(page.getKey()); + ConferencePage conferencePage = (ConferencePage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey()); + + conferencesPage.getFirstConference(); + String conferenceId = conferencePage.getId(); + Integer membersCount = conferencePage.getMemberCount(); + + conferencePage.clickTakePartBut(); + conferencePage.clickSaveBut(); + + getContext().goTo(applicationProperties.getBaseUrl() + String.format("/conferences/conference?id=%s", conferenceId)); + + Assert.assertTrue(membersCount + 1 == conferencePage.getMemberCount() + && conferencePage.isTakePartButDisabledValueTrue()); + } + + @Test + public void testEDeleteDeadlineAndSave() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + ConferencesPage conferencesPage = (ConferencesPage) getContext().initPage(page.getKey()); + ConferencePage conferencePage = (ConferencePage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey()); + + conferencesPage.getFirstConference(); + String conferenceId = conferencePage.getId(); + Integer deadlineCount = conferencePage.getDeadlineCount(); + + conferencePage.clickDeleteDeadlineBut(); + conferencePage.clickSaveBut(); + + getContext().goTo(applicationProperties.getBaseUrl() + String.format("/conferences/conference?id=%s", conferenceId)); + + Assert.assertEquals(deadlineCount - 1, (int) conferencePage.getDeadlineCount()); + } + + @Test + public void testFAttachArticle() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + ConferencesPage conferencesPage = (ConferencesPage) getContext().initPage(page.getKey()); + ConferencePage conferencePage = (ConferencePage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey()); + + conferencesPage.getFirstConference(); + String conferenceId = conferencePage.getId(); + Integer paperCount = conferencePage.getArticlesCount(); + + conferencePage.showAllowToAttachArticles(); + WebElement paper = conferencePage.selectArticle(); + String paperName = paper.findElement(By.className("text")).getText(); + conferencePage.clickSaveBut(); + + getContext().goTo(applicationProperties.getBaseUrl() + String.format("/conferences/conference?id=%s", conferenceId)); + + Assert.assertTrue(paperCount + 1 == conferencePage.getArticlesCount() + && conferencePage.checkArticle(paperName)); + } + + @Test + public void testGAddArticle() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + ConferencesPage conferencesPage = (ConferencesPage) getContext().initPage(page.getKey()); + ConferencePage conferencePage = (ConferencePage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey()); + + conferencesPage.getFirstConference(); + String conferenceId = conferencePage.getId(); + Integer paperCount = conferencePage.getArticlesCount(); + + conferencePage.clickAddPaperBut(); + List webElements = conferencePage.getArticles(); + String paperName = webElements.get(webElements.size() - 1).findElements(By.tagName("input")).get(1).getAttribute("value"); + conferencePage.clickSaveBut(); + + getContext().goTo(applicationProperties.getBaseUrl() + String.format("/conferences/conference?id=%s", conferenceId)); + + Assert.assertTrue(paperCount + 1 == conferencePage.getArticlesCount() + && conferencePage.checkArticle(paperName)); + } + + @Test + public void testHUndockArticle() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + ConferencesPage conferencesPage = (ConferencesPage) getContext().initPage(page.getKey()); + ConferencePage conferencePage = (ConferencePage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey()); + + conferencesPage.getFirstConference(); + String conferenceId = conferencePage.getId(); + Integer paperCount = conferencePage.getArticlesCount(); + + conferencePage.clickUndockArticleBut(); + conferencePage.clickSaveBut(); + + getContext().goTo(applicationProperties.getBaseUrl() + String.format("/conferences/conference?id=%s", conferenceId)); + + Assert.assertEquals(paperCount - 1, (int) conferencePage.getArticlesCount()); + } + + @Test + public void testISortAndFilterConferenceList() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + ConferencesPage conferencesPage = (ConferencesPage) getContext().initPage(page.getKey()); + + conferencesPage.selectMember(); + conferencesPage.selectYear(); + + Assert.assertEquals(1, conferencesPage.getConferencesList().size()); + } + + @Test + public void testJDeleteConf() throws InterruptedException { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + ConferencesPage conferencesPage = (ConferencesPage) getContext().initPage(page.getKey()); + + Integer size = conferencesPage.getConferencesList().size(); + conferencesPage.deleteFirst(); + Thread.sleep(3000); + conferencesPage.clickConfirm(); + + Assert.assertEquals(size - 1, conferencesPage.getConferencesList().size()); + } +} diff --git a/src/test/java/GrantTest.java b/src/test/java/GrantTest.java new file mode 100644 index 0000000..b824852 --- /dev/null +++ b/src/test/java/GrantTest.java @@ -0,0 +1,225 @@ +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Iterables; +import core.PageObject; +import core.TestTemplate; +import grant.GrantPage; +import grant.GrantsDashboardPage; +import grant.GrantsPage; +import org.junit.Assert; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.MethodSorters; +import org.openqa.selenium.WebElement; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import ru.ulstu.NgTrackerApplication; +import ru.ulstu.configuration.ApplicationProperties; + +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Map; + +@RunWith(SpringRunner.class) +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@SpringBootTest(classes = NgTrackerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +public class GrantTest extends TestTemplate { + private final Map> navigationHolder = ImmutableMap.of( + new GrantsPage(), Arrays.asList("ГРАНТЫ", "/grants/grants"), + new GrantPage(), Arrays.asList("РЕДАКТИРОВАНИЕ ГРАНТА", "/grants/grant?id=0"), + new GrantsDashboardPage(), Arrays.asList("Гранты", "/grants/dashboard") + ); + + @Autowired + private ApplicationProperties applicationProperties; + + @Test + public void aCreateNewGrant() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 1); + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + GrantPage grantPage = (GrantPage) getContext().initPage(page.getKey()); + GrantsPage grantsPage = (GrantsPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 0).getKey()); + + String newGrantName = "test grant" + (new Date()); + grantPage.setTitle(newGrantName); + String deadlineDate = new Date().toString(); + String deadlineDescription = "test deadline description"; + grantPage.setDeadline(deadlineDate, 0, deadlineDescription); + grantPage.setLeader(); + grantPage.saveGrant(); + + Assert.assertTrue(grantsPage.findGrantByTitle(newGrantName)); + } + + @Test + public void bCreateBlankGrant() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 1); + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + GrantPage grantPage = (GrantPage) getContext().initPage(page.getKey()); + + grantPage.saveGrant(); + + Assert.assertTrue(grantPage.checkBlankFields()); + } + + @Test + public void cUpdateGrantTitle() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + GrantsPage grantsPage = (GrantsPage) getContext().initPage(page.getKey()); + GrantPage grantPage = (GrantPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey()); + + grantsPage.getFirstGrant(); + String newGrantTitle = "test " + (new Date()); + grantPage.setTitle(newGrantTitle); + grantPage.saveGrant(); + + Assert.assertTrue(grantsPage.findGrantByTitle(newGrantTitle)); + } + + @Test + public void dAttachPaper() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + GrantsPage grantsPage = (GrantsPage) getContext().initPage(page.getKey()); + GrantPage grantPage = (GrantPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey()); + + grantsPage.getFirstGrant(); + Integer countPapers = grantPage.getAttachedPapers().size(); + + Assert.assertEquals(countPapers + 1, grantPage.attachPaper().size()); + } + + @Test + public void eDeletePaper() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + GrantsPage grantsPage = (GrantsPage) getContext().initPage(page.getKey()); + GrantPage grantPage = (GrantPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey()); + + grantsPage.getFirstGrant(); + Integer oldCountPapers = grantPage.getAttachedPapers().size(); + if (oldCountPapers == 0) { + oldCountPapers = grantPage.attachPaper().size(); + } + + Assert.assertEquals(oldCountPapers - 1, grantPage.deletePaper().size()); + } + + @Test + public void fAddDeadline() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + GrantsPage grantsPage = (GrantsPage) getContext().initPage(page.getKey()); + GrantPage grantPage = (GrantPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey()); + + grantsPage.getFirstGrant(); + String grantId = grantPage.getId(); + Integer deadlineCount = grantPage.getDeadlineCount(); + + String description = "deadline test"; + String date = "08.08.2019"; + String dateValue = "2019-08-08"; + grantPage.addDeadline(); + grantPage.setDeadline(date, deadlineCount, description); + grantPage.saveGrant(); + + getContext().goTo(applicationProperties.getBaseUrl() + String.format("/grants/grant?id=%s", grantId)); + + Assert.assertTrue(grantPage.checkDeadline(description, dateValue)); + } + + @Test + public void gDeleteDeadline() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + GrantsPage grantsPage = (GrantsPage) getContext().initPage(page.getKey()); + GrantPage grantPage = (GrantPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey()); + + grantsPage.getFirstGrant(); + String grantId = grantPage.getId(); + Integer deadlineCount = grantPage.getDeadlineCount(); + + grantPage.deleteDeadline(); + grantPage.saveGrant(); + + getContext().goTo(applicationProperties.getBaseUrl() + String.format("/grants/grant?id=%s", grantId)); + Integer newDeadlineCount = grantPage.getDeadlineCount(); + Assert.assertEquals(deadlineCount - 1, (int) newDeadlineCount); + } + + @Test + public void hAddAuthor() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + GrantsPage grantsPage = (GrantsPage) getContext().initPage(page.getKey()); + GrantPage grantPage = (GrantPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey()); + + WebElement grant = grantsPage.getFirstGrantWithoutClick(); + String grantTitle = grantsPage.getGrantTitle(grant); + Integer authorsCount = grantsPage.getAuthorsCount(grant); + + grantsPage.getFirstGrant(); + grantPage.addAuthor(); + grantPage.saveGrant(); + + grant = grantsPage.getGrantByTitle(grantTitle); + Integer newAuthorsCount = grantsPage.getAuthorsCount(grant); + + Assert.assertEquals(authorsCount + 1, (int) newAuthorsCount); + } + + @Test + public void iDeleteAuthor() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + GrantsPage grantsPage = (GrantsPage) getContext().initPage(page.getKey()); + GrantPage grantPage = (GrantPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey()); + + WebElement grant = grantsPage.getFirstGrantWithoutClick(); + String grantTitle = grantsPage.getGrantTitle(grant); + Integer authorsCount = grantsPage.getAuthorsCount(grant); + + grantsPage.getFirstGrant(); + grantPage.deleteAuthor(); + grantPage.saveGrant(); + + grant = grantsPage.getGrantByTitle(grantTitle); + Integer newAuthorsCount = grantsPage.getAuthorsCount(grant); + + authorsCount = (authorsCount == 0) ? 0 : authorsCount - 1; + + Assert.assertEquals((int) authorsCount, (int) newAuthorsCount); + } + + @Test + public void jUpdateGrantDescription() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + GrantsPage grantsPage = (GrantsPage) getContext().initPage(page.getKey()); + GrantPage grantPage = (GrantPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey()); + + String description = "newDescriptionForGrant"; + grantsPage.getFirstGrant(); + String grantId = grantPage.getId(); + grantPage.setDescription(description); + grantPage.saveGrant(); + + getContext().goTo(applicationProperties.getBaseUrl() + String.format("/grants/grant?id=%s", grantId)); + + Assert.assertTrue(description.equals(grantPage.getDescription())); + } + + @Test + public void kDeleteGrant() throws InterruptedException { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + GrantsPage grantsPage = (GrantsPage) getContext().initPage(page.getKey()); + + Integer size = grantsPage.getGrantsList().size(); + grantsPage.deleteFirst(); + Assert.assertEquals(size - 1, grantsPage.getGrantsList().size()); + } +} diff --git a/src/test/java/PaperTest.java b/src/test/java/PaperTest.java new file mode 100644 index 0000000..a08a1d8 --- /dev/null +++ b/src/test/java/PaperTest.java @@ -0,0 +1,247 @@ +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Iterables; +import core.PageObject; +import core.TestTemplate; +import org.junit.Assert; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.MethodSorters; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import paper.PaperPage; +import paper.PapersDashboardPage; +import paper.PapersPage; +import ru.ulstu.NgTrackerApplication; +import ru.ulstu.configuration.ApplicationProperties; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +@RunWith(SpringRunner.class) +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@SpringBootTest(classes = NgTrackerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +public class PaperTest extends TestTemplate { + private final Map> navigationHolder = ImmutableMap.of( + new PapersPage(), Arrays.asList("СТАТЬИ", "/papers/papers"), + new PaperPage(), Arrays.asList("РЕДАКТИРОВАНИЕ СТАТЬИ", "/papers/paper?id=0"), + new PapersDashboardPage(), Arrays.asList("СТАТЬИ", "/papers/dashboard") + ); + + @Autowired + private ApplicationProperties applicationProperties; + + private String getPaperPageUrl() { + return Iterables.get(navigationHolder.entrySet(), 1).getValue().get(1); + } + + private PaperPage getPaperPage() { + PaperPage paperPage = (PaperPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey()); + paperPage.initElements(); + return paperPage; + } + + private String getPapersPageUrl() { + return Iterables.get(navigationHolder.entrySet(), 0).getValue().get(1); + } + + private PapersPage getPapersPage() { + PapersPage papersPage = (PapersPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 0).getKey()); + papersPage.initElements(); + return papersPage; + } + + private String getPapersDashboardPageUrl() { + return Iterables.get(navigationHolder.entrySet(), 2).getValue().get(1); + } + + private PapersDashboardPage getPapersDashboardPage() { + PapersDashboardPage papersDashboardPage = (PapersDashboardPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 2).getKey()); + papersDashboardPage.initElements(); + return papersDashboardPage; + } + + @Test + public void createNewPaperTest() { + getContext().goTo(applicationProperties.getBaseUrl() + getPaperPageUrl()); + PaperPage paperPage = getPaperPage(); + + String testTitle = "test " + (String.valueOf(System.currentTimeMillis())); + fillRequiredFields(paperPage, testTitle); + paperPage.clickSaveBtn(); + + PapersPage papersPage = getPapersPage(); + + Assert.assertTrue(papersPage.havePaperWithTitle(testTitle)); + } + + @Test + public void editPaperTest() { + createNewPaper(); + getContext().goTo(applicationProperties.getBaseUrl() + getPapersPageUrl()); + PapersPage papersPage = getPapersPage(); + papersPage.clickFirstPaper(); + + PaperPage paperPage = getPaperPage(); + String testTitle = "test " + (String.valueOf(System.currentTimeMillis())); + paperPage.setTitle(testTitle); + paperPage.clickSaveBtn(); + + Assert.assertTrue(papersPage.havePaperWithTitle(testTitle)); + } + + private void createNewPaper() { + getContext().goTo(applicationProperties.getBaseUrl() + getPaperPageUrl()); + PaperPage paperPage = getPaperPage(); + String testTitle = "test " + (String.valueOf(System.currentTimeMillis())); + fillRequiredFields(paperPage, testTitle); + paperPage.clickSaveBtn(); + } + + @Test + public void addDeadlineTest() { + createNewPaper(); + getContext().goTo(applicationProperties.getBaseUrl() + getPapersPageUrl()); + PapersPage papersPage = getPapersPage(); + papersPage.clickFirstPaper(); + + PaperPage paperPage = getPaperPage(); + papersPage.clickAddDeadline(); + String testDate = "01.01.2019"; + String testDateResult = "2019-01-01"; + String testDesc = "desc"; + Integer deadlineNumber = 2; + paperPage.setDeadlineDate(deadlineNumber, testDate); + paperPage.setDeadlineDescription(deadlineNumber, testDesc); + String paperId = paperPage.getId(); + paperPage.clickSaveBtn(); + + getContext().goTo(applicationProperties.getBaseUrl() + String.format("/papers/paper?id=%s", paperId)); + + Assert.assertTrue(paperPage.deadlineExist(testDesc, testDateResult)); + } + + @Test + public void noDeadlinesValidationTest() { + getContext().goTo(applicationProperties.getBaseUrl() + getPaperPageUrl()); + PaperPage paperPage = getPaperPage(); + + String testTitle = "test " + (String.valueOf(System.currentTimeMillis())); + paperPage.setTitle(testTitle); + paperPage.clickSaveBtn(); + + Assert.assertTrue(paperPage.hasAlert("Не может быть пустым")); + } + + private void fillRequiredFields(PaperPage paperPage, String title) { + paperPage.setTitle(title); + String testDate = "01.01.2019"; + String testDesc = "desc"; + Integer deadlineNumber = 1; + paperPage.setDeadlineDate(deadlineNumber, testDate); + paperPage.setDeadlineDescription(deadlineNumber, testDesc); + } + + @Test + public void addReferenceTest() { + createNewPaper(); + getContext().goTo(applicationProperties.getBaseUrl() + getPapersPageUrl()); + PapersPage papersPage = getPapersPage(); + papersPage.clickFirstPaper(); + + PaperPage paperPage = getPaperPage(); + fillRequiredFields(paperPage, "test " + (String.valueOf(System.currentTimeMillis()))); + paperPage.clickReferenceTab(); + paperPage.clickAddReferenceButton(); + + paperPage.clickReferenceTab(); + paperPage.showFirstReference(); + String authors = "testAuthors"; + paperPage.setFirstReferenceAuthors(authors); + + String paperId = paperPage.getId(); + paperPage.clickSaveBtn(); + + getContext().goTo(applicationProperties.getBaseUrl() + String.format("/papers/paper?id=%s", paperId)); + + Assert.assertTrue(paperPage.authorsExists(authors)); + } + + @Test + public void referencesFormatTest() { + getContext().goTo(applicationProperties.getBaseUrl() + getPaperPageUrl()); + + PaperPage paperPage = getPaperPage(); + paperPage.setTitle("test"); + paperPage.clickReferenceTab(); + paperPage.clickAddReferenceButton(); + + paperPage.clickReferenceTab(); + paperPage.showFirstReference(); + paperPage.setFirstReferenceAuthors("authors"); + paperPage.setFirstReferencePublicationTitle("title"); + paperPage.setFirstReferencePublicationYear("2010"); + paperPage.setFirstReferencePublisher("publisher"); + paperPage.setFirstReferencePages("200"); + paperPage.setFirstReferenceJournalOrCollectionTitle("journal"); + paperPage.setFormatStandardSpringer(); + paperPage.clickFormatButton(); + + Assert.assertEquals("authors (2010) title. journal, publisher, pp 200", paperPage.getFormatString()); + } + + @Test + public void dashboardLinkTest() { + getContext().goTo(applicationProperties.getBaseUrl() + getPaperPageUrl()); + PaperPage paperPage = getPaperPage(); + + fillRequiredFields(paperPage, "test " + (String.valueOf(System.currentTimeMillis()))); + String testLink = "http://test.com/"; + paperPage.setUrl(testLink); + paperPage.clickSaveBtn(); + + getContext().goTo(applicationProperties.getBaseUrl() + getPapersDashboardPageUrl()); + PapersDashboardPage papersDashboardPage = getPapersDashboardPage(); + + Assert.assertTrue(papersDashboardPage.externalLinkExists(testLink)); + } + + @Test + public void deletePaperTest() { + createNewPaper(); + getContext().goTo(applicationProperties.getBaseUrl() + getPapersPageUrl()); + PapersPage papersPage = getPapersPage(); + + int size = papersPage.getPapersCount(); + papersPage.clickRemoveFirstPaperButton(); + papersPage.clickConfirmDeleteButton(); + + Assert.assertEquals(size - 1, papersPage.getPapersCount()); + } + + @Test + public void latexValidationTest() { + getContext().goTo(applicationProperties.getBaseUrl() + getPaperPageUrl()); + + PaperPage paperPage = getPaperPage(); + paperPage.setTitle("test"); + paperPage.clickLatexTab(); + paperPage.setLatexText("test"); + paperPage.clickPdfButton(); + + Assert.assertTrue(paperPage.dangerMessageExist("Ошибка при создании PDF")); + } + + @Test + public void titleValidationTest() { + getContext().goTo(applicationProperties.getBaseUrl() + getPaperPageUrl()); + PaperPage paperPage = getPaperPage(); + + paperPage.clickSaveBtn(); + + Assert.assertTrue(paperPage.hasAlert("не может быть пусто")); + } + +} diff --git a/src/test/java/ProjectTest.java b/src/test/java/ProjectTest.java new file mode 100644 index 0000000..f2c6367 --- /dev/null +++ b/src/test/java/ProjectTest.java @@ -0,0 +1,174 @@ +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Iterables; +import core.PageObject; +import core.TestTemplate; +import org.junit.Assert; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.MethodSorters; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import project.ProjectDashboard; +import project.ProjectPage; +import project.ProjectsPage; +import ru.ulstu.NgTrackerApplication; +import ru.ulstu.configuration.ApplicationProperties; + +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Map; + +@RunWith(SpringRunner.class) +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@SpringBootTest(classes = NgTrackerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +public class ProjectTest extends TestTemplate { + private final Map> navigationHolder = ImmutableMap.of( + new ProjectPage(), Arrays.asList("ПРОЕКТЫ", "/projects/projects"), + new ProjectsPage(), Arrays.asList("РЕДАКТИРОВАНИЕ ПРОЕКТА", "/projects/project?id=0"), + new ProjectDashboard(), Arrays.asList("ПРОЕКТЫ", "/projects/dashboard") + ); + + @Autowired + private ApplicationProperties applicationProperties; + + @Test + public void testACreateNewProject() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 1); + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + ProjectsPage projectsPage = (ProjectsPage) getContext().initPage(page.getKey()); + ProjectPage projectPage = (ProjectPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 0).getKey()); + String name = "Project " + (new Date()).getTime(); + String date = "01.01.2019"; + Integer deadNum = projectPage.getDeadlineCount(); + projectPage.setName(name); + projectPage.clickAddDeadline(); + projectPage.addDeadlineDate(date, deadNum); + projectPage.clickSave(); + Assert.assertTrue(projectsPage.checkNameInList(name)); + } + + @Test + public void testBChangeNameAndSave() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + ProjectPage projectPage = (ProjectPage) getContext().initPage(page.getKey()); + ProjectsPage projectsPage = (ProjectsPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey()); + projectsPage.getFirstProject(); + String name = "Project " + (new Date()).getTime(); + projectPage.clearName(); + projectPage.setName(name); + projectPage.clickSave(); + Assert.assertTrue(projectsPage.checkNameInList(name)); + } + + @Test + public void testCChangeDeadlineAndSave() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + ProjectPage projectPage = (ProjectPage) getContext().initPage(page.getKey()); + ProjectsPage projectsPage = (ProjectsPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey()); + projectsPage.getFirstProject(); + String name = projectPage.getName(); + String date = "01.01.2019"; + Integer deadNum = projectPage.getDeadlineCount(); + projectPage.addDeadlineDate(date, deadNum); + projectPage.clickSave(); + Assert.assertTrue(projectsPage.checkNameInList(name)); + } + + @Test + public void testDSetStatusAndSave() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + ProjectPage projectPage = (ProjectPage) getContext().initPage(page.getKey()); + ProjectsPage projectsPage = (ProjectsPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey()); + projectsPage.getFirstProject(); + String name = projectPage.getName(); + projectPage.setStatus(); + projectPage.clickSave(); + Assert.assertTrue(projectsPage.checkNameInList(name)); + } + + @Test + public void testEAddDescriptionAndSave() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + ProjectPage projectPage = (ProjectPage) getContext().initPage(page.getKey()); + ProjectsPage projectsPage = (ProjectsPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey()); + projectsPage.getFirstProject(); + String name = projectPage.getName(); + String description = "Description " + (new Date()).getTime(); + projectPage.addDescription(description); + projectPage.clickSave(); + Assert.assertTrue(projectsPage.checkNameInList(name)); + } + + @Test + public void testFAddLinkAndSave() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + ProjectPage projectPage = (ProjectPage) getContext().initPage(page.getKey()); + ProjectsPage projectsPage = (ProjectsPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey()); + projectsPage.getFirstProject(); + String name = projectPage.getName(); + String link = "Link " + (new Date()).getTime(); + projectPage.addLink(link); + projectPage.clickSave(); + Assert.assertTrue(projectsPage.checkNameInList(name)); + } + + @Test + public void testGAddDeadlineDescriptionAndSave() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + ProjectPage projectPage = (ProjectPage) getContext().initPage(page.getKey()); + ProjectsPage projectsPage = (ProjectsPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey()); + projectsPage.getFirstProject(); + String name = projectPage.getName(); + String deadDesc = "Description " + (new Date()).getTime(); + projectPage.addDeadlineDescription(deadDesc); + projectPage.clickSave(); + Assert.assertTrue(projectsPage.checkNameInList(name)); + } + + @Test + public void testHSetDeadlineCompletionAndSave() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + ProjectPage projectPage = (ProjectPage) getContext().initPage(page.getKey()); + ProjectsPage projectsPage = (ProjectsPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey()); + projectsPage.getFirstProject(); + String name = projectPage.getName(); + projectPage.setDeadlineCompletion(); + projectPage.clickSave(); + Assert.assertTrue(projectsPage.checkNameInList(name)); + } + + @Test + public void testIDeleteDeadline() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + ProjectPage projectPage = (ProjectPage) getContext().initPage(page.getKey()); + ProjectsPage projectsPage = (ProjectsPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey()); + projectsPage.getFirstProject(); + projectPage.clickDeleteDeadline(); + Assert.assertTrue(projectPage.getDeadlineCount() == 0); + } + + @Test + public void testJDeleteProject() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + ProjectPage projectPage = (ProjectPage) getContext().initPage(page.getKey()); + ProjectsPage projectsPage = (ProjectsPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey()); + projectsPage.getFirstProject(); + String name = projectPage.getName(); + projectPage.clickSave(); + projectsPage.deleteFirst(); + projectsPage.clickConfirm(); + Assert.assertFalse(projectsPage.checkNameInList(name)); + } +} diff --git a/src/test/java/StudentTaskTest.java b/src/test/java/StudentTaskTest.java new file mode 100644 index 0000000..f55a679 --- /dev/null +++ b/src/test/java/StudentTaskTest.java @@ -0,0 +1,214 @@ +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Iterables; +import core.PageObject; +import core.TestTemplate; +import org.junit.Assert; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.MethodSorters; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import ru.ulstu.NgTrackerApplication; +import ru.ulstu.configuration.ApplicationProperties; +import students.TaskPage; +import students.TasksDashboardPage; +import students.TasksPage; + +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Map; + +@RunWith(SpringRunner.class) +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@SpringBootTest(classes = NgTrackerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +public class StudentTaskTest extends TestTemplate { + private final Map> navigationHolder = ImmutableMap.of( + new TasksPage(), Arrays.asList("Список задач", "/students/tasks"), + new TasksDashboardPage(), Arrays.asList("Панель управления", "/students/dashboard"), + new TaskPage(), Arrays.asList("Создать задачу", "/students/task?id=0") + ); + + private final String tag = "ATag"; + + @Autowired + private ApplicationProperties applicationProperties; + + + @Test + public void testACreateTask() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 2); + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + + TaskPage taskPage = (TaskPage) getContext().initPage(page.getKey()); + TasksPage tasksPage = (TasksPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 0).getKey()); + String taskName = "Task " + (new Date()).getTime(); + + taskPage.setName(taskName); + taskPage.addDeadlineDate("01.01.2020", 0); + taskPage.addDeadlineDescription("Description", 0); + taskPage.save(); + + Assert.assertTrue(tasksPage.findTask(taskName)); + } + + @Test + public void testBEditTaskName() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + TasksPage tasksPage = (TasksPage) getContext().initPage(page.getKey()); + TaskPage taskPage = (TaskPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 2).getKey()); + String taskNewName = "Task " + (new Date()).getTime(); + + tasksPage.goToFirstTask(); + taskPage.removeName(); + taskPage.setName(taskNewName); + taskPage.save(); + + Assert.assertTrue(tasksPage.findTask(taskNewName)); + } + + @Test + public void testCDeleteTask() throws InterruptedException { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + TasksPage tasksPage = (TasksPage) getContext().initPage(page.getKey()); + + Integer size = tasksPage.getTasks().size(); + tasksPage.deleteFirstTask(); + Thread.sleep(3000); + tasksPage.submit(); + + Assert.assertEquals(size - 1, tasksPage.getTasks().size()); + } + + @Test + public void testDAddDeadline() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + TasksPage tasksPage = (TasksPage) getContext().initPage(page.getKey()); + TaskPage taskPage = (TaskPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 2).getKey()); + + tasksPage.goToFirstTask(); + String taskId = taskPage.getId(); + Integer deadnum = taskPage.getDeadNum(); + + String descr = "Description"; + String date = "06.06.2019"; + String dateValue = "2019-06-06"; + + taskPage.clickAddDeadline(); + taskPage.addDeadlineDescription(descr, deadnum); + taskPage.addDeadlineDate(date, deadnum); + taskPage.save(); + + getContext().goTo(applicationProperties.getBaseUrl() + String.format("/students/task?id=%s", taskId)); + + Assert.assertTrue(taskPage.hasDeadline(descr, dateValue)); + } + + @Test + public void testEEditDeadline() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + TasksPage tasksPage = (TasksPage) getContext().initPage(page.getKey()); + TaskPage taskPage = (TaskPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 2).getKey()); + + tasksPage.goToFirstTask(); + String taskId = taskPage.getId(); + + String descr = "DescriptionTwo"; + String date = "12.12.2019"; + String dateValue = "2019-12-12"; + + taskPage.clearDeadlineDate(0); + taskPage.clearDeadlineDescription(0); + taskPage.addDeadlineDescription(descr, 0); + taskPage.addDeadlineDate(date, 0); + taskPage.save(); + + getContext().goTo(applicationProperties.getBaseUrl() + String.format("/students/task?id=%s", taskId)); + + Assert.assertTrue(taskPage.hasDeadline(descr, dateValue)); + } + + @Test + public void testFDeleteDeadline() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + TasksPage tasksPage = (TasksPage) getContext().initPage(page.getKey()); + TaskPage taskPage = (TaskPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 2).getKey()); + + tasksPage.goToFirstTask(); + String taskId = taskPage.getId(); + Integer deadNum = taskPage.getDeadNum(); + + taskPage.deleteDeadline(); + taskPage.save(); + + getContext().goTo(applicationProperties.getBaseUrl() + String.format("/students/task?id=%s", taskId)); + + Assert.assertEquals(deadNum - 1, (int) taskPage.getDeadNum()); + } + + @Test + public void testGCreateTaskWithTag() throws InterruptedException { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 2); + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + + TaskPage taskPage = (TaskPage) getContext().initPage(page.getKey()); + TasksPage tasksPage = (TasksPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 0).getKey()); + String taskName = "Task " + (new Date()).getTime(); + + taskPage.setName(taskName); + taskPage.setTag(tag); + Thread.sleep(1000); + taskPage.addDeadlineDate("01.01.2020", 0); + taskPage.addDeadlineDescription("Description", 0); + taskPage.save(); + + Assert.assertTrue(tasksPage.findTaskByTag(taskName, tag)); + } + + @Test + public void testHFindTagInFilter() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + TasksPage tasksPage = (TasksPage) getContext().initPage(page.getKey()); + + + Assert.assertTrue(tasksPage.findTag(tag)); + } + + @Test + public void testIFilterByTag() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + TasksPage tasksPage = (TasksPage) getContext().initPage(page.getKey()); + tasksPage.selectTag(tag); + + Assert.assertTrue(tasksPage.findTasksByTag(tag)); + } + + @Test + public void testJFilterByStatus() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + TasksPage tasksPage = (TasksPage) getContext().initPage(page.getKey()); + + tasksPage.selectStatus(); + Assert.assertTrue(tasksPage.findAllStatus()); + } + + +} diff --git a/src/test/java/conference/ConferencePage.java b/src/test/java/conference/ConferencePage.java new file mode 100644 index 0000000..ef0d941 --- /dev/null +++ b/src/test/java/conference/ConferencePage.java @@ -0,0 +1,116 @@ +package conference; + +import core.PageObject; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; + +import java.util.List; + +public class ConferencePage extends PageObject { + + public String getSubTitle() { + return driver.findElement(By.tagName("h3")).getText(); + } + + public String getId() { + return driver.findElement(By.id("id")).getAttribute("value"); + } + + public void setName(String name) { + driver.findElement(By.id("title")).sendKeys(name); + } + + public String getName() { + return driver.findElement(By.id("title")).getAttribute("value"); + } + + public void clearName() { + driver.findElement(By.id("title")).clear(); + } + + public void clickSaveBut() { + driver.findElement(By.id("send-message-button")).click(); + } + + public void clickAddDeadlineBut() { + driver.findElement(By.id("addDeadline")).click(); + } + + public List getDeadlineList() { + return driver.findElements(By.className("deadline")); + } + + public Integer getDeadlineCount() { + return driver.findElements(By.className("deadline")).size(); + } + + public void setDeadlineDescription(String description, Integer i) { + driver.findElement(By.id(String.format("deadlines%d.description", i))).sendKeys(description); + } + + public void setDeadlineDate(String date, Integer i) { + driver.findElement(By.id(String.format("deadlines%d.date", i))).sendKeys(date); + } + + public void clickTakePartBut() { + driver.findElement(By.id("take-part")).click(); + } + + public Boolean isTakePartButDisabledValueTrue() { + return driver.findElement(By.id("take-part")).getAttribute("disabled").equals("true"); + } + + public Integer getMemberCount() { + return driver.findElements(By.className("member")).size(); + } + + public void clickDeleteDeadlineBut() { + driver.findElement(By.xpath("//*[@id=\"deadlines\"]/div/input[4]")).click(); + } + + public void showAllowToAttachArticles() { + driver.findElement(By.cssSelector("button[data-id=\"paperIds\"]")).click(); + } + + public void clickAddPaperBut() { + driver.findElement(By.id("add-paper")).click(); + } + + + public List getArticles() { + return driver.findElements(By.className("paper")); + } + + public Integer getArticlesCount() { + return driver.findElements(By.className("paper")).size(); + } + + public WebElement selectArticle() { + WebElement webElement = driver.findElement(By.xpath("//*[@id=\"conference-form\"]/div/div[2]/div[5]/div/div/div[2]/ul/li[1]/a")); + webElement.click(); + return webElement; + } + + public void clickUndockArticleBut() { + driver.findElement(By.name("removePaper")).click(); + } + + public boolean checkDeadline(String description, String dateValue) { + return getDeadlineList() + .stream() + .anyMatch(webElement -> { + return webElement.findElement(By.className("deadline-text")).getAttribute("value").equals(description) + && webElement.findElement(By.cssSelector("input[type=\"date\"]")).getAttribute("value").equals(dateValue); + }); + } + + public boolean checkArticle(String paperName) { + return getArticles() + .stream() + .anyMatch(webElement -> webElement + .findElements(By.tagName("input")) + .get(1).getAttribute("value") + .equals(paperName)); + } + +} \ No newline at end of file diff --git a/src/test/java/conference/ConferencesDashboardPage.java b/src/test/java/conference/ConferencesDashboardPage.java new file mode 100644 index 0000000..d358c4a --- /dev/null +++ b/src/test/java/conference/ConferencesDashboardPage.java @@ -0,0 +1,11 @@ +package conference; + +import core.PageObject; +import org.openqa.selenium.By; + +public class ConferencesDashboardPage extends PageObject { + + public String getSubTitle() { + return driver.findElement(By.tagName("h2")).getText(); + } +} diff --git a/src/test/java/conference/ConferencesPage.java b/src/test/java/conference/ConferencesPage.java new file mode 100644 index 0000000..c11429f --- /dev/null +++ b/src/test/java/conference/ConferencesPage.java @@ -0,0 +1,47 @@ +package conference; + +import core.PageObject; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; + +import java.util.List; + +public class ConferencesPage extends PageObject { + + public String getSubTitle() { + return driver.findElement(By.tagName("h3")).getText(); + } + + public List getConferencesList() { + return driver.findElements(By.cssSelector("span.h6.float-left.m-2")); + } + + public void getFirstConference() { + driver.findElement(By.xpath("//*[@id=\"conferences\"]/div/div[2]/div[1]/div[1]/div/a")).click(); + } + + public void selectMember() { + driver.findElements(By.className("bootstrap-select")).get(0).findElement(By.className("btn")).click(); + driver.findElements(By.className("bootstrap-select")).get(0).findElements(By.className("dropdown-item")).get(1).click(); + } + + public void selectYear() { + driver.findElements(By.className("bootstrap-select")).get(1).findElement(By.className("btn")).click(); + driver.findElements(By.className("bootstrap-select")).get(1).findElements(By.className("dropdown-item")).get(1).click(); + } + + public void deleteFirst() { + js.executeScript("$('input[data-confirm]').click();"); + } + + public void clickConfirm() { + driver.findElement(By.id("deleteConference")).click(); + } + + + public boolean checkNameInList(String newConferenceName) { + return getConferencesList() + .stream() + .anyMatch(webElement -> webElement.getText().equals(newConferenceName)); + } +} \ No newline at end of file diff --git a/src/test/java/context/Context.java b/src/test/java/context/Context.java index b32c08e..474b1cb 100644 --- a/src/test/java/context/Context.java +++ b/src/test/java/context/Context.java @@ -6,8 +6,6 @@ import org.openqa.selenium.WebDriver; import java.util.concurrent.TimeUnit; -//import org.openqa.selenium.support.PageFactory; - public abstract class Context { private final static String DRIVER_LOCATION = "drivers/%s"; diff --git a/src/test/java/core/PageObject.java b/src/test/java/core/PageObject.java index d1fae83..e8eae6e 100644 --- a/src/test/java/core/PageObject.java +++ b/src/test/java/core/PageObject.java @@ -1,14 +1,25 @@ package core; +import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; +import org.openqa.selenium.support.PageFactory; +import org.openqa.selenium.support.ui.WebDriverWait; public abstract class PageObject { protected WebDriver driver; + protected JavascriptExecutor js; + protected WebDriverWait waiter; public abstract String getSubTitle(); public PageObject setDriver(WebDriver driver) { this.driver = driver; + js = (JavascriptExecutor) driver; + waiter = new WebDriverWait(driver, 10); return this; } + + public void initElements() { + PageFactory.initElements(driver, this); + } } diff --git a/src/test/java/grant/GrantPage.java b/src/test/java/grant/GrantPage.java new file mode 100644 index 0000000..75fbf8a --- /dev/null +++ b/src/test/java/grant/GrantPage.java @@ -0,0 +1,149 @@ +package grant; + +import core.PageObject; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.Select; + +import java.util.List; + +public class GrantPage extends PageObject { + @Override + public String getSubTitle() { + return driver.findElement(By.tagName("h2")).getText(); + } + + public String getId() { + return driver.findElement(By.id("grantId")).getAttribute("value"); + } + + public void setTitle(String name) { + driver.findElement(By.id("title")).clear(); + driver.findElement(By.id("title")).sendKeys(name); + } + + public String getTitle() { + return driver.findElement(By.id("title")).getAttribute("value"); + } + + public void setDeadline(String date, Integer i, String description) { + driver.findElement(By.id(String.format("deadlines%d.date", i))).sendKeys(date); + driver.findElement(By.id(String.format("deadlines%d.description", i))).sendKeys(description); + } + + public void setLeader() { + WebElement webElement = driver.findElement(By.id("leaderId")); + Select selectLeader = new Select(webElement); + selectLeader.selectByVisibleText("Романов"); + } + + public void saveGrant() { + driver.findElement(By.id("sendMessageButton")).click(); + } + + public boolean checkBlankFields() { + return driver.findElements(By.className("alert-danger")).size() > 0; + } + + public List getAttachedPapers() { + try { + return driver.findElement(By.className("div-selected-papers")).findElements(By.tagName("div")); + } catch (Exception ex) { + return null; + } + } + + public List attachPaper() { + WebElement selectPapers = driver.findElement(By.id("allPapers")); + Select select = new Select(selectPapers); + List selectedOptions = select.getAllSelectedOptions(); + List allOptions = select.getOptions(); + if (selectedOptions.size() >= allOptions.size()) { + for (int i = 0; i < allOptions.size(); i++) { + if (!allOptions.get(i).equals(selectedOptions.get(i))) { + select.selectByVisibleText(allOptions.get(i).getText()); + selectedOptions.add(allOptions.get(i)); + return selectedOptions; + } + } + } else { + select.selectByVisibleText(allOptions.get(0).getText()); + selectedOptions.add(allOptions.get(0)); + return selectedOptions; + } + return null; + } + + public List deletePaper() { + WebElement selectPapers = driver.findElement(By.id("allPapers")); + Select select = new Select(selectPapers); + select.deselectByVisibleText(select.getFirstSelectedOption().getText()); + return select.getAllSelectedOptions(); + } + + public List getDeadlineList() { + return driver.findElements(By.id("deadlines")); + } + + public Integer getDeadlineCount() { + return getDeadlineList().size(); + } + + public void addDeadline() { + driver.findElement(By.id("addDeadline")).click(); + } + + public boolean checkDeadline(String description, String dateValue) { + return getDeadlineList() + .stream() + .anyMatch(webElement -> { + return webElement.findElement(By.className("div-deadline-description")).findElement( + By.tagName("input")).getAttribute("value").equals(description) + && webElement.findElement(By.className("form-deadline-date")).getAttribute("value").equals(dateValue); + }); + } + + public void deleteDeadline() { + driver.findElements(By.className("btn-delete-deadline")).get(0).click(); + } + + public List addAuthor() { + WebElement selectAuthors = driver.findElement(By.id("authors")); + Select select = new Select(selectAuthors); + List selectedOptions = select.getAllSelectedOptions(); + List allOptions = select.getOptions(); + int i = 0; + while (i < selectedOptions.size()) { + if (!allOptions.get(i).equals(selectedOptions.get(i))) { + select.selectByVisibleText(allOptions.get(i).getText()); + selectedOptions.add(allOptions.get(i)); + return selectedOptions; + } else { + i++; + } + } + if (selectedOptions.size() != allOptions.size()) { + select.selectByVisibleText(allOptions.get(i).getText()); + selectedOptions.add(allOptions.get(i)); + } + return selectedOptions; + } + + public void deleteAuthor() { + WebElement selectAuthors = driver.findElement(By.id("authors")); + Select select = new Select(selectAuthors); + List selectedOptions = select.getAllSelectedOptions(); + if (selectedOptions.size() != 0) { + select.deselectByVisibleText(selectedOptions.get(0).getText()); + } + } + + public void setDescription(String description) { + driver.findElement(By.id("comment")).clear(); + driver.findElement(By.id("comment")).sendKeys(description); + } + + public String getDescription() { + return driver.findElement(By.id("comment")).getText(); + } +} diff --git a/src/test/java/grant/GrantsDashboardPage.java b/src/test/java/grant/GrantsDashboardPage.java new file mode 100644 index 0000000..036e785 --- /dev/null +++ b/src/test/java/grant/GrantsDashboardPage.java @@ -0,0 +1,11 @@ +package grant; + +import core.PageObject; +import org.openqa.selenium.By; + +public class GrantsDashboardPage extends PageObject { + @Override + public String getSubTitle() { + return driver.findElement(By.tagName("h2")).getText(); + } +} diff --git a/src/test/java/grant/GrantsPage.java b/src/test/java/grant/GrantsPage.java new file mode 100644 index 0000000..33c388d --- /dev/null +++ b/src/test/java/grant/GrantsPage.java @@ -0,0 +1,66 @@ +package grant; + +import core.PageObject; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; + +import java.util.List; + +public class GrantsPage extends PageObject { + @Override + public String getSubTitle() { + return driver.findElement(By.tagName("h2")).getText(); + } + + public List getGrantsList() { + return driver.findElements(By.className("grant-row")); + } + + public boolean findGrantByTitle(String grantTitle) { + return getGrantsList() + .stream() + .map(el -> el.findElement(By.cssSelector("span.h6"))) + .anyMatch(webElement -> webElement.getText().equals(grantTitle)); + } + + public void deleteFirst() throws InterruptedException { + WebElement findDeleteButton = driver.findElement(By.xpath("//*[@id=\"grants\"]/div/div[2]/div[1]/div[1]/div")); + findDeleteButton.click(); + Thread.sleep(3000); + WebElement grant = driver.findElement(By.xpath("//*[@id=\"grants\"]/div/div[2]/div[1]/div[1]/div/a[2]")); + grant.click(); + WebElement ok = driver.findElement(By.id("dataConfirmOK")); + ok.click(); + } + + public void getFirstGrant() { + driver.findElement(By.xpath("//*[@id=\"grants\"]/div/div[2]/div[1]/div[1]/div/a[1]")).click(); + } + + public WebElement getFirstGrantWithoutClick() { + return driver.findElement(By.xpath("//*[@id=\"grants\"]/div/div[2]/div[1]/div[1]")); + } + + public String getGrantTitle(WebElement webElement) { + return webElement.findElement(By.cssSelector("span.h6")).getText(); + } + + public WebElement getGrantByTitle(String title) { + List list = getGrantsList(); + for (int i = 0; i < list.size(); i++) { + if (getGrantTitle(list.get(i)).equals(title)) { + return list.get(i); + } + } + return null; + } + + public Integer getAuthorsCount(WebElement webElement) { + String authors = webElement.findElement(By.className("text-muted")).getText(); + if (!authors.equals("")) { + String[] mas = authors.split(","); + return mas.length; + } + return 0; + } +} diff --git a/src/test/java/grant/KiasPage.java b/src/test/java/grant/KiasPage.java new file mode 100644 index 0000000..5864511 --- /dev/null +++ b/src/test/java/grant/KiasPage.java @@ -0,0 +1,11 @@ +package grant; + +import core.PageObject; +import org.openqa.selenium.By; + +public class KiasPage extends PageObject { + @Override + public String getSubTitle() { + return driver.findElement(By.tagName("h1")).getText(); + } +} diff --git a/src/test/java/paper/PaperPage.java b/src/test/java/paper/PaperPage.java index 9c3c357..908f8a1 100644 --- a/src/test/java/paper/PaperPage.java +++ b/src/test/java/paper/PaperPage.java @@ -2,10 +2,216 @@ package paper; import core.PageObject; import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.FindBy; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.Select; + +import java.util.List; public class PaperPage extends PageObject { + @FindBy(id = "title") + private WebElement titleInput; + + @FindBy(id = "sendMessageButton") + private WebElement sendMessageButton; + + @FindBy(id = "id") + private WebElement idInput; + + @FindBy(css = "#messages .alert-danger span") + private WebElement dangerMessage; + + @FindBy(className = "deadline") + private List deadlines; + + @FindBy(className = "deadline-date") + private List deadlineDates; + + @FindBy(className = "deadline-desc") + private List deadlineDescs; + + @FindBy(css = ".alert.alert-danger") + private List dangerAlerts; + + @FindBy(className = "collapse-heading") + private WebElement firstCollapsedLink; + + @FindBy(id = "nav-references-tab") + private WebElement referenceTab; + + @FindBy(id = "nav-latex-tab") + private WebElement latexTab; + + @FindBy(id = "latex-text") + private WebElement latexTextarea; + + @FindBy(id = "addReference") + private WebElement addReferenceButton; + + @FindBy(css = "input.author ") + private WebElement firstAuthorInput; + + @FindBy(css = "input.publicationTitle") + private WebElement firstPublicationTitleInput; + + @FindBy(css = "input.publicationYear") + private WebElement firstPublicationYearInput; + + @FindBy(css = "input.publisher") + private WebElement firstPublisherInput; + + @FindBy(css = "input.pages") + private WebElement firstPagesInput; + + @FindBy(css = "input.journalOrCollectionTitle") + private WebElement firstJournalOrCollectionTitleInput; + + @FindBy(id = "formatBtn") + private WebElement formatButton; + + @FindBy(id = "formattedReferencesArea") + private WebElement formatArea; + + @FindBy(id = "url") + private WebElement urlInput; + + @FindBy(id = "pdfBtn") + private WebElement pdfButton; + + @FindBy(css = "input.author ") + private List authorInputs; + public String getSubTitle() { return driver.findElement(By.tagName("h2")).getText(); } + + public void clickReferenceTab() { + js.executeScript("document.getElementById('nav-references-tab').scrollIntoView(false);"); + referenceTab.click(); + } + + public void clickLatexTab() { + latexTab.click(); + } + + public void showFirstReference() { + waiter.until(ExpectedConditions.elementToBeClickable(firstCollapsedLink)); + firstCollapsedLink.click(); + } + + public void clickAddReferenceButton() { + js.executeScript("arguments[0].click()", addReferenceButton); + } + + public void clickFormatButton() { + formatButton.click(); + } + + public void clickPdfButton() { + pdfButton.click(); + } + + public void setTitle(String title) { + titleInput.clear(); + titleInput.sendKeys(title); + } + + public void setLatexText(String text) { + waiter.until(ExpectedConditions.visibilityOf(latexTextarea)); + latexTextarea.clear(); + latexTextarea.sendKeys(text); + } + + public void setFirstReferenceAuthors(String authors) { + waiter.until(ExpectedConditions.visibilityOf(firstAuthorInput)); + + firstAuthorInput.clear(); + firstAuthorInput.sendKeys(authors); + } + + public void setFirstReferencePublicationTitle(String title) { + firstPublicationTitleInput.clear(); + firstPublicationTitleInput.sendKeys(title); + } + + public void setFirstReferencePublicationYear(String year) { + firstPublicationYearInput.clear(); + firstPublicationYearInput.sendKeys(year); + } + + public void setFirstReferencePublisher(String publisher) { + firstPublisherInput.clear(); + firstPublisherInput.sendKeys(publisher); + } + + public void setFirstReferencePages(String pages) { + firstPagesInput.clear(); + firstPagesInput.sendKeys(pages); + } + + public void setFirstReferenceJournalOrCollectionTitle(String journal) { + firstJournalOrCollectionTitleInput.clear(); + firstJournalOrCollectionTitleInput.sendKeys(journal); + } + + public void setUrl(String url) { + urlInput.clear(); + urlInput.sendKeys(url); + } + + public void setFormatStandardSpringer() { + Select standards = new Select(driver.findElement(By.id("formatStandard"))); + standards.selectByValue("SPRINGER"); + } + + public void setDeadlineDate(Integer deadlineNumber, String date) { + deadlineDates.get(deadlineNumber - 1).sendKeys(date); + } + + public void setDeadlineDescription(Integer deadlineNumber, String desc) { + deadlineDescs.get(deadlineNumber - 1).clear(); + deadlineDescs.get(deadlineNumber - 1).sendKeys(desc); + } + + public boolean hasAlert(String alertMessage) { + return dangerAlerts + .stream() + .anyMatch( + webElement -> webElement.getText().contains(alertMessage)); + } + + public void clickSaveBtn() { + sendMessageButton.click(); + } + + public String getId() { + return idInput.getAttribute("value"); + } + + public String getFormatString() { + waiter.until(ExpectedConditions.attributeToBeNotEmpty(formatArea, "value")); + return formatArea.getAttribute("value"); + } + + public boolean deadlineExist(String desc, String date) { + return deadlines + .stream() + .anyMatch( + webElement -> webElement.findElement(By.className("deadline-desc")).getAttribute("value").equals(desc) + && webElement.findElement(By.className("deadline-date")).getAttribute("value").equals(date)); + } + + public boolean authorsExists(String authors) { + return authorInputs + .stream() + .anyMatch( + webElement -> webElement.getAttribute("value").equals(authors)); + } + + public boolean dangerMessageExist(String message) { + waiter.until(ExpectedConditions.visibilityOf(dangerMessage)); + return dangerMessage.getText().equals(message); + } } diff --git a/src/test/java/paper/PapersDashboardPage.java b/src/test/java/paper/PapersDashboardPage.java index 51d7cb8..4567490 100644 --- a/src/test/java/paper/PapersDashboardPage.java +++ b/src/test/java/paper/PapersDashboardPage.java @@ -2,10 +2,23 @@ package paper; import core.PageObject; import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.FindBy; + +import java.util.List; public class PapersDashboardPage extends PageObject { + @FindBy(className = "externalLink") + private List externalLinks; public String getSubTitle() { return driver.findElement(By.tagName("h2")).getText(); } + + public boolean externalLinkExists(String link) { + return externalLinks + .stream() + .anyMatch( + webElement -> webElement.getAttribute("href").equals(link)); + } } diff --git a/src/test/java/paper/PapersPage.java b/src/test/java/paper/PapersPage.java index f191d9b..620d0c0 100644 --- a/src/test/java/paper/PapersPage.java +++ b/src/test/java/paper/PapersPage.java @@ -2,10 +2,60 @@ package paper; import core.PageObject; import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.FindBy; +import org.openqa.selenium.support.ui.ExpectedConditions; + +import java.util.List; public class PapersPage extends PageObject { + @FindBy(css = ".paper-row .h6") + private List paperTitles; + + @FindBy(className = "paper-row") + private List paperItems; + + @FindBy(className = "remove-paper") + private WebElement removeFirstPaperButton; + + @FindBy(id = "dataConfirmOK") + private WebElement confirmDeleteButton; + + @FindBy(id = "addDeadline") + private WebElement addDeadlineButton; + + @FindBy(css = ".paper-row a:nth-child(2)") + private WebElement firstPaper; public String getSubTitle() { return driver.findElement(By.tagName("h2")).getText(); } + + public void clickFirstPaper() { + firstPaper.click(); + } + + public void clickAddDeadline() { + addDeadlineButton.click(); + } + + public void clickRemoveFirstPaperButton() { + js.executeScript("arguments[0].click()", removeFirstPaperButton); + } + + public void clickConfirmDeleteButton() { + waiter.until(ExpectedConditions.visibilityOf(confirmDeleteButton)); + confirmDeleteButton.click(); + } + + public boolean havePaperWithTitle(String title) { + return paperTitles + .stream() + .anyMatch(webElement -> webElement.getText().equals(title)); + } + + public int getPapersCount() { + return paperItems.size(); + } + } diff --git a/src/test/java/project/ProjectDashboard.java b/src/test/java/project/ProjectDashboard.java new file mode 100644 index 0000000..0b36204 --- /dev/null +++ b/src/test/java/project/ProjectDashboard.java @@ -0,0 +1,11 @@ +package project; + +import core.PageObject; +import org.openqa.selenium.By; + +public class ProjectDashboard extends PageObject { + + public String getSubTitle() { + return driver.findElement(By.tagName("h2")).getText(); + } +} diff --git a/src/test/java/project/ProjectPage.java b/src/test/java/project/ProjectPage.java new file mode 100644 index 0000000..1bbad67 --- /dev/null +++ b/src/test/java/project/ProjectPage.java @@ -0,0 +1,141 @@ +package project; + +import core.PageObject; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; + +import java.util.List; + +public class ProjectPage extends PageObject { + + public String getSubTitle() { + return driver.findElement(By.tagName("h3")).getText(); + } + + public String getId() { + return driver.findElement(By.id("id")).getAttribute("value"); + } + + public void setName(String name) { + driver.findElement(By.id("title")).sendKeys(name); + } + + public String getName() { + return driver.findElement(By.id("title")).getAttribute("value"); + } + + public void clearName() { + driver.findElement(By.id("title")).clear(); + } + + public void clickSave() { + driver.findElement(By.id("sendMessageButton")).click(); + } + + public void clickAddDeadline() { + driver.findElement(By.id("addDeadline")).click(); + } + + public void addDeadlineDate(String deadDate, Integer deadNum) { + driver.findElement(By.id(String.format("deadlines%d.date", deadNum))).sendKeys(deadDate); + } + + public void addDeadlineDescription(String description) { + driver.findElement(By.id("deadlines0.description")).sendKeys(description); + } + + public void setDeadlineCompletion() { + driver.findElement(By.id("deadlines0.done1")).click(); + } + + public void setStatus() { + driver.findElement(By.id("status")).click(); + getFirstStatus(); + } + + public void getFirstStatus() { + driver.findElement(By.xpath("//*[@id=\"status\"]/option[1]")).click(); + } + + public void addDescription(String description) { + driver.findElement(By.id("description")).sendKeys(description); + } + + public void addLink(String link) { + driver.findElement(By.id("repository")).sendKeys(link); + } + + public List getDeadlineList() { + return driver.findElements(By.className("deadline")); + } + + public Integer getDeadlineCount() { + return driver.findElements(By.className("deadline")).size(); + } + + public void setExecutors() { + driver.findElement(By.id("status")).click(); + getFirstExecutor(); + } + + public void getFirstExecutor() { + driver.findElement(By.xpath("//*[@id=\"status\"]/option[1]")).click(); + } + + public void setDeadlineDescription(String description, Integer i) { + driver.findElement(By.id(String.format("deadlines%d.description", i))).sendKeys(description); + } + + public void setDeadlineDate(String date, Integer i) { + driver.findElement(By.id(String.format("deadlines%d.date", i))).sendKeys(date); + } + + public Boolean isTakePartButDisabledValueTrue() { + return driver.findElement(By.id("take-part")).getAttribute("disabled").equals("true"); + } + + public Integer getMemberCount() { + return driver.findElements(By.className("member")).size(); + } + + public void clickDeleteDeadline() { + driver.findElement(By.className("btn-danger")).click(); + } + + public void showAllowToAttachArticles() { + driver.findElement(By.cssSelector("button[data-id=\"paperIds\"]")).click(); + } + + public void clickAddPaperBut() { + driver.findElement(By.id("add-paper")).click(); + } + + + public List getArticles() { + return driver.findElements(By.className("paper")); + } + + public Integer getArticlesCount() { + return driver.findElements(By.className("paper")).size(); + } + + public WebElement selectArticle() { + WebElement webElement = driver.findElement(By.xpath("//*[@id=\"project-form\"]/div/div[2]/div[5]/div/div/div[2]/ul/li[1]/a")); + webElement.click(); + return webElement; + } + + public void clickUndockArticleBut() { + driver.findElement(By.name("removePaper")).click(); + } + + public boolean checkDeadline(String description, String dateValue) { + return getDeadlineList() + .stream() + .anyMatch(webElement -> { + return webElement.findElement(By.className("deadline-text")).getAttribute("value").equals(description) + && webElement.findElement(By.cssSelector("input[type=\"date\"]")).getAttribute("value").equals(dateValue); + }); + } + +} \ No newline at end of file diff --git a/src/test/java/project/ProjectsPage.java b/src/test/java/project/ProjectsPage.java new file mode 100644 index 0000000..64c50b7 --- /dev/null +++ b/src/test/java/project/ProjectsPage.java @@ -0,0 +1,41 @@ +package project; + +import core.PageObject; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; + +import java.util.List; + +public class ProjectsPage extends PageObject { + + public String getSubTitle() { + return driver.findElement(By.tagName("h2")).getText(); + } + + public List getProjectsList() { + return driver.findElements(By.cssSelector("span.h6")); + } + + public void getFirstProject() { + driver.findElement(By.xpath("//*[@id=\"projects\"]/div/div[2]/div[1]/div[1]/div/a")).click(); + } + + public void selectMember() { + driver.findElements(By.className("bootstrap-select")).get(0).findElement(By.className("btn")).click(); + driver.findElements(By.className("bootstrap-select")).get(0).findElements(By.className("dropdown-item")).get(1).click(); + } + + public void deleteFirst() { + js.executeScript("$('a[data-confirm]').click();"); + } + + public void clickConfirm() { + driver.findElement(By.id("dataConfirmOK")).click(); + } + + public boolean checkNameInList(String newProjectName) { + return getProjectsList() + .stream() + .anyMatch(webElement -> webElement.getText().equals(newProjectName)); + } +} \ No newline at end of file diff --git a/src/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java b/src/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java new file mode 100644 index 0000000..d4640b1 --- /dev/null +++ b/src/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java @@ -0,0 +1,278 @@ +package ru.ulstu.conference.service; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import org.springframework.data.domain.Sort; +import ru.ulstu.conference.model.Conference; +import ru.ulstu.conference.model.ConferenceDto; +import ru.ulstu.conference.model.ConferenceFilterDto; +import ru.ulstu.conference.model.ConferenceUser; +import ru.ulstu.conference.repository.ConferenceRepository; +import ru.ulstu.deadline.model.Deadline; +import ru.ulstu.deadline.service.DeadlineService; +import ru.ulstu.paper.model.Paper; +import ru.ulstu.paper.service.PaperService; +import ru.ulstu.ping.service.PingService; +import ru.ulstu.timeline.service.EventService; +import ru.ulstu.user.model.User; +import ru.ulstu.user.service.UserService; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class ConferenceServiceTest { + + @Mock + ConferenceRepository conferenceRepository; + + @Mock + DeadlineService deadlineService; + + @Mock + ConferenceUserService conferenceUserService; + + @Mock + PaperService paperService; + + @Mock + UserService userService; + + @Mock + EventService eventService; + + @Mock + ConferenceNotificationService conferenceNotificationService; + + @Mock + PingService pingService; + + @InjectMocks + ConferenceService conferenceService; + + private final static Integer ID = 1; + private final static Integer INDEX = 0; + private final static String NAME = "Name"; + private final static String DESCRIPTION = "Desc"; + private final static boolean TRUE = true; + private final static Integer YEAR = 2019; + private final static Sort SORT = new Sort(Sort.Direction.DESC, "beginDate"); + + private List conferences; + private List deadlines; + private List papers; + private List conferenceUsers; + + private Conference conferenceWithId; + + private Paper paperWithId; + private Paper paperWithoutId; + + private ConferenceDto conferenceDto; + private User user; + private Deadline deadline; + + @Before + public void setUp() throws Exception { + conferences = new ArrayList<>(); + conferenceWithId = new Conference(); + + conferenceWithId.setId(ID); + conferenceWithId.setTitle(NAME); + conferenceWithId.setDescription(DESCRIPTION); + + paperWithId = new Paper(); + paperWithId.setId(1); + paperWithId.setTitle(NAME); + + paperWithoutId = new Paper(); + paperWithoutId.setTitle(NAME); + + papers = new ArrayList<>(); + papers.add(paperWithId); + papers.add(paperWithoutId); + + deadlines = new ArrayList<>(); + deadline = new Deadline(new Date(), DESCRIPTION); + deadline.setId(ID); + deadlines.add(deadline); + + ConferenceUser conferenceUser = new ConferenceUser(); + conferenceUser.setDeposit(ConferenceUser.Deposit.ARTICLE); + conferenceUser.setParticipation(ConferenceUser.Participation.INTRAMURAL); + user = new User(); + user.setFirstName(NAME); + conferenceUser.setUser(user); + + conferenceUsers = new ArrayList<>(); + conferenceUsers.add(conferenceUser); + + conferences.add(conferenceWithId); + conferenceDto = new ConferenceDto(conferenceWithId); + } + + @Test + public void getExistConferenceById() { + when(conferenceRepository.findOne(ID)).thenReturn(conferenceWithId); + when(paperService.findAllNotSelect(new ArrayList<>())).thenReturn(papers); + when(userService.getCurrentUser()).thenReturn(user); + + ConferenceDto newConferenceDto = new ConferenceDto(conferenceWithId); + newConferenceDto.setNotSelectedPapers(papers); + newConferenceDto.setDisabledTakePart(!TRUE); + ConferenceDto result = conferenceService.getExistConferenceById(ID); + + assertEquals(newConferenceDto.getId(), result.getId()); + assertEquals(newConferenceDto.getNotSelectedPapers(), result.getNotSelectedPapers()); + assertEquals(newConferenceDto.isDisabledTakePart(), result.isDisabledTakePart()); + } + + @Test + public void getNewConference() { + when(paperService.findAllNotSelect(new ArrayList<>())).thenReturn(papers); + + ConferenceDto newConferenceDto = new ConferenceDto(); + newConferenceDto.setNotSelectedPapers(papers); + ConferenceDto result = conferenceService.getNewConference(); + + assertEquals(newConferenceDto.getId(), result.getId()); + assertEquals(newConferenceDto.getNotSelectedPapers(), result.getNotSelectedPapers()); + assertEquals(newConferenceDto.isDisabledTakePart(), result.isDisabledTakePart()); + } + + @Test + public void findAll() { + when(conferenceRepository.findAll(SORT)).thenReturn(conferences); + + assertEquals(Collections.singletonList(conferenceWithId), conferenceService.findAll()); + } + + @Test + public void create() throws IOException { + when(paperService.findPaperById(ID)).thenReturn(paperWithId); + when(paperService.create(new Paper())).thenReturn(paperWithoutId); + when(deadlineService.saveOrCreate(new ArrayList<>())).thenReturn(deadlines); + when(conferenceUserService.saveOrCreate(new ArrayList<>())).thenReturn(conferenceUsers); + when(conferenceRepository.save(new Conference())).thenReturn(conferenceWithId); + + conferenceDto.setPapers(papers); + conferenceDto.setDeadlines(deadlines); + conferenceDto.setUsers(conferenceUsers); + conferenceDto.getPaperIds().add(ID); + + Conference newConference = new Conference(); + newConference.setId(ID); + newConference.setTitle(NAME); + newConference.setDescription(DESCRIPTION); + newConference.setPapers(papers); + newConference.getPapers().add(paperWithId); + newConference.setDeadlines(deadlines); + newConference.setUsers(conferenceUsers); + + assertEquals(newConference, conferenceService.create(conferenceDto)); + } + + @Test + public void delete() { + when(conferenceRepository.exists(ID)).thenReturn(true); + when(conferenceRepository.findOne(ID)).thenReturn(conferenceWithId); + assertTrue(conferenceService.delete(ID)); + } + + @Test + public void addDeadline() { + ConferenceDto newConferenceDto = new ConferenceDto(); + newConferenceDto.getDeadlines().add(new Deadline()); + conferenceDto.getDeadlines().clear(); + + assertEquals(newConferenceDto.getDeadlines().get(0), conferenceService.addDeadline(conferenceDto).getDeadlines().get(0)); + } + + @Test + public void removeDeadline() throws IOException { + ConferenceDto newConferenceDto = new ConferenceDto(); + newConferenceDto.getRemovedDeadlineIds().add(ID); + conferenceDto.getDeadlines().add(deadline); + ConferenceDto result = conferenceService.removeDeadline(conferenceDto, INDEX); + + assertEquals(newConferenceDto.getDeadlines(), result.getDeadlines()); + assertEquals(newConferenceDto.getRemovedDeadlineIds(), result.getRemovedDeadlineIds()); + } + + @Test + public void addPaper() { + when(userService.getCurrentUser()).thenReturn(user); + + ConferenceDto newConferenceDto = new ConferenceDto(); + newConferenceDto.getPapers().add(paperWithoutId); + conferenceDto.getPapers().clear(); + ConferenceDto result = conferenceService.addPaper(conferenceDto); + result.getPapers().get(INDEX).setTitle(NAME); // приходится вручную назначать название, т.е. название зависит от даты + + assertEquals(newConferenceDto.getPapers(), result.getPapers()); + } + + @Test + public void removePaper() throws IOException { + ConferenceDto newConferenceDto = new ConferenceDto(); + newConferenceDto.getNotSelectedPapers().add(paperWithId); + newConferenceDto.getPapers().add(paperWithoutId); + conferenceDto.getPapers().add(paperWithId); + conferenceDto.getPapers().add(paperWithoutId); + ConferenceDto result = conferenceService.removePaper(conferenceDto, INDEX); + + assertEquals(newConferenceDto.getPapers(), result.getPapers()); + assertEquals(newConferenceDto.getNotSelectedPapers(), result.getNotSelectedPapers()); + } + + @Test + public void takePart() throws IOException { + when(userService.getCurrentUser()).thenReturn(user); + + ConferenceDto newConferenceDto = new ConferenceDto(); + newConferenceDto.setUsers(conferenceUsers); + newConferenceDto.setDisabledTakePart(TRUE); + conferenceDto.getPapers().clear(); + ConferenceDto result = conferenceService.takePart(conferenceDto); + + assertEquals(newConferenceDto.getUsers(), result.getUsers()); + assertEquals(newConferenceDto.isDisabledTakePart(), result.isDisabledTakePart()); + } + + @Test + public void getAllUsers() { + List users = Collections.singletonList(user); + when(userService.findAll()).thenReturn(users); + assertEquals(users, conferenceService.getAllUsers()); + } + + @Test + public void filter() { + when(userService.findById(ID)).thenReturn(user); + when(conferenceRepository.findByUserAndYear(user, YEAR)).thenReturn(conferences); + + ConferenceFilterDto conferenceFilterDto = new ConferenceFilterDto(); + conferenceFilterDto.setFilterUserId(ID); + conferenceFilterDto.setYear(YEAR); + + assertEquals(Collections.singletonList(conferenceDto), conferenceService.filter(conferenceFilterDto)); + } + + @Test + public void isAttachedToConference() { + when(conferenceRepository.isPaperAttached(ID)).thenReturn(TRUE); + + assertTrue(conferenceService.isAttachedToConference(ID)); + } +} \ No newline at end of file diff --git a/src/test/java/ru/ulstu/grant/service/GrantServiceTest.java b/src/test/java/ru/ulstu/grant/service/GrantServiceTest.java new file mode 100644 index 0000000..99d7ef6 --- /dev/null +++ b/src/test/java/ru/ulstu/grant/service/GrantServiceTest.java @@ -0,0 +1,231 @@ +package ru.ulstu.grant.service; + +import org.apache.commons.lang3.StringUtils; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.runners.MockitoJUnitRunner; +import ru.ulstu.deadline.model.Deadline; +import ru.ulstu.deadline.service.DeadlineService; +import ru.ulstu.grant.model.Grant; +import ru.ulstu.grant.model.GrantDto; +import ru.ulstu.grant.repository.GrantRepository; +import ru.ulstu.paper.model.Paper; +import ru.ulstu.paper.model.PaperDto; +import ru.ulstu.paper.service.PaperService; +import ru.ulstu.timeline.service.EventService; +import ru.ulstu.user.model.User; +import ru.ulstu.user.service.UserService; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class GrantServiceTest { + + @Mock + GrantRepository grantRepository; + + @Mock + DeadlineService deadlineService; + + @Mock + PaperService paperService; + + @Mock + UserService userService; + + @Mock + EventService eventService; + + @Mock + GrantNotificationService grantNotificationService; + + @InjectMocks + GrantService grantService; + + private final static Integer ID = 1; + private final static Integer INDEX = 0; + private final static String TITLE = "Title"; + private final static String COMMENT = "Comment"; + private final static boolean TRUE = true; + private final static Integer YEAR = 2019; + private final static Integer MAX_DISPLAY_SIZE = 50; + + private List grants; + private List grantDtos; + private List deadlines; + private List papers; + private PaperDto paperDto; + private List paperDtos; + private Set authors; + private GrantDto grantDto; + private Deadline deadline; + private User leader; + private User author; + + private Grant grantWithId; + private Paper paperWithId; + + + @Before + public void setUp() throws Exception { + grants = new ArrayList<>(); + grantDtos = new ArrayList<>(); + paperDtos = new ArrayList<>(); + grantWithId = new Grant(); + + deadlines = new ArrayList<>(); + deadline = new Deadline(new Date(), COMMENT); + deadline.setId(ID); + deadlines.add(deadline); + + leader = Mockito.mock(User.class); + + papers = new ArrayList<>(); + paperWithId = new Paper(); + paperWithId.setId(ID); + paperWithId.setTitle(TITLE); + papers.add(paperWithId); + paperDto = new PaperDto(paperWithId); + paperDtos.add(paperDto); + + authors = new HashSet<>(); + author = leader; + authors.add(author); + + grantWithId.setId(ID); + grantWithId.setTitle(TITLE); + grantWithId.setComment(COMMENT); + grantWithId.setDeadlines(deadlines); + grantWithId.setLeader(leader); + grantWithId.setPapers(papers); + grantWithId.setAuthors(authors); + + grants.add(grantWithId); + grantDto = new GrantDto(grantWithId); + grantDtos.add(grantDto); + } + + @Test + public void getExistGrantById() { + when(grantRepository.findOne(ID)).thenReturn(grantWithId); + + GrantDto newGrantDto = new GrantDto(grantWithId); + GrantDto result = grantService.getExistGrantById(ID); + + assertEquals(newGrantDto.getId(), result.getId()); + } + + @Test + public void findAll() { + when(grantRepository.findAll()).thenReturn(grants); + + assertEquals(Collections.singletonList(grantWithId), grantService.findAll()); + } + + @Test + public void create() throws IOException { + when(deadlineService.saveOrCreate(new ArrayList<>())).thenReturn(deadlines); + when(userService.getUserByLogin("admin")).thenReturn(leader); + when(grantRepository.save(new Grant())).thenReturn(grantWithId); + + Grant newGrant = new Grant(); + newGrant.setId(ID); + newGrant.setTitle(TITLE); + newGrant.setComment(COMMENT); + newGrant.setDeadlines(deadlines); + newGrant.setLeader(leader); + + assertEquals(newGrant, grantService.create(grantDto)); + } + + @Test + public void getGrantStatuses() { + assertEquals(Arrays.asList(Grant.GrantStatus.values()), grantService.getGrantStatuses()); + } + + @Test + public void getGrantPapers() { + when(paperService.findAllSelect(Collections.singletonList(ID))).thenReturn(paperDtos); + + assertEquals(paperDtos, grantService.getGrantPapers(Collections.singletonList(ID))); + } + + @Test + public void getAllUncompletedPapers() { + when(paperService.findAllNotCompleted()).thenReturn(paperDtos); + paperDtos.stream() + .forEach(paperDto -> { + paperDto.setTitle(StringUtils.abbreviate(paperDto.getTitle(), MAX_DISPLAY_SIZE)); + }); + + assertEquals(paperDtos, grantService.getAllUncompletedPapers()); + } + + @Test + public void delete() throws IOException { + when(grantRepository.findOne(ID)).thenReturn(grantWithId); + assertTrue(grantService.delete(grantWithId.getId())); + } + + @Test + public void removeDeadline() { + GrantDto newGrantDto = new GrantDto(); + newGrantDto.getRemovedDeadlineIds().add(ID); + grantDto.getDeadlines().add(deadline); + GrantDto result = grantService.removeDeadline(grantDto, INDEX); + + assertEquals(newGrantDto.getRemovedDeadlineIds(), result.getRemovedDeadlineIds()); + } + + @Test + public void findById() { + when(grantRepository.findOne(ID)).thenReturn(grantWithId); + Grant findGrant = grantService.findById(ID); + + assertEquals(grantWithId.getId(), findGrant.getId()); + } + + @Test + public void attachPaper() { + when(grantRepository.findOne(ID)).thenReturn(grantWithId); + when(paperService.findAllSelect(Collections.singletonList(ID))).thenReturn(paperDtos); + GrantDto newGrantDto = new GrantDto(grantWithId); + + if (!newGrantDto.getPaperIds().isEmpty()) { + newGrantDto.getPapers().clear(); + newGrantDto.setPapers(paperDtos); + } else { + newGrantDto.getPapers().clear(); + } + + assertEquals(newGrantDto.getPapers(), grantService.attachPaper(grantDto)); + } + + @Test + public void filterEmptyDeadlines() { + when(grantRepository.findOne(ID)).thenReturn(grantWithId); + GrantDto newGrantDto = new GrantDto(grantWithId); + + newGrantDto.setDeadlines(newGrantDto.getDeadlines().stream() + .filter(dto -> dto.getDate() != null || !StringUtils.isEmpty(dto.getDescription())) + .collect(Collectors.toList())); + + assertEquals(newGrantDto.getDeadlines(), grantService.filterEmptyDeadlines(grantDto)); + } +} \ No newline at end of file diff --git a/src/test/java/ru/ulstu/project/service/ProjectServiceTest.java b/src/test/java/ru/ulstu/project/service/ProjectServiceTest.java new file mode 100644 index 0000000..25a201b --- /dev/null +++ b/src/test/java/ru/ulstu/project/service/ProjectServiceTest.java @@ -0,0 +1,151 @@ +package ru.ulstu.project.service; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import ru.ulstu.deadline.model.Deadline; +import ru.ulstu.deadline.service.DeadlineService; +import ru.ulstu.file.model.FileData; +import ru.ulstu.file.service.FileService; +import ru.ulstu.grant.model.GrantDto; +import ru.ulstu.grant.service.GrantService; +import ru.ulstu.project.model.Project; +import ru.ulstu.project.model.ProjectDto; +import ru.ulstu.project.repository.ProjectRepository; +import ru.ulstu.timeline.service.EventService; +import ru.ulstu.user.model.User; +import ru.ulstu.user.service.UserService; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.List; + +import static junit.framework.TestCase.assertTrue; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class ProjectServiceTest { + + @Mock + ProjectRepository projectRepository; + + @Mock + DeadlineService deadlineService; + + @Mock + EventService eventService; + + @Mock + FileService fileService; + + @Mock + UserService userService; + + @Mock + GrantService grantService; + + @InjectMocks + ProjectService projectService; + + private final static String TITLE = "title"; + private final static String DESCR = "descr"; + private final static Integer ID = 1; + private final static Integer INDEX = 0; + private final static String NAME = "name"; + + private List projects; + private Project project; + private ProjectDto projectDto; + private Deadline deadline; + private List deadlines; + private FileData file; + private List files; + private User user; + private GrantDto grant; + private List grants; + + @Before + public void setUp() throws Exception { + projects = new ArrayList<>(); + project = new Project(); + + projects.add(project); + projectDto = new ProjectDto(project); + + deadlines = new ArrayList<>(); + deadline = new Deadline(new Date(), DESCR); + deadline.setId(ID); + deadlines.add(deadline); + + user = new User(); + user.setFirstName(NAME); + + grants = new ArrayList<>(); + grant = new GrantDto(); + grant.setId(ID); + grants.add(grant); + } + + @Test + public void findAll() { + when(projectRepository.findAll()).thenReturn(projects); + assertEquals(projects, projectService.findAll()); + } + + @Test + public void create() throws IOException { + when(deadlineService.saveOrCreate(new ArrayList<>())).thenReturn(deadlines); + when(projectRepository.save(new Project())).thenReturn(project); + eventService.createFromObject(new Project(), Collections.emptyList(), false, "проекта"); + + projectDto.setTitle(TITLE); + projectDto.setDeadlines(deadlines); + + project.setId(ID); + project.setTitle(TITLE); + project.setDescription(DESCR); + project.setDeadlines(deadlines); + project.setFiles(files); + + assertEquals(project.getId(), (projectService.create(projectDto)).getId()); + } + + @Test + public void delete() throws IOException { + when(projectRepository.exists(ID)).thenReturn(true); + when(projectRepository.findOne(ID)).thenReturn(project); + + assertTrue(projectService.delete(ID)); + } + + @Test + public void getProjectExecutors() { + List executors = Collections.singletonList(user); + when(userService.findAll()).thenReturn(executors); + + assertEquals(executors, projectService.getProjectExecutors(projectDto)); + } + + @Test + public void findById() { + when(projectRepository.findOne(ID)).thenReturn(project); + assertEquals(project, projectService.findById(ID)); + } + + @Test + public void removeDeadline() throws IOException { + ProjectDto newProjectDto = new ProjectDto(); + newProjectDto.getRemovedDeadlineIds().add(INDEX); + projectDto.getDeadlines().add(deadline); + ProjectDto result = projectService.removeDeadline(projectDto, INDEX); + + assertEquals(newProjectDto.getDeadlines(), result.getDeadlines()); + assertEquals(newProjectDto.getRemovedDeadlineIds(), result.getRemovedDeadlineIds()); + } +} \ No newline at end of file diff --git a/src/test/java/ru/ulstu/students/service/TaskServiceTest.java b/src/test/java/ru/ulstu/students/service/TaskServiceTest.java new file mode 100644 index 0000000..d3db954 --- /dev/null +++ b/src/test/java/ru/ulstu/students/service/TaskServiceTest.java @@ -0,0 +1,216 @@ +package ru.ulstu.students.service; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import org.springframework.data.domain.Sort; +import ru.ulstu.core.util.DateUtils; +import ru.ulstu.deadline.model.Deadline; +import ru.ulstu.deadline.service.DeadlineService; +import ru.ulstu.students.model.Scheduler; +import ru.ulstu.students.model.Task; +import ru.ulstu.students.model.TaskDto; +import ru.ulstu.students.model.TaskFilterDto; +import ru.ulstu.students.repository.SchedulerRepository; +import ru.ulstu.students.repository.TaskRepository; +import ru.ulstu.tags.model.Tag; +import ru.ulstu.tags.service.TagService; +import ru.ulstu.timeline.service.EventService; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashSet; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class TaskServiceTest { + + @Mock + TaskRepository taskRepository; + + @Mock + SchedulerRepository schedulerRepository; + + @Mock + private TagService tagService; + + @Mock + DeadlineService deadlineService; + + @Mock + EventService eventService; + + @InjectMocks + TaskService taskService; + + private final static Sort SORT = new Sort(Sort.Direction.DESC, "createDate"); + private final static Integer ID = 1; + private final static Task.TaskStatus STATUS = Task.TaskStatus.IN_WORK; + private final static String TITLE = "title"; + private final static String DESCR = "descr"; + private final static String TAG = "tag"; + private final static Date YEAR = DateUtils.clearTime(DateUtils.addYears(new Date(), 0)); + + private List tasks; + private List tags; + private Task task; + private Task taskForSchedule; + private TaskDto taskDto; + private Tag tag; + private Deadline deadline; + private List deadlines; + private Scheduler scheduler; + + + @Before + public void setUp() throws Exception { + + tasks = new ArrayList<>(); + task = new Task(); + + task.setId(ID); + task.setTitle(TITLE); + task.setDescription(DESCR); + + + tag = new Tag(); + tag.setId(ID); + tag.setTagName(TAG); + + deadlines = new ArrayList<>(); + deadline = new Deadline(new Date(), DESCR); + deadline.setId(ID); + deadlines.add(deadline); + + task.setDeadlines(deadlines); + + tags = new ArrayList<>(); + tags.add(tag); + + tasks.add(task); + taskDto = new TaskDto(task); + + taskForSchedule = new Task(); + taskForSchedule.setTitle(TITLE); + taskForSchedule.setDescription(DESCR); + + scheduler = new Scheduler(); + scheduler.setDate(new Date()); + scheduler.setTask(taskForSchedule); + + + } + + @Test + public void findAll() { + + when(taskRepository.findAll(SORT)).thenReturn(tasks); + assertEquals(Collections.singletonList(task), taskService.findAll()); + } + + @Test + public void filter() { + when(tagService.findById(ID)).thenReturn(tag); + when(taskRepository.filterNew(STATUS, tag)).thenReturn(tasks); + + TaskFilterDto taskFilterDto = new TaskFilterDto(); + taskFilterDto.setTag(ID); + taskFilterDto.setOrder("new"); + taskFilterDto.setStatus(STATUS); + + assertEquals(Collections.singletonList(taskDto), taskService.filter(taskFilterDto)); + } + + @Test + public void create() throws IOException { + when(tagService.saveOrCreate(new ArrayList<>())).thenReturn(tags); + when(deadlineService.saveOrCreate(new ArrayList<>())).thenReturn(deadlines); + when(taskRepository.save(new Task())).thenReturn(task); + eventService.createFromObject(new Task(), Collections.emptyList(), true, "задачи"); + + taskDto.setTags(tags); + taskDto.setDeadlines(deadlines); + + Task newTask = new Task(); + task.setId(ID); + task.setTitle(TITLE); + task.setDescription(DESCR); + task.setTags(tags); + task.setDeadlines(deadlines); + + assertEquals(task.getId(), taskService.create(taskDto)); + } + + @Test + public void delete() throws IOException { + when(taskRepository.exists(ID)).thenReturn(true); + when(taskRepository.findOne(ID)).thenReturn(task); + when(schedulerRepository.findOneByTask(task)).thenReturn(null); + + assertTrue(taskService.delete(ID)); + } + + @Test + public void generateYearTasks() { + when(tagService.getTags()).thenReturn(tags); + tasks.get(0).setTags(tags); + when(taskRepository.findAllYear(DateUtils.clearTime(DateUtils.addYears(new Date(), -1)))).thenReturn(tasks); + tasks.get(0).setCreateDate(DateUtils.clearTime(DateUtils.addYears(new Date(), -1))); + when(taskRepository.findByTag(tag)).thenReturn(tasks); + + Task newTask = new Task(); + newTask.setTitle(tasks.get(0).getTitle()); + newTask.setTags(tasks.get(0).getTags()); + newTask.setCreateDate(new Date()); + newTask.setStatus(Task.TaskStatus.LOADED_FROM_KIAS); + + Deadline newDeadline = new Deadline(); + newDeadline.setId(ID); + newDeadline.setDescription(deadline.getDescription()); + newDeadline.setDate(DateUtils.addYears(deadline.getDate(), 1)); + when(deadlineService.create(newDeadline)).thenReturn(newDeadline); + newTask.setDeadlines(Arrays.asList(newDeadline)); + + when(taskRepository.save(newTask)).thenReturn(task); + + assertEquals(Arrays.asList(task), taskService.generateYearTasks()); + } + + @Test + public void checkRepeatingTags() { + when(tagService.getTags()).thenReturn(tags); + tasks.get(0).setTags(tags); + when(taskRepository.findAllYear(DateUtils.clearTime(DateUtils.addYears(new Date(), -1)))).thenReturn(tasks); + + assertEquals(new HashSet(Arrays.asList(tag)), taskService.checkRepeatingTags(false)); + } + + @Test + public void createPeriodTask() { + Task newTask = new Task(); + newTask.setTitle(scheduler.getTask().getTitle()); + newTask.setTags(scheduler.getTask().getTags()); + newTask.setCreateDate(new Date()); + + Deadline newDeadline = new Deadline(); + newDeadline.setId(ID); + newDeadline.setDescription(deadline.getDescription()); + newDeadline.setDate(DateUtils.addYears(deadline.getDate(), 1)); + when(deadlineService.create(newDeadline)).thenReturn(newDeadline); + newTask.setDeadlines(Arrays.asList(newDeadline)); + + when(taskRepository.save(newTask)).thenReturn(taskForSchedule); + + assertEquals(taskForSchedule, taskService.createPeriodTask(scheduler)); + } +} \ No newline at end of file diff --git a/src/test/java/students/TaskPage.java b/src/test/java/students/TaskPage.java new file mode 100644 index 0000000..c0105b2 --- /dev/null +++ b/src/test/java/students/TaskPage.java @@ -0,0 +1,81 @@ +package students; + +import core.PageObject; +import org.openqa.selenium.By; +import org.openqa.selenium.Keys; +import org.openqa.selenium.WebElement; + +import java.util.List; + +public class TaskPage extends PageObject { + + @Override + public String getSubTitle() { + return driver.findElement(By.tagName("h3")).getText(); + } + + public void setName(String name) { + driver.findElement(By.id("title")).sendKeys(name); + } + + public void save() { + driver.findElement(By.id("sendMessageButton")).click(); + } + + public void addDeadlineDate(String deadDate, Integer deadNum) { + driver.findElement(By.id(String.format("deadlines%d.date", deadNum))).sendKeys(deadDate); + } + + public void addDeadlineDescription(String deadDescr, Integer deadNum) { + driver.findElement(By.id(String.format("deadlines%d.description", deadNum))).sendKeys(deadDescr); + } + + public void removeName() { + driver.findElement(By.id("title")).clear(); + } + + public String getId() { + return driver.findElement(By.id("id")).getAttribute("value"); + } + + public Integer getDeadNum() { + return driver.findElements(By.cssSelector("#task-form .form-group:nth-of-type(5) .row")).size(); + } + + public void clickAddDeadline() { + driver.findElement(By.cssSelector("#addDeadline")).click(); + } + + public List getDeadlines() { + return driver.findElements(By.cssSelector(".form-group:nth-of-type(5) .row")); + } + + public void deleteDeadline() { + driver.findElement(By.xpath("//*[@id=\"task-form\"]/div/div[1]/div[5]/div[1]/div[3]/a")).click(); + + } + + public void clearDeadlineDate(Integer deadNum) { + driver.findElement(By.id(String.format("deadlines%d.date", deadNum))).sendKeys(Keys.DELETE); + } + + public void clearDeadlineDescription(Integer deadNum) { + driver.findElement(By.id(String.format("deadlines%d.description", deadNum))).clear(); + } + + public boolean hasDeadline(String deadDescr, String deadValue) { + return getDeadlines() + .stream() + .anyMatch(webElement -> { + return webElement.findElement(By.cssSelector("input[type=\"text\"]")).getAttribute("value").equals(deadDescr) + && webElement.findElement(By.cssSelector("input[type=\"date\"]")).getAttribute("value").equals(deadValue); + }); + } + + public void setTag(String tag) { + driver.findElement(By.className("input-tag-name")).sendKeys(tag); + driver.findElement(By.className("input-tag-name")).sendKeys(Keys.ENTER); + } + + +} diff --git a/src/test/java/students/TasksDashboardPage.java b/src/test/java/students/TasksDashboardPage.java new file mode 100644 index 0000000..8cc6eda --- /dev/null +++ b/src/test/java/students/TasksDashboardPage.java @@ -0,0 +1,10 @@ +package students; + +import core.PageObject; + +public class TasksDashboardPage extends PageObject { + @Override + public String getSubTitle() { + return null; + } +} diff --git a/src/test/java/students/TasksPage.java b/src/test/java/students/TasksPage.java new file mode 100644 index 0000000..5c5d42c --- /dev/null +++ b/src/test/java/students/TasksPage.java @@ -0,0 +1,75 @@ +package students; + +import core.PageObject; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; + +import java.util.List; + +public class TasksPage extends PageObject { + + @Override + public String getSubTitle() { + return driver.findElement(By.tagName("h3")).getText(); + } + + public List getTasks() { + return driver.findElements(By.cssSelector("span.h6")); + } + + public List getTaskRows() { + return driver.findElements(By.className("task-row")); + } + + public void goToFirstTask() { + driver.findElement(By.xpath("//*[@id=\"tasks\"]/div/div[2]/div[1]/div/div/a[1]")).click(); + } + + public boolean findTask(String taskName) { + return getTasks().stream() + .anyMatch(webElement -> webElement.getText().equals(taskName)); + + } + + public void deleteFirstTask() { + js.executeScript("$('a[data-confirm]').click();"); + } + + public void submit() { + driver.findElement(By.xpath("//*[@id=\"dataConfirmOK\"]")).click(); + } + + public boolean findTag(String tag) { + driver.findElements(By.className("bootstrap-select")).get(2).findElement(By.className("btn")).click(); + driver.findElement(By.cssSelector(".bs-searchbox input")).sendKeys(tag); + return driver.findElement(By.xpath("//*[@id=\"tasks\"]/div/div[2]/div[2]/div[2]/div[2]/div/div[2]/ul")).findElement(By.className("text")).getText().equals(tag); + } + + public boolean findTaskByTag(String name, String tag) { + return getTasks().stream() + .anyMatch(webElement -> webElement.getText().equals(name) + && webElement.findElement(By.xpath("//*[@id=\"tasks\"]/div/div[2]/div[1]/div/div/a[1]/span[3]")).getText().equals(tag)); + } + + public boolean findTasksByTag(String tag) { + return getTaskRows().stream() + .allMatch(webElement -> webElement.findElement(By.cssSelector("span.text-muted")).getText().equals(tag)); + } + + public void selectTag(String tag) { + driver.findElements(By.className("bootstrap-select")).get(2).findElement(By.className("btn")).click(); + driver.findElement(By.cssSelector(".bs-searchbox input")).sendKeys(tag); + driver.findElement(By.xpath("//*[@id=\"tasks\"]/div/div[2]/div[2]/div[2]/div[2]/div/div[2]/ul/li/a")).click(); + } + + + public void selectStatus() { + driver.findElements(By.className("bootstrap-select")).get(1).findElement(By.className("btn")).click(); + driver.findElement(By.xpath("//*[@id=\"tasks\"]/div/div[2]/div[2]/div[2]/div[1]/div/div/ul/li[2]/a")).click(); + } + + public boolean findAllStatus() { + return getTaskRows().stream() + .allMatch(webElement -> webElement.findElement(By.cssSelector("div i.text-primary")).isDisplayed()); + } +}