diff --git a/build.gradle b/build.gradle index 38de2c7..71c9977 100644 --- a/build.gradle +++ b/build.gradle @@ -126,6 +126,6 @@ dependencies { compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.6.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' } \ No newline at end of file diff --git a/deploy/gdccloud/deploy.sh b/deploy/gdccloud/deploy.sh index 26604b7..de785fd 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 >> /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 5aecb51..f9a4bac 100644 --- a/src/main/java/ru/ulstu/conference/controller/ConferenceController.java +++ b/src/main/java/ru/ulstu/conference/controller/ConferenceController.java @@ -74,12 +74,9 @@ public class ConferenceController { @PostMapping(value = "/conference", params = "save") public String save(@Valid ConferenceDto conferenceDto, Errors errors) throws IOException { - conferenceService.filterEmptyDeadlines(conferenceDto); - conferenceService.checkEmptyFieldsOfDeadline(conferenceDto, errors); - if (errors.hasErrors()) { + if (!conferenceService.save(conferenceDto, errors)) { return CONFERENCE_PAGE; } - conferenceService.save(conferenceDto); return String.format(REDIRECT_TO, CONFERENCES_PAGE); } diff --git a/src/main/java/ru/ulstu/conference/model/Conference.java b/src/main/java/ru/ulstu/conference/model/Conference.java index 7e18ac0..4df1a1f 100644 --- a/src/main/java/ru/ulstu/conference/model/Conference.java +++ b/src/main/java/ru/ulstu/conference/model/Conference.java @@ -42,12 +42,12 @@ public class Conference extends BaseEntity { @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) diff --git a/src/main/java/ru/ulstu/conference/model/ConferenceDto.java b/src/main/java/ru/ulstu/conference/model/ConferenceDto.java index 2e2f13b..5759f4e 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.hibernate.validator.constraints.NotEmpty; import org.springframework.format.annotation.DateTimeFormat; import ru.ulstu.deadline.model.Deadline; +import ru.ulstu.name.NameContainer; import ru.ulstu.paper.model.Paper; import javax.persistence.Temporal; @@ -13,10 +14,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 = "Конец: "; @@ -218,4 +220,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/repository/ConferenceRepository.java b/src/main/java/ru/ulstu/conference/repository/ConferenceRepository.java index 3a8bbe1..8f9e05f 100644 --- a/src/main/java/ru/ulstu/conference/repository/ConferenceRepository.java +++ b/src/main/java/ru/ulstu/conference/repository/ConferenceRepository.java @@ -5,12 +5,13 @@ 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); @@ -24,4 +25,12 @@ public interface ConferenceRepository extends JpaRepository @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/ConferenceService.java b/src/main/java/ru/ulstu/conference/service/ConferenceService.java index 38de435..1b8e67b 100644 --- a/src/main/java/ru/ulstu/conference/service/ConferenceService.java +++ b/src/main/java/ru/ulstu/conference/service/ConferenceService.java @@ -13,8 +13,10 @@ 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.model.Ping; import ru.ulstu.ping.service.PingService; import ru.ulstu.timeline.service.EventService; import ru.ulstu.user.model.User; @@ -31,7 +33,7 @@ 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; @@ -51,6 +53,7 @@ public class ConferenceService { PingService pingService, ConferenceNotificationService conferenceNotificationService, EventService eventService) { + this.baseRepository = conferenceRepository; this.conferenceRepository = conferenceRepository; this.conferenceUserService = conferenceUserService; this.deadlineService = deadlineService; @@ -62,7 +65,7 @@ public class ConferenceService { } public ConferenceDto getExistConferenceById(Integer id) { - ConferenceDto conferenceDto = findOneDto(id); + ConferenceDto conferenceDto = new ConferenceDto(conferenceRepository.findOne(id)); conferenceDto.setNotSelectedPapers(getNotSelectPapers(conferenceDto.getPaperIds())); conferenceDto.setDisabledTakePart(isCurrentUserParticipant(conferenceDto.getUsers())); return conferenceDto; @@ -70,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; } @@ -85,29 +88,40 @@ public class ConferenceService { return conferences; } - public ConferenceDto findOneDto(Integer id) { - return new ConferenceDto(conferenceRepository.findOne(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); conferenceNotificationService.sendCreateNotification(newConference); eventService.createFromConference(newConference); - return newConference.getId(); + return newConference; } @Transactional - public Integer update(ConferenceDto conferenceDto) throws IOException { + public Conference update(ConferenceDto conferenceDto) throws IOException { Conference conference = conferenceRepository.findOne(conferenceDto.getId()); List oldDeadlines = conference.getDeadlines().stream() .map(this::copyDeadline) @@ -121,49 +135,56 @@ public class ConferenceService { 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.exists(conferenceId)) { + eventService.removeConferencesEvent(conferenceRepository.findOne(conferenceId)); conferenceRepository.delete(conferenceId); + return true; } + return false; } - public void addDeadline(ConferenceDto conferenceDto) { + 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 addPaper(ConferenceDto conferenceDto) { + 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 void removePaper(ConferenceDto conferenceDto, Integer paperIndex) throws IOException { + public ConferenceDto removePaper(ConferenceDto conferenceDto, Integer paperIndex) throws IOException { Paper removedPaper = conferenceDto.getPapers().remove((int) paperIndex); 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); } @@ -197,7 +218,7 @@ public class ConferenceService { } - public boolean isCurrentUserParticipant(List conferenceUsers) { + private boolean isCurrentUserParticipant(List conferenceUsers) { return conferenceUsers.stream().anyMatch(participant -> participant.getUser().equals(userService.getCurrentUser())); } @@ -212,7 +233,7 @@ public class ConferenceService { return convert(findAllActive(), ConferenceDto::new); } - public List findAllActive() { + private List findAllActive() { return conferenceRepository.findAllActive(new Date()); } @@ -221,12 +242,13 @@ public class ConferenceService { } @Transactional - public void ping(ConferenceDto conferenceDto) throws IOException { - pingService.addPing(findOne(conferenceDto.getId())); + public Ping ping(ConferenceDto conferenceDto) throws IOException { + Ping ping = pingService.addPing(findOne(conferenceDto.getId())); conferenceRepository.updatePingConference(conferenceDto.getId()); + return ping; } - public Conference findOne(Integer conferenceId) { + private Conference findOne(Integer conferenceId) { return conferenceRepository.findOne(conferenceId); } @@ -252,7 +274,7 @@ public class ConferenceService { modelMap.addAttribute("offshoreSales", offshoreSales); } - public void sendNotificationAfterUpdateDeadlines(Conference conference, List oldDeadlines) { + private void sendNotificationAfterUpdateDeadlines(Conference conference, List oldDeadlines) { if (oldDeadlines.size() != conference.getDeadlines().size()) { conferenceNotificationService.updateDeadlineNotification(conference); return; @@ -266,7 +288,7 @@ public class ConferenceService { } } - public Deadline copyDeadline(Deadline oldDeadline) { + private Deadline copyDeadline(Deadline oldDeadline) { Deadline newDeadline = new Deadline(oldDeadline.getDate(), oldDeadline.getDescription()); newDeadline.setId(oldDeadline.getId()); return newDeadline; @@ -280,10 +302,19 @@ public class ConferenceService { } } + 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 f771b2a..16842c1 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 f75f53f..49efac4 100644 --- a/src/main/java/ru/ulstu/configuration/ApplicationProperties.java +++ b/src/main/java/ru/ulstu/configuration/ApplicationProperties.java @@ -21,6 +21,8 @@ public class ApplicationProperties { private boolean checkRun; + private String debugEmail; + public boolean isUseHttps() { return useHttps; } @@ -60,4 +62,12 @@ public class ApplicationProperties { public void setCheckRun(boolean checkRun) { this.checkRun = checkRun; } + + public String getDebugEmail() { + return debugEmail; + } + + public void setDebugEmail(String debugEmail) { + this.debugEmail = debugEmail; + } } 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..894cf39 100644 --- a/src/main/java/ru/ulstu/configuration/SecurityConfiguration.java +++ b/src/main/java/ru/ulstu/configuration/SecurityConfiguration.java @@ -104,7 +104,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 27ba6c9..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,11 +35,6 @@ public class AdviceController { this.userService = userService; } - @ModelAttribute("currentUser") - public String getCurrentUser() { - return userService.getCurrentUser().getUserAbbreviate(); - } - @ModelAttribute("flashMessage") public String getFlashMessage() { return null; @@ -112,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/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/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..3a38452 100644 --- a/src/main/java/ru/ulstu/core/util/DateUtils.java +++ b/src/main/java/ru/ulstu/core/util/DateUtils.java @@ -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 148697c..17287a8 100644 --- a/src/main/java/ru/ulstu/deadline/model/Deadline.java +++ b/src/main/java/ru/ulstu/deadline/model/Deadline.java @@ -4,11 +4,15 @@ 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 @@ -20,6 +24,11 @@ public class Deadline extends BaseEntity { @DateTimeFormat(pattern = "yyyy-MM-dd") private Date date; + @OneToMany(targetEntity = User.class, fetch = FetchType.EAGER) + private List executors; + + private Boolean done; + public Deadline() { } @@ -28,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() { @@ -53,6 +73,22 @@ public class Deadline extends BaseEntity { 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) { @@ -65,13 +101,20 @@ public class Deadline extends BaseEntity { 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); + date.equals(deadline.date) && + executors.equals(deadline.executors) && + done.equals(deadline.done); } @Override public int hashCode() { - return Objects.hash(super.hashCode(), description, date); + 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..3f237e4 100644 --- a/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java +++ b/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java @@ -2,8 +2,15 @@ package ru.ulstu.deadline.repository; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; import ru.ulstu.deadline.model.Deadline; +import java.util.Date; + public interface DeadlineRepository extends JpaRepository { + @Query( + value = "SELECT date FROM Deadline d WHERE (d.grant_id = ?1) AND (d.date = ?2)", + nativeQuery = true) + Date findByGrantIdAndDate(Integer grantId, 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 0ef8a4f..9c45537 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.findOne(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.delete(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 85a0cd9..a9c01ed 100644 --- a/src/main/java/ru/ulstu/grant/controller/GrantController.java +++ b/src/main/java/ru/ulstu/grant/controller/GrantController.java @@ -13,16 +13,14 @@ 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.Paper; +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; @@ -45,7 +43,7 @@ public class GrantController { @GetMapping("/dashboard") public void getDashboard(ModelMap modelMap) { - modelMap.put("grants", grantService.findAllDto()); + modelMap.put("grants", grantService.findAllActiveDto()); } @GetMapping("/grant") @@ -62,17 +60,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); } @@ -89,7 +79,7 @@ public class GrantController { @PostMapping(value = "/grant", params = "addDeadline") public String addDeadline(@Valid GrantDto grantDto, Errors errors) { - filterEmptyDeadlines(grantDto); + grantService.filterEmptyDeadlines(grantDto); if (errors.hasErrors()) { return GRANT_PAGE; } @@ -104,7 +94,6 @@ public class GrantController { return GRANT_PAGE; } - @PostMapping(value = "/grant", params = "createProject") public String createProject(@Valid GrantDto grantDto, Errors errors) throws IOException { if (errors.hasErrors()) { @@ -131,13 +120,7 @@ public class GrantController { } @ModelAttribute("allPapers") - public List getAllPapers() { - return grantService.getAllPapers(); - } - - private void filterEmptyDeadlines(GrantDto grantDto) { - grantDto.setDeadlines(grantDto.getDeadlines().stream() - .filter(dto -> dto.getDate() != null || !isEmpty(dto.getDescription())) - .collect(Collectors.toList())); + public List getAllPapers() { + return grantService.getAllUncompletedPapers(); } } diff --git a/src/main/java/ru/ulstu/grant/model/Grant.java b/src/main/java/ru/ulstu/grant/model/Grant.java index 760895e..369568f 100644 --- a/src/main/java/ru/ulstu/grant/model/Grant.java +++ b/src/main/java/ru/ulstu/grant/model/Grant.java @@ -43,7 +43,8 @@ public class Grant extends BaseEntity implements UserContainer { IN_WORK("В работе"), COMPLETED("Завершен"), FAILED("Провалены сроки"), - LOADED_FROM_KIAS("Загружен автоматически"); + LOADED_FROM_KIAS("Загружен автоматически"), + SKIPPED("Не интересует"); private String statusName; @@ -62,19 +63,18 @@ 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<>(); private String comment; - @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @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") private Project project; diff --git a/src/main/java/ru/ulstu/grant/model/GrantDto.java b/src/main/java/ru/ulstu/grant/model/GrantDto.java index e842b10..9e59d86 100644 --- a/src/main/java/ru/ulstu/grant/model/GrantDto.java +++ b/src/main/java/ru/ulstu/grant/model/GrantDto.java @@ -6,18 +6,20 @@ import org.apache.commons.lang3.StringUtils; import org.hibernate.validator.constraints.NotEmpty; import ru.ulstu.deadline.model.Deadline; import ru.ulstu.file.model.FileDataDto; -import ru.ulstu.paper.model.Paper; +import ru.ulstu.name.NameContainer; +import ru.ulstu.paper.model.PaperDto; import ru.ulstu.project.model.ProjectDto; import ru.ulstu.user.model.UserDto; 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; @@ -37,7 +39,7 @@ public class GrantDto { private boolean hasBAKPapers; private boolean hasScopusPapers; private List paperIds = new ArrayList<>(); - private List papers = new ArrayList<>(); + private List papers = new ArrayList<>(); private List removedDeadlineIds = new ArrayList<>(); public GrantDto() { @@ -54,12 +56,12 @@ public class GrantDto { @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("paperIds") List paperIds, - @JsonProperty("papers") List papers) { + @JsonProperty("papers") List papers) { this.id = id; this.title = title; this.status = status; @@ -92,7 +94,13 @@ public class GrantDto { this.hasAge = false; this.hasDegree = false; this.paperIds = convert(grant.getPapers(), paper -> paper.getId()); - this.papers = grant.getPapers(); + 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() { @@ -214,11 +222,11 @@ public class GrantDto { this.paperIds = paperIds; } - public List getPapers() { + public List getPapers() { return papers; } - public void setPapers(List papers) { + public void setPapers(List papers) { this.papers = papers; } 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..631f5db --- /dev/null +++ b/src/main/java/ru/ulstu/grant/page/KiasPage.java @@ -0,0 +1,50 @@ +package ru.ulstu.grant.page; + +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; + +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 WebDriver driver; + + public KiasPage(WebDriver webDriver) { + this.driver = webDriver; + } + + public boolean goToNextPage() { + try { + if (driver.findElements(By.id("js-ctrlNext")).size() > 0) { + driver.findElement(By.id("js-ctrlNext")).click(); + return true; + } + } finally { + return false; + } + } + + public List getPageOfGrants() { + WebElement listContest = driver.findElement(By.tagName("tBody")); + List grants = listContest.findElements(By.cssSelector("tr.tr")); + return grants; + } + + public String getGrantTitle(WebElement grant) { + return grant.findElement(By.cssSelector("td.tertiary")).findElement(By.tagName("a")).getText(); + } + + public Date parseDeadLineDate(WebElement 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(WebElement grantElement) { + return grantElement.findElement(By.xpath("./td[5]")).getText(); + } +} diff --git a/src/main/java/ru/ulstu/grant/repository/GrantRepository.java b/src/main/java/ru/ulstu/grant/repository/GrantRepository.java index 44c2cc0..876a8c1 100644 --- a/src/main/java/ru/ulstu/grant/repository/GrantRepository.java +++ b/src/main/java/ru/ulstu/grant/repository/GrantRepository.java @@ -1,11 +1,23 @@ 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); + + @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..a2950a6 --- /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.findAll(), 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 9cff4b6..86f8f1b 100644 --- a/src/main/java/ru/ulstu/grant/service/GrantService.java +++ b/src/main/java/ru/ulstu/grant/service/GrantService.java @@ -1,8 +1,11 @@ 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.deadline.model.Deadline; import ru.ulstu.deadline.service.DeadlineService; import ru.ulstu.file.model.FileDataDto; @@ -10,7 +13,9 @@ 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.name.BaseService; import ru.ulstu.paper.model.Paper; +import ru.ulstu.paper.model.PaperDto; import ru.ulstu.paper.service.PaperService; import ru.ulstu.project.model.Project; import ru.ulstu.project.model.ProjectDto; @@ -20,10 +25,14 @@ 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; @@ -31,8 +40,8 @@ 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; @@ -41,6 +50,8 @@ public class GrantService { private final UserService userService; private final PaperService paperService; private final EventService eventService; + private final GrantNotificationService grantNotificationService; + private final KiasService kiasService; public GrantService(GrantRepository grantRepository, FileService fileService, @@ -48,14 +59,19 @@ public class GrantService { ProjectService projectService, UserService userService, PaperService paperService, - EventService eventService) { + EventService eventService, + GrantNotificationService grantNotificationService, + KiasService kiasService) { 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; } public List findAll() { @@ -63,9 +79,7 @@ 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; + return convert(findAll(), GrantDto::new); } public GrantDto findOneDto(Integer id) { @@ -77,6 +91,7 @@ public class GrantService { Grant newGrant = copyFromDto(new Grant(), grantDto); newGrant = grantRepository.save(newGrant); eventService.createFromGrant(newGrant); + grantNotificationService.sendCreateNotification(newGrant); return newGrant.getId(); } @@ -113,6 +128,8 @@ public class GrantService { @Transactional public Integer update(GrantDto grantDto) throws IOException { Grant grant = grantRepository.findOne(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())) { @@ -120,6 +137,20 @@ public class GrantService { } 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(); } @@ -148,16 +179,63 @@ public class GrantService { grant = grantRepository.save(grant); eventService.createFromGrant(grant); + grantNotificationService.sendCreateNotification(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 = grantDto.getDeadlines().get(0).getDate(); //дата с сайта киас + if (deadlineService.findByGrantIdAndDate(id, date).compareTo(date) == 0) { //если есть такая строка с датой + return true; + } + return false; } public List getGrantAuthors(GrantDto grantDto) { @@ -187,13 +265,12 @@ public class GrantService { .collect(toList()); } - public List getGrantPapers(List paperIds) { + public List getGrantPapers(List paperIds) { return paperService.findAllSelect(paperIds); - } - public List getAllPapers() { - return paperService.findAll(); + public List getAllUncompletedPapers() { + return paperService.findAllNotCompleted(); } public void attachPaper(GrantDto grantDto) { @@ -218,7 +295,6 @@ public class GrantService { .filter(paper -> paper.getAuthors() != null) .flatMap(paper -> paper.getAuthors().stream()) .collect(toList()); - } private List getBAKAuthors() { @@ -235,4 +311,29 @@ public class GrantService { .filter(author -> Collections.frequency(authors, author) > 3) .collect(toList()); } + + public void filterEmptyDeadlines(GrantDto grantDto) { + grantDto.setDeadlines(grantDto.getDeadlines().stream() + .filter(dto -> dto.getDate() != null || !org.springframework.util.StringUtils.isEmpty(dto.getDescription())) + .collect(Collectors.toList())); + } + + @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); + } + + private List findAllActive() { + return grantRepository.findAllActive(); + } } 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..618e83c --- /dev/null +++ b/src/main/java/ru/ulstu/grant/service/KiasService.java @@ -0,0 +1,92 @@ +package ru.ulstu.grant.service; + +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.chrome.ChromeDriver; +import org.openqa.selenium.chrome.ChromeOptions; +import org.springframework.stereotype.Service; +import ru.ulstu.grant.model.GrantDto; +import ru.ulstu.grant.page.KiasPage; +import ru.ulstu.user.service.UserService; + +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 static String DRIVER_LOCATION = "drivers/%s"; + private final static String WINDOWS_DRIVER = "chromedriver.exe"; + private final static String LINUX_DRIVER = "chromedriver"; + private final static String DRIVER_TYPE = "webdriver.chrome.driver"; + + private final UserService userService; + + public KiasService(UserService userService) { + this.userService = userService; + } + + public List getNewGrantsDto() throws ParseException { + WebDriver webDriver = getDriver(); + Integer leaderId = userService.findOneByLoginIgnoreCase("admin").getId(); + List grants = new ArrayList<>(); + for (Integer year : generateGrantYears()) { + webDriver.get(String.format(BASE_URL, CONTEST_STATUS_ID, CONTEST_TYPE, year)); + grants.addAll(getKiasGrants(webDriver)); + } + grants.forEach(grantDto -> grantDto.setLeaderId(leaderId)); + webDriver.quit(); + return grants; + } + + public List getKiasGrants(WebDriver webDriver) throws ParseException { + List newGrants = new ArrayList<>(); + KiasPage kiasPage = new KiasPage(webDriver); + do { + newGrants.addAll(getGrantsFromPage(kiasPage)); + } while (kiasPage.goToNextPage()); //проверка существования следующей страницы с грантами + return newGrants; + } + + private List getGrantsFromPage(KiasPage kiasPage) throws ParseException { + List grants = new ArrayList<>(); + for (WebElement grantElement : kiasPage.getPageOfGrants()) { + 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); + } + + private WebDriver getDriver() { + System.setProperty(DRIVER_TYPE, getDriverExecutablePath()); + final ChromeOptions chromeOptions = new ChromeOptions(); + chromeOptions.addArguments("--headless"); + return new ChromeDriver(chromeOptions); + } + + private String getDriverExecutablePath() { + return KiasService.class.getClassLoader().getResource( + String.format(DRIVER_LOCATION, getDriverExecutable(isWindows()))).getFile(); + } + + private String getDriverExecutable(boolean isWindows) { + return isWindows ? WINDOWS_DRIVER : LINUX_DRIVER; + } + + private boolean isWindows() { + return System.getProperty("os.name").toLowerCase().contains("windows"); + } +} 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 41d5586..29da57d 100644 --- a/src/main/java/ru/ulstu/paper/controller/PaperController.java +++ b/src/main/java/ru/ulstu/paper/controller/PaperController.java @@ -13,9 +13,11 @@ 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.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; @@ -105,6 +107,15 @@ public class PaperController { return "/papers/paper"; } + @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") public List getPaperStatuses() { return paperService.getPaperStatuses(); @@ -129,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(); @@ -137,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/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 65bd32c..413c5db 100644 --- a/src/main/java/ru/ulstu/paper/model/Paper.java +++ b/src/main/java/ru/ulstu/paper/model/Paper.java @@ -3,10 +3,12 @@ package ru.ulstu.paper.model; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; import org.hibernate.validator.constraints.NotBlank; +import ru.ulstu.conference.model.Conference; import ru.ulstu.core.model.BaseEntity; import ru.ulstu.core.model.UserContainer; 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; @@ -27,6 +29,7 @@ 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; @@ -114,6 +117,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; } @@ -218,11 +232,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() { return getAuthors(); } + public List getReferences() { + return references; + } + + public void setReferences(List references) { + this.references = references; + } + public Optional getNextDeadline() { return deadlines .stream() @@ -240,4 +278,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 11d6dfc..8474a34 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/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 index 8d71ae5..1705e08 100644 --- a/src/main/java/ru/ulstu/paper/model/ReferenceDto.java +++ b/src/main/java/ru/ulstu/paper/model/ReferenceDto.java @@ -34,6 +34,7 @@ public class ReferenceDto { } } + private Integer id; private String authors; private String publicationTitle; private Integer publicationYear; @@ -42,9 +43,11 @@ public class ReferenceDto { 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, @@ -52,7 +55,9 @@ public class ReferenceDto { @JsonProperty("pages") String pages, @JsonProperty("journalOrCollectionTitle") String journalOrCollectionTitle, @JsonProperty("referenceType") ReferenceType referenceType, - @JsonProperty("formatStandard") FormatStandard formatStandard) { + @JsonProperty("formatStandard") FormatStandard formatStandard, + @JsonProperty("isDeleted") boolean deleted) { + this.id = id; this.authors = authors; this.publicationTitle = publicationTitle; this.publicationYear = publicationYear; @@ -61,6 +66,22 @@ public class ReferenceDto { 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() { @@ -126,4 +147,20 @@ public class ReferenceDto { 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 f935247..42d3703 100644 --- a/src/main/java/ru/ulstu/paper/repository/PaperRepository.java +++ b/src/main/java/ru/ulstu/paper/repository/PaperRepository.java @@ -18,4 +18,10 @@ public interface PaperRepository extends JpaRepository { 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/PaperService.java b/src/main/java/ru/ulstu/paper/service/PaperService.java index f98997d..2393af4 100644 --- a/src/main/java/ru/ulstu/paper/service/PaperService.java +++ b/src/main/java/ru/ulstu/paper/service/PaperService.java @@ -7,11 +7,14 @@ 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.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.timeline.service.EventService; import ru.ulstu.user.model.User; import ru.ulstu.user.service.UserService; @@ -39,6 +42,7 @@ 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"; @@ -49,14 +53,17 @@ public class PaperService { private final DeadlineService deadlineService; private final FileService fileService; private final EventService eventService; + private final ReferenceRepository referenceRepository; public PaperService(PaperRepository paperRepository, + ReferenceRepository referenceRepository, FileService fileService, PaperNotificationService paperNotificationService, UserService userService, DeadlineService deadlineService, EventService eventService) { this.paperRepository = paperRepository; + this.referenceRepository = referenceRepository; this.fileService = fileService; this.paperNotificationService = paperNotificationService; this.userService = userService; @@ -117,6 +124,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()))); @@ -127,6 +135,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.findOne(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.findOne(paperDto.getId()); @@ -139,6 +182,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 -> { @@ -168,6 +216,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(); @@ -242,15 +298,18 @@ public class PaperService { 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 sortPapers(paperRepository.findAllByIdIn(paperIds)); + public List findAllSelect(List paperIds) { + return convert(paperRepository.findAllByIdIn(paperIds), PaperDto::new); } public List getPaperAuthors() { @@ -284,12 +343,23 @@ public class PaperService { : 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().toString(), + referenceDto.getPublicationYear() != null ? referenceDto.getPublicationYear().toString() : "", referenceDto.getPages(), StringUtils.isEmpty(referenceDto.getJournalOrCollectionTitle()) ? "." : " // " + referenceDto.getJournalOrCollectionTitle() + "."); } @@ -297,7 +367,7 @@ public class PaperService { public String getSpringerReference(ReferenceDto referenceDto) { return MessageFormat.format("{0} ({1}) {2}.{3} {4}pp {5}", referenceDto.getAuthors(), - referenceDto.getPublicationYear().toString(), + referenceDto.getPublicationYear() != null ? referenceDto.getPublicationYear().toString() : "", referenceDto.getPublicationTitle(), referenceDto.getReferenceType() == ARTICLE ? " " + referenceDto.getJournalOrCollectionTitle() + "," : "", StringUtils.isEmpty(referenceDto.getPublisher()) ? "" : referenceDto.getPublisher() + ", ", @@ -307,4 +377,13 @@ public class PaperService { 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; + } } diff --git a/src/main/java/ru/ulstu/ping/service/PingService.java b/src/main/java/ru/ulstu/ping/service/PingService.java index f7156f0..6666fdd 100644 --- a/src/main/java/ru/ulstu/ping/service/PingService.java +++ b/src/main/java/ru/ulstu/ping/service/PingService.java @@ -23,10 +23,10 @@ public class PingService { } @Transactional - public void addPing(Conference conference) throws IOException { + public Ping addPing(Conference conference) throws IOException { Ping newPing = new Ping(new Date(), userService.getCurrentUser()); newPing.setConference(conference); - pingRepository.save(newPing); + return pingRepository.save(newPing); } public Integer countPingYesterday(Conference conference, Calendar calendar) { diff --git a/src/main/java/ru/ulstu/project/controller/ProjectController.java b/src/main/java/ru/ulstu/project/controller/ProjectController.java index ae09658..88f0c7a 100644 --- a/src/main/java/ru/ulstu/project/controller/ProjectController.java +++ b/src/main/java/ru/ulstu/project/controller/ProjectController.java @@ -13,6 +13,7 @@ import ru.ulstu.deadline.model.Deadline; 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; @@ -79,12 +80,24 @@ 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); + } + private void filterEmptyDeadlines(ProjectDto projectDto) { projectDto.setDeadlines(projectDto.getDeadlines().stream() .filter(dto -> dto.getDate() != null || !isEmpty(dto.getDescription())) diff --git a/src/main/java/ru/ulstu/project/model/Project.java b/src/main/java/ru/ulstu/project/model/Project.java index a596b76..cb53645 100644 --- a/src/main/java/ru/ulstu/project/model/Project.java +++ b/src/main/java/ru/ulstu/project/model/Project.java @@ -2,31 +2,36 @@ package ru.ulstu.project.model; import org.hibernate.validator.constraints.NotBlank; import ru.ulstu.core.model.BaseEntity; +import ru.ulstu.core.model.UserContainer; 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.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.JoinColumn; +import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.validation.constraints.NotNull; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; +import java.util.Set; @Entity -public class Project extends BaseEntity { +public class Project extends BaseEntity implements UserContainer { + public enum ProjectStatus { - APPLICATION("Заявка"), - ON_COMPETITION("Отправлен на конкурс"), - SUCCESSFUL_PASSAGE("Успешное прохождение"), + TECHNICAL_TASK("Техническое задание"), + OPEN("Открыт"), IN_WORK("В работе"), - COMPLETED("Завершен"), + CERTIFICATE_ISSUED("Оформление свидетельства"), + CLOSED("Закрыт"), FAILED("Провалены сроки"); private String statusName; @@ -44,7 +49,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; @@ -68,6 +73,9 @@ public class Project extends BaseEntity { @JoinColumn(name = "project_id") private List events = new ArrayList<>(); + @ManyToMany(fetch = FetchType.LAZY) + private List executors = new ArrayList<>(); + public String getTitle() { return title; } @@ -131,4 +139,18 @@ public class Project extends BaseEntity { public void setEvents(List events) { this.events = events; } + + public List getExecutors() { + return executors; + } + + public void setExecutors(List executors) { + this.executors = executors; + } + + @Override + public Set getUsers() { + Set users = new HashSet(getExecutors()); + return users; + } } diff --git a/src/main/java/ru/ulstu/project/model/ProjectDto.java b/src/main/java/ru/ulstu/project/model/ProjectDto.java index 4e03365..affee4e 100644 --- a/src/main/java/ru/ulstu/project/model/ProjectDto.java +++ b/src/main/java/ru/ulstu/project/model/ProjectDto.java @@ -3,11 +3,19 @@ package ru.ulstu.project.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import org.hibernate.validator.constraints.NotEmpty; +import org.thymeleaf.util.StringUtils; import ru.ulstu.deadline.model.Deadline; import ru.ulstu.grant.model.GrantDto; +import ru.ulstu.user.model.User; +import ru.ulstu.user.model.UserDto; 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; @@ -20,6 +28,11 @@ public class ProjectDto { private GrantDto grant; private String repository; private String applicationFileName; + private List removedDeadlineIds = new ArrayList<>(); + private Set executorIds; + private List executors; + + private final static int MAX_EXECUTORS_LENGTH = 40; public ProjectDto() { } @@ -35,7 +48,9 @@ public class ProjectDto { @JsonProperty("description") String description, @JsonProperty("grant") GrantDto grant, @JsonProperty("repository") String repository, - @JsonProperty("deadlines") List deadlines) { + @JsonProperty("deadlines") List deadlines, + @JsonProperty("executorIds") Set executorIds, + @JsonProperty("executors") List executors) { this.id = id; this.title = title; this.status = status; @@ -44,10 +59,13 @@ public class ProjectDto { this.repository = repository; this.deadlines = deadlines; this.applicationFileName = null; + this.executorIds = executorIds; + this.executors = executors; } public ProjectDto(Project project) { + Set users = new HashSet(project.getExecutors()); this.id = project.getId(); this.title = project.getTitle(); this.status = project.getStatus(); @@ -56,6 +74,8 @@ public class ProjectDto { 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); } public Integer getId() { @@ -121,4 +141,35 @@ public class ProjectDto { public void setApplicationFileName(String applicationFileName) { this.applicationFileName = applicationFileName; } + + 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); + } } diff --git a/src/main/java/ru/ulstu/project/service/ProjectService.java b/src/main/java/ru/ulstu/project/service/ProjectService.java index 247624d..fe8813c 100644 --- a/src/main/java/ru/ulstu/project/service/ProjectService.java +++ b/src/main/java/ru/ulstu/project/service/ProjectService.java @@ -9,6 +9,8 @@ import ru.ulstu.grant.repository.GrantRepository; import ru.ulstu.project.model.Project; import ru.ulstu.project.model.ProjectDto; import ru.ulstu.project.repository.ProjectRepository; +import ru.ulstu.user.model.User; +import ru.ulstu.user.service.UserService; import java.io.IOException; import java.util.Arrays; @@ -16,7 +18,7 @@ import java.util.List; 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 +28,18 @@ public class ProjectService { private final DeadlineService deadlineService; private final GrantRepository grantRepository; private final FileService fileService; + private final UserService userService; public ProjectService(ProjectRepository projectRepository, DeadlineService deadlineService, GrantRepository grantRepository, - FileService fileService) { + FileService fileService, + UserService userService) { this.projectRepository = projectRepository; this.deadlineService = deadlineService; this.grantRepository = grantRepository; this.fileService = fileService; + this.userService = userService; } public List findAll() { @@ -83,7 +88,7 @@ public class ProjectService { 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.findOne(projectDto.getGrant().getId())); @@ -104,8 +109,20 @@ public class ProjectService { } } + public void removeDeadline(ProjectDto projectDto, Integer deadlineId) { + if (deadlineId != null) { + projectDto.getRemovedDeadlineIds().add(deadlineId); + } + projectDto.getDeadlines().remove((int) deadlineId); + } + public Project findById(Integer id) { return projectRepository.findOne(id); } + public List getProjectExecutors(ProjectDto projectDto) { + List users = userService.findAll(); + return users; + } + } 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 8ec9081..2a03e37 100644 --- a/src/main/java/ru/ulstu/students/model/Task.java +++ b/src/main/java/ru/ulstu/students/model/Task.java @@ -67,6 +67,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")}) @@ -127,4 +128,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 8d52e01..2df691f 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 ru.ulstu.tags.model.Tag; 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; @@ -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/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 ee49ab8..af277d1 100644 --- a/src/main/java/ru/ulstu/students/repository/TaskRepository.java +++ b/src/main/java/ru/ulstu/students/repository/TaskRepository.java @@ -6,6 +6,7 @@ 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 { @@ -15,4 +16,12 @@ 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 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..9d14926 --- /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.exists(schedulerId)) { + schedulerRepository.delete(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 a8747c7..e89aedf 100644 --- a/src/main/java/ru/ulstu/students/service/TaskService.java +++ b/src/main/java/ru/ulstu/students/service/TaskService.java @@ -4,18 +4,29 @@ 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.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; @@ -27,14 +38,19 @@ 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 taskRepository, - DeadlineService deadlineService, TagService tagService) { + 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() { @@ -67,6 +83,7 @@ public class TaskService { public Integer create(TaskDto taskDto) throws IOException { Task newTask = copyFromDto(new Task(), taskDto); newTask = taskRepository.save(newTask); + eventService.createFromTask(newTask); return newTask.getId(); } @@ -86,14 +103,22 @@ public class TaskService { public Integer update(TaskDto taskDto) throws IOException { Task task = taskRepository.findOne(taskDto.getId()); taskRepository.save(copyFromDto(task, taskDto)); + eventService.updateTaskDeadlines(task); return task.getId(); } @Transactional - public void delete(Integer taskId) throws IOException { + public boolean delete(Integer taskId) throws IOException { if (taskRepository.exists(taskId)) { + Task scheduleTask = taskRepository.findOne(taskId); + Scheduler sch = schedulerRepository.findOneByTask(scheduleTask); + if (sch != null) { + schedulerRepository.delete(sch.getId()); + } taskRepository.delete(taskId); + return true; } + return false; } @@ -105,6 +130,112 @@ 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()); } @@ -113,4 +244,14 @@ public class TaskService { 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 aed000f..e1c63d2 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.Column; import javax.persistence.Entity; import javax.persistence.Table; 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/timeline/model/Event.java b/src/main/java/ru/ulstu/timeline/model/Event.java index 9252cec..8038f0b 100644 --- a/src/main/java/ru/ulstu/timeline/model/Event.java +++ b/src/main/java/ru/ulstu/timeline/model/Event.java @@ -5,6 +5,7 @@ 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.students.model.Task; import ru.ulstu.user.model.User; import javax.persistence.CascadeType; @@ -64,8 +65,8 @@ public class Event extends BaseEntity { private String description; - @ManyToMany(fetch = FetchType.EAGER) - private List recipients = new ArrayList(); + @ManyToMany(fetch = FetchType.LAZY) + private List recipients = new ArrayList<>(); @ManyToOne @JoinColumn(name = "child_id") @@ -87,6 +88,10 @@ public class Event extends BaseEntity { @JoinColumn(name = "grant_id") private Grant grant; + @ManyToOne + @JoinColumn(name = "task_id") + private Task task; + public String getTitle() { return title; } @@ -190,4 +195,12 @@ public class Event extends BaseEntity { public void setGrant(Grant grant) { this.grant = grant; } + + 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 89df5d8..ccf0f0a 100644 --- a/src/main/java/ru/ulstu/timeline/model/EventDto.java +++ b/src/main/java/ru/ulstu/timeline/model/EventDto.java @@ -6,6 +6,7 @@ import org.hibernate.validator.constraints.NotBlank; import ru.ulstu.conference.model.ConferenceDto; import ru.ulstu.grant.model.GrantDto; import ru.ulstu.paper.model.PaperDto; +import ru.ulstu.students.model.TaskDto; import ru.ulstu.user.model.UserDto; import javax.validation.constraints.NotNull; @@ -29,6 +30,7 @@ public class EventDto { private PaperDto paperDto; private ConferenceDto conferenceDto; private GrantDto grantDto; + private TaskDto taskDto; @JsonCreator public EventDto(@JsonProperty("id") Integer id, @@ -42,7 +44,8 @@ public class EventDto { @JsonProperty("paperDto") PaperDto paperDto, @JsonProperty("recipients") List recipients, @JsonProperty("conferenceDto") ConferenceDto conferenceDto, - @JsonProperty("grantDto") GrantDto grantDto) { + @JsonProperty("grantDto") GrantDto grantDto, + @JsonProperty("taskDto") TaskDto taskDto) { this.id = id; this.title = title; this.period = period; @@ -55,6 +58,7 @@ public class EventDto { this.paperDto = paperDto; this.conferenceDto = conferenceDto; this.grantDto = grantDto; + this.taskDto = taskDto; } public EventDto(Event event) { @@ -76,6 +80,9 @@ public class EventDto { if (grantDto != null) { this.grantDto = new GrantDto(event.getGrant()); } + if (taskDto != null) { + this.taskDto = new TaskDto(event.getTask()); + } } public Integer getId() { @@ -137,4 +144,12 @@ public class EventDto { public void setGrantDto(GrantDto grantDto) { this.grantDto = grantDto; } + + 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 e01037a..7ebd3c9 100644 --- a/src/main/java/ru/ulstu/timeline/repository/EventRepository.java +++ b/src/main/java/ru/ulstu/timeline/repository/EventRepository.java @@ -5,6 +5,7 @@ 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.students.model.Task; import ru.ulstu.timeline.model.Event; import java.util.List; @@ -21,4 +22,6 @@ public interface EventRepository extends JpaRepository { List findAllByConference(Conference conference); List findAllByGrant(Grant grant); + + 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 b935f16..8c68291 100644 --- a/src/main/java/ru/ulstu/timeline/service/EventService.java +++ b/src/main/java/ru/ulstu/timeline/service/EventService.java @@ -8,6 +8,7 @@ import ru.ulstu.conference.model.Conference; import ru.ulstu.deadline.model.Deadline; import ru.ulstu.grant.model.Grant; import ru.ulstu.paper.model.Paper; +import ru.ulstu.students.model.Task; import ru.ulstu.timeline.model.Event; import ru.ulstu.timeline.model.EventDto; import ru.ulstu.timeline.model.Timeline; @@ -203,4 +204,38 @@ public class EventService { eventRepository.delete(eventRepository.findAllByGrant(grant)); createFromGrant(grant); } + + public void removeConferencesEvent(Conference conference) { + List eventList = eventRepository.findAllByConference(conference); + eventList.forEach(event -> eventRepository.delete(event.getId())); + } + + public void createFromTask(Task newTask) { + List timelines = timelineService.findAll(); + Timeline timeline = timelines.isEmpty() ? new Timeline() : timelines.get(0); + + for (Deadline deadline : newTask.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.setStatus(Event.EventStatus.NEW); + newEvent.setExecuteDate(deadline.getDate()); + newEvent.setCreateDate(new Date()); + newEvent.setUpdateDate(new Date()); + newEvent.setDescription("Дедлайн '" + deadline.getDescription() + "' задачи '" + newTask.getTitle() + "'"); + newEvent.getRecipients().add(userService.getCurrentUser()); + newEvent.setTask(newTask); + eventRepository.save(newEvent); + + timeline.getEvents().add(newEvent); + timelineService.save(timeline); + } + } + + public void updateTaskDeadlines(Task task) { + eventRepository.delete(eventRepository.findAllByTask(task)); + createFromTask(task); + } } diff --git a/src/main/java/ru/ulstu/user/controller/UserController.java b/src/main/java/ru/ulstu/user/controller/UserController.java index d7db909..c40ed8f 100644 --- a/src/main/java/ru/ulstu/user/controller/UserController.java +++ b/src/main/java/ru/ulstu/user/controller/UserController.java @@ -3,6 +3,7 @@ package ru.ulstu.user.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.access.annotation.Secured; +import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @@ -19,6 +20,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,8 +30,12 @@ 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; @RestController @@ -141,30 +147,28 @@ 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); } } 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..044bde8 --- /dev/null +++ b/src/main/java/ru/ulstu/user/controller/UserMvcController.java @@ -0,0 +1,56 @@ +package ru.ulstu.user.controller; + +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.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import ru.ulstu.configuration.Constants; +import ru.ulstu.odin.controller.OdinController; +import ru.ulstu.user.model.UserDto; +import ru.ulstu.user.model.User; +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; + +@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()); + } +} 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 7946f04..520b439 100644 --- a/src/main/java/ru/ulstu/user/model/User.java +++ b/src/main/java/ru/ulstu/user/model/User.java @@ -26,7 +26,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) @@ -232,7 +232,7 @@ public class User extends BaseEntity { 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 33d84bc..58e7462 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 da1da6d..3724792 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,17 +15,16 @@ 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; @Service public class MailService { - private final Logger log = LoggerFactory.getLogger(MailService.class); - private static final String USER = "user"; private static final String BASE_URL = "baseUrl"; - + private final Logger log = LoggerFactory.getLogger(MailService.class); private final JavaMailSender javaMailSender; private final SpringTemplateEngine templateEngine; private final MailProperties mailProperties; @@ -38,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); } } @@ -64,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: выделить сервис нотификаций @@ -75,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 @@ -83,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 c98e4b7..217215b 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.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; @@ -11,6 +14,7 @@ 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; @@ -25,8 +29,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; @@ -35,11 +41,18 @@ 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.List; +import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; @@ -48,6 +61,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; @@ -55,19 +70,27 @@ 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; public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder, UserRoleRepository userRoleRepository, UserMapper userMapper, MailService mailService, - ApplicationProperties applicationProperties) { + ApplicationProperties applicationProperties, + @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; } private User getUserByEmail(String email) { @@ -122,7 +145,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); @@ -192,10 +215,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()); @@ -205,49 +228,31 @@ 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.findOne(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(); - 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) { + public boolean requestUserPasswordReset(String email) { User user = userRepository.findOneByEmailIgnoreCase(email); if (user == null) { throw new UserNotFoundException(email); @@ -258,23 +263,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; } @@ -328,4 +340,53 @@ 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); + } } 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 de585a5..ec58dd9 100644 --- a/src/main/java/ru/ulstu/user/util/UserUtils.java +++ b/src/main/java/ru/ulstu/user/util/UserUtils.java @@ -5,6 +5,7 @@ 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 +33,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..d65e276 --- /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..e4e37f9 --- /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..b1b1707 --- /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..925d9a8 --- /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 038ddcf..f4be778 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -35,5 +35,6 @@ liquibase.change-log=classpath:db/changelog-master.xml 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 diff --git a/src/main/resources/db/changelog-20190505_000000-schema.xml b/src/main/resources/db/changelog-20190505_000000-schema.xml index ac8707a..ad56dac 100644 --- a/src/main/resources/db/changelog-20190505_000000-schema.xml +++ b/src/main/resources/db/changelog-20190505_000000-schema.xml @@ -2,6 +2,7 @@ + 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 index 6962e7d..0cdb99b 100644 --- a/src/main/resources/db/changelog-20190507_000000-schema.xml +++ b/src/main/resources/db/changelog-20190507_000000-schema.xml @@ -2,13 +2,7 @@ - - - - - - + + 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..7df707c --- /dev/null +++ b/src/main/resources/db/changelog-20190528_000002-schema.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + diff --git a/src/main/resources/db/changelog-master.xml b/src/main/resources/db/changelog-master.xml index 65a07c2..1cede5f 100644 --- a/src/main/resources/db/changelog-master.xml +++ b/src/main/resources/db/changelog-master.xml @@ -38,5 +38,16 @@ + + + + + + + + + + + \ 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/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/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/userInviteEmail.html b/src/main/resources/mail_templates/userInviteEmail.html new file mode 100644 index 0000000..98fe85f --- /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/base.css b/src/main/resources/public/css/base.css new file mode 100644 index 0000000..0c69e7c --- /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 73a96ae..60a866d 100644 --- a/src/main/resources/public/css/conference.css +++ b/src/main/resources/public/css/conference.css @@ -23,11 +23,17 @@ body { 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; @@ -140,6 +146,7 @@ body { .paper-name { flex: 1; + overflow: hidden; } .paper-name:hover { @@ -156,6 +163,15 @@ body { float: left; } +.paper-name span:nth-child(2) { + max-width: 326px; + white-space: nowrap; +} + +.dropdown-menu { + max-width: 445px; +} + .icon { 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 7e350ed..936dd84 100644 --- a/src/main/resources/public/css/tasks.css +++ b/src/main/resources/public/css/tasks.css @@ -38,6 +38,65 @@ width: auto; 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; 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 18a8c67..8273557 100644 --- a/src/main/resources/public/js/conference.js +++ b/src/main/resources/public/js/conference.js @@ -25,4 +25,5 @@ $(document).ready(function () { $('#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..cc42258 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 */ diff --git a/src/main/resources/public/js/tasks.js b/src/main/resources/public/js/tasks.js index f756199..f1cf868 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'); diff --git a/src/main/resources/public/js/users.js b/src/main/resources/public/js/users.js new file mode 100644 index 0000000..e31d3ad --- /dev/null +++ b/src/main/resources/public/js/users.js @@ -0,0 +1,127 @@ +function changePassword() { + oldPassword = $("#oldPassword").val() + password = $("#password").val() + confirmPassword = $("#confirmPassword").val() + + if ([oldPassword.length, password.length, confirmPassword.length].includes(0)) { + showFeedbackMessage("Заполните все поля", MessageTypesEnum.WARNING); + return; + } + + if (password != confirmPassword) { + showFeedbackMessage("Повторный пароль введен неверно", MessageTypesEnum.WARNING); + return; + } + + $.ajax({ + url:"/api/1.0/users/changePassword", + contentType: "application/json; charset=utf-8", + data: JSON.stringify({ + "oldPassword": oldPassword, + "password": password, + "confirmPassword": confirmPassword, + }), + method: "POST", + success: function() { + $("#closeModalPassword").click(); + showFeedbackMessage("Пароль был обновлен", MessageTypesEnum.SUCCESS) + + }, + error: function(errorData) { + showFeedbackMessage(errorData.responseJSON.error.message, MessageTypesEnum.WARNING) + } + }) +} + +function inviteUser() { + email = $("#email").val(); + if (!isEmailValid(email)) { + showFeedbackMessage("Некорректный почтовый ящик", MessageTypesEnum.WARNING); + return; + } + + $.ajax({ + url:"/api/1.0/users/invite?email=" + email, + contentType: "application/json; charset=utf-8", + method: "POST", + success: function() { + $("#closeModalInvite").click(); + showFeedbackMessage("Пользователь был успешно приглашен", MessageTypesEnum.SUCCESS) + }, + error: function(errorData) { + showFeedbackMessage(errorData.responseJSON.error.message, MessageTypesEnum.WARNING) + } + }) +} + +function requestResetPassword() { + email = $("#emailReset").val() + + if (!isEmailValid(email)) { + showFeedbackMessage("Некорректный почтовый ящик", MessageTypesEnum.WARNING); + return; + } + $("#dvloader").show(); + + $.ajax({ + url:"/api/1.0/users/password-reset-request?email=" + email, + contentType: "application/json; charset=utf-8", + method: "POST", + success: function() { + showFeedbackMessage("Проверочный код был отправлен на указанный почтовый ящик", MessageTypesEnum.SUCCESS) + $("#passwordNew").show() + $("#passwordConfirm").show() + $("#btnReset").show() + $("#resetKey").show() + $("#emailReset").hide() + $("#btnSend").hide() + $("#dvloader").hide() + + }, + error: function(errorData) { + showFeedbackMessage(errorData.responseJSON.error.message, MessageTypesEnum.WARNING) + $("#dvloader").hide() + } + }) + +} + +function resetPassword() { + passwordNew = $("#passwordNew").val(); + passwordConfirm = $("#passwordConfirm").val(); + resetKey = $("#resetKey").val(); + + if ([passwordNew, passwordConfirm, resetKey].includes("")) { + showFeedbackMessage("Заполните все поля", MessageTypesEnum.WARNING); + return; + } + + if (passwordNew != passwordConfirm) { + showFeedbackMessage("Пароли не совпадают", MessageTypesEnum.WARNING); + return; + } + + $.ajax({ + url:"/api/1.0/users/password-reset", + contentType: "application/json; charset=utf-8", + method: "POST", + data: JSON.stringify({ + "password": passwordNew, + "passwordConfirm": passwordConfirm, + "resetKey": resetKey, + }), + success: function() { + showFeedbackMessage("Пользователь был успешно приглашен", MessageTypesEnum.SUCCESS) + window.location.href = "/login" + }, + error: function(errorData) { + showFeedbackMessage(errorData.responseJSON.error.message, MessageTypesEnum.WARNING) + } + }) +} + + +function isEmailValid(email) { + re = /\S+@\S+\.\S+/; + return re.test(email) +} \ No newline at end of file diff --git a/src/main/resources/templates/conferences/conference.html b/src/main/resources/templates/conferences/conference.html index d5906b6..201aa01 100644 --- a/src/main/resources/templates/conferences/conference.html +++ b/src/main/resources/templates/conferences/conference.html @@ -30,23 +30,32 @@ -

Incorrect title

-

+

Incorrect title

+

+
+

Incorrect description

+

+
+

Incorrect description

+

+
@@ -64,6 +73,7 @@
+

Incorrect title

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

Incorrect date

+

@@ -122,7 +136,6 @@
- diff --git a/src/main/resources/templates/conferences/dashboard.html b/src/main/resources/templates/conferences/dashboard.html index 86be4f2..e8cfa49 100644 --- a/src/main/resources/templates/conferences/dashboard.html +++ b/src/main/resources/templates/conferences/dashboard.html @@ -24,24 +24,24 @@

- - + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/templates/default.html b/src/main/resources/templates/default.html index 65e0be6..32939e7 100644 --- a/src/main/resources/templates/default.html +++ b/src/main/resources/templates/default.html @@ -61,13 +61,24 @@ - +
+
@@ -379,6 +507,63 @@ } } + 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/projects/fragments/projectStatusFragment.html b/src/main/resources/templates/projects/fragments/projectStatusFragment.html index d8f29cc..bf0d3f6 100644 --- a/src/main/resources/templates/projects/fragments/projectStatusFragment.html +++ b/src/main/resources/templates/projects/fragments/projectStatusFragment.html @@ -6,19 +6,19 @@ -
+
-
+
-
+
-
+
-
+
diff --git a/src/main/resources/templates/projects/project.html b/src/main/resources/templates/projects/project.html index dc3fa6d..2c4a67b 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"> - + @@ -71,7 +71,8 @@
-
+
+
+
+ +
+
+ +

Incorrect title

diff --git a/src/main/resources/templates/resetRequest.html b/src/main/resources/templates/resetRequest.html index 2adab37..4a2aeab 100644 --- a/src/main/resources/templates/resetRequest.html +++ b/src/main/resources/templates/resetRequest.html @@ -1,57 +1,59 @@ + layout:decorator="default" xmlns:th="http://www.w3.org/1999/xhtml"> + +
-
-
-
-
- -
- -
- - Вернуться к странице входа - +
+
+ +
+
+
+
+ +
+
+ +
+
+ +
+
+ +
+ + + + +
-
-
+
+
- - - \ No newline at end of file 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/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/users/changePassword.html b/src/main/resources/templates/users/changePassword.html new file mode 100644 index 0000000..bc96b5c --- /dev/null +++ b/src/main/resources/templates/users/changePassword.html @@ -0,0 +1,36 @@ + + + + + + + + + + \ 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..e5b7563 --- /dev/null +++ b/src/main/resources/templates/users/dashboard.html @@ -0,0 +1,35 @@ + + + + + + +
+
+
+
+

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

+
+
+

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..267bbf8 --- /dev/null +++ b/src/main/resources/templates/users/fragments/userDashboardFragment.html @@ -0,0 +1,18 @@ + + + + + + +
+
+
+

+

+

+

Онлайн

+
+
+
+ + \ 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..c91b397 --- /dev/null +++ b/src/main/resources/templates/users/inviteModal.html @@ -0,0 +1,31 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/templates/users/profile.html b/src/main/resources/templates/users/profile.html new file mode 100644 index 0000000..93adfc7 --- /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/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/core/PageObject.java b/src/test/java/core/PageObject.java index d1fae83..f3e5cb8 100644 --- a/src/test/java/core/PageObject.java +++ b/src/test/java/core/PageObject.java @@ -1,14 +1,17 @@ package core; +import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; public abstract class PageObject { protected WebDriver driver; + protected JavascriptExecutor js; public abstract String getSubTitle(); public PageObject setDriver(WebDriver driver) { this.driver = driver; + js = (JavascriptExecutor) driver; return this; } } 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/ru/ulstu/conference/service/ConferenceServiceTest.java b/src/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java new file mode 100644 index 0000000..95f4820 --- /dev/null +++ b/src/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java @@ -0,0 +1,289 @@ +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.model.Ping; +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)); + } + + @Test + public void ping() throws IOException { + Ping ping = new Ping(); + when(conferenceRepository.findOne(ID)).thenReturn(conferenceWithId); + when(pingService.addPing(conferenceWithId)).thenReturn(ping); + when(conferenceRepository.updatePingConference(ID)).thenReturn(INDEX); + + assertEquals(ping, conferenceService.ping(conferenceDto)); + } +} \ 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..8edfc77 --- /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.createFromTask(new Task()); + + 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()); + } +}