#103 merge with dev

This commit is contained in:
T-Midnight 2019-06-05 09:34:51 +04:00
commit c77702704f
112 changed files with 3989 additions and 392 deletions

View File

@ -126,7 +126,8 @@ dependencies {
compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.6.0' 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.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'
compile group: 'org.seleniumhq.selenium', name: 'selenium-support', version: '3.3.1' testCompile group: 'org.seleniumhq.selenium', name: 'selenium-support', version: '3.3.1'
testCompile group: 'com.google.guava', name: 'guava', version: '21.0'
} }

View File

@ -5,8 +5,11 @@ import org.hibernate.annotations.FetchMode;
import org.hibernate.validator.constraints.NotBlank; import org.hibernate.validator.constraints.NotBlank;
import org.springframework.format.annotation.DateTimeFormat; import org.springframework.format.annotation.DateTimeFormat;
import ru.ulstu.core.model.BaseEntity; import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.core.model.EventSource;
import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.paper.model.Paper; import ru.ulstu.paper.model.Paper;
import ru.ulstu.timeline.model.Event;
import ru.ulstu.user.model.User;
import javax.persistence.CascadeType; import javax.persistence.CascadeType;
import javax.persistence.Column; import javax.persistence.Column;
@ -28,7 +31,7 @@ import java.util.Optional;
@Entity @Entity
@Table(name = "conference") @Table(name = "conference")
public class Conference extends BaseEntity { public class Conference extends BaseEntity implements EventSource {
@NotBlank @NotBlank
private String title; private String title;
@ -71,6 +74,19 @@ public class Conference extends BaseEntity {
return title; return title;
} }
@Override
public List<User> getRecipients() {
List<User> list = new ArrayList<>();
getUsers().forEach(conferenceUser -> list.add(conferenceUser.getUser()));
return list;
}
@Override
public void addObjectToEvent(Event event) {
event.setConference(this);
}
public void setTitle(String title) { public void setTitle(String title) {
this.title = title; this.title = title;
} }

View File

@ -29,4 +29,8 @@ public interface ConferenceRepository extends JpaRepository<Conference, Integer>
@Override @Override
@Query("SELECT title FROM Conference c WHERE (c.title = :name) AND (:id IS NULL OR c.id != :id) ") @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); 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);
} }

View File

@ -27,6 +27,7 @@ import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Collections;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static org.springframework.util.ObjectUtils.isEmpty; import static org.springframework.util.ObjectUtils.isEmpty;
@ -92,6 +93,7 @@ public class ConferenceService extends BaseService {
conferenceDto.setName(conferenceDto.getTitle()); conferenceDto.setName(conferenceDto.getTitle());
filterEmptyDeadlines(conferenceDto); filterEmptyDeadlines(conferenceDto);
checkEmptyFieldsOfDeadline(conferenceDto, errors); checkEmptyFieldsOfDeadline(conferenceDto, errors);
checkEmptyFieldsOfDates(conferenceDto, errors);
checkUniqueName(conferenceDto, checkUniqueName(conferenceDto,
errors, errors,
conferenceDto.getId(), conferenceDto.getId(),
@ -115,7 +117,7 @@ public class ConferenceService extends BaseService {
Conference newConference = copyFromDto(new Conference(), conferenceDto); Conference newConference = copyFromDto(new Conference(), conferenceDto);
newConference = conferenceRepository.save(newConference); newConference = conferenceRepository.save(newConference);
conferenceNotificationService.sendCreateNotification(newConference); conferenceNotificationService.sendCreateNotification(newConference);
eventService.createFromConference(newConference); eventService.createFromObject(newConference, Collections.emptyList(), false, "конференции");
return newConference; return newConference;
} }
@ -301,9 +303,19 @@ public class ConferenceService extends BaseService {
} }
} }
private void checkEmptyFieldsOfDates(ConferenceDto conferenceDto, Errors errors) {
if (conferenceDto.getBeginDate() == null || conferenceDto.getEndDate() == null) {
errors.rejectValue("beginDate", "errorCode", "Даты должны быть заполнены");
}
}
public void filterEmptyDeadlines(ConferenceDto conferenceDto) { public void filterEmptyDeadlines(ConferenceDto conferenceDto) {
conferenceDto.setDeadlines(conferenceDto.getDeadlines().stream() conferenceDto.setDeadlines(conferenceDto.getDeadlines().stream()
.filter(dto -> dto.getDate() != null || !org.springframework.util.StringUtils.isEmpty(dto.getDescription())) .filter(dto -> dto.getDate() != null || !org.springframework.util.StringUtils.isEmpty(dto.getDescription()))
.collect(Collectors.toList())); .collect(Collectors.toList()));
} }
public Conference getActiveConferenceByUser(User user) {
return conferenceRepository.findActiveByUser(user);
}
} }

View File

@ -43,6 +43,4 @@ public class ConferenceUserService {
newUser = conferenceUserRepository.save(newUser); newUser = conferenceUserRepository.save(newUser);
return newUser; return newUser;
} }
} }

View File

@ -21,6 +21,8 @@ public class ApplicationProperties {
private boolean checkRun; private boolean checkRun;
private String debugEmail;
public boolean isUseHttps() { public boolean isUseHttps() {
return useHttps; return useHttps;
} }
@ -60,4 +62,12 @@ public class ApplicationProperties {
public void setCheckRun(boolean checkRun) { public void setCheckRun(boolean checkRun) {
this.checkRun = checkRun; this.checkRun = checkRun;
} }
public String getDebugEmail() {
return debugEmail;
}
public void setDebugEmail(String debugEmail) {
this.debugEmail = debugEmail;
}
} }

View File

@ -21,4 +21,5 @@ public class Constants {
public static final String PASSWORD_RESET_REQUEST_PAGE = "/resetRequest"; public static final String PASSWORD_RESET_REQUEST_PAGE = "/resetRequest";
public static final String PASSWORD_RESET_PAGE = "/reset"; public static final String PASSWORD_RESET_PAGE = "/reset";
public static final int RESET_KEY_LENGTH = 6;
} }

View File

@ -104,7 +104,8 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
.antMatchers("/css/**") .antMatchers("/css/**")
.antMatchers("/js/**") .antMatchers("/js/**")
.antMatchers("/templates/**") .antMatchers("/templates/**")
.antMatchers("/webjars/**"); .antMatchers("/webjars/**")
.antMatchers("/img/**");
} }
@Autowired @Autowired

View File

@ -35,11 +35,6 @@ public class AdviceController {
this.userService = userService; this.userService = userService;
} }
@ModelAttribute("currentUser")
public String getCurrentUser() {
return userService.getCurrentUser().getUserAbbreviate();
}
@ModelAttribute("flashMessage") @ModelAttribute("flashMessage")
public String getFlashMessage() { public String getFlashMessage() {
return null; return null;

View File

@ -9,9 +9,9 @@ public enum ErrorConstants {
USER_EMAIL_EXISTS(102, "Пользователь с таким почтовым ящиком уже существует"), USER_EMAIL_EXISTS(102, "Пользователь с таким почтовым ящиком уже существует"),
USER_LOGIN_EXISTS(103, "Пользователь с таким логином уже существует"), USER_LOGIN_EXISTS(103, "Пользователь с таким логином уже существует"),
USER_PASSWORDS_NOT_VALID_OR_NOT_MATCH(104, "Пароли введены неверно"), USER_PASSWORDS_NOT_VALID_OR_NOT_MATCH(104, "Пароли введены неверно"),
USER_NOT_FOUND(105, "User is not found"), USER_NOT_FOUND(105, "Аккаунт не найден"),
USER_NOT_ACTIVATED(106, "User is not activated"), 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"), 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, "Во время отправки приглашения пользователю произошла ошибка"); USER_SENDING_MAIL_EXCEPTION(111, "Во время отправки приглашения пользователю произошла ошибка");

View File

@ -0,0 +1,17 @@
package ru.ulstu.core.model;
import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.timeline.model.Event;
import ru.ulstu.user.model.User;
import java.util.List;
public interface EventSource {
List<Deadline> getDeadlines();
String getTitle();
List<User> getRecipients();
void addObjectToEvent(Event event);
}

View File

@ -4,11 +4,15 @@ import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.format.annotation.DateTimeFormat; import org.springframework.format.annotation.DateTimeFormat;
import ru.ulstu.core.model.BaseEntity; import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.user.model.User;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.persistence.Temporal; import javax.persistence.Temporal;
import javax.persistence.TemporalType; import javax.persistence.TemporalType;
import java.util.Date; import java.util.Date;
import java.util.List;
import java.util.Objects; import java.util.Objects;
@Entity @Entity
@ -20,6 +24,11 @@ public class Deadline extends BaseEntity {
@DateTimeFormat(pattern = "yyyy-MM-dd") @DateTimeFormat(pattern = "yyyy-MM-dd")
private Date date; private Date date;
@OneToMany(targetEntity = User.class, fetch = FetchType.EAGER)
private List<User> executors;
private Boolean done;
public Deadline() { public Deadline() {
} }
@ -28,13 +37,24 @@ public class Deadline extends BaseEntity {
this.description = description; this.description = description;
} }
public Deadline(Date deadlineDate, String description, List<User> executors, Boolean done) {
this.date = deadlineDate;
this.description = description;
this.executors = executors;
this.done = done;
}
@JsonCreator @JsonCreator
public Deadline(@JsonProperty("id") Integer id, public Deadline(@JsonProperty("id") Integer id,
@JsonProperty("description") String description, @JsonProperty("description") String description,
@JsonProperty("date") Date date) { @JsonProperty("date") Date date,
@JsonProperty("executors") List<User> executors,
@JsonProperty("done") Boolean done) {
this.setId(id); this.setId(id);
this.description = description; this.description = description;
this.date = date; this.date = date;
this.executors = executors;
this.done = done;
} }
public String getDescription() { public String getDescription() {
@ -53,6 +73,22 @@ public class Deadline extends BaseEntity {
this.date = date; this.date = date;
} }
public List<User> getExecutors() {
return executors;
}
public void setExecutors(List<User> executors) {
this.executors = executors;
}
public Boolean getDone() {
return done;
}
public void setDone(Boolean done) {
this.done = done;
}
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) { if (this == o) {
@ -72,11 +108,13 @@ public class Deadline extends BaseEntity {
} }
return getId().equals(deadline.getId()) && return getId().equals(deadline.getId()) &&
description.equals(deadline.description) && description.equals(deadline.description) &&
date.equals(deadline.date); date.equals(deadline.date) &&
executors.equals(deadline.executors) &&
done.equals(deadline.done);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(super.hashCode(), description, date); return Objects.hash(super.hashCode(), description, date, executors, done);
} }
} }

View File

@ -2,8 +2,15 @@ package ru.ulstu.deadline.repository;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.model.Deadline;
import java.util.Date;
public interface DeadlineRepository extends JpaRepository<Deadline, Integer> { public interface DeadlineRepository extends JpaRepository<Deadline, Integer> {
@Query(
value = "SELECT date FROM Deadline d WHERE (d.grant_id = ?1) AND (d.date = ?2)",
nativeQuery = true)
Date findByGrantIdAndDate(Integer grantId, Date date);
} }

View File

@ -5,6 +5,7 @@ import org.springframework.transaction.annotation.Transactional;
import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.deadline.repository.DeadlineRepository; import ru.ulstu.deadline.repository.DeadlineRepository;
import java.util.Date;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -29,6 +30,8 @@ public class DeadlineService {
Deadline updateDeadline = deadlineRepository.findOne(deadline.getId()); Deadline updateDeadline = deadlineRepository.findOne(deadline.getId());
updateDeadline.setDate(deadline.getDate()); updateDeadline.setDate(deadline.getDate());
updateDeadline.setDescription(deadline.getDescription()); updateDeadline.setDescription(deadline.getDescription());
updateDeadline.setExecutors(deadline.getExecutors());
updateDeadline.setDone(deadline.getDone());
deadlineRepository.save(updateDeadline); deadlineRepository.save(updateDeadline);
return updateDeadline; return updateDeadline;
} }
@ -38,6 +41,8 @@ public class DeadlineService {
Deadline newDeadline = new Deadline(); Deadline newDeadline = new Deadline();
newDeadline.setDate(deadline.getDate()); newDeadline.setDate(deadline.getDate());
newDeadline.setDescription(deadline.getDescription()); newDeadline.setDescription(deadline.getDescription());
newDeadline.setExecutors(deadline.getExecutors());
newDeadline.setDone(deadline.getDone());
newDeadline = deadlineRepository.save(newDeadline); newDeadline = deadlineRepository.save(newDeadline);
return newDeadline; return newDeadline;
} }
@ -46,4 +51,8 @@ public class DeadlineService {
public void remove(Integer deadlineId) { public void remove(Integer deadlineId) {
deadlineRepository.delete(deadlineId); deadlineRepository.delete(deadlineId);
} }
public Date findByGrantIdAndDate(Integer id, Date date) {
return deadlineRepository.findByGrantIdAndDate(id, date);
}
} }

View File

@ -20,9 +20,7 @@ import springfox.documentation.annotations.ApiIgnore;
import javax.validation.Valid; import javax.validation.Valid;
import java.io.IOException; import java.io.IOException;
import java.util.List; 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.GRANTS_PAGE;
import static ru.ulstu.core.controller.Navigation.GRANT_PAGE; import static ru.ulstu.core.controller.Navigation.GRANT_PAGE;
import static ru.ulstu.core.controller.Navigation.REDIRECT_TO; import static ru.ulstu.core.controller.Navigation.REDIRECT_TO;
@ -45,7 +43,7 @@ public class GrantController {
@GetMapping("/dashboard") @GetMapping("/dashboard")
public void getDashboard(ModelMap modelMap) { public void getDashboard(ModelMap modelMap) {
modelMap.put("grants", grantService.findAllDto()); modelMap.put("grants", grantService.findAllActiveDto());
} }
@GetMapping("/grant") @GetMapping("/grant")
@ -62,17 +60,9 @@ public class GrantController {
@PostMapping(value = "/grant", params = "save") @PostMapping(value = "/grant", params = "save")
public String save(@Valid GrantDto grantDto, Errors errors) public String save(@Valid GrantDto grantDto, Errors errors)
throws IOException { throws IOException {
filterEmptyDeadlines(grantDto); if (!grantService.save(grantDto, errors)) {
if (grantDto.getDeadlines().isEmpty()) {
errors.rejectValue("deadlines", "errorCode", "Не может быть пусто");
}
if (grantDto.getLeaderId().equals(-1)) {
errors.rejectValue("leaderId", "errorCode", "Укажите руководителя");
}
if (errors.hasErrors()) {
return GRANT_PAGE; return GRANT_PAGE;
} }
grantService.save(grantDto);
return String.format(REDIRECT_TO, GRANTS_PAGE); return String.format(REDIRECT_TO, GRANTS_PAGE);
} }
@ -89,7 +79,7 @@ public class GrantController {
@PostMapping(value = "/grant", params = "addDeadline") @PostMapping(value = "/grant", params = "addDeadline")
public String addDeadline(@Valid GrantDto grantDto, Errors errors) { public String addDeadline(@Valid GrantDto grantDto, Errors errors) {
filterEmptyDeadlines(grantDto); grantService.filterEmptyDeadlines(grantDto);
if (errors.hasErrors()) { if (errors.hasErrors()) {
return GRANT_PAGE; return GRANT_PAGE;
} }
@ -133,10 +123,4 @@ public class GrantController {
public List<PaperDto> getAllPapers() { public List<PaperDto> getAllPapers() {
return grantService.getAllUncompletedPapers(); return grantService.getAllUncompletedPapers();
} }
private void filterEmptyDeadlines(GrantDto grantDto) {
grantDto.setDeadlines(grantDto.getDeadlines().stream()
.filter(dto -> dto.getDate() != null || !isEmpty(dto.getDescription()))
.collect(Collectors.toList()));
}
} }

View File

@ -4,6 +4,7 @@ import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode; import org.hibernate.annotations.FetchMode;
import org.hibernate.validator.constraints.NotBlank; import org.hibernate.validator.constraints.NotBlank;
import ru.ulstu.core.model.BaseEntity; import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.core.model.EventSource;
import ru.ulstu.core.model.UserContainer; import ru.ulstu.core.model.UserContainer;
import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.file.model.FileData; import ru.ulstu.file.model.FileData;
@ -26,6 +27,7 @@ import javax.persistence.OrderBy;
import javax.persistence.Table; import javax.persistence.Table;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.Date; import java.util.Date;
import java.util.HashSet; import java.util.HashSet;
@ -35,7 +37,7 @@ import java.util.Set;
@Entity @Entity
@Table(name = "grants") @Table(name = "grants")
public class Grant extends BaseEntity implements UserContainer { public class Grant extends BaseEntity implements UserContainer, EventSource {
public enum GrantStatus { public enum GrantStatus {
APPLICATION("Заявка"), APPLICATION("Заявка"),
ON_COMPETITION("Отправлен на конкурс"), ON_COMPETITION("Отправлен на конкурс"),
@ -43,7 +45,8 @@ public class Grant extends BaseEntity implements UserContainer {
IN_WORK("В работе"), IN_WORK("В работе"),
COMPLETED("Завершен"), COMPLETED("Завершен"),
FAILED("Провалены сроки"), FAILED("Провалены сроки"),
LOADED_FROM_KIAS("Загружен автоматически"); LOADED_FROM_KIAS("Загружен автоматически"),
SKIPPED("Не интересует");
private String statusName; private String statusName;
@ -62,14 +65,14 @@ public class Grant extends BaseEntity implements UserContainer {
@Enumerated(value = EnumType.STRING) @Enumerated(value = EnumType.STRING)
private GrantStatus status = GrantStatus.APPLICATION; private GrantStatus status = GrantStatus.APPLICATION;
@OneToMany(cascade = CascadeType.ALL) @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "grant_id") @JoinColumn(name = "grant_id")
@OrderBy("date") @OrderBy("date")
private List<Deadline> deadlines = new ArrayList<>(); private List<Deadline> deadlines = new ArrayList<>();
private String comment; private String comment;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "grant_id", unique = true) @JoinColumn(name = "grant_id", unique = true)
@Fetch(FetchMode.SUBSELECT) @Fetch(FetchMode.SUBSELECT)
private List<FileData> files = new ArrayList<>(); private List<FileData> files = new ArrayList<>();
@ -133,6 +136,16 @@ public class Grant extends BaseEntity implements UserContainer {
return title; return title;
} }
@Override
public List<User> getRecipients() {
return authors != null ? new ArrayList<>(authors) : Collections.emptyList();
}
@Override
public void addObjectToEvent(Event event) {
event.setGrant(this);
}
public void setTitle(String title) { public void setTitle(String title) {
this.title = title; this.title = title;
} }

View File

@ -6,18 +6,20 @@ import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.NotEmpty; import org.hibernate.validator.constraints.NotEmpty;
import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.file.model.FileDataDto; import ru.ulstu.file.model.FileDataDto;
import ru.ulstu.name.NameContainer;
import ru.ulstu.paper.model.PaperDto; import ru.ulstu.paper.model.PaperDto;
import ru.ulstu.project.model.ProjectDto; import ru.ulstu.project.model.ProjectDto;
import ru.ulstu.user.model.UserDto; import ru.ulstu.user.model.UserDto;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static ru.ulstu.core.util.StreamApiUtils.convert; 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 final static int MAX_AUTHORS_LENGTH = 60;
private Integer id; private Integer id;
@ -95,6 +97,12 @@ public class GrantDto {
this.papers = convert(grant.getPapers(), PaperDto::new); 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() { public Integer getId() {
return id; return id;
} }

View File

@ -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<WebElement> getPageOfGrants() {
WebElement listContest = driver.findElement(By.tagName("tBody"));
List<WebElement> 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();
}
}

View File

@ -1,11 +1,25 @@
package ru.ulstu.grant.repository; package ru.ulstu.grant.repository;
import org.springframework.data.jpa.repository.JpaRepository; 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.grant.model.Grant;
import ru.ulstu.name.BaseRepository;
import java.util.List; import java.util.List;
public interface GrantRepository extends JpaRepository<Grant, Integer> { public interface GrantRepository extends JpaRepository<Grant, Integer>, BaseRepository {
List<Grant> findByStatus(Grant.GrantStatus status); List<Grant> findByStatus(Grant.GrantStatus status);
Grant findByTitle(String title);
Grant findGrantById(Integer grantId);
@Override
@Query("SELECT title FROM Grant g WHERE (g.title = :name) AND (:id IS NULL OR g.id != :id) ")
String findByNameAndNotId(@Param("name") String name, @Param("id") Integer id);
@Query("SELECT g FROM Grant g WHERE (g.status <> 'SKIPPED') AND (g.status <> 'COMPLETED')")
List<Grant> findAllActive();
} }

View File

@ -5,6 +5,9 @@ import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.io.IOException;
import java.text.ParseException;
@Service @Service
public class GrantScheduler { public class GrantScheduler {
private final static boolean IS_DEADLINE_NOTIFICATION_BEFORE_WEEK = true; private final static boolean IS_DEADLINE_NOTIFICATION_BEFORE_WEEK = true;
@ -27,4 +30,15 @@ public class GrantScheduler {
grantNotificationService.sendDeadlineNotifications(grantService.findAll(), IS_DEADLINE_NOTIFICATION_BEFORE_WEEK); grantNotificationService.sendDeadlineNotifications(grantService.findAll(), IS_DEADLINE_NOTIFICATION_BEFORE_WEEK);
log.debug("GrantScheduler.checkDeadlineBeforeWeek finished"); 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");
}
} }

View File

@ -1,8 +1,11 @@
package ru.ulstu.grant.service; package ru.ulstu.grant.service;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Errors;
import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.deadline.service.DeadlineService; import ru.ulstu.deadline.service.DeadlineService;
import ru.ulstu.file.model.FileDataDto; import ru.ulstu.file.model.FileDataDto;
@ -10,6 +13,7 @@ import ru.ulstu.file.service.FileService;
import ru.ulstu.grant.model.Grant; import ru.ulstu.grant.model.Grant;
import ru.ulstu.grant.model.GrantDto; import ru.ulstu.grant.model.GrantDto;
import ru.ulstu.grant.repository.GrantRepository; import ru.ulstu.grant.repository.GrantRepository;
import ru.ulstu.name.BaseService;
import ru.ulstu.paper.model.Paper; import ru.ulstu.paper.model.Paper;
import ru.ulstu.paper.model.PaperDto; import ru.ulstu.paper.model.PaperDto;
import ru.ulstu.paper.service.PaperService; import ru.ulstu.paper.service.PaperService;
@ -21,12 +25,14 @@ import ru.ulstu.user.model.User;
import ru.ulstu.user.service.UserService; import ru.ulstu.user.service.UserService;
import java.io.IOException; import java.io.IOException;
import java.text.ParseException;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toList;
import static org.springframework.util.ObjectUtils.isEmpty; import static org.springframework.util.ObjectUtils.isEmpty;
@ -34,8 +40,8 @@ import static ru.ulstu.core.util.StreamApiUtils.convert;
import static ru.ulstu.grant.model.Grant.GrantStatus.APPLICATION; import static ru.ulstu.grant.model.Grant.GrantStatus.APPLICATION;
@Service @Service
public class GrantService { public class GrantService extends BaseService {
private final static int MAX_DISPLAY_SIZE = 50; private final Logger log = LoggerFactory.getLogger(GrantService.class);
private final GrantRepository grantRepository; private final GrantRepository grantRepository;
private final ProjectService projectService; private final ProjectService projectService;
@ -45,6 +51,7 @@ public class GrantService {
private final PaperService paperService; private final PaperService paperService;
private final EventService eventService; private final EventService eventService;
private final GrantNotificationService grantNotificationService; private final GrantNotificationService grantNotificationService;
private final KiasService kiasService;
public GrantService(GrantRepository grantRepository, public GrantService(GrantRepository grantRepository,
FileService fileService, FileService fileService,
@ -53,8 +60,11 @@ public class GrantService {
UserService userService, UserService userService,
PaperService paperService, PaperService paperService,
EventService eventService, EventService eventService,
GrantNotificationService grantNotificationService) { GrantNotificationService grantNotificationService,
KiasService kiasService) {
this.grantRepository = grantRepository; this.grantRepository = grantRepository;
this.kiasService = kiasService;
this.baseRepository = grantRepository;
this.fileService = fileService; this.fileService = fileService;
this.deadlineService = deadlineService; this.deadlineService = deadlineService;
this.projectService = projectService; this.projectService = projectService;
@ -69,9 +79,7 @@ public class GrantService {
} }
public List<GrantDto> findAllDto() { public List<GrantDto> findAllDto() {
List<GrantDto> grants = convert(findAll(), GrantDto::new); return convert(findAll(), GrantDto::new);
grants.forEach(grantDto -> grantDto.setTitle(StringUtils.abbreviate(grantDto.getTitle(), MAX_DISPLAY_SIZE)));
return grants;
} }
public GrantDto findOneDto(Integer id) { public GrantDto findOneDto(Integer id) {
@ -82,7 +90,7 @@ public class GrantService {
public Integer create(GrantDto grantDto) throws IOException { public Integer create(GrantDto grantDto) throws IOException {
Grant newGrant = copyFromDto(new Grant(), grantDto); Grant newGrant = copyFromDto(new Grant(), grantDto);
newGrant = grantRepository.save(newGrant); newGrant = grantRepository.save(newGrant);
eventService.createFromGrant(newGrant); eventService.createFromObject(newGrant, Collections.emptyList(), false, "гранта");
grantNotificationService.sendCreateNotification(newGrant); grantNotificationService.sendCreateNotification(newGrant);
return newGrant.getId(); return newGrant.getId();
} }
@ -170,18 +178,62 @@ public class GrantService {
grant.getPapers().add(paper); grant.getPapers().add(paper);
grant = grantRepository.save(grant); grant = grantRepository.save(grant);
eventService.createFromGrant(grant); eventService.createFromObject(grant, Collections.emptyList(), false, "гранта");
grantNotificationService.sendCreateNotification(grant); grantNotificationService.sendCreateNotification(grant);
return 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())) { if (isEmpty(grantDto.getId())) {
create(grantDto); create(grantDto);
} else { } else {
update(grantDto); 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(); //дата с сайта киас
Date foundGrantDate = deadlineService.findByGrantIdAndDate(id, date);
return foundGrantDate != null && foundGrantDate.compareTo(date) == 0;
} }
public List<User> getGrantAuthors(GrantDto grantDto) { public List<User> getGrantAuthors(GrantDto grantDto) {
@ -216,11 +268,7 @@ public class GrantService {
} }
public List<PaperDto> getAllUncompletedPapers() { public List<PaperDto> getAllUncompletedPapers() {
List<PaperDto> papers = paperService.findAllNotCompleted(); return paperService.findAllNotCompleted();
papers.stream()
.forEach(paper ->
paper.setTitle(StringUtils.abbreviate(paper.getTitle(), MAX_DISPLAY_SIZE)));
return papers;
} }
public void attachPaper(GrantDto grantDto) { public void attachPaper(GrantDto grantDto) {
@ -261,4 +309,33 @@ public class GrantService {
.filter(author -> Collections.frequency(authors, author) > 3) .filter(author -> Collections.frequency(authors, author) > 3)
.collect(toList()); .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<GrantDto> findAllActiveDto() {
return convert(findAllActive(), GrantDto::new);
}
private List<Grant> findAllActive() {
return grantRepository.findAllActive();
}
public Grant findGrantById(Integer grantId) {
return grantRepository.findOne(grantId);
}
} }

View File

@ -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<GrantDto> getNewGrantsDto() throws ParseException {
WebDriver webDriver = getDriver();
Integer leaderId = userService.findOneByLoginIgnoreCase("admin").getId();
List<GrantDto> 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<GrantDto> getKiasGrants(WebDriver webDriver) throws ParseException {
List<GrantDto> newGrants = new ArrayList<>();
KiasPage kiasPage = new KiasPage(webDriver);
do {
newGrants.addAll(getGrantsFromPage(kiasPage));
} while (kiasPage.goToNextPage()); //проверка существования следующей страницы с грантами
return newGrants;
}
private List<GrantDto> getGrantsFromPage(KiasPage kiasPage) throws ParseException {
List<GrantDto> 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<Integer> 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");
}
}

View File

@ -13,4 +13,11 @@ public abstract class BaseService {
errors.rejectValue(checkField, "errorCode", errorMessage); 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;
}
} }

View File

@ -13,9 +13,11 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import ru.ulstu.conference.service.ConferenceService; import ru.ulstu.conference.service.ConferenceService;
import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.paper.model.AutoCompleteData;
import ru.ulstu.paper.model.Paper; import ru.ulstu.paper.model.Paper;
import ru.ulstu.paper.model.PaperDto; import ru.ulstu.paper.model.PaperDto;
import ru.ulstu.paper.model.PaperListDto; import ru.ulstu.paper.model.PaperListDto;
import ru.ulstu.paper.model.ReferenceDto;
import ru.ulstu.paper.service.LatexService; import ru.ulstu.paper.service.LatexService;
import ru.ulstu.paper.service.PaperService; import ru.ulstu.paper.service.PaperService;
import ru.ulstu.user.model.User; import ru.ulstu.user.model.User;
@ -105,6 +107,15 @@ public class PaperController {
return "/papers/paper"; 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") @ModelAttribute("allStatuses")
public List<Paper.PaperStatus> getPaperStatuses() { public List<Paper.PaperStatus> getPaperStatuses() {
return paperService.getPaperStatuses(); return paperService.getPaperStatuses();
@ -129,6 +140,16 @@ public class PaperController {
return years; return years;
} }
@ModelAttribute("allFormatStandards")
public List<ReferenceDto.FormatStandard> getFormatStandards() {
return paperService.getFormatStandards();
}
@ModelAttribute("allReferenceTypes")
public List<ReferenceDto.ReferenceType> getReferenceTypes() {
return paperService.getReferenceTypes();
}
@PostMapping("/generatePdf") @PostMapping("/generatePdf")
public ResponseEntity<byte[]> getPdfFile(PaperDto paper) throws IOException, InterruptedException { public ResponseEntity<byte[]> getPdfFile(PaperDto paper) throws IOException, InterruptedException {
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
@ -137,6 +158,16 @@ public class PaperController {
return new ResponseEntity<>(latexService.generatePdfFromLatexFile(paper), headers, HttpStatus.OK); return new ResponseEntity<>(latexService.generatePdfFromLatexFile(paper), headers, HttpStatus.OK);
} }
@PostMapping("/getFormattedReferences")
public ResponseEntity<String> 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) { private void filterEmptyDeadlines(PaperDto paperDto) {
paperDto.setDeadlines(paperDto.getDeadlines().stream() paperDto.setDeadlines(paperDto.getDeadlines().stream()
.filter(dto -> dto.getDate() != null || !isEmpty(dto.getDescription())) .filter(dto -> dto.getDate() != null || !isEmpty(dto.getDescription()))

View File

@ -0,0 +1,43 @@
package ru.ulstu.paper.model;
import java.util.ArrayList;
import java.util.List;
public class AutoCompleteData {
private List<String> authors = new ArrayList<>();
private List<String> publicationTitles = new ArrayList<>();
private List<String> publishers = new ArrayList<>();
private List<String> journalOrCollectionTitles = new ArrayList<>();
public List<String> getAuthors() {
return authors;
}
public void setAuthors(List<String> authors) {
this.authors = authors;
}
public List<String> getPublicationTitles() {
return publicationTitles;
}
public void setPublicationTitles(List<String> publicationTitles) {
this.publicationTitles = publicationTitles;
}
public List<String> getPublishers() {
return publishers;
}
public void setPublishers(List<String> publishers) {
this.publishers = publishers;
}
public List<String> getJournalOrCollectionTitles() {
return journalOrCollectionTitles;
}
public void setJournalOrCollectionTitles(List<String> journalOrCollectionTitles) {
this.journalOrCollectionTitles = journalOrCollectionTitles;
}
}

View File

@ -5,6 +5,7 @@ import org.hibernate.annotations.FetchMode;
import org.hibernate.validator.constraints.NotBlank; import org.hibernate.validator.constraints.NotBlank;
import ru.ulstu.conference.model.Conference; import ru.ulstu.conference.model.Conference;
import ru.ulstu.core.model.BaseEntity; import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.core.model.EventSource;
import ru.ulstu.core.model.UserContainer; import ru.ulstu.core.model.UserContainer;
import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.file.model.FileData; import ru.ulstu.file.model.FileData;
@ -34,7 +35,7 @@ import java.util.Optional;
import java.util.Set; import java.util.Set;
@Entity @Entity
public class Paper extends BaseEntity implements UserContainer { public class Paper extends BaseEntity implements UserContainer, EventSource {
public enum PaperStatus { public enum PaperStatus {
ATTENTION("Обратить внимание"), ATTENTION("Обратить внимание"),
ON_PREPARATION("На подготовке"), ON_PREPARATION("На подготовке"),
@ -123,6 +124,11 @@ public class Paper extends BaseEntity implements UserContainer {
@ManyToMany(mappedBy = "papers") @ManyToMany(mappedBy = "papers")
private List<Grant> grants; private List<Grant> grants;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "paper_id", unique = true)
@Fetch(FetchMode.SUBSELECT)
private List<Reference> references = new ArrayList<>();
public PaperStatus getStatus() { public PaperStatus getStatus() {
return status; return status;
} }
@ -191,6 +197,16 @@ public class Paper extends BaseEntity implements UserContainer {
return title; return title;
} }
@Override
public List<User> getRecipients() {
return new ArrayList(authors);
}
@Override
public void addObjectToEvent(Event event) {
event.setPaper(this);
}
public void setTitle(String title) { public void setTitle(String title) {
this.title = title; this.title = title;
} }
@ -248,6 +264,14 @@ public class Paper extends BaseEntity implements UserContainer {
return getAuthors(); return getAuthors();
} }
public List<Reference> getReferences() {
return references;
}
public void setReferences(List<Reference> references) {
this.references = references;
}
public Optional<Deadline> getNextDeadline() { public Optional<Deadline> getNextDeadline() {
return deadlines return deadlines
.stream() .stream()

View File

@ -38,6 +38,8 @@ public class PaperDto {
private Set<UserDto> authors; private Set<UserDto> authors;
private Integer filterAuthorId; private Integer filterAuthorId;
private String latexText; private String latexText;
private List<ReferenceDto> references = new ArrayList<>();
private ReferenceDto.FormatStandard formatStandard = ReferenceDto.FormatStandard.GOST;
public PaperDto() { public PaperDto() {
deadlines.add(new Deadline()); deadlines.add(new Deadline());
@ -57,7 +59,9 @@ public class PaperDto {
@JsonProperty("locked") Boolean locked, @JsonProperty("locked") Boolean locked,
@JsonProperty("files") List<FileDataDto> files, @JsonProperty("files") List<FileDataDto> files,
@JsonProperty("authorIds") Set<Integer> authorIds, @JsonProperty("authorIds") Set<Integer> authorIds,
@JsonProperty("authors") Set<UserDto> authors) { @JsonProperty("authors") Set<UserDto> authors,
@JsonProperty("references") List<ReferenceDto> references,
@JsonProperty("formatStandard") ReferenceDto.FormatStandard formatStandard) {
this.id = id; this.id = id;
this.title = title; this.title = title;
this.status = status; this.status = status;
@ -71,6 +75,8 @@ public class PaperDto {
this.locked = locked; this.locked = locked;
this.files = files; this.files = files;
this.authors = authors; this.authors = authors;
this.references = references;
this.formatStandard = formatStandard;
} }
public PaperDto(Paper paper) { public PaperDto(Paper paper) {
@ -88,6 +94,7 @@ public class PaperDto {
this.files = convert(paper.getFiles(), FileDataDto::new); this.files = convert(paper.getFiles(), FileDataDto::new);
this.authorIds = convert(paper.getAuthors(), user -> user.getId()); this.authorIds = convert(paper.getAuthors(), user -> user.getId());
this.authors = convert(paper.getAuthors(), UserDto::new); this.authors = convert(paper.getAuthors(), UserDto::new);
this.references = convert(paper.getReferences(), ReferenceDto::new);
} }
public Integer getId() { public Integer getId() {
@ -216,4 +223,20 @@ public class PaperDto {
public void setFilterAuthorId(Integer filterAuthorId) { public void setFilterAuthorId(Integer filterAuthorId) {
this.filterAuthorId = filterAuthorId; this.filterAuthorId = filterAuthorId;
} }
public List<ReferenceDto> getReferences() {
return references;
}
public void setReferences(List<ReferenceDto> references) {
this.references = references;
}
public ReferenceDto.FormatStandard getFormatStandard() {
return formatStandard;
}
public void setFormatStandard(ReferenceDto.FormatStandard formatStandard) {
this.formatStandard = formatStandard;
}
} }

View File

@ -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;
}
}

View File

@ -34,6 +34,7 @@ public class ReferenceDto {
} }
} }
private Integer id;
private String authors; private String authors;
private String publicationTitle; private String publicationTitle;
private Integer publicationYear; private Integer publicationYear;
@ -42,9 +43,11 @@ public class ReferenceDto {
private String journalOrCollectionTitle; private String journalOrCollectionTitle;
private ReferenceType referenceType; private ReferenceType referenceType;
private FormatStandard formatStandard; private FormatStandard formatStandard;
private boolean deleted;
@JsonCreator @JsonCreator
public ReferenceDto( public ReferenceDto(
@JsonProperty("id") Integer id,
@JsonProperty("authors") String authors, @JsonProperty("authors") String authors,
@JsonProperty("publicationTitle") String publicationTitle, @JsonProperty("publicationTitle") String publicationTitle,
@JsonProperty("publicationYear") Integer publicationYear, @JsonProperty("publicationYear") Integer publicationYear,
@ -52,7 +55,9 @@ public class ReferenceDto {
@JsonProperty("pages") String pages, @JsonProperty("pages") String pages,
@JsonProperty("journalOrCollectionTitle") String journalOrCollectionTitle, @JsonProperty("journalOrCollectionTitle") String journalOrCollectionTitle,
@JsonProperty("referenceType") ReferenceType referenceType, @JsonProperty("referenceType") ReferenceType referenceType,
@JsonProperty("formatStandard") FormatStandard formatStandard) { @JsonProperty("formatStandard") FormatStandard formatStandard,
@JsonProperty("isDeleted") boolean deleted) {
this.id = id;
this.authors = authors; this.authors = authors;
this.publicationTitle = publicationTitle; this.publicationTitle = publicationTitle;
this.publicationYear = publicationYear; this.publicationYear = publicationYear;
@ -61,6 +66,22 @@ public class ReferenceDto {
this.journalOrCollectionTitle = journalOrCollectionTitle; this.journalOrCollectionTitle = journalOrCollectionTitle;
this.referenceType = referenceType; this.referenceType = referenceType;
this.formatStandard = formatStandard; 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() { public String getAuthors() {
@ -126,4 +147,20 @@ public class ReferenceDto {
public void setFormatStandard(FormatStandard formatStandard) { public void setFormatStandard(FormatStandard formatStandard) {
this.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;
}
} }

View File

@ -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<Reference, Integer> {
void deleteById(Integer id);
@Query("SELECT DISTINCT r.authors FROM Reference r")
List<String> findDistinctAuthors();
@Query("SELECT DISTINCT r.publicationTitle FROM Reference r")
List<String> findDistinctPublicationTitles();
@Query("SELECT DISTINCT r.publisher FROM Reference r")
List<String> findDistinctPublishers();
@Query("SELECT DISTINCT r.journalOrCollectionTitle FROM Reference r where r.journalOrCollectionTitle <> ''")
List<String> findDistinctJournalOrCollectionTitles();
}

View File

@ -42,8 +42,9 @@ public class LatexService {
InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream()); InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream());
try (BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) { try (BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
while ((bufferedReader.readLine()) != null) { String line = bufferedReader.readLine();
// while (line != null) {
line = bufferedReader.readLine();
} }
} }

View File

@ -7,11 +7,14 @@ import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.deadline.service.DeadlineService; import ru.ulstu.deadline.service.DeadlineService;
import ru.ulstu.file.model.FileDataDto; import ru.ulstu.file.model.FileDataDto;
import ru.ulstu.file.service.FileService; import ru.ulstu.file.service.FileService;
import ru.ulstu.paper.model.AutoCompleteData;
import ru.ulstu.paper.model.Paper; import ru.ulstu.paper.model.Paper;
import ru.ulstu.paper.model.PaperDto; import ru.ulstu.paper.model.PaperDto;
import ru.ulstu.paper.model.PaperListDto; import ru.ulstu.paper.model.PaperListDto;
import ru.ulstu.paper.model.Reference;
import ru.ulstu.paper.model.ReferenceDto; import ru.ulstu.paper.model.ReferenceDto;
import ru.ulstu.paper.repository.PaperRepository; import ru.ulstu.paper.repository.PaperRepository;
import ru.ulstu.paper.repository.ReferenceRepository;
import ru.ulstu.timeline.service.EventService; import ru.ulstu.timeline.service.EventService;
import ru.ulstu.user.model.User; import ru.ulstu.user.model.User;
import ru.ulstu.user.service.UserService; 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; import static ru.ulstu.paper.model.ReferenceDto.ReferenceType.BOOK;
@Service @Service
@Transactional
public class PaperService { public class PaperService {
private final static int MAX_DISPLAY_SIZE = 40; private final static int MAX_DISPLAY_SIZE = 40;
private final static String PAPER_FORMATTED_TEMPLATE = "%s %s"; private final static String PAPER_FORMATTED_TEMPLATE = "%s %s";
@ -49,14 +53,17 @@ public class PaperService {
private final DeadlineService deadlineService; private final DeadlineService deadlineService;
private final FileService fileService; private final FileService fileService;
private final EventService eventService; private final EventService eventService;
private final ReferenceRepository referenceRepository;
public PaperService(PaperRepository paperRepository, public PaperService(PaperRepository paperRepository,
ReferenceRepository referenceRepository,
FileService fileService, FileService fileService,
PaperNotificationService paperNotificationService, PaperNotificationService paperNotificationService,
UserService userService, UserService userService,
DeadlineService deadlineService, DeadlineService deadlineService,
EventService eventService) { EventService eventService) {
this.paperRepository = paperRepository; this.paperRepository = paperRepository;
this.referenceRepository = referenceRepository;
this.fileService = fileService; this.fileService = fileService;
this.paperNotificationService = paperNotificationService; this.paperNotificationService = paperNotificationService;
this.userService = userService; this.userService = userService;
@ -117,6 +124,7 @@ public class PaperService {
paper.setTitle(paperDto.getTitle()); paper.setTitle(paperDto.getTitle());
paper.setUpdateDate(new Date()); paper.setUpdateDate(new Date());
paper.setDeadlines(deadlineService.saveOrCreate(paperDto.getDeadlines())); paper.setDeadlines(deadlineService.saveOrCreate(paperDto.getDeadlines()));
paper.setReferences(saveOrCreateReferences(paperDto.getReferences()));
paper.setFiles(fileService.saveOrCreate(paperDto.getFiles().stream() paper.setFiles(fileService.saveOrCreate(paperDto.getFiles().stream()
.filter(f -> !f.isDeleted()) .filter(f -> !f.isDeleted())
.collect(toList()))); .collect(toList())));
@ -127,6 +135,41 @@ public class PaperService {
return paper; return paper;
} }
public List<Reference> saveOrCreateReferences(List<ReferenceDto> 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 @Transactional
public Integer update(PaperDto paperDto) throws IOException { public Integer update(PaperDto paperDto) throws IOException {
Paper paper = paperRepository.findOne(paperDto.getId()); Paper paper = paperRepository.findOne(paperDto.getId());
@ -139,6 +182,11 @@ public class PaperService {
fileService.delete(file.getId()); fileService.delete(file.getId());
} }
paperRepository.save(copyFromDto(paper, paperDto)); 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); eventService.updatePaperDeadlines(paper);
paper.getAuthors().forEach(author -> { paper.getAuthors().forEach(author -> {
@ -168,6 +216,14 @@ public class PaperService {
return Arrays.asList(Paper.PaperType.values()); return Arrays.asList(Paper.PaperType.values());
} }
public List<ReferenceDto.FormatStandard> getFormatStandards() {
return Arrays.asList(ReferenceDto.FormatStandard.values());
}
public List<ReferenceDto.ReferenceType> getReferenceTypes() {
return Arrays.asList(ReferenceDto.ReferenceType.values());
}
@Transactional @Transactional
public Paper create(String title, User user, Date deadlineDate) { public Paper create(String title, User user, Date deadlineDate) {
Paper paper = new Paper(); Paper paper = new Paper();
@ -287,12 +343,23 @@ public class PaperService {
: getSpringerReference(referenceDto); : getSpringerReference(referenceDto);
} }
public String getFormattedReferences(PaperDto paperDto) {
return String.join("\r\n", paperDto.getReferences()
.stream()
.filter(r -> !r.getDeleted())
.map(r -> {
r.setFormatStandard(paperDto.getFormatStandard());
return getFormattedReference(r);
})
.collect(Collectors.toList()));
}
public String getGostReference(ReferenceDto referenceDto) { public String getGostReference(ReferenceDto referenceDto) {
return MessageFormat.format(referenceDto.getReferenceType() == BOOK ? "{0} {1} - {2}{3}. - {4}с." : "{0} {1}{5} {2}{3}. С. {4}.", return MessageFormat.format(referenceDto.getReferenceType() == BOOK ? "{0} {1} - {2}{3}. - {4}с." : "{0} {1}{5} {2}{3}. С. {4}.",
referenceDto.getAuthors(), referenceDto.getAuthors(),
referenceDto.getPublicationTitle(), referenceDto.getPublicationTitle(),
StringUtils.isEmpty(referenceDto.getPublisher()) ? "" : referenceDto.getPublisher() + ", ", StringUtils.isEmpty(referenceDto.getPublisher()) ? "" : referenceDto.getPublisher() + ", ",
referenceDto.getPublicationYear().toString(), referenceDto.getPublicationYear() != null ? referenceDto.getPublicationYear().toString() : "",
referenceDto.getPages(), referenceDto.getPages(),
StringUtils.isEmpty(referenceDto.getJournalOrCollectionTitle()) ? "." : " // " + referenceDto.getJournalOrCollectionTitle() + "."); StringUtils.isEmpty(referenceDto.getJournalOrCollectionTitle()) ? "." : " // " + referenceDto.getJournalOrCollectionTitle() + ".");
} }
@ -300,7 +367,7 @@ public class PaperService {
public String getSpringerReference(ReferenceDto referenceDto) { public String getSpringerReference(ReferenceDto referenceDto) {
return MessageFormat.format("{0} ({1}) {2}.{3} {4}pp {5}", return MessageFormat.format("{0} ({1}) {2}.{3} {4}pp {5}",
referenceDto.getAuthors(), referenceDto.getAuthors(),
referenceDto.getPublicationYear().toString(), referenceDto.getPublicationYear() != null ? referenceDto.getPublicationYear().toString() : "",
referenceDto.getPublicationTitle(), referenceDto.getPublicationTitle(),
referenceDto.getReferenceType() == ARTICLE ? " " + referenceDto.getJournalOrCollectionTitle() + "," : "", referenceDto.getReferenceType() == ARTICLE ? " " + referenceDto.getJournalOrCollectionTitle() + "," : "",
StringUtils.isEmpty(referenceDto.getPublisher()) ? "" : referenceDto.getPublisher() + ", ", StringUtils.isEmpty(referenceDto.getPublisher()) ? "" : referenceDto.getPublisher() + ", ",
@ -310,4 +377,13 @@ public class PaperService {
public List<Paper> findAllCompletedByType(Paper.PaperType type) { public List<Paper> findAllCompletedByType(Paper.PaperType type) {
return paperRepository.findByTypeAndStatus(type, Paper.PaperStatus.COMPLETED); 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;
}
} }

View File

@ -10,9 +10,12 @@ import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.grant.model.Grant;
import ru.ulstu.grant.model.GrantDto;
import ru.ulstu.project.model.Project; import ru.ulstu.project.model.Project;
import ru.ulstu.project.model.ProjectDto; import ru.ulstu.project.model.ProjectDto;
import ru.ulstu.project.service.ProjectService; import ru.ulstu.project.service.ProjectService;
import ru.ulstu.user.model.User;
import springfox.documentation.annotations.ApiIgnore; import springfox.documentation.annotations.ApiIgnore;
import javax.validation.Valid; import javax.validation.Valid;
@ -45,6 +48,8 @@ public class ProjectController {
@GetMapping("/project") @GetMapping("/project")
public void getProject(ModelMap modelMap, @RequestParam(value = "id") Integer id) { public void getProject(ModelMap modelMap, @RequestParam(value = "id") Integer id) {
if (id != null && id > 0) { if (id != null && id > 0) {
ProjectDto projectDto = projectService.findOneDto(id);
attachGrant(projectDto);
modelMap.put("projectDto", projectService.findOneDto(id)); modelMap.put("projectDto", projectService.findOneDto(id));
} else { } else {
modelMap.put("projectDto", new ProjectDto()); modelMap.put("projectDto", new ProjectDto());
@ -69,6 +74,12 @@ public class ProjectController {
return String.format("redirect:%s", "/projects/projects"); return String.format("redirect:%s", "/projects/projects");
} }
@PostMapping(value = "/project", params = "attachGrant")
public String attachGrant(ProjectDto projectDto) {
projectService.attachGrant(projectDto);
return "/projects/project";
}
@PostMapping(value = "/project", params = "addDeadline") @PostMapping(value = "/project", params = "addDeadline")
public String addDeadline(@Valid ProjectDto projectDto, Errors errors) { public String addDeadline(@Valid ProjectDto projectDto, Errors errors) {
filterEmptyDeadlines(projectDto); filterEmptyDeadlines(projectDto);
@ -79,12 +90,29 @@ public class ProjectController {
return "/projects/project"; 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}") @GetMapping("/delete/{project-id}")
public String delete(@PathVariable("project-id") Integer projectId) throws IOException { public String delete(@PathVariable("project-id") Integer projectId) throws IOException {
projectService.delete(projectId); projectService.delete(projectId);
return String.format("redirect:%s", "/projects/projects"); return String.format("redirect:%s", "/projects/projects");
} }
@ModelAttribute("allExecutors")
public List<User> getAllExecutors(ProjectDto projectDto) {
return projectService.getProjectExecutors(projectDto);
}
@ModelAttribute("allGrants")
public List<GrantDto> getAllGrants() {
return projectService.getAllGrants();
}
private void filterEmptyDeadlines(ProjectDto projectDto) { private void filterEmptyDeadlines(ProjectDto projectDto) {
projectDto.setDeadlines(projectDto.getDeadlines().stream() projectDto.setDeadlines(projectDto.getDeadlines().stream()
.filter(dto -> dto.getDate() != null || !isEmpty(dto.getDescription())) .filter(dto -> dto.getDate() != null || !isEmpty(dto.getDescription()))

View File

@ -1,30 +1,43 @@
package ru.ulstu.project.model; package ru.ulstu.project.model;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.validator.constraints.NotBlank; import org.hibernate.validator.constraints.NotBlank;
import ru.ulstu.core.model.BaseEntity; import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.core.model.EventSource;
import ru.ulstu.core.model.UserContainer;
import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.file.model.FileData; import ru.ulstu.file.model.FileData;
import ru.ulstu.grant.model.Grant; 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.Entity;
import javax.persistence.EnumType; import javax.persistence.EnumType;
import javax.persistence.Enumerated; import javax.persistence.Enumerated;
import javax.persistence.OneToMany;
import javax.persistence.CascadeType;
import javax.persistence.JoinColumn; import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne; import javax.persistence.ManyToOne;
import javax.persistence.OneToMany; import javax.persistence.FetchType;
import javax.persistence.ManyToMany;
import javax.persistence.JoinTable;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set;
@Entity @Entity
public class Project extends BaseEntity { public class Project extends BaseEntity implements UserContainer, EventSource {
public enum ProjectStatus { public enum ProjectStatus {
APPLICATION("Заявка"), TECHNICAL_TASK("Техническое задание"),
ON_COMPETITION("Отправлен на конкурс"), OPEN("Открыт"),
SUCCESSFUL_PASSAGE("Успешное прохождение"),
IN_WORK("В работе"), IN_WORK("В работе"),
COMPLETED("Завершен"), CERTIFICATE_ISSUED("Оформление свидетельства"),
CLOSED("Закрыт"),
FAILED("Провалены сроки"); FAILED("Провалены сроки");
private String statusName; private String statusName;
@ -42,7 +55,7 @@ public class Project extends BaseEntity {
private String title; private String title;
@Enumerated(value = EnumType.STRING) @Enumerated(value = EnumType.STRING)
private ProjectStatus status = ProjectStatus.APPLICATION; private ProjectStatus status = ProjectStatus.TECHNICAL_TASK;
@NotNull @NotNull
private String description; private String description;
@ -58,14 +71,39 @@ public class Project extends BaseEntity {
@NotNull @NotNull
private String repository; private String repository;
@ManyToOne @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "file_id") @JoinColumn(name = "project_id", unique = true)
private FileData application; @Fetch(FetchMode.SUBSELECT)
private List<FileData> files = new ArrayList<>();
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "project_id")
private List<Event> events = new ArrayList<>();
@ManyToMany(fetch = FetchType.LAZY)
private List<User> executors = new ArrayList<>();
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "project_grants",
joinColumns = {@JoinColumn(name = "project_id")},
inverseJoinColumns = {@JoinColumn(name = "grants_id")})
@Fetch(FetchMode.SUBSELECT)
private List<Grant> grants = new ArrayList<>();
public String getTitle() { public String getTitle() {
return title; return title;
} }
@Override
public List<User> getRecipients() {
return executors != null ? new ArrayList<>(executors) : Collections.emptyList();
}
@Override
public void addObjectToEvent(Event event) {
event.setProject(this);
}
public void setTitle(String title) { public void setTitle(String title) {
this.title = title; this.title = title;
} }
@ -110,11 +148,41 @@ public class Project extends BaseEntity {
this.deadlines = deadlines; this.deadlines = deadlines;
} }
public FileData getApplication() { public List<FileData> getFiles() {
return application; return files;
} }
public void setApplication(FileData application) { public void setFiles(List<FileData> files) {
this.application = application; this.files = files;
}
public List<Event> getEvents() {
return events;
}
public void setEvents(List<Event> events) {
this.events = events;
}
public List<User> getExecutors() {
return executors;
}
public void setExecutors(List<User> executors) {
this.executors = executors;
}
@Override
public Set<User> getUsers() {
Set<User> users = new HashSet<User>(getExecutors());
return users;
}
public List<Grant> getGrants() {
return grants;
}
public void setGrants(List<Grant> grants) {
this.grants = grants;
} }
} }

View File

@ -3,11 +3,20 @@ package ru.ulstu.project.model;
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.NotEmpty; import org.hibernate.validator.constraints.NotEmpty;
import org.thymeleaf.util.StringUtils;
import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.file.model.FileDataDto;
import ru.ulstu.grant.model.GrantDto; 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.ArrayList;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static ru.ulstu.core.util.StreamApiUtils.convert;
public class ProjectDto { public class ProjectDto {
private Integer id; private Integer id;
@ -19,7 +28,14 @@ public class ProjectDto {
private List<Deadline> deadlines = new ArrayList<>(); private List<Deadline> deadlines = new ArrayList<>();
private GrantDto grant; private GrantDto grant;
private String repository; private String repository;
private String applicationFileName; private List<FileDataDto> files = new ArrayList<>();
private List<Integer> removedDeadlineIds = new ArrayList<>();
private Set<Integer> executorIds;
private List<UserDto> executors;
private List<Integer> grantIds;
private List<GrantDto> grants;
private final static int MAX_EXECUTORS_LENGTH = 40;
public ProjectDto() { public ProjectDto() {
} }
@ -35,7 +51,12 @@ public class ProjectDto {
@JsonProperty("description") String description, @JsonProperty("description") String description,
@JsonProperty("grant") GrantDto grant, @JsonProperty("grant") GrantDto grant,
@JsonProperty("repository") String repository, @JsonProperty("repository") String repository,
@JsonProperty("deadlines") List<Deadline> deadlines) { @JsonProperty("files") List<FileDataDto> files,
@JsonProperty("deadlines") List<Deadline> deadlines,
@JsonProperty("executorIds") Set<Integer> executorIds,
@JsonProperty("executors") List<UserDto> executors,
@JsonProperty("grantIds") List<Integer> grantIds,
@JsonProperty("grants") List<GrantDto> grants) {
this.id = id; this.id = id;
this.title = title; this.title = title;
this.status = status; this.status = status;
@ -43,19 +64,28 @@ public class ProjectDto {
this.grant = grant; this.grant = grant;
this.repository = repository; this.repository = repository;
this.deadlines = deadlines; this.deadlines = deadlines;
this.applicationFileName = null; this.files = files;
this.executorIds = executorIds;
this.executors = executors;
this.grantIds = grantIds;
this.grants = grants;
} }
public ProjectDto(Project project) { public ProjectDto(Project project) {
Set<User> users = new HashSet<User>(project.getExecutors());
this.id = project.getId(); this.id = project.getId();
this.title = project.getTitle(); this.title = project.getTitle();
this.status = project.getStatus(); this.status = project.getStatus();
this.description = project.getDescription(); this.description = project.getDescription();
this.applicationFileName = project.getApplication() == null ? null : project.getApplication().getName(); this.files = convert(project.getFiles(), FileDataDto::new);
this.grant = project.getGrant() == null ? null : new GrantDto(project.getGrant()); this.grant = project.getGrant() == null ? null : new GrantDto(project.getGrant());
this.repository = project.getRepository(); this.repository = project.getRepository();
this.deadlines = project.getDeadlines(); this.deadlines = project.getDeadlines();
this.executorIds = convert(users, user -> user.getId());
this.executors = convert(project.getExecutors(), UserDto::new);
this.grantIds = convert(project.getGrants(), grant -> grant.getId());
this.grants = convert(project.getGrants(), GrantDto::new);
} }
public Integer getId() { public Integer getId() {
@ -114,11 +144,58 @@ public class ProjectDto {
this.deadlines = deadlines; this.deadlines = deadlines;
} }
public String getApplicationFileName() { public List<FileDataDto> getFiles() {
return applicationFileName; return files;
} }
public void setApplicationFileName(String applicationFileName) { public void setFiles(List<FileDataDto> files) {
this.applicationFileName = applicationFileName; this.files = files;
}
public List<Integer> getRemovedDeadlineIds() {
return removedDeadlineIds;
}
public void setRemovedDeadlineIds(List<Integer> removedDeadlineIds) {
this.removedDeadlineIds = removedDeadlineIds;
}
public Set<Integer> getExecutorIds() {
return executorIds;
}
public void setExecutorIds(Set<Integer> executorIds) {
this.executorIds = executorIds;
}
public List<UserDto> getExecutors() {
return executors;
}
public void setExecutors(List<UserDto> executors) {
this.executors = executors;
}
public String getExecutorsString() {
return StringUtils.abbreviate(executors
.stream()
.map(executor -> executor.getLastName())
.collect(Collectors.joining(", ")), MAX_EXECUTORS_LENGTH);
}
public List<Integer> getGrantIds() {
return grantIds;
}
public void setGrantIds(List<Integer> grantIds) {
this.grantIds = grantIds;
}
public List<GrantDto> getGrants() {
return grants;
}
public void setGrants(List<GrantDto> grants) {
this.grants = grants;
} }
} }

View File

@ -4,19 +4,26 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.util.StringUtils; import org.thymeleaf.util.StringUtils;
import ru.ulstu.deadline.service.DeadlineService; import ru.ulstu.deadline.service.DeadlineService;
import ru.ulstu.file.model.FileDataDto;
import ru.ulstu.file.service.FileService; import ru.ulstu.file.service.FileService;
import ru.ulstu.grant.model.GrantDto;
import ru.ulstu.grant.repository.GrantRepository; import ru.ulstu.grant.repository.GrantRepository;
import ru.ulstu.project.model.Project; import ru.ulstu.project.model.Project;
import ru.ulstu.project.model.ProjectDto; import ru.ulstu.project.model.ProjectDto;
import ru.ulstu.project.repository.ProjectRepository; import ru.ulstu.project.repository.ProjectRepository;
import ru.ulstu.timeline.service.EventService;
import ru.ulstu.user.model.User;
import ru.ulstu.user.service.UserService;
import java.io.IOException; import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections;
import java.util.List; import java.util.List;
import static java.util.stream.Collectors.toList;
import static org.springframework.util.ObjectUtils.isEmpty; import static org.springframework.util.ObjectUtils.isEmpty;
import static ru.ulstu.core.util.StreamApiUtils.convert; 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 @Service
public class ProjectService { public class ProjectService {
@ -26,15 +33,21 @@ public class ProjectService {
private final DeadlineService deadlineService; private final DeadlineService deadlineService;
private final GrantRepository grantRepository; private final GrantRepository grantRepository;
private final FileService fileService; private final FileService fileService;
private final EventService eventService;
private final UserService userService;
public ProjectService(ProjectRepository projectRepository, public ProjectService(ProjectRepository projectRepository,
DeadlineService deadlineService, DeadlineService deadlineService,
GrantRepository grantRepository, GrantRepository grantRepository,
FileService fileService) { FileService fileService,
EventService eventService,
UserService userService) {
this.projectRepository = projectRepository; this.projectRepository = projectRepository;
this.deadlineService = deadlineService; this.deadlineService = deadlineService;
this.grantRepository = grantRepository; this.grantRepository = grantRepository;
this.fileService = fileService; this.fileService = fileService;
this.eventService = eventService;
this.userService = userService;
} }
public List<Project> findAll() { public List<Project> findAll() {
@ -59,39 +72,48 @@ public class ProjectService {
public Project create(ProjectDto projectDto) throws IOException { public Project create(ProjectDto projectDto) throws IOException {
Project newProject = copyFromDto(new Project(), projectDto); Project newProject = copyFromDto(new Project(), projectDto);
newProject = projectRepository.save(newProject); newProject = projectRepository.save(newProject);
eventService.createFromObject(newProject, Collections.emptyList(), false, "проекта");
return newProject; return newProject;
} }
@Transactional @Transactional
public Project update(ProjectDto projectDto) throws IOException { public Project update(ProjectDto projectDto) throws IOException {
Project project = projectRepository.findOne(projectDto.getId()); Project project = projectRepository.findOne(projectDto.getId());
if (projectDto.getApplicationFileName() != null && project.getApplication() != null) {
fileService.deleteFile(project.getApplication());
}
projectRepository.save(copyFromDto(project, projectDto)); projectRepository.save(copyFromDto(project, projectDto));
eventService.updateProjectDeadlines(project);
for (FileDataDto file : projectDto.getFiles().stream()
.filter(f -> f.isDeleted() && f.getId() != null)
.collect(toList())) {
fileService.delete(file.getId());
}
return project; return project;
} }
@Transactional @Transactional
public void delete(Integer projectId) throws IOException { public boolean delete(Integer projectId) throws IOException {
if (projectRepository.exists(projectId)) {
Project project = projectRepository.findOne(projectId); Project project = projectRepository.findOne(projectId);
if (project.getApplication() != null) {
fileService.deleteFile(project.getApplication());
}
projectRepository.delete(project); projectRepository.delete(project);
return true;
}
return false;
} }
private Project copyFromDto(Project project, ProjectDto projectDto) throws IOException { private Project copyFromDto(Project project, ProjectDto projectDto) throws IOException {
project.setDescription(projectDto.getDescription()); 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()); project.setTitle(projectDto.getTitle());
if (projectDto.getGrant() != null && projectDto.getGrant().getId() != null) { if (projectDto.getGrant() != null && projectDto.getGrant().getId() != null) {
project.setGrant(grantRepository.findOne(projectDto.getGrant().getId())); project.setGrant(grantRepository.findOne(projectDto.getGrant().getId()));
} }
project.setRepository(projectDto.getRepository()); project.setRepository(projectDto.getRepository());
project.setDeadlines(deadlineService.saveOrCreate(projectDto.getDeadlines())); project.setDeadlines(deadlineService.saveOrCreate(projectDto.getDeadlines()));
if (projectDto.getApplicationFileName() != null) { project.setFiles(fileService.saveOrCreate(projectDto.getFiles().stream()
project.setApplication(fileService.createFileFromTmp(projectDto.getApplicationFileName())); .filter(f -> !f.isDeleted())
.collect(toList())));
project.getGrants().clear();
if (projectDto.getGrantIds() != null && !projectDto.getGrantIds().isEmpty()) {
projectDto.getGrantIds().forEach(grantIds -> project.getGrants().add(grantRepository.findGrantById(grantIds)));
} }
return project; return project;
} }
@ -104,8 +126,39 @@ public class ProjectService {
} }
} }
public ProjectDto removeDeadline(ProjectDto projectDto, Integer deadlineId) {
if (deadlineId != null) {
projectDto.getRemovedDeadlineIds().add(deadlineId);
}
projectDto.getDeadlines().remove((int) deadlineId);
return projectDto;
}
public Project findById(Integer id) { public Project findById(Integer id) {
return projectRepository.findOne(id); return projectRepository.findOne(id);
} }
public List<User> getProjectExecutors(ProjectDto projectDto) {
List<User> users = userService.findAll();
return users;
}
public List<GrantDto> getAllGrants() {
List<GrantDto> grants = convert(grantRepository.findAll(), GrantDto::new);
return grants;
}
public List<GrantDto> getProjectGrants(List<Integer> grantIds) {
return convert(grantRepository.findAll(grantIds), GrantDto::new);
}
public void attachGrant(ProjectDto projectDto) {
if (!projectDto.getGrantIds().isEmpty()) {
projectDto.getGrants().clear();
projectDto.setGrants(getProjectGrants(projectDto.getGrantIds()));
} else {
projectDto.getGrants().clear();
}
}
} }

View File

@ -4,8 +4,17 @@ import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode; import org.hibernate.annotations.FetchMode;
import org.hibernate.validator.constraints.NotBlank; import org.hibernate.validator.constraints.NotBlank;
import ru.ulstu.core.model.BaseEntity; import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.core.model.EventSource;
import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.deadline.service.DeadlineService;
import ru.ulstu.students.repository.SchedulerRepository;
import ru.ulstu.students.repository.TaskRepository;
import ru.ulstu.tags.model.Tag; import ru.ulstu.tags.model.Tag;
import ru.ulstu.tags.service.TagService;
import ru.ulstu.timeline.model.Event;
import ru.ulstu.timeline.service.EventService;
import ru.ulstu.user.model.User;
import ru.ulstu.user.service.UserService;
import javax.persistence.CascadeType; import javax.persistence.CascadeType;
import javax.persistence.Column; import javax.persistence.Column;
@ -20,12 +29,14 @@ import javax.persistence.OneToMany;
import javax.persistence.OrderBy; import javax.persistence.OrderBy;
import javax.persistence.Temporal; import javax.persistence.Temporal;
import javax.persistence.TemporalType; import javax.persistence.TemporalType;
import javax.persistence.Transient;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
@Entity @Entity
public class Task extends BaseEntity { public class Task extends BaseEntity implements EventSource {
public enum TaskStatus { public enum TaskStatus {
IN_WORK("В работе"), IN_WORK("В работе"),
@ -49,6 +60,17 @@ public class Task extends BaseEntity {
private String description; private String description;
@Transient
private UserService userService;
public Task() {
}
public Task(UserService userService) {
this.userService = userService;
}
@Enumerated(value = EnumType.STRING) @Enumerated(value = EnumType.STRING)
private TaskStatus status = TaskStatus.IN_WORK; private TaskStatus status = TaskStatus.IN_WORK;
@ -77,6 +99,16 @@ public class Task extends BaseEntity {
return title; return title;
} }
@Override
public List<User> getRecipients() {
return Collections.emptyList();
}
@Override
public void addObjectToEvent(Event event) {
event.setTask(this);
}
public void setTitle(String title) { public void setTitle(String title) {
this.title = title; this.title = title;
} }

View File

@ -10,6 +10,7 @@ import ru.ulstu.tags.model.Tag;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -135,6 +136,29 @@ public class TaskDto {
this.tags = tags; 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() { public String getTagsString() {
return StringUtils.abbreviate(tags return StringUtils.abbreviate(tags
.stream() .stream()

View File

@ -18,14 +18,15 @@ import ru.ulstu.tags.service.TagService;
import ru.ulstu.timeline.service.EventService; import ru.ulstu.timeline.service.EventService;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar; import java.util.Calendar;
import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.Map;
import java.util.TreeMap; import java.util.TreeMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static org.springframework.util.ObjectUtils.isEmpty; import static org.springframework.util.ObjectUtils.isEmpty;
@ -83,7 +84,7 @@ public class TaskService {
public Integer create(TaskDto taskDto) throws IOException { public Integer create(TaskDto taskDto) throws IOException {
Task newTask = copyFromDto(new Task(), taskDto); Task newTask = copyFromDto(new Task(), taskDto);
newTask = taskRepository.save(newTask); newTask = taskRepository.save(newTask);
eventService.createFromTask(newTask); eventService.createFromObject(newTask, Collections.emptyList(), true, "задачи");
return newTask.getId(); return newTask.getId();
} }
@ -108,7 +109,7 @@ public class TaskService {
} }
@Transactional @Transactional
public void delete(Integer taskId) throws IOException { public boolean delete(Integer taskId) throws IOException {
if (taskRepository.exists(taskId)) { if (taskRepository.exists(taskId)) {
Task scheduleTask = taskRepository.findOne(taskId); Task scheduleTask = taskRepository.findOne(taskId);
Scheduler sch = schedulerRepository.findOneByTask(scheduleTask); Scheduler sch = schedulerRepository.findOneByTask(scheduleTask);
@ -116,7 +117,9 @@ public class TaskService {
schedulerRepository.delete(sch.getId()); schedulerRepository.delete(sch.getId());
} }
taskRepository.delete(taskId); taskRepository.delete(taskId);
return true;
} }
return false;
} }
@ -128,14 +131,14 @@ public class TaskService {
} }
} }
public void copyMainPart(Task newTask, Task task) { private void copyMainPart(Task newTask, Task task) {
newTask.setTitle(task.getTitle()); newTask.setTitle(task.getTitle());
newTask.setTags(tagService.saveOrCreate(task.getTags())); newTask.setTags(tagService.saveOrCreate(task.getTags()));
newTask.setCreateDate(new Date()); newTask.setCreateDate(new Date());
newTask.setStatus(Task.TaskStatus.LOADED_FROM_KIAS); newTask.setStatus(Task.TaskStatus.LOADED_FROM_KIAS);
} }
public Task copyTaskWithNewDates(Task task) { private Task copyTaskWithNewDates(Task task) {
Task newTask = new Task(); Task newTask = new Task();
copyMainPart(newTask, task); copyMainPart(newTask, task);
Calendar cal1 = DateUtils.getCalendar(newTask.getCreateDate()); Calendar cal1 = DateUtils.getCalendar(newTask.getCreateDate());
@ -157,7 +160,7 @@ public class TaskService {
}).collect(Collectors.toList()); }).collect(Collectors.toList());
} }
public Task copyTaskWithNewYear(Task task) { private Task copyTaskWithNewYear(Task task) {
Task newTask = new Task(); Task newTask = new Task();
copyMainPart(newTask, task); copyMainPart(newTask, task);
newTask.setDeadlines(newYearDeadlines(task.getDeadlines())); newTask.setDeadlines(newYearDeadlines(task.getDeadlines()));
@ -184,7 +187,7 @@ public class TaskService {
} }
@Transactional @Transactional
public void generateYearTasks() { public List<Task> generateYearTasks() {
Set<Tag> tags = checkRepeatingTags(false); Set<Tag> tags = checkRepeatingTags(false);
List<Task> tasks = new ArrayList<>(); List<Task> tasks = new ArrayList<>();
tags.forEach(tag -> { tags.forEach(tag -> {
@ -200,7 +203,9 @@ public class TaskService {
Task newTask = copyTaskWithNewYear(task); Task newTask = copyTaskWithNewYear(task);
taskRepository.save(newTask); taskRepository.save(newTask);
}); });
return tasks;
} }
return null;
} }
@ -245,8 +250,9 @@ public class TaskService {
} }
@Transactional @Transactional
public void createPeriodTask(Scheduler scheduler) { public Task createPeriodTask(Scheduler scheduler) {
Task newTask = copyTaskWithNewDates(scheduler.getTask()); Task newTask = copyTaskWithNewDates(scheduler.getTask());
taskRepository.save(newTask); taskRepository.save(newTask);
return newTask;
} }
} }

View File

@ -5,6 +5,7 @@ import ru.ulstu.conference.model.Conference;
import ru.ulstu.core.model.BaseEntity; import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.grant.model.Grant; import ru.ulstu.grant.model.Grant;
import ru.ulstu.paper.model.Paper; import ru.ulstu.paper.model.Paper;
import ru.ulstu.project.model.Project;
import ru.ulstu.students.model.Task; import ru.ulstu.students.model.Task;
import ru.ulstu.user.model.User; import ru.ulstu.user.model.User;
@ -65,8 +66,8 @@ public class Event extends BaseEntity {
private String description; private String description;
@ManyToMany(fetch = FetchType.EAGER) @ManyToMany(fetch = FetchType.LAZY)
private List<User> recipients = new ArrayList<User>(); private List<User> recipients = new ArrayList<>();
@ManyToOne @ManyToOne
@JoinColumn(name = "child_id") @JoinColumn(name = "child_id")
@ -88,6 +89,10 @@ public class Event extends BaseEntity {
@JoinColumn(name = "grant_id") @JoinColumn(name = "grant_id")
private Grant grant; private Grant grant;
@ManyToOne
@JoinColumn(name = "project_id")
private Project project;
@ManyToOne @ManyToOne
@JoinColumn(name = "task_id") @JoinColumn(name = "task_id")
private Task task; private Task task;
@ -196,6 +201,14 @@ public class Event extends BaseEntity {
this.grant = grant; this.grant = grant;
} }
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
public Task getTask() { public Task getTask() {
return task; return task;
} }

View File

@ -6,6 +6,7 @@ import org.hibernate.validator.constraints.NotBlank;
import ru.ulstu.conference.model.ConferenceDto; import ru.ulstu.conference.model.ConferenceDto;
import ru.ulstu.grant.model.GrantDto; import ru.ulstu.grant.model.GrantDto;
import ru.ulstu.paper.model.PaperDto; import ru.ulstu.paper.model.PaperDto;
import ru.ulstu.project.model.ProjectDto;
import ru.ulstu.students.model.TaskDto; import ru.ulstu.students.model.TaskDto;
import ru.ulstu.user.model.UserDto; import ru.ulstu.user.model.UserDto;
@ -30,6 +31,7 @@ public class EventDto {
private PaperDto paperDto; private PaperDto paperDto;
private ConferenceDto conferenceDto; private ConferenceDto conferenceDto;
private GrantDto grantDto; private GrantDto grantDto;
private ProjectDto projectDto;
private TaskDto taskDto; private TaskDto taskDto;
@JsonCreator @JsonCreator
@ -45,6 +47,7 @@ public class EventDto {
@JsonProperty("recipients") List<UserDto> recipients, @JsonProperty("recipients") List<UserDto> recipients,
@JsonProperty("conferenceDto") ConferenceDto conferenceDto, @JsonProperty("conferenceDto") ConferenceDto conferenceDto,
@JsonProperty("grantDto") GrantDto grantDto, @JsonProperty("grantDto") GrantDto grantDto,
@JsonProperty("projectDto") ProjectDto projectDto,
@JsonProperty("taskDto") TaskDto taskDto) { @JsonProperty("taskDto") TaskDto taskDto) {
this.id = id; this.id = id;
this.title = title; this.title = title;
@ -58,6 +61,7 @@ public class EventDto {
this.paperDto = paperDto; this.paperDto = paperDto;
this.conferenceDto = conferenceDto; this.conferenceDto = conferenceDto;
this.grantDto = grantDto; this.grantDto = grantDto;
this.projectDto = projectDto;
this.taskDto = taskDto; this.taskDto = taskDto;
} }
@ -80,6 +84,9 @@ public class EventDto {
if (grantDto != null) { if (grantDto != null) {
this.grantDto = new GrantDto(event.getGrant()); this.grantDto = new GrantDto(event.getGrant());
} }
if (projectDto != null) {
this.projectDto = new ProjectDto(event.getProject());
}
if (taskDto != null) { if (taskDto != null) {
this.taskDto = new TaskDto(event.getTask()); this.taskDto = new TaskDto(event.getTask());
} }
@ -145,6 +152,14 @@ public class EventDto {
this.grantDto = grantDto; this.grantDto = grantDto;
} }
public ProjectDto getProjectDto() {
return projectDto;
}
public void setProjectDto(ProjectDto projectDto) {
this.projectDto = projectDto;
}
public TaskDto getTaskDto() { public TaskDto getTaskDto() {
return taskDto; return taskDto;
} }

View File

@ -5,6 +5,7 @@ import org.springframework.data.jpa.repository.Query;
import ru.ulstu.conference.model.Conference; import ru.ulstu.conference.model.Conference;
import ru.ulstu.grant.model.Grant; import ru.ulstu.grant.model.Grant;
import ru.ulstu.paper.model.Paper; import ru.ulstu.paper.model.Paper;
import ru.ulstu.project.model.Project;
import ru.ulstu.students.model.Task; import ru.ulstu.students.model.Task;
import ru.ulstu.timeline.model.Event; import ru.ulstu.timeline.model.Event;
@ -23,5 +24,7 @@ public interface EventRepository extends JpaRepository<Event, Integer> {
List<Event> findAllByGrant(Grant grant); List<Event> findAllByGrant(Grant grant);
List<Event> findAllByProject(Project project);
List<Event> findAllByTask(Task task); List<Event> findAllByTask(Task task);
} }

View File

@ -5,9 +5,11 @@ import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import ru.ulstu.conference.model.Conference; import ru.ulstu.conference.model.Conference;
import ru.ulstu.core.model.EventSource;
import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.grant.model.Grant; import ru.ulstu.grant.model.Grant;
import ru.ulstu.paper.model.Paper; import ru.ulstu.paper.model.Paper;
import ru.ulstu.project.model.Project;
import ru.ulstu.students.model.Task; import ru.ulstu.students.model.Task;
import ru.ulstu.timeline.model.Event; import ru.ulstu.timeline.model.Event;
import ru.ulstu.timeline.model.EventDto; import ru.ulstu.timeline.model.EventDto;
@ -17,6 +19,7 @@ import ru.ulstu.user.model.UserDto;
import ru.ulstu.user.service.UserService; import ru.ulstu.user.service.UserService;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -103,33 +106,39 @@ public class EventService {
} }
public void createFromPaper(Paper newPaper) { public void createFromPaper(Paper newPaper) {
createFromObject(newPaper, Collections.emptyList(), false, "статьи");
}
public void createFromObject(EventSource eventSource, List<Event> events, Boolean addCurrentUser, String suffix) {
List<Timeline> timelines = timelineService.findAll(); List<Timeline> timelines = timelineService.findAll();
Timeline timeline = timelines.isEmpty() ? new Timeline() : timelines.get(0); Timeline timeline = timelines.isEmpty() ? new Timeline() : timelines.get(0);
for (Deadline deadline : newPaper.getDeadlines() timeline.getEvents().removeAll(events);
for (Deadline deadline : eventSource.getDeadlines()
.stream() .stream()
.filter(d -> d.getDate().after(new Date()) || DateUtils.isSameDay(d.getDate(), new Date())) .filter(d -> d.getDate().after(new Date()) || DateUtils.isSameDay(d.getDate(), new Date()))
.collect(Collectors.toList())) { .collect(Collectors.toList())) {
Event newEvent = new Event(); Event newEvent = new Event();
newEvent.setTitle("Дедлайн статьи"); newEvent.setTitle("Дедлайн " + suffix);
newEvent.setStatus(Event.EventStatus.NEW); newEvent.setStatus(Event.EventStatus.NEW);
newEvent.setExecuteDate(deadline.getDate()); newEvent.setExecuteDate(deadline.getDate());
newEvent.setCreateDate(new Date()); newEvent.setCreateDate(new Date());
newEvent.setUpdateDate(new Date()); newEvent.setUpdateDate(new Date());
newEvent.setDescription("Дедлайн '" + deadline.getDescription() + "' cтатьи '" + newPaper.getTitle() + "'"); newEvent.setDescription("Дедлайн '" + deadline.getDescription() + "' " + suffix + " '"
newEvent.setRecipients(new ArrayList(newPaper.getAuthors())); + eventSource.getTitle() + "'");
newEvent.setPaper(newPaper); if (addCurrentUser) {
eventRepository.save(newEvent); newEvent.getRecipients().add(userService.getCurrentUser());
}
timeline.getEvents().add(newEvent); newEvent.setRecipients(eventSource.getRecipients());
eventSource.addObjectToEvent(newEvent);
timeline.getEvents().add(eventRepository.save(newEvent));
}
timelineService.save(timeline); timelineService.save(timeline);
} }
}
public void updatePaperDeadlines(Paper paper) { public void updatePaperDeadlines(Paper paper) {
eventRepository.delete(eventRepository.findAllByPaper(paper)); List<Event> foundEvents = eventRepository.findAllByPaper(paper);
eventRepository.delete(foundEvents);
createFromPaper(paper); createFromObject(paper, foundEvents, false, "статьи");
} }
public List<Event> findByCurrentDate() { public List<Event> findByCurrentDate() {
@ -144,65 +153,19 @@ public class EventService {
return convert(findAllFuture(), EventDto::new); return convert(findAllFuture(), EventDto::new);
} }
public void createFromConference(Conference newConference) {
List<Timeline> timelines = timelineService.findAll();
Timeline timeline = timelines.isEmpty() ? new Timeline() : timelines.get(0);
for (Deadline deadline : newConference.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() + "' конференции '" + newConference.getTitle() + "'");
newConference.getUsers().forEach(conferenceUser -> newEvent.getRecipients().add(conferenceUser.getUser()));
newEvent.setConference(newConference);
save(newEvent);
timeline.getEvents().add(newEvent);
timelineService.save(timeline);
}
}
public void updateConferenceDeadlines(Conference conference) { public void updateConferenceDeadlines(Conference conference) {
eventRepository.delete(eventRepository.findAllByConference(conference)); eventRepository.delete(eventRepository.findAllByConference(conference));
createFromConference(conference); createFromObject(conference, Collections.emptyList(), false, "конференции");
}
public void createFromGrant(Grant newGrant) {
List<Timeline> timelines = timelineService.findAll();
Timeline timeline = timelines.isEmpty() ? new Timeline() : timelines.get(0);
for (Deadline deadline : newGrant.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() + "' гранта '" + newGrant.getTitle() + "'");
if (newGrant.getAuthors() != null) {
newEvent.setRecipients(new ArrayList(newGrant.getAuthors()));
}
newEvent.getRecipients().add(newGrant.getLeader());
newEvent.setGrant(newGrant);
eventRepository.save(newEvent);
timeline.getEvents().add(newEvent);
timelineService.save(timeline);
}
} }
public void updateGrantDeadlines(Grant grant) { public void updateGrantDeadlines(Grant grant) {
eventRepository.delete(eventRepository.findAllByGrant(grant)); eventRepository.delete(eventRepository.findAllByGrant(grant));
createFromGrant(grant); createFromObject(grant, Collections.emptyList(), false, "гранта");
}
public void updateProjectDeadlines(Project project) {
eventRepository.delete(eventRepository.findAllByProject(project));
createFromObject(project, Collections.emptyList(), false, "проекта");
} }
public void removeConferencesEvent(Conference conference) { public void removeConferencesEvent(Conference conference) {
@ -210,32 +173,8 @@ public class EventService {
eventList.forEach(event -> eventRepository.delete(event.getId())); eventList.forEach(event -> eventRepository.delete(event.getId()));
} }
public void createFromTask(Task newTask) {
List<Timeline> 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) { public void updateTaskDeadlines(Task task) {
eventRepository.delete(eventRepository.findAllByTask(task)); eventRepository.delete(eventRepository.findAllByTask(task));
createFromTask(task); createFromObject(task, Collections.emptyList(), true, "задачи");
} }
} }

View File

@ -148,16 +148,15 @@ public class UserController extends OdinController<UserListDto, UserDto> {
} }
@PostMapping(PASSWORD_RESET_REQUEST_URL) @PostMapping(PASSWORD_RESET_REQUEST_URL)
public Response<Boolean> requestPasswordReset(@RequestParam("email") String email) { public void requestPasswordReset(@RequestParam("email") String email) {
log.debug("REST: UserController.requestPasswordReset( {} )", email); log.debug("REST: UserController.requestPasswordReset( {} )", email);
return new Response<>(userService.requestUserPasswordReset(email)); userService.requestUserPasswordReset(email);
} }
@PostMapping(PASSWORD_RESET_URL) @PostMapping(PASSWORD_RESET_URL)
public Response<Boolean> finishPasswordReset(@RequestParam("key") String key, public Response<Boolean> finishPasswordReset(@RequestBody UserResetPasswordDto userResetPasswordDto) {
@RequestBody UserResetPasswordDto userResetPasswordDto) { log.debug("REST: UserController.requestPasswordReset( {} )", userResetPasswordDto.getResetKey());
log.debug("REST: UserController.requestPasswordReset( {} )", key); return new Response<>(userService.completeUserPasswordReset(userResetPasswordDto));
return new Response<>(userService.completeUserPasswordReset(key, userResetPasswordDto));
} }
@PostMapping("/changePassword") @PostMapping("/changePassword")

View File

@ -48,4 +48,9 @@ public class UserMvcController extends OdinController<UserListDto, UserDto> {
User user = userSessionService.getUserBySessionId(sessionId); User user = userSessionService.getUserBySessionId(sessionId);
modelMap.addAttribute("userDto", userService.updateUserInformation(user, userDto)); modelMap.addAttribute("userDto", userService.updateUserInformation(user, userDto));
} }
@GetMapping("/dashboard")
public void getUsersDashboard(ModelMap modelMap) {
modelMap.addAllAttributes(userService.getUsersInfo());
}
} }

View File

@ -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;
}
}

View File

@ -14,6 +14,10 @@ public class UserResetPasswordDto {
@Size(min = Constants.MIN_PASSWORD_LENGTH, max = 50) @Size(min = Constants.MIN_PASSWORD_LENGTH, max = 50)
private String passwordConfirm; private String passwordConfirm;
@NotEmpty
@Size(min = Constants.RESET_KEY_LENGTH)
private String resetKey;
public String getPassword() { public String getPassword() {
return password; return password;
} }
@ -25,4 +29,8 @@ public class UserResetPasswordDto {
public boolean isPasswordsValid() { public boolean isPasswordsValid() {
return Objects.equals(password, passwordConfirm); return Objects.equals(password, passwordConfirm);
} }
public String getResetKey() {
return resetKey;
}
} }

View File

@ -1,6 +1,7 @@
package ru.ulstu.user.repository; package ru.ulstu.user.repository;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import ru.ulstu.user.model.User;
import ru.ulstu.user.model.UserSession; import ru.ulstu.user.model.UserSession;
import java.util.Date; import java.util.Date;
@ -10,4 +11,6 @@ public interface UserSessionRepository extends JpaRepository<UserSession, Intege
UserSession findOneBySessionId(String sessionId); UserSession findOneBySessionId(String sessionId);
List<UserSession> findAllByLogoutTimeIsNullAndLoginTimeBefore(Date date); List<UserSession> findAllByLogoutTimeIsNullAndLoginTimeBefore(Date date);
List<UserSession> findAllByUserAndLogoutTimeIsNullAndLoginTimeBefore(User user, Date date);
} }

View File

@ -1,5 +1,6 @@
package ru.ulstu.user.service; package ru.ulstu.user.service;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.mail.MailProperties; import org.springframework.boot.autoconfigure.mail.MailProperties;
@ -21,11 +22,9 @@ import java.util.Map;
@Service @Service
public class MailService { public class MailService {
private final Logger log = LoggerFactory.getLogger(MailService.class);
private static final String USER = "user"; private static final String USER = "user";
private static final String BASE_URL = "baseUrl"; private static final String BASE_URL = "baseUrl";
private final Logger log = LoggerFactory.getLogger(MailService.class);
private final JavaMailSender javaMailSender; private final JavaMailSender javaMailSender;
private final SpringTemplateEngine templateEngine; private final SpringTemplateEngine templateEngine;
private final MailProperties mailProperties; private final MailProperties mailProperties;
@ -48,10 +47,18 @@ public class MailService {
message.setFrom(mailProperties.getUsername()); message.setFrom(mailProperties.getUsername());
message.setSubject(subject); message.setSubject(subject);
message.setText(content, true); message.setText(content, true);
modifyForDebug(message, subject);
javaMailSender.send(mimeMessage); javaMailSender.send(mimeMessage);
log.debug("Sent email to User '{}'", to); 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);
}
}
@Async @Async
public void sendEmailFromTemplate(User user, String templateName, String subject) { public void sendEmailFromTemplate(User user, String templateName, String subject) {
Context context = new Context(); Context context = new Context();
@ -106,8 +113,7 @@ public class MailService {
sendEmailFromTemplate(user, "activationEmail", Constants.MAIL_ACTIVATE); sendEmailFromTemplate(user, "activationEmail", Constants.MAIL_ACTIVATE);
} }
@Async public void sendPasswordResetMail(User user) throws MessagingException, MailException {
public void sendPasswordResetMail(User user) {
sendEmailFromTemplate(user, "passwordResetEmail", Constants.MAIL_RESET); sendEmailFromTemplate(user, "passwordResetEmail", Constants.MAIL_RESET);
} }
@ -118,6 +124,5 @@ public class MailService {
@Async @Async
public void sendChangePasswordMail(User user) { public void sendChangePasswordMail(User user) {
sendEmailFromTemplate(user, "passwordChangeEmail", Constants.MAIL_CHANGE_PASSWORD); sendEmailFromTemplate(user, "passwordChangeEmail", Constants.MAIL_CHANGE_PASSWORD);
} }
} }

View File

@ -3,6 +3,7 @@ package ru.ulstu.user.service;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
import org.springframework.mail.MailException; import org.springframework.mail.MailException;
@ -13,6 +14,7 @@ import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import ru.ulstu.conference.service.ConferenceService;
import ru.ulstu.configuration.ApplicationProperties; import ru.ulstu.configuration.ApplicationProperties;
import ru.ulstu.core.error.EntityIdIsNullException; import ru.ulstu.core.error.EntityIdIsNullException;
import ru.ulstu.core.jpa.OffsetablePageRequest; import ru.ulstu.core.jpa.OffsetablePageRequest;
@ -30,6 +32,7 @@ import ru.ulstu.user.error.UserResetKeyError;
import ru.ulstu.user.error.UserSendingMailException; import ru.ulstu.user.error.UserSendingMailException;
import ru.ulstu.user.model.User; import ru.ulstu.user.model.User;
import ru.ulstu.user.model.UserDto; import ru.ulstu.user.model.UserDto;
import ru.ulstu.user.model.UserInfoNow;
import ru.ulstu.user.model.UserListDto; import ru.ulstu.user.model.UserListDto;
import ru.ulstu.user.model.UserResetPasswordDto; import ru.ulstu.user.model.UserResetPasswordDto;
import ru.ulstu.user.model.UserRole; import ru.ulstu.user.model.UserRole;
@ -38,8 +41,13 @@ import ru.ulstu.user.model.UserRoleDto;
import ru.ulstu.user.repository.UserRepository; import ru.ulstu.user.repository.UserRepository;
import ru.ulstu.user.repository.UserRoleRepository; import ru.ulstu.user.repository.UserRoleRepository;
import ru.ulstu.user.util.UserUtils; 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 javax.mail.MessagingException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.Date; import java.util.Date;
@ -62,19 +70,27 @@ public class UserService implements UserDetailsService {
private final UserMapper userMapper; private final UserMapper userMapper;
private final MailService mailService; private final MailService mailService;
private final ApplicationProperties applicationProperties; private final ApplicationProperties applicationProperties;
private final TimetableService timetableService;
private final ConferenceService conferenceService;
private final UserSessionService userSessionService;
public UserService(UserRepository userRepository, public UserService(UserRepository userRepository,
PasswordEncoder passwordEncoder, PasswordEncoder passwordEncoder,
UserRoleRepository userRoleRepository, UserRoleRepository userRoleRepository,
UserMapper userMapper, UserMapper userMapper,
MailService mailService, MailService mailService,
ApplicationProperties applicationProperties) { ApplicationProperties applicationProperties,
@Lazy ConferenceService conferenceRepository,
@Lazy UserSessionService userSessionService) throws ParseException {
this.userRepository = userRepository; this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder; this.passwordEncoder = passwordEncoder;
this.userRoleRepository = userRoleRepository; this.userRoleRepository = userRoleRepository;
this.userMapper = userMapper; this.userMapper = userMapper;
this.mailService = mailService; this.mailService = mailService;
this.applicationProperties = applicationProperties; this.applicationProperties = applicationProperties;
this.conferenceService = conferenceRepository;
this.timetableService = new TimetableService();
this.userSessionService = userSessionService;
} }
private User getUserByEmail(String email) { private User getUserByEmail(String email) {
@ -247,23 +263,30 @@ public class UserService implements UserDetailsService {
user.setResetKey(UserUtils.generateResetKey()); user.setResetKey(UserUtils.generateResetKey());
user.setResetDate(new Date()); user.setResetDate(new Date());
user = userRepository.save(user); user = userRepository.save(user);
try {
mailService.sendPasswordResetMail(user); mailService.sendPasswordResetMail(user);
} catch (MessagingException | MailException e) {
throw new UserSendingMailException(email);
}
log.debug("Created Reset Password Request for User: {}", user.getLogin()); log.debug("Created Reset Password Request for User: {}", user.getLogin());
return true; return true;
} }
public boolean completeUserPasswordReset(String key, UserResetPasswordDto userResetPasswordDto) { public boolean completeUserPasswordReset(UserResetPasswordDto userResetPasswordDto) {
if (!userResetPasswordDto.isPasswordsValid()) { if (!userResetPasswordDto.isPasswordsValid()) {
throw new UserPasswordsNotValidOrNotMatchException(""); throw new UserPasswordsNotValidOrNotMatchException("Пароли не совпадают");
} }
User user = userRepository.findOneByResetKey(key); User user = userRepository.findOneByResetKey(userResetPasswordDto.getResetKey());
if (user == null) { if (user == null) {
throw new UserResetKeyError(key); throw new UserResetKeyError(userResetPasswordDto.getResetKey());
} }
user.setPassword(passwordEncoder.encode(userResetPasswordDto.getPassword())); user.setPassword(passwordEncoder.encode(userResetPasswordDto.getPassword()));
user.setResetKey(null); user.setResetKey(null);
user.setResetDate(null); user.setResetDate(null);
user = userRepository.save(user); user = userRepository.save(user);
mailService.sendChangePasswordMail(user);
log.debug("Reset Password for User: {}", user.getLogin()); log.debug("Reset Password for User: {}", user.getLogin());
return true; return true;
} }
@ -341,4 +364,29 @@ public class UserService implements UserDetailsService {
throw new UserSendingMailException(email); throw new UserSendingMailException(email);
} }
} }
public User findOneByLoginIgnoreCase(String login) {
return userRepository.findOneByLoginIgnoreCase(login);
}
public Map<String, Object> getUsersInfo() {
List<UserInfoNow> 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);
}
} }

View File

@ -14,6 +14,8 @@ import ru.ulstu.user.model.UserSession;
import ru.ulstu.user.model.UserSessionListDto; import ru.ulstu.user.model.UserSessionListDto;
import ru.ulstu.user.repository.UserSessionRepository; import ru.ulstu.user.repository.UserSessionRepository;
import java.util.Date;
import static ru.ulstu.core.util.StreamApiUtils.convert; import static ru.ulstu.core.util.StreamApiUtils.convert;
@Service @Service
@ -58,4 +60,8 @@ public class UserSessionService {
public User getUserBySessionId(String sessionId) { public User getUserBySessionId(String sessionId) {
return userSessionRepository.findOneBySessionId(sessionId).getUser(); return userSessionRepository.findOneBySessionId(sessionId).getUser();
} }
public boolean isOnline(User user) {
return !userSessionRepository.findAllByUserAndLogoutTimeIsNullAndLoginTimeBefore(user, new Date()).isEmpty();
}
} }

View File

@ -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<Lesson> 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);
}
}

View File

@ -0,0 +1,7 @@
package ru.ulstu.utils.timetable.errors;
public class TimetableClientException extends RuntimeException {
public TimetableClientException(String message) {
super(message);
}
}

View File

@ -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<List<Lesson>> lessons = new ArrayList<>();
public Integer getDay() {
return day;
}
public void setDay(Integer day) {
this.day = day;
}
public List<List<Lesson>> getLessons() {
return lessons;
}
public void setLessons(List<List<Lesson>> lessons) {
this.lessons = lessons;
}
}

View File

@ -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;
}
}

View File

@ -0,0 +1,17 @@
package ru.ulstu.utils.timetable.model;
import java.util.ArrayList;
import java.util.List;
public class Response {
private List<Week> weeks = new ArrayList<>();
public List<Week> getWeeks() {
return weeks;
}
public void setWeeks(List<Week> weeks) {
this.weeks = weeks;
}
}

View File

@ -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;
}
}

View File

@ -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<Day> days = new ArrayList<>();
public List<Day> getDays() {
return days;
}
public void setDays(List<Day> days) {
this.days = days;
}
}

View File

@ -35,5 +35,6 @@ liquibase.change-log=classpath:db/changelog-master.xml
ng-tracker.base-url=http://127.0.0.1:8080 ng-tracker.base-url=http://127.0.0.1:8080
ng-tracker.undead-user-login=admin ng-tracker.undead-user-login=admin
ng-tracker.dev-mode=true ng-tracker.dev-mode=true
ng-tracker.debug_email=
ng-tracker.use-https=false ng-tracker.use-https=false
ng-tracker.check-run=false ng-tracker.check-run=false

View File

@ -0,0 +1,13 @@
<?xml version="1.1" encoding="UTF-8" standalone="no"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<changeSet author="anton" id="20190506_000000-1">
<addColumn tableName="deadline">
<column name="executor" type="varchar(255)"/>
</addColumn>
<addColumn tableName="deadline">
<column name="done" type="boolean"/>
</addColumn>
</changeSet>
</databaseChangeLog>

View File

@ -0,0 +1,17 @@
<?xml version="1.1" encoding="UTF-8" standalone="no"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<changeSet author="anton" id="20190506_000000-2">
<createTable tableName="project_executors">
<column name="project_id" type="integer"/>
<column name="executors_id" type="integer"/>
</createTable>
<addForeignKeyConstraint baseTableName="project_executors" baseColumnNames="project_id"
constraintName="fk_project_project_executors" referencedTableName="project"
referencedColumnNames="id"/>
<addForeignKeyConstraint baseTableName="project_executors" baseColumnNames="executors_id"
constraintName="fk_user_project_executors" referencedTableName="users"
referencedColumnNames="id"/>
</changeSet>
</databaseChangeLog>

View File

@ -0,0 +1,13 @@
<?xml version="1.1" encoding="UTF-8" standalone="no"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<changeSet author="anton" id="20190507_000002-1">
<addColumn tableName="event">
<column name="project_id" type="integer"/>
</addColumn>
<addForeignKeyConstraint baseTableName="event" baseColumnNames="project_id"
constraintName="fk_event_project_id" referencedTableName="project"
referencedColumnNames="id"/>
</changeSet>
</databaseChangeLog>

View File

@ -0,0 +1,14 @@
<?xml version="1.1" encoding="UTF-8" standalone="no"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<changeSet author="anton" id="20190517_000001-1">
<modifyDataType tableName="deadline"
columnName="executor"
newDataType="integer"
schemaName="public"/>
<addForeignKeyConstraint baseTableName="deadline" baseColumnNames="executor"
constraintName="fk_deadline_executor" referencedTableName="users"
referencedColumnNames="id"/>
</changeSet>
</databaseChangeLog>

View File

@ -0,0 +1,8 @@
<?xml version="1.1" encoding="UTF-8" standalone="no"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<changeSet author="tanya" id="20190520_000000-1">
<dropColumn columnName="applicationFileName" tableName="grants"/>
</changeSet>
</databaseChangeLog>

View File

@ -0,0 +1,27 @@
<?xml version="1.1" encoding="UTF-8" standalone="no"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<changeSet author="masha" id="20190523_000000-1">
<createTable tableName="reference">
<column name="id" type="integer">
<constraints nullable="false"/>
</column>
<column name="authors" type="varchar(255)"/>
<column name="publication_title" type="varchar(255)"/>
<column name="publication_year" type="integer"/>
<column name="paper_id" type="integer"/>
<column name="publisher" type="varchar(255)"/>
<column name="pages" type="varchar(255)"/>
<column name="journal_or_collection_title" type="varchar(255)"/>
<column name="reference_type" type="varchar(255)">
<constraints nullable="false"/>
</column>
<column name="version" type="integer"/>
</createTable>
<addPrimaryKey columnNames="id" constraintName="pk_reference" tableName="reference"/>
<addForeignKeyConstraint baseTableName="reference" baseColumnNames="paper_id"
constraintName="fk_reference_paper_id" referencedTableName="paper"
referencedColumnNames="id"/>
</changeSet>
</databaseChangeLog>

View File

@ -0,0 +1,11 @@
<?xml version="1.1" encoding="UTF-8" standalone="no"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<changeSet author="anton" id="20190528_000000-1">
<renameColumn tableName="deadline"
columnDataType="integer"
newColumnName="executors"
oldColumnName="executor"/>
</changeSet>
</databaseChangeLog>

View File

@ -0,0 +1,17 @@
<?xml version="1.1" encoding="UTF-8" standalone="no"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<changeSet author="anton" id="20190528_000002-1">
<createTable tableName="deadline_executors">
<column name="deadline_id" type="integer"/>
<column name="executors_id" type="integer"/>
</createTable>
<addForeignKeyConstraint baseTableName="deadline_executors" baseColumnNames="deadline_id"
constraintName="fk_deadline_deadline_executors" referencedTableName="deadline"
referencedColumnNames="id"/>
<addForeignKeyConstraint baseTableName="deadline_executors" baseColumnNames="executors_id"
constraintName="fk_user_deadline_executors" referencedTableName="users"
referencedColumnNames="id"/>
</changeSet>
</databaseChangeLog>

View File

@ -0,0 +1,17 @@
<?xml version="1.1" encoding="UTF-8" standalone="no"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<changeSet author="anton" id="20190528_000000-3">
<createTable tableName="project_grants">
<column name="project_id" type="integer"/>
<column name="grants_id" type="integer"/>
</createTable>
<addForeignKeyConstraint baseTableName="project_grants" baseColumnNames="project_id"
constraintName="fk_project_project_grants" referencedTableName="project"
referencedColumnNames="id"/>
<addForeignKeyConstraint baseTableName="project_grants" baseColumnNames="grants_id"
constraintName="fk_grant_project_grants" referencedTableName="grants"
referencedColumnNames="id"/>
</changeSet>
</databaseChangeLog>

View File

@ -0,0 +1,13 @@
<?xml version="1.1" encoding="UTF-8" standalone="no"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<changeSet author="anton" id="20190529_000001-1">
<addColumn tableName="file">
<column name="project_id" type="integer"/>
</addColumn>
<addForeignKeyConstraint baseTableName="file" baseColumnNames="project_id"
constraintName="fk_file_project" referencedTableName="project"
referencedColumnNames="id"/>
</changeSet>
</databaseChangeLog>

View File

@ -2,9 +2,9 @@
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" <databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd"> xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<changeSet author="anton" id="20190428_000000-1"> <changeSet author="anton" id="20190601_000000-1">
<update tableName="project"> <update tableName="project">
<column name="status" value="APPLICATION"/> <column name="status" value="TECHNICAL_TASK"/>
</update> </update>
</changeSet> </changeSet>
</databaseChangeLog> </databaseChangeLog>

View File

@ -35,11 +35,21 @@
<include file="db/changelog-20190422_000000-schema.xml"/> <include file="db/changelog-20190422_000000-schema.xml"/>
<include file="db/changelog-20190424_000000-schema.xml"/> <include file="db/changelog-20190424_000000-schema.xml"/>
<include file="db/changelog-20190426_000000-schema.xml"/> <include file="db/changelog-20190426_000000-schema.xml"/>
<include file="db/changelog-20190428_000000-schema.xml"/>
<include file="db/changelog-20190430_000000-schema.xml"/> <include file="db/changelog-20190430_000000-schema.xml"/>
<include file="db/changelog-20190505_000000-schema.xml"/> <include file="db/changelog-20190505_000000-schema.xml"/>
<include file="db/changelog-20190505_000001-schema.xml"/> <include file="db/changelog-20190505_000001-schema.xml"/>
<include file="db/changelog-20190506_000000-schema.xml"/>
<include file="db/changelog-20190506_000001-schema.xml"/>
<include file="db/changelog-20190507_000000-schema.xml"/> <include file="db/changelog-20190507_000000-schema.xml"/>
<include file="db/changelog-20190507_000001-schema.xml"/> <include file="db/changelog-20190507_000001-schema.xml"/>
<include file="db/changelog-20190507_000002-schema.xml"/>
<include file="db/changelog-20190511_000000-schema.xml"/> <include file="db/changelog-20190511_000000-schema.xml"/>
<include file="db/changelog-20190517_000001-schema.xml"/>
<include file="db/changelog-20190520_000000-schema.xml"/>
<include file="db/changelog-20190523_000000-schema.xml"/>
<include file="db/changelog-20190528_000000-schema.xml"/>
<include file="db/changelog-20190528_000002-schema.xml"/>
<include file="db/changelog-20190529_000000-schema.xml"/>
<include file="db/changelog-20190529_000001-schema.xml"/>
<include file="db/changelog-20190601_000001-schema.xml"/>
</databaseChangeLog> </databaseChangeLog>

0
src/main/resources/drivers/chromedriver Normal file → Executable file
View File

0
src/main/resources/drivers/geckodriver Normal file → Executable file
View File

View File

@ -1,23 +1,19 @@
<!DOCTYPE html> <!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"> <html xmlns:th="http://www.thymeleaf.org">
<head> <head>
<title>Password reset</title> <title>Восстановление пароля</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="shortcut icon" th:href="@{|${baseUrl}/favicon.ico|}"/> <link rel="shortcut icon" th:href="@{|${baseUrl}/favicon.ico|}"/>
</head> </head>
<body> <body>
<p> <p>
Dear <span th:text="${user.firstName + ' ' + user.lastName}">Ivan Ivanov</span> Дорогой <span th:text="${user.firstName + ' ' + user.lastName}">Ivan Ivanov</span>
</p> </p>
<p> <p>
For your account a password reset was requested, please click on the URL below to Ваш ключ для восстановления пароля <span th:text="${user.resetKey}"></span>
</p> </p>
<p> <p>
<a th:href="@{|${baseUrl}/reset?key=${user.resetKey}|}" С уважением,
th:text="@{|${baseUrl}/reset?key=${user.resetKey}|}">Reset Link</a>
</p>
<p>
Regards,
<br/> <br/>
<em>Balance Team.</em> <em>Balance Team.</em>
</p> </p>

View File

@ -0,0 +1,3 @@
.loader {
padding-left:50%
}

View File

@ -7,3 +7,34 @@
.nav-tabs { .nav-tabs {
margin-bottom: 20px; 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;
}

View File

@ -0,0 +1,5 @@
.div-deadline-done {
width: 60%;
height: 100%;
float: right;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 673 B

View File

@ -4,6 +4,7 @@
var urlFileUpload = "/api/1.0/files/uploadTmpFile"; var urlFileUpload = "/api/1.0/files/uploadTmpFile";
var urlFileDownload = "/api/1.0/files/download/"; var urlFileDownload = "/api/1.0/files/download/";
var urlPdfGenerating = "/papers/generatePdf"; var urlPdfGenerating = "/papers/generatePdf";
var urlReferencesFormatting = "/papers/getFormattedReferences";
var urlFileDownloadTmp = "/api/1.0/files/download-tmp/"; var urlFileDownloadTmp = "/api/1.0/files/download-tmp/";
/* exported MessageTypesEnum */ /* exported MessageTypesEnum */

View File

@ -1,7 +1,7 @@
function changePassword() { function changePassword() {
oldPassword = document.getElementById("oldPassword").value oldPassword = $("#oldPassword").val()
password = document.getElementById("password").value password = $("#password").val()
confirmPassword = document.getElementById("confirmPassword").value confirmPassword = $("#confirmPassword").val()
if ([oldPassword.length, password.length, confirmPassword.length].includes(0)) { if ([oldPassword.length, password.length, confirmPassword.length].includes(0)) {
showFeedbackMessage("Заполните все поля", MessageTypesEnum.WARNING); showFeedbackMessage("Заполните все поля", MessageTypesEnum.WARNING);
@ -23,7 +23,7 @@ function changePassword() {
}), }),
method: "POST", method: "POST",
success: function() { success: function() {
document.getElementById("closeModalPassword").click(); $("#closeModalPassword").click();
showFeedbackMessage("Пароль был обновлен", MessageTypesEnum.SUCCESS) showFeedbackMessage("Пароль был обновлен", MessageTypesEnum.SUCCESS)
}, },
@ -34,11 +34,8 @@ function changePassword() {
} }
function inviteUser() { function inviteUser() {
email = document.getElementById("email").value; email = $("#email").val();
re = /\S+@\S+\.\S+/; if (!isEmailValid(email)) {
if (!re.test(email)) {
showFeedbackMessage("Некорректный почтовый ящик", MessageTypesEnum.WARNING); showFeedbackMessage("Некорректный почтовый ящик", MessageTypesEnum.WARNING);
return; return;
} }
@ -48,7 +45,7 @@ function inviteUser() {
contentType: "application/json; charset=utf-8", contentType: "application/json; charset=utf-8",
method: "POST", method: "POST",
success: function() { success: function() {
document.getElementById("closeModalInvite").click(); $("#closeModalInvite").click();
showFeedbackMessage("Пользователь был успешно приглашен", MessageTypesEnum.SUCCESS) showFeedbackMessage("Пользователь был успешно приглашен", MessageTypesEnum.SUCCESS)
}, },
error: function(errorData) { error: function(errorData) {
@ -56,3 +53,75 @@ function inviteUser() {
} }
}) })
} }
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)
}

View File

@ -42,12 +42,20 @@
placeholder="http://"/> placeholder="http://"/>
</div> </div>
<p th:if="${#fields.hasErrors('url')}" th:errors="*{url}"
class="alert alert-danger">Incorrect description</p>
<p class="help-block text-danger"></p>
<div class="form-group"> <div class="form-group">
<label for="description">Описание:</label> <label for="description">Описание:</label>
<textarea class="form-control" rows="8" th:field="*{description}" id="description"> <textarea class="form-control" rows="8" th:field="*{description}" id="description">
</textarea> </textarea>
</div> </div>
<p th:if="${#fields.hasErrors('description')}" th:errors="*{description}"
class="alert alert-danger">Incorrect description</p>
<p class="help-block text-danger"></p>
<div class="form-group"> <div class="form-group">
<label for="deadlines">Дедлайны:</label> <label for="deadlines">Дедлайны:</label>
<div class="deadline-list form-control list-group" id="deadlines"> <div class="deadline-list form-control list-group" id="deadlines">
@ -65,6 +73,7 @@
</div> </div>
</div> </div>
</div> </div>
<p th:if="${#fields.hasErrors('deadlines')}" th:errors="*{deadlines}" <p th:if="${#fields.hasErrors('deadlines')}" th:errors="*{deadlines}"
class="alert alert-danger">Incorrect title</p> class="alert alert-danger">Incorrect title</p>
<p class="help-block text-danger"></p> <p class="help-block text-danger"></p>
@ -94,6 +103,10 @@
</div> </div>
</div> </div>
</div> </div>
<p th:if="${#fields.hasErrors('beginDate') || #fields.hasErrors('endDate')}"
th:errors="*{beginDate}"
class="alert alert-danger">Incorrect date</p>
<p class="help-block text-danger"></p>
<div class="form-group"> <div class="form-group">
<label for="members">Участники:</label> <label for="members">Участники:</label>
@ -123,7 +136,6 @@
</div> </div>
<div class="form-group d-flex justify-content-between flex-wrap"> <div class="form-group d-flex justify-content-between flex-wrap">
<!--<input type="hidden" th:value="*{ping}" th:name="ping"/>-->
<input id="ping-button" class="btn btn-primary" <input id="ping-button" class="btn btn-primary"
type="submit" name="pingConference" value="Ping участникам" type="submit" name="pingConference" value="Ping участникам"
th:disabled="*{id == null ? 'true' : 'false'}"/> th:disabled="*{id == null ? 'true' : 'false'}"/>

View File

@ -8,7 +8,8 @@
<div class="col"> <div class="col">
<span th:replace="grants/fragments/grantStatusFragment :: grantStatus(grantStatus=${grant.status})"/> <span th:replace="grants/fragments/grantStatusFragment :: grantStatus(grantStatus=${grant.status})"/>
<a th:href="@{'grant?id='+${grant.id}}"> <a th:href="@{'grant?id='+${grant.id}}">
<span class="h6" th:text="${grant.title}"/> <span class="h6" th:if="${#strings.length(grant.title) > 50}" th:text="${#strings.substring(grant.title, 0, 50)} + '...'" th:title="${grant.title}"/>
<span class="h6" th:if="${#strings.length(grant.title) le 50}" th:text="${grant.title}" th:title="${grant.title}"/>
<span class="text-muted" th:text="${grant.authorsString}"/> <span class="text-muted" th:text="${grant.authorsString}"/>
</a> </a>
<input class="id-class" type="hidden" th:value="${grant.id}"/> <input class="id-class" type="hidden" th:value="${grant.id}"/>

View File

@ -186,47 +186,7 @@
<div class="row"> <div class="row">
<div class="form-control list-group div-selected-papers" id="selected-papers"> <div class="form-control list-group div-selected-papers" id="selected-papers">
<div th:each="paper, rowStat : *{papers}"> <div th:each="paper, rowStat : *{papers}">
<input type="hidden" th:field="*{papers[__${rowStat.index}__].id}"/> <div th:replace="papers/fragments/paperLineFragment :: paperLine(paper=${paper})"/>
<div class="col">
<a th:href="@{'/papers/paper?id=' + *{papers[__${rowStat.index}__].id} + ''}">
<img class="icon-paper" src="/img/conference/paper.png"/>
<span th:text="*{papers[__${rowStat.index}__].title}">
Название статьи
</span>
</a>
</div>
<div class="col">
<label>Статус: </label>
<span th:text="*{papers[__${rowStat.index}__].status.statusName}">
Статус статьи
</span>
</div>
<!--
<div class="col" th:unless="${#lists.isEmpty(paper.grants)}">
<label>Гранты: </label>
<div th:each="grant, grantRowStat : *{papers[__${rowStat.index}__].grants}"
th:remove="tag">
<div th:unless="${grant.id}==*{id}" th:remove="tag">
<li>
<a th:href="@{'/grants/grant?id=' + ${grant.id} + ''}">
<span th:text="${grant.title} "></span>
</a>
</li>
</div>
</div>
</div>
<div class="col" th:unless="${#lists.isEmpty(paper.conferences)}">
<label>Конференции: </label>
<div th:each="conference, conferenceRowStat : *{papers[__${rowStat.index}__].conferences}"
th:remove="tag">
<li>
<a th:href="@{'/conferences/conference?id=' + ${conference.id} + ''}">
<span th:text="${conference.title}"></span>
</a>
</li>
</div>
</div>
-->
</div> </div>
</div> </div>
</div> </div>

View File

@ -40,7 +40,7 @@
</div> </div>
</div> </div>
<div class="col-md-4 col-sm-6 portfolio-item"> <div class="col-md-4 col-sm-6 portfolio-item">
<a class="portfolio-link" href="./projects/dashboard"> <a class="portfolio-link" href="./projects/projects">
<div class="portfolio-hover"> <div class="portfolio-hover">
<div class="portfolio-hover-content"> <div class="portfolio-hover-content">
<i class="fa fa-arrow-right fa-3x"></i> <i class="fa fa-arrow-right fa-3x"></i>

View File

@ -10,7 +10,8 @@
<span th:replace="papers/fragments/paperStatusFragment :: paperStatus(paperStatus=${paper.status})"/> <span th:replace="papers/fragments/paperStatusFragment :: paperStatus(paperStatus=${paper.status})"/>
</div> </div>
<div class="col col-10 text-right"> <div class="col col-10 text-right">
<p th:if="${paper.url!=null and paper.url!=''}"><a target="_blank" th:href="${paper.url}"><i <p th:if="${paper.url!=null and paper.url!=''}"><a target="_blank" class="externalLink"
th:href="${paper.url}"><i
class="fa fa-external-link fa-1x" class="fa fa-external-link fa-1x"
aria-hidden="true"></i></a></p> aria-hidden="true"></i></a></p>
<p th:unless="${paper.url!=null and paper.url!=''}"><i class="fa fa-fw fa-2x" aria-hidden="true"></i></p> <p th:unless="${paper.url!=null and paper.url!=''}"><i class="fa fa-fw fa-2x" aria-hidden="true"></i></p>

View File

@ -8,7 +8,8 @@
<div class="col"> <div class="col">
<span th:replace="papers/fragments/paperStatusFragment :: paperStatus(paperStatus=${paper.status})"/> <span th:replace="papers/fragments/paperStatusFragment :: paperStatus(paperStatus=${paper.status})"/>
<a th:href="@{'paper?id='+${paper.id}}"> <a th:href="@{'paper?id='+${paper.id}}">
<span class="h6" th:text="${paper.title}"/> <span class="h6" th:if="${#strings.length(paper.title)} > 50" th:text="${#strings.substring(paper.title, 0, 50) + '...'}" th:title="${paper.title}"/>
<span class="h6" th:if="${#strings.length(paper.title) le 50}" th:text="${paper.title}" th:title="${paper.title}"/>
<span class="text-muted" th:text="${paper.authorsString}"/> <span class="text-muted" th:text="${paper.authorsString}"/>
</a> </a>
<input class="id-class" type="hidden" th:value="${paper.id}"/> <input class="id-class" type="hidden" th:value="${paper.id}"/>

View File

@ -4,6 +4,10 @@
layout:decorator="default" xmlns:th="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/html"> layout:decorator="default" xmlns:th="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/html">
<head> <head>
<link rel="stylesheet" href="../css/paper.css"/> <link rel="stylesheet" href="../css/paper.css"/>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"/>
<script type="text/javascript" src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head> </head>
<body> <body>
@ -31,6 +35,9 @@
href="#nav-main" role="tab" aria-controls="nav-main" aria-selected="true">Статья</a> href="#nav-main" role="tab" aria-controls="nav-main" aria-selected="true">Статья</a>
<a class="nav-item nav-link" id="nav-latex-tab" data-toggle="tab" <a class="nav-item nav-link" id="nav-latex-tab" data-toggle="tab"
href="#nav-latex" role="tab" aria-controls="nav-latex" aria-selected="false">Latex</a> href="#nav-latex" role="tab" aria-controls="nav-latex" aria-selected="false">Latex</a>
<a class="nav-item nav-link" id="nav-references-tab" data-toggle="tab"
href="#nav-references" role="tab" aria-controls="nav-references"
aria-selected="false">References</a>
</div> </div>
</nav> </nav>
<div class="tab-content" id="nav-tabContent"> <div class="tab-content" id="nav-tabContent">
@ -80,14 +87,16 @@
<div class="form-group"> <div class="form-group">
<label>Дедлайны:</label> <label>Дедлайны:</label>
<div class="row" th:each="deadline, rowStat : *{deadlines}"> <div class="row deadline" th:each="deadline, rowStat : *{deadlines}">
<input type="hidden" th:field="*{deadlines[__${rowStat.index}__].id}"/> <input type="hidden" th:field="*{deadlines[__${rowStat.index}__].id}"/>
<div class="col-6"> <div class="col-6">
<input type="date" class="form-control" name="deadline" <input type="date" class="form-control deadline-date"
name="deadline"
th:field="*{deadlines[__${rowStat.index}__].date}"/> th:field="*{deadlines[__${rowStat.index}__].date}"/>
</div> </div>
<div class="col-4"> <div class="col-4">
<input class="form-control" type="text" placeholder="Описание" <input class="form-control deadline-desc" type="text"
placeholder="Описание"
th:field="*{deadlines[__${rowStat.index}__].description}"/> th:field="*{deadlines[__${rowStat.index}__].description}"/>
</div> </div>
<div class="col-2"> <div class="col-2">
@ -103,13 +112,15 @@
class="alert alert-danger">Incorrect title</p> class="alert alert-danger">Incorrect title</p>
</div> </div>
<div class="form-group"> <div class="form-group">
<input type="submit" id="addDeadline" name="addDeadline" class="btn btn-primary" <input type="submit" id="addDeadline" name="addDeadline"
class="btn btn-primary"
value="Добавить value="Добавить
дедлайн"/> дедлайн"/>
</div> </div>
<div class="form-group"> <div class="form-group">
<label>Авторы:</label> <label>Авторы:</label>
<select class="selectpicker form-control" multiple="true" data-live-search="true" <select class="selectpicker form-control" multiple="true"
data-live-search="true"
title="-- Выберите авторов --" title="-- Выберите авторов --"
th:field="*{authorIds}"> th:field="*{authorIds}">
<option th:each="author: ${allAuthors}" th:value="${author.id}" <option th:each="author: ${allAuthors}" th:value="${author.id}"
@ -167,6 +178,127 @@
</button> </button>
</div> </div>
</div> </div>
<div class="tab-pane fade" id="nav-references" role="tabpanel"
aria-labelledby="nav-profile-tab">
<div class="form-group">
<label>References:</label>
<th:block th:each="reference, rowStat : *{references}">
<div class="row" th:id="|reference${rowStat.index}|"
th:style="${reference.deleted} ? 'display: none;' :''">
<div class="form-group col-11">
<a data-toggle="collapse"
th:href="${'#collapseReference'+rowStat.index}"
aria-expanded="false">
<div class="collapse-heading"
th:text="${(reference.referenceType.toString() == 'ARTICLE'?'Статья':'Книга') +'. '
+(reference.publicationTitle==null?'':reference.publicationTitle+'. ')+(reference.authors==null?'':reference.authors+'. ') }">
</div>
</a>
</div>
<div class="col-1">
<a class="btn btn-danger float-right"
th:onclick="|$('#references${rowStat.index}\\.deleted').val('true'); $('#reference${rowStat.index}').hide(); |"><span
aria-hidden="true"><i class="fa fa-times"/></span>
</a>
</div>
<div class="collapse" th:id="${'collapseReference'+rowStat.index}">
<input type="hidden"
th:field="*{references[__${rowStat.index}__].id}"/>
<input type="hidden"
th:field="*{references[__${rowStat.index}__].deleted}"/>
<div class="form-group col-12">
<label class="col-4">Вид публикации:</label>
<select class="form-control col-7"
th:field="*{references[__${rowStat.index}__].referenceType}">
<option th:each="type : ${allReferenceTypes}"
th:value="${type}"
th:text="${type.typeName}">Type
</option>
</select>
</div>
<div class="form-group col-12">
<label class="col-4">Авторы:</label>
<input type="text"
class="form-control col-7 autocomplete author"
name="authors"
th:field="*{references[__${rowStat.index}__].authors}"/>
</div>
<div class="form-group col-12">
<label class="col-4 ">Название публикации:</label>
<input type="text"
class="form-control col-7 autocomplete publicationTitle"
name="publicationTitle"
th:field="*{references[__${rowStat.index}__].publicationTitle}"/>
</div>
<div class="form-group col-12">
<label class="col-4">Год издания:</label>
<input type="number"
class="form-control col-7 publicationYear"
name="publicationYear"
th:field="*{references[__${rowStat.index}__].publicationYear}"/>
</div>
<div class="form-group col-12">
<label class="col-4">Издательство:</label>
<input type="text"
class="form-control col-7 autocomplete publisher"
name="publisher"
th:field="*{references[__${rowStat.index}__].publisher}"/>
</div>
<div class="form-group col-12">
<label class="col-4">Страницы:</label>
<input type="text" class="form-control col-7 pages"
name="pages"
th:field="*{references[__${rowStat.index}__].pages}"/>
</div>
<div class="form-group col-12">
<label class="col-4">Название журнала или сборника статей
конференции:</label>
<input type="text"
class="form-control col-7 autocomplete journalOrCollectionTitle"
name="journalOrCollectionTitle"
th:field="*{references[__${rowStat.index}__].journalOrCollectionTitle}"/>
</div>
</div>
</div>
</th:block>
<div class="form-group">
<input type="submit" id="addReference" name="addReference"
class="btn btn-primary"
value="Добавить источник"/>
</div>
<div class="form-group">
<div class="col-12 form-group">
<label for="formatStandard">Стандарт форматирования:</label>
<select class="form-control" th:field="*{formatStandard}"
id="formatStandard">
<option th:each="standard : ${allFormatStandards}"
th:value="${standard}"
th:text="${standard.standardName}">standard
</option>
</select>
</div>
<div class="col-12 form-group">
<button id="formatBtn" class="btn btn-primary text-uppercase"
onclick="getFormattedReferences()"
type="button">
Форматировать
</button>
</div>
<div class="col-12">
<textarea class="form-control"
id="formattedReferencesArea"></textarea>
</div>
</div>
</div>
</div>
</div> </div>
</div> </div>
<div class="col-md-4 offset-md-1 col-sm-12 offset-sm-0"> <div class="col-md-4 offset-md-1 col-sm-12 offset-sm-0">
@ -379,6 +511,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);
}
}
}
</script>
<script th:inline="javascript">
/*<![CDATA[*/
var autoCompleteData = /*[[${autocompleteData}]]*/ 'default';
console.log(autoCompleteData);
$(".autocomplete.author").autocomplete({
source: autoCompleteData.authors,
minLength: 0,
}).focus(function () {
$(this).autocomplete("search");
});
$(".autocomplete.publicationTitle").autocomplete({
source: autoCompleteData.publicationTitles,
minLength: 0,
}).focus(function () {
$(this).autocomplete("search");
});
$(".autocomplete.publisher").autocomplete({
source: autoCompleteData.publishers,
minLength: 0,
}).focus(function () {
$(this).autocomplete("search");
});
$(".autocomplete.journalOrCollectionTitle").autocomplete({
source: autoCompleteData.journalOrCollectionTitles,
minLength: 0,
}).focus(function () {
$(this).autocomplete("search");
});
/*]]>*/
</script> </script>
</div> </div>

View File

@ -17,6 +17,7 @@
<div th:replace="projects/fragments/projectDashboardFragment :: projectDashboard(project=${project})"/> <div th:replace="projects/fragments/projectDashboardFragment :: projectDashboard(project=${project})"/>
</th:block> </th:block>
</div> </div>
<div th:replace="fragments/noRecordsFragment :: noRecords(entities=${projects}, noRecordsMessage=' одного проекта', url='project')"/>
</div> </div>
</section> </section>
</div> </div>

View File

@ -0,0 +1,40 @@
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
</head>
<body>
<body>
<div th:fragment="filesList">
<th:block th:each="file, rowStat : *{files}">
<div class="row" th:id="|files${rowStat.index}|"
th:style="${file.deleted} ? 'display: none;' :''">
<input type="hidden" th:field="*{files[__${rowStat.index}__].id}"/>
<input type="hidden"
th:field="*{files[__${rowStat.index}__].deleted}"/>
<input type="hidden"
th:field="*{files[__${rowStat.index}__].name}"/>
<input type="hidden"
th:field="*{files[__${rowStat.index}__].tmpFileName}"/>
<div class="col-2">
<a class="btn btn-danger float-right"
th:onclick="|$('#files${rowStat.index}\\.deleted').val('true'); $('#files${rowStat.index}').hide(); |">
<span aria-hidden="true"><i class="fa fa-times"/></span>
</a>
</div>
<div class="col-10">
<a th:onclick="${file.id==null} ? 'downloadFile('+${file.tmpFileName}+',null,\''+${file.name}+'\')':
'downloadFile(null,'+${file.id}+',\''+${file.name}+'\')' "
href="javascript:void(0)"
th:text="*{files[__${rowStat.index}__].name}">
</a>
</div>
</div>
</th:block>
</div>
</body>
</body>
</html>

View File

@ -6,19 +6,19 @@
<body> <body>
<span th:fragment="projectStatus (projectStatus)" class="fa-stack fa-1x"> <span th:fragment="projectStatus (projectStatus)" class="fa-stack fa-1x">
<th:block th:switch="${projectStatus.name()}"> <th:block th:switch="${projectStatus.name()}">
<div th:case="'APPLICATION'"> <div th:case="'TECHNICAL_TASK'">
<i class="fa fa-circle fa-stack-2x text-draft"></i> <i class="fa fa-circle fa-stack-2x text-draft"></i>
</div> </div>
<div th:case="'ON_COMPETITION'"> <div th:case="'OPEN'">
<i class="fa fa-circle fa-stack-2x text-review"></i> <i class="fa fa-circle fa-stack-2x text-review"></i>
</div> </div>
<div th:case="'SUCCESSFUL_PASSAGE'"> <div th:case="'IN_WORK'">
<i class="fa fa-circle fa-stack-2x text-accepted"></i> <i class="fa fa-circle fa-stack-2x text-accepted"></i>
</div> </div>
<div th:case="'IN_WORK'"> <div th:case="'CERTIFICATE_ISSUED'">
<i class="fa fa-circle fa-stack-2x text-primary"></i> <i class="fa fa-circle fa-stack-2x text-primary"></i>
</div> </div>
<div th:case="'COMPLETED'"> <div th:case="'CLOSED'">
<i class="fa fa-circle fa-stack-2x text-success"></i> <i class="fa fa-circle fa-stack-2x text-success"></i>
</div> </div>
<div th:case="'FAILED'"> <div th:case="'FAILED'">

View File

@ -3,7 +3,7 @@
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" 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"> layout:decorator="default" xmlns:th="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/html">
<head> <head>
<link rel="stylesheet" href="../css/project.css"/>
</head> </head>
<body> <body>
@ -51,12 +51,18 @@
</div> </div>
<div class="form-group"> <div class="form-group">
<label for="createGrant">Добавить грант:</label> <label>Добавить грант:</label>
<div th:if="*{grant} == null"> <div class="row">
<input type="submit" id="createGrant" name="createGrant" class="btn btn-primary" <div class="col-10">
value="Добавить грант"/> <select class="selectpicker form-control" data-live-search="true"
title="-- Прикрепить грант --" id="allGrants"
th:field="*{grantIds}" data-size="5">
<option th:each="grant : ${allGrants}" th:value="${grant.id}"
th:text="${grant.title}"> Грант для прикрепления
</option>
</select>
</div>
</div> </div>
<input type="hidden" th:field="*{grant.id}"/>
</div> </div>
<div class="form-group"> <div class="form-group">
@ -71,7 +77,8 @@
<div class="form-group"> <div class="form-group">
<label>Дедлайны показателей:</label> <label>Дедлайны показателей:</label>
<div class="row" th:each="deadline, rowStat : *{deadlines}"> <div class="row" th:each="deadline, rowStat : *{deadlines}"
style="margin-bottom: 15px;">
<input type="hidden" th:field="*{deadlines[__${rowStat.index}__].id}"/> <input type="hidden" th:field="*{deadlines[__${rowStat.index}__].id}"/>
<div class="col-6 div-deadline-date"> <div class="col-6 div-deadline-date">
<input type="date" class="form-control form-deadline-date" name="deadline" <input type="date" class="form-control form-deadline-date" name="deadline"
@ -89,6 +96,20 @@
aria-hidden="true"><i class="fa fa-times"/></span> aria-hidden="true"><i class="fa fa-times"/></span>
</a> </a>
</div> </div>
<div class="col-12" style="margin-bottom: 15px;"></div>
<div class="col-10 div-deadline-executor">
<select class="selectpicker form-control" multiple="true" data-live-search="true"
title="-- Выберите исполнителя --" id="executors"
th:field="*{deadlines[__${rowStat.index}__].executors}" data-size="5">
<option th:each="executors : ${allExecutors}" th:value="${executors.id}"
th:text="${executors.lastName}"> Участник
</option>
</select>
</div>
<div class="col-2">
<input class="form-control div-deadline-done" type="checkbox"
th:field="*{deadlines[__${rowStat.index}__].done}"/>
</div>
</div> </div>
<p th:if="${#fields.hasErrors('deadlines')}" th:errors="*{deadlines}" <p th:if="${#fields.hasErrors('deadlines')}" th:errors="*{deadlines}"
class="alert alert-danger">Incorrect title</p> class="alert alert-danger">Incorrect title</p>
@ -98,6 +119,13 @@
value="Добавить дедлайн"/> value="Добавить дедлайн"/>
</div> </div>
<div class="form-group files-list" id="files-list">
<label>Файлы:</label>
<div th:replace="projects/fragments/projectFilesListFragment"/>
</div>
<div class="form-group"> <div class="form-group">
<label for="loader">Загрузить файл:</label> <label for="loader">Загрузить файл:</label>
<div id="loader"> <div id="loader">
@ -133,17 +161,103 @@
new FileLoader({ new FileLoader({
div: "loader", div: "loader",
url: urlFileUpload, url: urlFileUpload,
maxSize: 2, maxSize: -1,
extensions: ["doc", "docx", "xls", "jpg", "png", "pdf", "txt"], extensions: [],
callback: function (response) { callback: function (response) {
showFeedbackMessage("Файл успешно загружен"); showFeedbackMessage("Файл успешно загружен");
console.debug(response); console.debug(response);
addNewFile(response, $("#files-list"));
} }
}); });
$('.selectpicker').selectpicker(); $('.selectpicker').selectpicker();
}); });
/*]]>*/ /*]]>*/
function addNewFile(fileDto, listElement) {
var fileNumber = $('.files-list div.row').length;
var newFileRow = $("<div/>")
.attr("id", 'files' + fileNumber)
.addClass("row");
var idInput = $("<input/>")
.attr("type", "hidden")
.attr("id", "files" + fileNumber + ".id")
.attr("value", '')
.attr("name", "files[" + fileNumber + "].id");
newFileRow.append(idInput);
var flagInput = $("<input/>")
.attr("type", "hidden")
.attr("id", "files" + fileNumber + ".deleted")
.attr("value", "false")
.attr("name", "files[" + fileNumber + "].deleted");
newFileRow.append(flagInput);
var nameInput = $("<input/>")
.attr("type", "hidden")
.attr("id", "files" + fileNumber + ".name")
.attr("value", fileDto.fileName)
.attr("name", "files[" + fileNumber + "].name");
newFileRow.append(nameInput);
var tmpFileNameInput = $("<input/>")
.attr("type", "hidden")
.attr("id", "files" + fileNumber + ".tmpFileName")
.attr("value", fileDto.tmpFileName)
.attr("name", "files[" + fileNumber + "].tmpFileName");
newFileRow.append(tmpFileNameInput);
var nextDiv = $("<div/>")
.addClass("col-2");
var nextA = $("<a/>")
.addClass("btn btn-danger float-right")
.attr("onclick", "$('#files" + fileNumber + "\\\\.deleted').val('true'); $('#files" + fileNumber + "').hide();")
.append(($("<span/>").attr("aria-hidden", "true")).append($("<i/>").addClass("fa fa-times")))
;
nextDiv.append(nextA)
newFileRow.append(nextDiv);
var nameDiv = $("<div/>")
.addClass("col-10")
.append($("<a/>").text(fileDto.fileName)
.attr("href", 'javascript:void(0)')
.attr("onclick", "downloadFile('" + fileDto.tmpFileName + "',null,'" + fileDto.fileName + "')"));
newFileRow.append(nameDiv);
listElement.append(newFileRow);
}
function downloadFile(tmpName, fileId, downloadName) {
let xhr = new XMLHttpRequest();
if (fileId != null) xhr.open('GET', urlFileDownload + fileId);
if (tmpName != null) xhr.open('GET', urlFileDownloadTmp + tmpName);
xhr.responseType = 'blob';
var formData = new FormData();
if (fileId != null) formData.append("file-id", fileId);
if (tmpName != null) formData.append("tmp-file-name", tmpName);
xhr.send(formData);
xhr.onload = function () {
if (this.status == 200) {
console.debug(this.response);
var blob = new Blob([this.response], {type: '*'});
let a = document.createElement("a");
a.style = "display: none";
document.body.appendChild(a);
let url = window.URL.createObjectURL(blob);
a.href = url;
a.download = downloadName;
a.click();
window.URL.revokeObjectURL(url);
} else {
}
}
}
</script> </script>
</div> </div>

View File

@ -24,6 +24,7 @@
</div> </div>
<div class="col-md-3 col-sm-12"> <div class="col-md-3 col-sm-12">
</div> </div>
<div th:replace="fragments/noRecordsFragment :: noRecords(entities=${projects}, noRecordsMessage=' одного проекта', url='project')"/>
</div> </div>
</div> </div>
</section> </section>

View File

@ -1,57 +1,59 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en" <html lang="en"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorator="default"> layout:decorator="default" xmlns:th="http://www.w3.org/1999/xhtml">
<head> <head>
<script src="/js/users.js"></script>
<link rel="stylesheet" href="../css/base.css"/>
</head> </head>
<body> <body>
<nav layout:fragment="navbar"> <nav layout:fragment="navbar">
<div class="navbar-header"> <div class="navbar-header">
<a class="navbar-brand" href="/"><span class="ui-menuitem-text"><i <a class="navbar-brand" href="/"><span class="ui-menuitem-text"><i
class="fa fa-plane fa-4" aria-hidden="true"></i> Balance</span></a> class="fa fa-plane fa-4" aria-style="display:none"></i> Balance</span></a>
</div> </div>
</nav> </nav>
<div class="container" layout:fragment="content"> <div layout:fragment="content">
<form id="reset-form" method="post" class="margined-top-10"> <section class="bg-light" id="portfolio">
<fieldset>
<div class="container">
<div class="row justify-content-md-center">
<div class="col-lg-6">
<div class="form-group"> <div class="form-group">
<input type="email" name="email" id="email" class="form-control" <input type="text" name="email" id="emailReset" class="form-control"
placeholder="E-Mail" required="true" autofocus="autofocus"/> placeholder="E-Mail"/>
</div> </div>
<button type="submit" class="btn btn-success btn-block">Сбросить пароль</button> <div class="form-group">
<input type="password" name="email" id="passwordNew" class="form-control"
placeholder="Новый пароль" style="display:none"/>
</div>
<div class="form-group">
<input type="password" name="email" id="passwordConfirm" class="form-control"
placeholder="Подтвердите пароль" style="display:none"/>
</div>
<div class="form-group">
<input type="text" name="email" id="resetKey" class="form-control"
placeholder="Код подтверждения" style="display:none"/>
</div>
<div id="dvloader" class="loader" style="display:none"><img src="../img/main/ajax-loader.gif" /></div>
<button id="btnSend" type="button" onclick="requestResetPassword()"
class="btn btn-success btn-block">
Отправить код подтверждения
</button>
<button id="btnReset" style="display:none" type="button" onclick="resetPassword()"
class="btn btn-success btn-block">
Сбросить
пароль
</button>
<div class="form-group"> <div class="form-group">
<small class="form-text text-muted"> <small class="form-text text-muted">
<a href="/login">Вернуться к странице входа</a> <a href="/login">Вернуться к странице входа</a>
</small> </small>
</div> </div>
</fieldset>
</form>
</div> </div>
<th:block layout:fragment="data-scripts"> </div>
<script type="text/javascript"> </div>
/*<![CDATA[*/ </section>
$(document).ready(function () { </div>
$("#reset-form").submit(function () {
var email = $("#email").val();
if (isEmpty(email)) {
showFeedbackMessage("Адрес электронной почты не задан", MessageTypesEnum.DANGER);
return false;
}
postToRest(urlUsersPasswordResetRequest + "?email=" + email, null,
function () {
showFeedbackMessage("Запрос на смену пароля отправлен");
},
function () {
$("#email").val("");
}
);
return false;
});
});
/*]]>*/
</script>
</th:block>
</body> </body>
</html> </html>

View File

@ -0,0 +1,35 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorator="default" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<script src="/js/core.js"></script>
</head>
<body>
<div class="container" layout:fragment="content">
<section id="services">
<div class="container">
<div class="col-lg-12 text-center">
<h2 class="section-heading text-uppercase">Пользователи</h2>
</div>
<div class="text-center">
<h2 th:text="${error}">teste</h2>
</div>
<div class="row justify-content-center" id="dashboard">
<th:block th:each="user : ${users}">
<div th:replace="users/fragments/userDashboardFragment :: userDashboard(user=${user})"/>
</th:block>
</div>
</div>
</section>
<script th:inline="javascript">
/*<![CDATA[*/
$(document).ready(function () {
var error = /*[[${error}]]*/
showFeedbackMessage(error, MessageTypesEnum.WARNING)
});
/*]]>*/
</script>
</div>
</body>
</html>

View File

@ -0,0 +1,18 @@
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head th:fragment="headerfiles">
<meta charset="UTF-8"/>
</head>
<body>
<div th:fragment="userDashboard (user)" class="col-12 col-sm-12 col-md-12 col-lg-4 col-xl-3 dashboard-card">
<div class="row">
<div class="col col-10">
<b><p th:text="${user.user.lastName} + ' ' + ${user.user.firstName} + ' ' + ${user.user.patronymic}"></p></b>
<i><p th:if="${user.conference != null}" th:text="'Сейчас на конференции ' + ${user.conference.title}"></p></i>
<i><p th:if="${user.lesson != null}" th:text="'Сейчас на паре ' + ${user.lesson.nameOfLesson} + ' в аудитории ' + ${user.lesson.room}"></p></i>
<p th:if="${user.isOnline()}">Онлайн</p>
</div>
</div>
</div>
</body>
</html>

View File

@ -26,7 +26,7 @@ import java.util.Map;
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING) @FixMethodOrder(MethodSorters.NAME_ASCENDING)
@SpringBootTest(classes = NgTrackerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) @SpringBootTest(classes = NgTrackerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class IndexConferenceTest extends TestTemplate { public class ConferenceTest extends TestTemplate {
private final Map<PageObject, List<String>> navigationHolder = ImmutableMap.of( private final Map<PageObject, List<String>> navigationHolder = ImmutableMap.of(
new ConferencesPage(), Arrays.asList("КОНФЕРЕНЦИИ", "/conferences/conferences"), new ConferencesPage(), Arrays.asList("КОНФЕРЕНЦИИ", "/conferences/conferences"),
new ConferencePage(), Arrays.asList("РЕДАКТИРОВАНИЕ КОНФЕРЕНЦИИ", "/conferences/conference?id=0"), new ConferencePage(), Arrays.asList("РЕДАКТИРОВАНИЕ КОНФЕРЕНЦИИ", "/conferences/conference?id=0"),

View File

@ -0,0 +1,247 @@
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import core.PageObject;
import core.TestTemplate;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import paper.PaperPage;
import paper.PapersDashboardPage;
import paper.PapersPage;
import ru.ulstu.NgTrackerApplication;
import ru.ulstu.configuration.ApplicationProperties;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@RunWith(SpringRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@SpringBootTest(classes = NgTrackerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class PaperTest extends TestTemplate {
private final Map<PageObject, List<String>> navigationHolder = ImmutableMap.of(
new PapersPage(), Arrays.asList("СТАТЬИ", "/papers/papers"),
new PaperPage(), Arrays.asList("РЕДАКТИРОВАНИЕ СТАТЬИ", "/papers/paper?id=0"),
new PapersDashboardPage(), Arrays.asList("СТАТЬИ", "/papers/dashboard")
);
@Autowired
private ApplicationProperties applicationProperties;
private String getPaperPageUrl() {
return Iterables.get(navigationHolder.entrySet(), 1).getValue().get(1);
}
private PaperPage getPaperPage() {
PaperPage paperPage = (PaperPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey());
paperPage.initElements();
return paperPage;
}
private String getPapersPageUrl() {
return Iterables.get(navigationHolder.entrySet(), 0).getValue().get(1);
}
private PapersPage getPapersPage() {
PapersPage papersPage = (PapersPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 0).getKey());
papersPage.initElements();
return papersPage;
}
private String getPapersDashboardPageUrl() {
return Iterables.get(navigationHolder.entrySet(), 2).getValue().get(1);
}
private PapersDashboardPage getPapersDashboardPage() {
PapersDashboardPage papersDashboardPage = (PapersDashboardPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 2).getKey());
papersDashboardPage.initElements();
return papersDashboardPage;
}
@Test
public void createNewPaperTest() {
getContext().goTo(applicationProperties.getBaseUrl() + getPaperPageUrl());
PaperPage paperPage = getPaperPage();
String testTitle = "test " + (String.valueOf(System.currentTimeMillis()));
fillRequiredFields(paperPage, testTitle);
paperPage.clickSaveBtn();
PapersPage papersPage = getPapersPage();
Assert.assertTrue(papersPage.havePaperWithTitle(testTitle));
}
@Test
public void editPaperTest() {
createNewPaper();
getContext().goTo(applicationProperties.getBaseUrl() + getPapersPageUrl());
PapersPage papersPage = getPapersPage();
papersPage.clickFirstPaper();
PaperPage paperPage = getPaperPage();
String testTitle = "test " + (String.valueOf(System.currentTimeMillis()));
paperPage.setTitle(testTitle);
paperPage.clickSaveBtn();
Assert.assertTrue(papersPage.havePaperWithTitle(testTitle));
}
private void createNewPaper() {
getContext().goTo(applicationProperties.getBaseUrl() + getPaperPageUrl());
PaperPage paperPage = getPaperPage();
String testTitle = "test " + (String.valueOf(System.currentTimeMillis()));
fillRequiredFields(paperPage, testTitle);
paperPage.clickSaveBtn();
}
@Test
public void addDeadlineTest() {
createNewPaper();
getContext().goTo(applicationProperties.getBaseUrl() + getPapersPageUrl());
PapersPage papersPage = getPapersPage();
papersPage.clickFirstPaper();
PaperPage paperPage = getPaperPage();
papersPage.clickAddDeadline();
String testDate = "01.01.2019";
String testDateResult = "2019-01-01";
String testDesc = "desc";
Integer deadlineNumber = 2;
paperPage.setDeadlineDate(deadlineNumber, testDate);
paperPage.setDeadlineDescription(deadlineNumber, testDesc);
String paperId = paperPage.getId();
paperPage.clickSaveBtn();
getContext().goTo(applicationProperties.getBaseUrl() + String.format("/papers/paper?id=%s", paperId));
Assert.assertTrue(paperPage.deadlineExist(testDesc, testDateResult));
}
@Test
public void noDeadlinesValidationTest() {
getContext().goTo(applicationProperties.getBaseUrl() + getPaperPageUrl());
PaperPage paperPage = getPaperPage();
String testTitle = "test " + (String.valueOf(System.currentTimeMillis()));
paperPage.setTitle(testTitle);
paperPage.clickSaveBtn();
Assert.assertTrue(paperPage.hasAlert("Не может быть пустым"));
}
private void fillRequiredFields(PaperPage paperPage, String title) {
paperPage.setTitle(title);
String testDate = "01.01.2019";
String testDesc = "desc";
Integer deadlineNumber = 1;
paperPage.setDeadlineDate(deadlineNumber, testDate);
paperPage.setDeadlineDescription(deadlineNumber, testDesc);
}
@Test
public void addReferenceTest() {
createNewPaper();
getContext().goTo(applicationProperties.getBaseUrl() + getPapersPageUrl());
PapersPage papersPage = getPapersPage();
papersPage.clickFirstPaper();
PaperPage paperPage = getPaperPage();
fillRequiredFields(paperPage, "test " + (String.valueOf(System.currentTimeMillis())));
paperPage.clickReferenceTab();
paperPage.clickAddReferenceButton();
paperPage.clickReferenceTab();
paperPage.showFirstReference();
String authors = "testAuthors";
paperPage.setFirstReferenceAuthors(authors);
String paperId = paperPage.getId();
paperPage.clickSaveBtn();
getContext().goTo(applicationProperties.getBaseUrl() + String.format("/papers/paper?id=%s", paperId));
Assert.assertTrue(paperPage.authorsExists(authors));
}
@Test
public void referencesFormatTest() {
getContext().goTo(applicationProperties.getBaseUrl() + getPaperPageUrl());
PaperPage paperPage = getPaperPage();
paperPage.setTitle("test");
paperPage.clickReferenceTab();
paperPage.clickAddReferenceButton();
paperPage.clickReferenceTab();
paperPage.showFirstReference();
paperPage.setFirstReferenceAuthors("authors");
paperPage.setFirstReferencePublicationTitle("title");
paperPage.setFirstReferencePublicationYear("2010");
paperPage.setFirstReferencePublisher("publisher");
paperPage.setFirstReferencePages("200");
paperPage.setFirstReferenceJournalOrCollectionTitle("journal");
paperPage.setFormatStandardSpringer();
paperPage.clickFormatButton();
Assert.assertEquals("authors (2010) title. journal, publisher, pp 200", paperPage.getFormatString());
}
@Test
public void dashboardLinkTest() {
getContext().goTo(applicationProperties.getBaseUrl() + getPaperPageUrl());
PaperPage paperPage = getPaperPage();
fillRequiredFields(paperPage, "test " + (String.valueOf(System.currentTimeMillis())));
String testLink = "http://test.com/";
paperPage.setUrl(testLink);
paperPage.clickSaveBtn();
getContext().goTo(applicationProperties.getBaseUrl() + getPapersDashboardPageUrl());
PapersDashboardPage papersDashboardPage = getPapersDashboardPage();
Assert.assertTrue(papersDashboardPage.externalLinkExists(testLink));
}
@Test
public void deletePaperTest() {
createNewPaper();
getContext().goTo(applicationProperties.getBaseUrl() + getPapersPageUrl());
PapersPage papersPage = getPapersPage();
int size = papersPage.getPapersCount();
papersPage.clickRemoveFirstPaperButton();
papersPage.clickConfirmDeleteButton();
Assert.assertEquals(size - 1, papersPage.getPapersCount());
}
@Test
public void latexValidationTest() {
getContext().goTo(applicationProperties.getBaseUrl() + getPaperPageUrl());
PaperPage paperPage = getPaperPage();
paperPage.setTitle("test");
paperPage.clickLatexTab();
paperPage.setLatexText("test");
paperPage.clickPdfButton();
Assert.assertTrue(paperPage.dangerMessageExist("Ошибка при создании PDF"));
}
@Test
public void titleValidationTest() {
getContext().goTo(applicationProperties.getBaseUrl() + getPaperPageUrl());
PaperPage paperPage = getPaperPage();
paperPage.clickSaveBtn();
Assert.assertTrue(paperPage.hasAlert("не может быть пусто"));
}
}

View File

@ -0,0 +1,174 @@
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import core.PageObject;
import core.TestTemplate;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import project.ProjectDashboard;
import project.ProjectPage;
import project.ProjectsPage;
import ru.ulstu.NgTrackerApplication;
import ru.ulstu.configuration.ApplicationProperties;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
@RunWith(SpringRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@SpringBootTest(classes = NgTrackerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class ProjectTest extends TestTemplate {
private final Map<PageObject, List<String>> navigationHolder = ImmutableMap.of(
new ProjectPage(), Arrays.asList("ПРОЕКТЫ", "/projects/projects"),
new ProjectsPage(), Arrays.asList("РЕДАКТИРОВАНИЕ ПРОЕКТА", "/projects/project?id=0"),
new ProjectDashboard(), Arrays.asList("ПРОЕКТЫ", "/projects/dashboard")
);
@Autowired
private ApplicationProperties applicationProperties;
@Test
public void testACreateNewProject() {
Map.Entry<PageObject, List<String>> page = Iterables.get(navigationHolder.entrySet(), 1);
getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1));
ProjectsPage projectsPage = (ProjectsPage) getContext().initPage(page.getKey());
ProjectPage projectPage = (ProjectPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 0).getKey());
String name = "Project " + (new Date()).getTime();
String date = "01.01.2019";
Integer deadNum = projectPage.getDeadlineCount();
projectPage.setName(name);
projectPage.clickAddDeadline();
projectPage.addDeadlineDate(date, deadNum);
projectPage.clickSave();
Assert.assertTrue(projectsPage.checkNameInList(name));
}
@Test
public void testBChangeNameAndSave() {
Map.Entry<PageObject, List<String>> page = Iterables.get(navigationHolder.entrySet(), 0);
getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1));
ProjectPage projectPage = (ProjectPage) getContext().initPage(page.getKey());
ProjectsPage projectsPage = (ProjectsPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey());
projectsPage.getFirstProject();
String name = "Project " + (new Date()).getTime();
projectPage.clearName();
projectPage.setName(name);
projectPage.clickSave();
Assert.assertTrue(projectsPage.checkNameInList(name));
}
@Test
public void testCChangeDeadlineAndSave() {
Map.Entry<PageObject, List<String>> page = Iterables.get(navigationHolder.entrySet(), 0);
getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1));
ProjectPage projectPage = (ProjectPage) getContext().initPage(page.getKey());
ProjectsPage projectsPage = (ProjectsPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey());
projectsPage.getFirstProject();
String name = projectPage.getName();
String date = "01.01.2019";
Integer deadNum = projectPage.getDeadlineCount();
projectPage.addDeadlineDate(date, deadNum);
projectPage.clickSave();
Assert.assertTrue(projectsPage.checkNameInList(name));
}
@Test
public void testDSetStatusAndSave() {
Map.Entry<PageObject, List<String>> page = Iterables.get(navigationHolder.entrySet(), 0);
getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1));
ProjectPage projectPage = (ProjectPage) getContext().initPage(page.getKey());
ProjectsPage projectsPage = (ProjectsPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey());
projectsPage.getFirstProject();
String name = projectPage.getName();
projectPage.setStatus();
projectPage.clickSave();
Assert.assertTrue(projectsPage.checkNameInList(name));
}
@Test
public void testEAddDescriptionAndSave() {
Map.Entry<PageObject, List<String>> page = Iterables.get(navigationHolder.entrySet(), 0);
getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1));
ProjectPage projectPage = (ProjectPage) getContext().initPage(page.getKey());
ProjectsPage projectsPage = (ProjectsPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey());
projectsPage.getFirstProject();
String name = projectPage.getName();
String description = "Description " + (new Date()).getTime();
projectPage.addDescription(description);
projectPage.clickSave();
Assert.assertTrue(projectsPage.checkNameInList(name));
}
@Test
public void testFAddLinkAndSave() {
Map.Entry<PageObject, List<String>> page = Iterables.get(navigationHolder.entrySet(), 0);
getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1));
ProjectPage projectPage = (ProjectPage) getContext().initPage(page.getKey());
ProjectsPage projectsPage = (ProjectsPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey());
projectsPage.getFirstProject();
String name = projectPage.getName();
String link = "Link " + (new Date()).getTime();
projectPage.addLink(link);
projectPage.clickSave();
Assert.assertTrue(projectsPage.checkNameInList(name));
}
@Test
public void testGAddDeadlineDescriptionAndSave() {
Map.Entry<PageObject, List<String>> page = Iterables.get(navigationHolder.entrySet(), 0);
getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1));
ProjectPage projectPage = (ProjectPage) getContext().initPage(page.getKey());
ProjectsPage projectsPage = (ProjectsPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey());
projectsPage.getFirstProject();
String name = projectPage.getName();
String deadDesc = "Description " + (new Date()).getTime();
projectPage.addDeadlineDescription(deadDesc);
projectPage.clickSave();
Assert.assertTrue(projectsPage.checkNameInList(name));
}
@Test
public void testHSetDeadlineCompletionAndSave() {
Map.Entry<PageObject, List<String>> page = Iterables.get(navigationHolder.entrySet(), 0);
getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1));
ProjectPage projectPage = (ProjectPage) getContext().initPage(page.getKey());
ProjectsPage projectsPage = (ProjectsPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey());
projectsPage.getFirstProject();
String name = projectPage.getName();
projectPage.setDeadlineCompletion();
projectPage.clickSave();
Assert.assertTrue(projectsPage.checkNameInList(name));
}
@Test
public void testIDeleteDeadline() {
Map.Entry<PageObject, List<String>> page = Iterables.get(navigationHolder.entrySet(), 0);
getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1));
ProjectPage projectPage = (ProjectPage) getContext().initPage(page.getKey());
ProjectsPage projectsPage = (ProjectsPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey());
projectsPage.getFirstProject();
projectPage.clickDeleteDeadline();
Assert.assertTrue(projectPage.getDeadlineCount() == 0);
}
@Test
public void testJDeleteProject() {
Map.Entry<PageObject, List<String>> page = Iterables.get(navigationHolder.entrySet(), 0);
getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1));
ProjectPage projectPage = (ProjectPage) getContext().initPage(page.getKey());
ProjectsPage projectsPage = (ProjectsPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 1).getKey());
projectsPage.getFirstProject();
String name = projectPage.getName();
projectPage.clickSave();
projectsPage.deleteFirst();
projectsPage.clickConfirm();
Assert.assertFalse(projectsPage.checkNameInList(name));
}
}

View File

@ -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<PageObject, List<String>> 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<PageObject, List<String>> 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<PageObject, List<String>> 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<PageObject, List<String>> 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<PageObject, List<String>> 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<PageObject, List<String>> 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<PageObject, List<String>> 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<PageObject, List<String>> 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<PageObject, List<String>> 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<PageObject, List<String>> 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<PageObject, List<String>> 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());
}
}

View File

@ -2,16 +2,24 @@ package core;
import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.WebDriverWait;
public abstract class PageObject { public abstract class PageObject {
protected WebDriver driver; protected WebDriver driver;
protected JavascriptExecutor js; protected JavascriptExecutor js;
protected WebDriverWait waiter;
public abstract String getSubTitle(); public abstract String getSubTitle();
public PageObject setDriver(WebDriver driver) { public PageObject setDriver(WebDriver driver) {
this.driver = driver; this.driver = driver;
js = (JavascriptExecutor) driver; js = (JavascriptExecutor) driver;
waiter = new WebDriverWait(driver, 10);
return this; return this;
} }
public void initElements() {
PageFactory.initElements(driver, this);
}
} }

Some files were not shown because too many files have changed in this diff Show More