From 8fbce550286d4dcd6ba02dce5104690653f8cdfd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=92=D0=B0=D1=81=D0=B8=D0=BD=20=D0=90=D0=BD=D1=82=D0=BE?= =?UTF-8?q?=D0=BD?= Date: Wed, 17 Apr 2019 11:04:35 +0300 Subject: [PATCH 01/74] #86 projects main page --- .../project/controller/ProjectController.java | 39 +++++++++++++++++++ .../ulstu/project/service/ProjectService.java | 9 +++++ src/main/resources/templates/index.html | 2 +- .../templates/projects/dashboard.html | 24 ++++++++++++ .../fragments/projectNavigationFragment.html | 26 +++++++++++++ .../templates/projects/projects.html | 33 ++++++++++++++++ 6 files changed, 132 insertions(+), 1 deletion(-) create mode 100644 src/main/java/ru/ulstu/project/controller/ProjectController.java create mode 100644 src/main/resources/templates/projects/dashboard.html create mode 100644 src/main/resources/templates/projects/fragments/projectNavigationFragment.html create mode 100644 src/main/resources/templates/projects/projects.html diff --git a/src/main/java/ru/ulstu/project/controller/ProjectController.java b/src/main/java/ru/ulstu/project/controller/ProjectController.java new file mode 100644 index 0000000..5b5eb4a --- /dev/null +++ b/src/main/java/ru/ulstu/project/controller/ProjectController.java @@ -0,0 +1,39 @@ +package ru.ulstu.project.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.validation.Errors; +import org.springframework.web.bind.annotation.*; +import ru.ulstu.deadline.model.Deadline; +import ru.ulstu.project.model.Project; +import ru.ulstu.project.model.ProjectDto; +import ru.ulstu.project.service.ProjectService; +import springfox.documentation.annotations.ApiIgnore; + +import javax.validation.Valid; +import java.io.IOException; +import java.util.List; +import java.util.stream.Collectors; + +import static liquibase.util.StringUtils.isEmpty; + +@Controller() +@RequestMapping(value = "/projects") +@ApiIgnore +public class ProjectController { + private final ProjectService projectService; + + public ProjectController(ProjectService projectService) { + this.projectService = projectService; + } + + @GetMapping("/dashboard") + public void getDashboard(ModelMap modelMap) { + modelMap.put("projects", projectService.findAllDto()); + } + + @GetMapping("/projects") + public void getProjects(ModelMap modelMap) { + modelMap.put("projects", projectService.findAllDto()); + } +} diff --git a/src/main/java/ru/ulstu/project/service/ProjectService.java b/src/main/java/ru/ulstu/project/service/ProjectService.java index b54a60a..78a9d3c 100644 --- a/src/main/java/ru/ulstu/project/service/ProjectService.java +++ b/src/main/java/ru/ulstu/project/service/ProjectService.java @@ -2,6 +2,7 @@ package ru.ulstu.project.service; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.thymeleaf.util.StringUtils; import ru.ulstu.deadline.service.DeadlineService; import ru.ulstu.project.model.Project; import ru.ulstu.project.model.ProjectDto; @@ -10,9 +11,11 @@ import ru.ulstu.project.repository.ProjectRepository; import java.util.List; import static org.springframework.util.ObjectUtils.isEmpty; +import static ru.ulstu.core.util.StreamApiUtils.convert; @Service public class ProjectService { + private final static int MAX_DISPLAY_SIZE = 40; private final ProjectRepository projectRepository; private final DeadlineService deadlineService; @@ -27,6 +30,12 @@ public class ProjectService { return projectRepository.findAll(); } + public List findAllDto() { + List projects = convert(findAll(), ProjectDto::new); + projects.forEach(projectDto -> projectDto.setTitle(StringUtils.abbreviate(projectDto.getTitle(), MAX_DISPLAY_SIZE))); + return projects; + } + @Transactional public Project create(ProjectDto projectDto) { Project newProject = copyFromDto(new Project(), projectDto); diff --git a/src/main/resources/templates/index.html b/src/main/resources/templates/index.html index 2d86945..6ca1c12 100644 --- a/src/main/resources/templates/index.html +++ b/src/main/resources/templates/index.html @@ -46,7 +46,7 @@
- +
diff --git a/src/main/resources/templates/projects/dashboard.html b/src/main/resources/templates/projects/dashboard.html new file mode 100644 index 0000000..882c202 --- /dev/null +++ b/src/main/resources/templates/projects/dashboard.html @@ -0,0 +1,24 @@ + + + + + +
+
+
+
+

Проекты

+
+
+
+ +
+ +
+
+
+
+ + \ No newline at end of file diff --git a/src/main/resources/templates/projects/fragments/projectNavigationFragment.html b/src/main/resources/templates/projects/fragments/projectNavigationFragment.html new file mode 100644 index 0000000..c26d8b8 --- /dev/null +++ b/src/main/resources/templates/projects/fragments/projectNavigationFragment.html @@ -0,0 +1,26 @@ + + + + + + +
+ + \ No newline at end of file diff --git a/src/main/resources/templates/projects/projects.html b/src/main/resources/templates/projects/projects.html new file mode 100644 index 0000000..0336770 --- /dev/null +++ b/src/main/resources/templates/projects/projects.html @@ -0,0 +1,33 @@ + + + + + +
+
+ +
+
+
+
+

Проекты

+
+
+
+
+
+ +
+ +
+
+
+
+
+
+
+
+ + From ee55e08feee4ea20dfa52403996f0659cd42f1d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=92=D0=B0=D1=81=D0=B8=D0=BD=20=D0=90=D0=BD=D1=82=D0=BE?= =?UTF-8?q?=D0=BD?= Date: Mon, 6 May 2019 17:43:20 +0300 Subject: [PATCH 02/74] #98 project tasks deadline edited --- .../conference/service/ConferenceService.java | 3 +- .../ru/ulstu/deadline/model/Deadline.java | 35 ++++++++++++++++--- .../ru/ulstu/grant/service/GrantService.java | 2 +- .../ru/ulstu/paper/service/PaperService.java | 2 +- .../project/controller/ProjectController.java | 7 ++++ .../ru/ulstu/project/model/ProjectDto.java | 9 +++++ .../ulstu/project/service/ProjectService.java | 7 ++++ .../db/changelog-20190506_000000-schema.xml | 13 +++++++ src/main/resources/db/changelog-master.xml | 1 + .../resources/templates/projects/project.html | 8 +++-- 10 files changed, 78 insertions(+), 9 deletions(-) create mode 100644 src/main/resources/db/changelog-20190506_000000-schema.xml diff --git a/src/main/java/ru/ulstu/conference/service/ConferenceService.java b/src/main/java/ru/ulstu/conference/service/ConferenceService.java index 38de435..b42f981 100644 --- a/src/main/java/ru/ulstu/conference/service/ConferenceService.java +++ b/src/main/java/ru/ulstu/conference/service/ConferenceService.java @@ -267,7 +267,8 @@ public class ConferenceService { } public Deadline copyDeadline(Deadline oldDeadline) { - Deadline newDeadline = new Deadline(oldDeadline.getDate(), oldDeadline.getDescription()); + Deadline newDeadline = new Deadline(oldDeadline.getDate(), oldDeadline.getDescription(), + oldDeadline.getExecutor(), oldDeadline.getDone()); newDeadline.setId(oldDeadline.getId()); return newDeadline; } diff --git a/src/main/java/ru/ulstu/deadline/model/Deadline.java b/src/main/java/ru/ulstu/deadline/model/Deadline.java index 148697c..9ab9acd 100644 --- a/src/main/java/ru/ulstu/deadline/model/Deadline.java +++ b/src/main/java/ru/ulstu/deadline/model/Deadline.java @@ -20,21 +20,30 @@ public class Deadline extends BaseEntity { @DateTimeFormat(pattern = "yyyy-MM-dd") private Date date; + private String executor; + private Boolean done; + public Deadline() { } - public Deadline(Date deadlineDate, String description) { + public Deadline(Date deadlineDate, String description, String executor, Boolean done) { this.date = deadlineDate; this.description = description; + this.executor = executor; + this.done = done; } @JsonCreator public Deadline(@JsonProperty("id") Integer id, @JsonProperty("description") String description, - @JsonProperty("date") Date date) { + @JsonProperty("date") Date date, + @JsonProperty("executor") String executor, + @JsonProperty("done") Boolean done) { this.setId(id); this.description = description; this.date = date; + this.executor = executor; + this.done = done; } public String getDescription() { @@ -53,6 +62,22 @@ public class Deadline extends BaseEntity { this.date = date; } + public String getExecutor() { + return executor; + } + + public void setExecutor(String executor) { + this.executor = executor; + } + + public Boolean getDone() { + return done; + } + + public void setDone(Boolean done) { + this.done = done; + } + @Override public boolean equals(Object o) { if (this == o) { @@ -67,11 +92,13 @@ public class Deadline extends BaseEntity { Deadline deadline = (Deadline) o; return getId().equals(deadline.getId()) && description.equals(deadline.description) && - date.equals(deadline.date); + date.equals(deadline.date) && + executor.equals(deadline.executor) && + done.equals(deadline.done); } @Override public int hashCode() { - return Objects.hash(super.hashCode(), description, date); + return Objects.hash(super.hashCode(), description, date, executor, done); } } diff --git a/src/main/java/ru/ulstu/grant/service/GrantService.java b/src/main/java/ru/ulstu/grant/service/GrantService.java index 9cff4b6..0837b49 100644 --- a/src/main/java/ru/ulstu/grant/service/GrantService.java +++ b/src/main/java/ru/ulstu/grant/service/GrantService.java @@ -141,7 +141,7 @@ public class GrantService { grant.setComment("Комментарий к гранту 1"); grant.setProject(projectId); grant.setStatus(APPLICATION); - grant.getDeadlines().add(new Deadline(deadlineDate, "первый дедлайн")); + grant.getDeadlines().add(new Deadline(deadlineDate, "первый дедлайн", "", false)); grant.getAuthors().add(user); grant.setLeader(user); grant.getPapers().add(paper); diff --git a/src/main/java/ru/ulstu/paper/service/PaperService.java b/src/main/java/ru/ulstu/paper/service/PaperService.java index f98997d..1188c28 100644 --- a/src/main/java/ru/ulstu/paper/service/PaperService.java +++ b/src/main/java/ru/ulstu/paper/service/PaperService.java @@ -173,7 +173,7 @@ public class PaperService { Paper paper = new Paper(); paper.setTitle(title); paper.getAuthors().add(user); - paper.getDeadlines().add(new Deadline(deadlineDate, "первый дедлайн")); + paper.getDeadlines().add(new Deadline(deadlineDate, "первый дедлайн", "", false)); paper.setCreateDate(new Date()); paper.setUpdateDate(new Date()); paper.setStatus(DRAFT); diff --git a/src/main/java/ru/ulstu/project/controller/ProjectController.java b/src/main/java/ru/ulstu/project/controller/ProjectController.java index ae09658..14b8736 100644 --- a/src/main/java/ru/ulstu/project/controller/ProjectController.java +++ b/src/main/java/ru/ulstu/project/controller/ProjectController.java @@ -79,6 +79,13 @@ public class ProjectController { return "/projects/project"; } + @PostMapping(value = "/project", params = "removeDeadline") + public String removeDeadline(ProjectDto projectDto, + @RequestParam(value = "removeDeadline") Integer deadlineId) { + projectService.removeDeadline(projectDto, deadlineId); + return "/projects/project"; + } + @GetMapping("/delete/{project-id}") public String delete(@PathVariable("project-id") Integer projectId) throws IOException { projectService.delete(projectId); diff --git a/src/main/java/ru/ulstu/project/model/ProjectDto.java b/src/main/java/ru/ulstu/project/model/ProjectDto.java index 4e03365..319609c 100644 --- a/src/main/java/ru/ulstu/project/model/ProjectDto.java +++ b/src/main/java/ru/ulstu/project/model/ProjectDto.java @@ -20,6 +20,7 @@ public class ProjectDto { private GrantDto grant; private String repository; private String applicationFileName; + private List removedDeadlineIds = new ArrayList<>(); public ProjectDto() { } @@ -121,4 +122,12 @@ public class ProjectDto { public void setApplicationFileName(String applicationFileName) { this.applicationFileName = applicationFileName; } + + public List getRemovedDeadlineIds() { + return removedDeadlineIds; + } + + public void setRemovedDeadlineIds(List removedDeadlineIds) { + this.removedDeadlineIds = removedDeadlineIds; + } } diff --git a/src/main/java/ru/ulstu/project/service/ProjectService.java b/src/main/java/ru/ulstu/project/service/ProjectService.java index 247624d..4a79e6c 100644 --- a/src/main/java/ru/ulstu/project/service/ProjectService.java +++ b/src/main/java/ru/ulstu/project/service/ProjectService.java @@ -104,6 +104,13 @@ public class ProjectService { } } + public void removeDeadline(ProjectDto projectDto, Integer deadlineId) { + if (projectDto.getDeadlines().get(deadlineId).getId() != null) { + projectDto.getRemovedDeadlineIds().add(projectDto.getDeadlines().get(deadlineId).getId()); + } + projectDto.getDeadlines().remove((int) deadlineId); + } + public Project findById(Integer id) { return projectRepository.findOne(id); } diff --git a/src/main/resources/db/changelog-20190506_000000-schema.xml b/src/main/resources/db/changelog-20190506_000000-schema.xml new file mode 100644 index 0000000..cd5a59b --- /dev/null +++ b/src/main/resources/db/changelog-20190506_000000-schema.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + diff --git a/src/main/resources/db/changelog-master.xml b/src/main/resources/db/changelog-master.xml index 83ff280..3b455a8 100644 --- a/src/main/resources/db/changelog-master.xml +++ b/src/main/resources/db/changelog-master.xml @@ -38,4 +38,5 @@ + \ No newline at end of file diff --git a/src/main/resources/templates/projects/project.html b/src/main/resources/templates/projects/project.html index dc3fa6d..cd49319 100644 --- a/src/main/resources/templates/projects/project.html +++ b/src/main/resources/templates/projects/project.html @@ -73,14 +73,18 @@
-
+
-
+
+
+ +
-
+
-
+
-
+
-
- -
+
+
+
+ +
+
+
From 4025aa67ca1720d75cdda18dcf4221868470f162 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=92=D0=B0=D1=81=D0=B8=D0=BD=20=D0=90=D0=BD=D1=82=D0=BE?= =?UTF-8?q?=D0=BD?= Date: Mon, 6 May 2019 21:51:58 +0300 Subject: [PATCH 04/74] #98 project completion added --- .../java/ru/ulstu/project/model/Project.java | 16 ++++++++ .../ru/ulstu/project/model/ProjectDto.java | 41 ++++++++++++++++++- .../db/changelog-20190506_000001-schema.xml | 17 ++++++++ src/main/resources/db/changelog-master.xml | 1 + src/main/resources/public/css/project.css | 5 +++ .../resources/templates/projects/project.html | 15 +++---- 6 files changed, 87 insertions(+), 8 deletions(-) create mode 100644 src/main/resources/db/changelog-20190506_000001-schema.xml create mode 100644 src/main/resources/public/css/project.css diff --git a/src/main/java/ru/ulstu/project/model/Project.java b/src/main/java/ru/ulstu/project/model/Project.java index c971c4b..acf0d0f 100644 --- a/src/main/java/ru/ulstu/project/model/Project.java +++ b/src/main/java/ru/ulstu/project/model/Project.java @@ -5,17 +5,22 @@ import ru.ulstu.core.model.BaseEntity; import ru.ulstu.deadline.model.Deadline; import ru.ulstu.file.model.FileData; import ru.ulstu.grant.model.Grant; +import ru.ulstu.user.model.User; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; +import javax.persistence.FetchType; import javax.persistence.JoinColumn; +import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.validation.constraints.NotNull; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; +import java.util.Set; @Entity public class Project extends BaseEntity { @@ -62,6 +67,9 @@ public class Project extends BaseEntity { @JoinColumn(name = "file_id") private FileData application; + @ManyToMany(fetch = FetchType.EAGER) + private Set executors = new HashSet<>(); + public String getTitle() { return title; } @@ -117,4 +125,12 @@ public class Project extends BaseEntity { public void setApplication(FileData application) { this.application = application; } + + public Set getExecutors() { + return executors; + } + + public void setExecutors(Set executors) { + this.executors = executors; + } } diff --git a/src/main/java/ru/ulstu/project/model/ProjectDto.java b/src/main/java/ru/ulstu/project/model/ProjectDto.java index 319609c..0f86e1a 100644 --- a/src/main/java/ru/ulstu/project/model/ProjectDto.java +++ b/src/main/java/ru/ulstu/project/model/ProjectDto.java @@ -3,11 +3,17 @@ package ru.ulstu.project.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import org.hibernate.validator.constraints.NotEmpty; +import org.thymeleaf.util.StringUtils; import ru.ulstu.deadline.model.Deadline; import ru.ulstu.grant.model.GrantDto; +import ru.ulstu.user.model.UserDto; import java.util.ArrayList; import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import static ru.ulstu.core.util.StreamApiUtils.convert; public class ProjectDto { private Integer id; @@ -21,6 +27,10 @@ public class ProjectDto { private String repository; private String applicationFileName; private List removedDeadlineIds = new ArrayList<>(); + private Set executorIds; + private Set executors; + + private final static int MAX_EXECUTORS_LENGTH = 40; public ProjectDto() { } @@ -36,7 +46,9 @@ public class ProjectDto { @JsonProperty("description") String description, @JsonProperty("grant") GrantDto grant, @JsonProperty("repository") String repository, - @JsonProperty("deadlines") List deadlines) { + @JsonProperty("deadlines") List deadlines, + @JsonProperty("executorIds") Set executorIds, + @JsonProperty("executors") Set executors) { this.id = id; this.title = title; this.status = status; @@ -45,6 +57,8 @@ public class ProjectDto { this.repository = repository; this.deadlines = deadlines; this.applicationFileName = null; + this.executorIds = executorIds; + this.executors = executors; } @@ -57,6 +71,8 @@ public class ProjectDto { this.grant = project.getGrant() == null ? null : new GrantDto(project.getGrant()); this.repository = project.getRepository(); this.deadlines = project.getDeadlines(); + this.executorIds = convert(project.getExecutors(), user -> user.getId()); + this.executors = convert(project.getExecutors(), UserDto::new); } public Integer getId() { @@ -130,4 +146,27 @@ public class ProjectDto { public void setRemovedDeadlineIds(List removedDeadlineIds) { this.removedDeadlineIds = removedDeadlineIds; } + + public Set getExecutorIds() { + return executorIds; + } + + public void setExecutorIds(Set executorIds) { + this.executorIds = executorIds; + } + + public Set getExecutors() { + return executors; + } + + public void setExecutors(Set executors) { + this.executors = executors; + } + + public String getExecutorsString() { + return StringUtils.abbreviate(executors + .stream() + .map(executor -> executor.getLastName()) + .collect(Collectors.joining(", ")), MAX_EXECUTORS_LENGTH); + } } diff --git a/src/main/resources/db/changelog-20190506_000001-schema.xml b/src/main/resources/db/changelog-20190506_000001-schema.xml new file mode 100644 index 0000000..e28d009 --- /dev/null +++ b/src/main/resources/db/changelog-20190506_000001-schema.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + diff --git a/src/main/resources/db/changelog-master.xml b/src/main/resources/db/changelog-master.xml index 3b455a8..051c953 100644 --- a/src/main/resources/db/changelog-master.xml +++ b/src/main/resources/db/changelog-master.xml @@ -39,4 +39,5 @@ + \ No newline at end of file diff --git a/src/main/resources/public/css/project.css b/src/main/resources/public/css/project.css new file mode 100644 index 0000000..24e12ea --- /dev/null +++ b/src/main/resources/public/css/project.css @@ -0,0 +1,5 @@ +.div-deadline-done { + width: 60%; + height: 100%; + float: right; +} \ No newline at end of file diff --git a/src/main/resources/templates/projects/project.html b/src/main/resources/templates/projects/project.html index 2a0b7cf..8385694 100644 --- a/src/main/resources/templates/projects/project.html +++ b/src/main/resources/templates/projects/project.html @@ -3,7 +3,7 @@ xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorator="default" xmlns:th="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/html"> - + @@ -90,17 +90,18 @@ aria-hidden="true">
-
-

Incorrect title

-
-
-
+
+
+ +
+

Incorrect title

Date: Mon, 6 May 2019 22:10:40 +0300 Subject: [PATCH 05/74] #98 deadline edited --- src/main/java/ru/ulstu/deadline/model/Deadline.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/ru/ulstu/deadline/model/Deadline.java b/src/main/java/ru/ulstu/deadline/model/Deadline.java index 5a05ea1..9ab9acd 100644 --- a/src/main/java/ru/ulstu/deadline/model/Deadline.java +++ b/src/main/java/ru/ulstu/deadline/model/Deadline.java @@ -66,7 +66,9 @@ public class Deadline extends BaseEntity { return executor; } - public void setExecutor(String executor) { this.executor = executor; } + public void setExecutor(String executor) { + this.executor = executor; + } public Boolean getDone() { return done; From b1e101c94036eb56b7d6c9d67667179433ae0c53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=92=D0=B0=D1=81=D0=B8=D0=BD=20=D0=90=D0=BD=D1=82=D0=BE?= =?UTF-8?q?=D0=BD?= Date: Tue, 7 May 2019 13:34:00 +0300 Subject: [PATCH 06/74] #101 db event edited --- .../db/changelog-20190507_000000-schema.xml | 14 ++++++++++++++ src/main/resources/db/changelog-master.xml | 1 + 2 files changed, 15 insertions(+) create mode 100644 src/main/resources/db/changelog-20190507_000000-schema.xml diff --git a/src/main/resources/db/changelog-20190507_000000-schema.xml b/src/main/resources/db/changelog-20190507_000000-schema.xml new file mode 100644 index 0000000..6962e7d --- /dev/null +++ b/src/main/resources/db/changelog-20190507_000000-schema.xml @@ -0,0 +1,14 @@ + + + + + + + + + + diff --git a/src/main/resources/db/changelog-master.xml b/src/main/resources/db/changelog-master.xml index 83ff280..65a07c2 100644 --- a/src/main/resources/db/changelog-master.xml +++ b/src/main/resources/db/changelog-master.xml @@ -38,4 +38,5 @@ + \ No newline at end of file From 279cc0e18a876ee6bf70fc06087680162cbd45ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=92=D0=B0=D1=81=D0=B8=D0=BD=20=D0=90=D0=BD=D1=82=D0=BE?= =?UTF-8?q?=D0=BD?= Date: Tue, 7 May 2019 14:00:24 +0300 Subject: [PATCH 07/74] #101 project model edited --- src/main/java/ru/ulstu/project/model/Project.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/main/java/ru/ulstu/project/model/Project.java b/src/main/java/ru/ulstu/project/model/Project.java index c971c4b..a596b76 100644 --- a/src/main/java/ru/ulstu/project/model/Project.java +++ b/src/main/java/ru/ulstu/project/model/Project.java @@ -5,11 +5,13 @@ import ru.ulstu.core.model.BaseEntity; import ru.ulstu.deadline.model.Deadline; import ru.ulstu.file.model.FileData; import ru.ulstu.grant.model.Grant; +import ru.ulstu.timeline.model.Event; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; +import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; @@ -62,6 +64,10 @@ public class Project extends BaseEntity { @JoinColumn(name = "file_id") private FileData application; + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) + @JoinColumn(name = "project_id") + private List events = new ArrayList<>(); + public String getTitle() { return title; } @@ -117,4 +123,12 @@ public class Project extends BaseEntity { public void setApplication(FileData application) { this.application = application; } + + public List getEvents() { + return events; + } + + public void setEvents(List events) { + this.events = events; + } } From f960d4de1b78cd9a8cd01ea43bdd6304fcc7d844 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=92=D0=B0=D1=81=D0=B8=D0=BD=20=D0=90=D0=BD=D1=82=D0=BE?= =?UTF-8?q?=D0=BD?= Date: Fri, 17 May 2019 11:30:26 +0300 Subject: [PATCH 08/74] #98 deadline model edited --- src/main/java/ru/ulstu/deadline/model/Deadline.java | 5 +++++ src/main/java/ru/ulstu/grant/service/GrantService.java | 2 +- src/main/java/ru/ulstu/paper/service/PaperService.java | 2 +- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/main/java/ru/ulstu/deadline/model/Deadline.java b/src/main/java/ru/ulstu/deadline/model/Deadline.java index 9ab9acd..5ab9f47 100644 --- a/src/main/java/ru/ulstu/deadline/model/Deadline.java +++ b/src/main/java/ru/ulstu/deadline/model/Deadline.java @@ -26,6 +26,11 @@ public class Deadline extends BaseEntity { public Deadline() { } + public Deadline(Date deadlineDate, String description) { + this.date = deadlineDate; + this.description = description; + } + public Deadline(Date deadlineDate, String description, String executor, Boolean done) { this.date = deadlineDate; this.description = description; diff --git a/src/main/java/ru/ulstu/grant/service/GrantService.java b/src/main/java/ru/ulstu/grant/service/GrantService.java index c06a71c..45f9b2f 100644 --- a/src/main/java/ru/ulstu/grant/service/GrantService.java +++ b/src/main/java/ru/ulstu/grant/service/GrantService.java @@ -164,7 +164,7 @@ public class GrantService { grant.setComment("Комментарий к гранту 1"); grant.setProject(projectId); grant.setStatus(APPLICATION); - grant.getDeadlines().add(new Deadline(deadlineDate, "первый дедлайн", "", false)); + grant.getDeadlines().add(new Deadline(deadlineDate, "первый дедлайн")); grant.getAuthors().add(user); grant.setLeader(user); grant.getPapers().add(paper); diff --git a/src/main/java/ru/ulstu/paper/service/PaperService.java b/src/main/java/ru/ulstu/paper/service/PaperService.java index 0a60c92..db810f5 100644 --- a/src/main/java/ru/ulstu/paper/service/PaperService.java +++ b/src/main/java/ru/ulstu/paper/service/PaperService.java @@ -173,7 +173,7 @@ public class PaperService { Paper paper = new Paper(); paper.setTitle(title); paper.getAuthors().add(user); - paper.getDeadlines().add(new Deadline(deadlineDate, "первый дедлайн", "", false)); + paper.getDeadlines().add(new Deadline(deadlineDate, "первый дедлайн")); paper.setCreateDate(new Date()); paper.setUpdateDate(new Date()); paper.setStatus(DRAFT); From 90799356abb70d879df883f4000c9b876b29e44a Mon Sep 17 00:00:00 2001 From: "Artem.Arefev" Date: Sun, 19 May 2019 00:42:24 +0400 Subject: [PATCH 09/74] 89 password reset --- .../ru/ulstu/configuration/Constants.java | 1 + .../configuration/SecurityConfiguration.java | 3 +- .../core/controller/AdviceController.java | 10 +- .../ru/ulstu/core/model/ErrorConstants.java | 4 +- .../ulstu/user/controller/UserController.java | 11 +-- .../user/model/UserResetPasswordDto.java | 8 ++ .../ru/ulstu/user/service/MailService.java | 4 +- .../ru/ulstu/user/service/UserService.java | 19 ++-- .../mail_templates/passwordResetEmail.html | 12 +-- src/main/resources/public/css/base.css | 3 + .../resources/public/img/main/ajax-loader.gif | Bin 0 -> 673 bytes src/main/resources/public/js/users.js | 78 +++++++++++++++- .../resources/templates/resetRequest.html | 86 +++++++++--------- 13 files changed, 162 insertions(+), 77 deletions(-) create mode 100644 src/main/resources/public/css/base.css create mode 100644 src/main/resources/public/img/main/ajax-loader.gif diff --git a/src/main/java/ru/ulstu/configuration/Constants.java b/src/main/java/ru/ulstu/configuration/Constants.java index f910108..77a9a4d 100644 --- a/src/main/java/ru/ulstu/configuration/Constants.java +++ b/src/main/java/ru/ulstu/configuration/Constants.java @@ -21,4 +21,5 @@ public class Constants { public static final String PASSWORD_RESET_REQUEST_PAGE = "/resetRequest"; public static final String PASSWORD_RESET_PAGE = "/reset"; + public static final int RESET_KEY_LENGTH = 6; } \ No newline at end of file diff --git a/src/main/java/ru/ulstu/configuration/SecurityConfiguration.java b/src/main/java/ru/ulstu/configuration/SecurityConfiguration.java index 591fa0c..894cf39 100644 --- a/src/main/java/ru/ulstu/configuration/SecurityConfiguration.java +++ b/src/main/java/ru/ulstu/configuration/SecurityConfiguration.java @@ -104,7 +104,8 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter { .antMatchers("/css/**") .antMatchers("/js/**") .antMatchers("/templates/**") - .antMatchers("/webjars/**"); + .antMatchers("/webjars/**") + .antMatchers("/img/**"); } @Autowired diff --git a/src/main/java/ru/ulstu/core/controller/AdviceController.java b/src/main/java/ru/ulstu/core/controller/AdviceController.java index 27c9d5b..37078b9 100644 --- a/src/main/java/ru/ulstu/core/controller/AdviceController.java +++ b/src/main/java/ru/ulstu/core/controller/AdviceController.java @@ -34,11 +34,11 @@ public class AdviceController { public AdviceController(UserService userService) { this.userService = userService; } - - @ModelAttribute("currentUser") - public String getCurrentUser() { - return userService.getCurrentUser().getUserAbbreviate(); - } +// +// @ModelAttribute("currentUser") +// public String getCurrentUser() { +// return userService.getCurrentUser().getUserAbbreviate(); +// } @ModelAttribute("flashMessage") public String getFlashMessage() { diff --git a/src/main/java/ru/ulstu/core/model/ErrorConstants.java b/src/main/java/ru/ulstu/core/model/ErrorConstants.java index 55832f3..017725a 100644 --- a/src/main/java/ru/ulstu/core/model/ErrorConstants.java +++ b/src/main/java/ru/ulstu/core/model/ErrorConstants.java @@ -9,9 +9,9 @@ public enum ErrorConstants { USER_EMAIL_EXISTS(102, "Пользователь с таким почтовым ящиком уже существует"), USER_LOGIN_EXISTS(103, "Пользователь с таким логином уже существует"), 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_RESET_ERROR(107, "Invalid reset key"), + USER_RESET_ERROR(107, "Некорректный ключ подтверждения"), USER_UNDEAD_ERROR(108, "Can't edit/delete that user"), FILE_UPLOAD_ERROR(110, "File upload error"), USER_SENDING_MAIL_EXCEPTION(111, "Во время отправки приглашения пользователю произошла ошибка"); diff --git a/src/main/java/ru/ulstu/user/controller/UserController.java b/src/main/java/ru/ulstu/user/controller/UserController.java index 59e023b..c40ed8f 100644 --- a/src/main/java/ru/ulstu/user/controller/UserController.java +++ b/src/main/java/ru/ulstu/user/controller/UserController.java @@ -148,16 +148,15 @@ public class UserController extends OdinController { } @PostMapping(PASSWORD_RESET_REQUEST_URL) - public Response requestPasswordReset(@RequestParam("email") String email) { + public void requestPasswordReset(@RequestParam("email") String email) { log.debug("REST: UserController.requestPasswordReset( {} )", email); - return new Response<>(userService.requestUserPasswordReset(email)); + userService.requestUserPasswordReset(email); } @PostMapping(PASSWORD_RESET_URL) - public Response finishPasswordReset(@RequestParam("key") String key, - @RequestBody UserResetPasswordDto userResetPasswordDto) { - log.debug("REST: UserController.requestPasswordReset( {} )", key); - return new Response<>(userService.completeUserPasswordReset(key, userResetPasswordDto)); + public Response finishPasswordReset(@RequestBody UserResetPasswordDto userResetPasswordDto) { + log.debug("REST: UserController.requestPasswordReset( {} )", userResetPasswordDto.getResetKey()); + return new Response<>(userService.completeUserPasswordReset(userResetPasswordDto)); } @PostMapping("/changePassword") diff --git a/src/main/java/ru/ulstu/user/model/UserResetPasswordDto.java b/src/main/java/ru/ulstu/user/model/UserResetPasswordDto.java index 33d84bc..58e7462 100644 --- a/src/main/java/ru/ulstu/user/model/UserResetPasswordDto.java +++ b/src/main/java/ru/ulstu/user/model/UserResetPasswordDto.java @@ -14,6 +14,10 @@ public class UserResetPasswordDto { @Size(min = Constants.MIN_PASSWORD_LENGTH, max = 50) private String passwordConfirm; + @NotEmpty + @Size(min = Constants.RESET_KEY_LENGTH) + private String resetKey; + public String getPassword() { return password; } @@ -25,4 +29,8 @@ public class UserResetPasswordDto { public boolean isPasswordsValid() { return Objects.equals(password, passwordConfirm); } + + public String getResetKey() { + return resetKey; + } } diff --git a/src/main/java/ru/ulstu/user/service/MailService.java b/src/main/java/ru/ulstu/user/service/MailService.java index ec91739..864b749 100644 --- a/src/main/java/ru/ulstu/user/service/MailService.java +++ b/src/main/java/ru/ulstu/user/service/MailService.java @@ -106,8 +106,7 @@ public class MailService { sendEmailFromTemplate(user, "activationEmail", Constants.MAIL_ACTIVATE); } - @Async - public void sendPasswordResetMail(User user) { + public void sendPasswordResetMail(User user) throws MessagingException, MailException { sendEmailFromTemplate(user, "passwordResetEmail", Constants.MAIL_RESET); } @@ -118,6 +117,5 @@ public class MailService { @Async public void sendChangePasswordMail(User user) { sendEmailFromTemplate(user, "passwordChangeEmail", Constants.MAIL_CHANGE_PASSWORD); - } } diff --git a/src/main/java/ru/ulstu/user/service/UserService.java b/src/main/java/ru/ulstu/user/service/UserService.java index c889caa..8089a8e 100644 --- a/src/main/java/ru/ulstu/user/service/UserService.java +++ b/src/main/java/ru/ulstu/user/service/UserService.java @@ -236,7 +236,7 @@ public class UserService implements UserDetailsService { mailService.sendChangePasswordMail(user); } - public boolean requestUserPasswordReset(String email) { + public boolean requestUserPasswordReset(String email) { User user = userRepository.findOneByEmailIgnoreCase(email); if (user == null) { throw new UserNotFoundException(email); @@ -247,23 +247,30 @@ public class UserService implements UserDetailsService { user.setResetKey(UserUtils.generateResetKey()); user.setResetDate(new Date()); user = userRepository.save(user); - mailService.sendPasswordResetMail(user); + try { + mailService.sendPasswordResetMail(user); + } catch (MessagingException | MailException e) { + throw new UserSendingMailException(email); + } log.debug("Created Reset Password Request for User: {}", user.getLogin()); return true; } - public boolean completeUserPasswordReset(String key, UserResetPasswordDto userResetPasswordDto) { + public boolean completeUserPasswordReset(UserResetPasswordDto userResetPasswordDto) { if (!userResetPasswordDto.isPasswordsValid()) { - throw new UserPasswordsNotValidOrNotMatchException(""); + throw new UserPasswordsNotValidOrNotMatchException("Пароли не совпадают"); } - User user = userRepository.findOneByResetKey(key); + User user = userRepository.findOneByResetKey(userResetPasswordDto.getResetKey()); if (user == null) { - throw new UserResetKeyError(key); + throw new UserResetKeyError(userResetPasswordDto.getResetKey()); } user.setPassword(passwordEncoder.encode(userResetPasswordDto.getPassword())); user.setResetKey(null); user.setResetDate(null); user = userRepository.save(user); + + mailService.sendChangePasswordMail(user); + log.debug("Reset Password for User: {}", user.getLogin()); return true; } diff --git a/src/main/resources/mail_templates/passwordResetEmail.html b/src/main/resources/mail_templates/passwordResetEmail.html index a1034d4..99e4f77 100644 --- a/src/main/resources/mail_templates/passwordResetEmail.html +++ b/src/main/resources/mail_templates/passwordResetEmail.html @@ -1,23 +1,19 @@ - Password reset + Восстановление пароля

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

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

- Reset Link -

-

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

diff --git a/src/main/resources/public/css/base.css b/src/main/resources/public/css/base.css new file mode 100644 index 0000000..0c69e7c --- /dev/null +++ b/src/main/resources/public/css/base.css @@ -0,0 +1,3 @@ +.loader { + padding-left:50% +} \ No newline at end of file diff --git a/src/main/resources/public/img/main/ajax-loader.gif b/src/main/resources/public/img/main/ajax-loader.gif new file mode 100644 index 0000000000000000000000000000000000000000..f2a1bc0c6f545e20e631a96e8e92f9822e75d046 GIT binary patch literal 673 zcmZ?wbhEHb6krfw_{6~Q|Nnmm28Kh24mmkF0U1e2Nli^nlO|14{3qpHl$uzQnxasi zS(2fUn3Y(Olb@KPmzkHA&!G5|g@FsGT=74*pKD04vtxj(k)8oFBTz^Oh=E26FfcG1 zbL_hF&)}42ws10s6^G;;cE1^EoUR)U5A70}d2pLv!jVIT7j&Z~EblI3x0K*v_sV|m z0W=b9G$XP(CLnYCdK49;TX=SFc-G}o=oA=|U?{1O;Nu!CwW3C5Yw7*Bi4yD$3fCnb zwK+>}QdQ9sf*QnxY>*kpE+b{_Q;sJloS71)&(@kO!}mqf@1v(v;*8Y=G9S3kY~Cw# zY=t&c z;3~JK4HxB^lY(MD+sYeQ=t%XSSW;x^1M?dTvN=W^yNcAcy`HCte31C;)5xP%b~qs> zDP&4(%TBqBNGHwnryK;BdMI$fEg xd0mc!C@j^ZpLxYv4HmnPfI0THYuv<%+6iSmMn&w3dPGDfL1|=LY008wP(boU~ literal 0 HcmV?d00001 diff --git a/src/main/resources/public/js/users.js b/src/main/resources/public/js/users.js index 76bd41d..a49bdc6 100644 --- a/src/main/resources/public/js/users.js +++ b/src/main/resources/public/js/users.js @@ -35,10 +35,7 @@ function changePassword() { function inviteUser() { email = document.getElementById("email").value; - re = /\S+@\S+\.\S+/; - - - if (!re.test(email)) { + if (!isEmailValid(email)) { showFeedbackMessage("Некорректный почтовый ящик", MessageTypesEnum.WARNING); return; } @@ -55,4 +52,77 @@ function inviteUser() { showFeedbackMessage(errorData.responseJSON.error.message, MessageTypesEnum.WARNING) } }) +} + +function requestResetPassword() { + email = document.getElementById("emailReset").value + + if (!isEmailValid(email)) { + showFeedbackMessage("Некорректный почтовый ящик", MessageTypesEnum.WARNING); + return; + } + document.getElementById("dvloader").hidden = false; + + $.ajax({ + url:"/api/1.0/users/password-reset-request?email=" + email, + contentType: "application/json; charset=utf-8", + method: "POST", + success: function() { + showFeedbackMessage("Проверочный код был отправлен на указанный почтовый ящик", MessageTypesEnum.SUCCESS) + document.getElementById("passwordNew").hidden = false + document.getElementById("passwordConfirm").hidden = false + document.getElementById("btnReset").hidden = false + document.getElementById("resetKey").hidden = false + document.getElementById("emailReset").hidden = true + document.getElementById("btnSend").hidden = true + document.getElementById("dvloader").hidden = true; + + }, + error: function(errorData) { + showFeedbackMessage(errorData.responseJSON.error.message, MessageTypesEnum.WARNING) + document.getElementById("dvloader").hidden = true; + + } + }) + +} + +function resetPassword() { + passwordNew = document.getElementById("passwordNew").value; + passwordConfirm = document.getElementById("passwordConfirm").value; + resetKey = document.getElementById("resetKey").value; + + if ([passwordNew, passwordConfirm, resetKey].includes("")) { + showFeedbackMessage("Заполните все поля", MessageTypesEnum.WARNING); + return; + } + + if (passwordNew != passwordConfirm) { + showFeedbackMessage("Пароли не совпадают", MessageTypesEnum.WARNING); + return; + } + + $.ajax({ + url:"/api/1.0/users/password-reset", + contentType: "application/json; charset=utf-8", + method: "POST", + data: JSON.stringify({ + "password": passwordNew, + "passwordConfirm": passwordConfirm, + "resetKey": resetKey, + }), + success: function() { + showFeedbackMessage("Пользователь был успешно приглашен", MessageTypesEnum.SUCCESS) + window.location.href = "/login" + }, + error: function(errorData) { + showFeedbackMessage(errorData.responseJSON.error.message, MessageTypesEnum.WARNING) + } + }) +} + + +function isEmailValid(email) { + re = /\S+@\S+\.\S+/; + return re.test(email) } \ No newline at end of file diff --git a/src/main/resources/templates/resetRequest.html b/src/main/resources/templates/resetRequest.html index 2adab37..73bff76 100644 --- a/src/main/resources/templates/resetRequest.html +++ b/src/main/resources/templates/resetRequest.html @@ -1,9 +1,10 @@ + layout:decorator="default" xmlns:th="http://www.w3.org/1999/xhtml"> + +
-
-
-
-
- -
- - -
-
-
- - - +
+
+
+
+ +
+
+ +
+
+ +
+
+ +
+ + + + +
+
+
+ +
\ No newline at end of file From e468646cd6c5b2b214b15ba25855de5c824dfb90 Mon Sep 17 00:00:00 2001 From: "Artem.Arefev" Date: Sun, 19 May 2019 00:47:49 +0400 Subject: [PATCH 10/74] 89 removed getCurrentUser --- src/main/java/ru/ulstu/core/controller/AdviceController.java | 5 ----- src/main/resources/public/js/users.js | 1 - 2 files changed, 6 deletions(-) diff --git a/src/main/java/ru/ulstu/core/controller/AdviceController.java b/src/main/java/ru/ulstu/core/controller/AdviceController.java index 37078b9..f89001a 100644 --- a/src/main/java/ru/ulstu/core/controller/AdviceController.java +++ b/src/main/java/ru/ulstu/core/controller/AdviceController.java @@ -34,11 +34,6 @@ public class AdviceController { public AdviceController(UserService userService) { this.userService = userService; } -// -// @ModelAttribute("currentUser") -// public String getCurrentUser() { -// return userService.getCurrentUser().getUserAbbreviate(); -// } @ModelAttribute("flashMessage") public String getFlashMessage() { diff --git a/src/main/resources/public/js/users.js b/src/main/resources/public/js/users.js index a49bdc6..1ea26e3 100644 --- a/src/main/resources/public/js/users.js +++ b/src/main/resources/public/js/users.js @@ -81,7 +81,6 @@ function requestResetPassword() { error: function(errorData) { showFeedbackMessage(errorData.responseJSON.error.message, MessageTypesEnum.WARNING) document.getElementById("dvloader").hidden = true; - } }) From 1823c1ba50c959dde3197fbfa64a516e9ffa1b3c Mon Sep 17 00:00:00 2001 From: T-Midnight Date: Mon, 20 May 2019 18:37:24 +0400 Subject: [PATCH 11/74] #120 create kias page --- src/test/java/grant/KiasPage.java | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 src/test/java/grant/KiasPage.java diff --git a/src/test/java/grant/KiasPage.java b/src/test/java/grant/KiasPage.java new file mode 100644 index 0000000..49b40d9 --- /dev/null +++ b/src/test/java/grant/KiasPage.java @@ -0,0 +1,28 @@ +package grant; + +import core.PageObject; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; + +import java.util.List; + +public class KiasPage extends PageObject { + @Override + public String getSubTitle() { + return driver.findElement(By.tagName("h1")).getText(); + } + + public List getGrants() { + WebElement listContest = driver.findElement(By.tagName("tBody")); + return listContest.findElements(By.cssSelector("tr.tr")); + + } + + public String getGrantTitle(WebElement grant) { + return grant.findElement(By.cssSelector("td.tertiary")).findElement(By.tagName("a")).getText(); + } + + public String getFirstDeadline(WebElement grant) { + return grant.findElement(By.xpath("./td[5]")).getText(); + } +} From c0e66e81a2e50d85a0859d1f779572a7e1065f1a Mon Sep 17 00:00:00 2001 From: T-Midnight Date: Mon, 20 May 2019 20:47:10 +0400 Subject: [PATCH 12/74] #120 drop unnecessary table column --- .../resources/db/changelog-20190520_000000-schema.xml | 8 ++++++++ src/main/resources/db/changelog-master.xml | 1 + 2 files changed, 9 insertions(+) create mode 100644 src/main/resources/db/changelog-20190520_000000-schema.xml diff --git a/src/main/resources/db/changelog-20190520_000000-schema.xml b/src/main/resources/db/changelog-20190520_000000-schema.xml new file mode 100644 index 0000000..69cdad0 --- /dev/null +++ b/src/main/resources/db/changelog-20190520_000000-schema.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/src/main/resources/db/changelog-master.xml b/src/main/resources/db/changelog-master.xml index 18bd645..d2ccbca 100644 --- a/src/main/resources/db/changelog-master.xml +++ b/src/main/resources/db/changelog-master.xml @@ -42,4 +42,5 @@ + \ No newline at end of file From bb9f412480fc9948e41680a5a4c009a0c26f60b6 Mon Sep 17 00:00:00 2001 From: T-Midnight Date: Mon, 20 May 2019 20:49:03 +0400 Subject: [PATCH 13/74] #120 check unique grant name --- .../grant/controller/GrantController.java | 20 +--------- .../java/ru/ulstu/grant/model/GrantDto.java | 3 +- .../grant/repository/GrantRepository.java | 9 ++++- .../ru/ulstu/grant/service/GrantService.java | 37 ++++++++++++++++++- 4 files changed, 47 insertions(+), 22 deletions(-) diff --git a/src/main/java/ru/ulstu/grant/controller/GrantController.java b/src/main/java/ru/ulstu/grant/controller/GrantController.java index ad5e992..91b0f91 100644 --- a/src/main/java/ru/ulstu/grant/controller/GrantController.java +++ b/src/main/java/ru/ulstu/grant/controller/GrantController.java @@ -20,9 +20,7 @@ import springfox.documentation.annotations.ApiIgnore; import javax.validation.Valid; import java.io.IOException; import java.util.List; -import java.util.stream.Collectors; -import static org.springframework.util.StringUtils.isEmpty; import static ru.ulstu.core.controller.Navigation.GRANTS_PAGE; import static ru.ulstu.core.controller.Navigation.GRANT_PAGE; import static ru.ulstu.core.controller.Navigation.REDIRECT_TO; @@ -62,17 +60,9 @@ public class GrantController { @PostMapping(value = "/grant", params = "save") public String save(@Valid GrantDto grantDto, Errors errors) throws IOException { - filterEmptyDeadlines(grantDto); - if (grantDto.getDeadlines().isEmpty()) { - errors.rejectValue("deadlines", "errorCode", "Не может быть пусто"); - } - if (grantDto.getLeaderId().equals(-1)) { - errors.rejectValue("leaderId", "errorCode", "Укажите руководителя"); - } - if (errors.hasErrors()) { + if (!grantService.save(grantDto, errors)) { return GRANT_PAGE; } - grantService.save(grantDto); return String.format(REDIRECT_TO, GRANTS_PAGE); } @@ -89,7 +79,7 @@ public class GrantController { @PostMapping(value = "/grant", params = "addDeadline") public String addDeadline(@Valid GrantDto grantDto, Errors errors) { - filterEmptyDeadlines(grantDto); + grantService.filterEmptyDeadlines(grantDto); if (errors.hasErrors()) { return GRANT_PAGE; } @@ -133,10 +123,4 @@ public class GrantController { public List getAllPapers() { return grantService.getAllUncompletedPapers(); } - - private void filterEmptyDeadlines(GrantDto grantDto) { - grantDto.setDeadlines(grantDto.getDeadlines().stream() - .filter(dto -> dto.getDate() != null || !isEmpty(dto.getDescription())) - .collect(Collectors.toList())); - } } diff --git a/src/main/java/ru/ulstu/grant/model/GrantDto.java b/src/main/java/ru/ulstu/grant/model/GrantDto.java index 203d306..5a561b1 100644 --- a/src/main/java/ru/ulstu/grant/model/GrantDto.java +++ b/src/main/java/ru/ulstu/grant/model/GrantDto.java @@ -6,6 +6,7 @@ import org.apache.commons.lang3.StringUtils; import org.hibernate.validator.constraints.NotEmpty; import ru.ulstu.deadline.model.Deadline; import ru.ulstu.file.model.FileDataDto; +import ru.ulstu.name.NameContainer; import ru.ulstu.paper.model.PaperDto; import ru.ulstu.project.model.ProjectDto; import ru.ulstu.user.model.UserDto; @@ -17,7 +18,7 @@ import java.util.stream.Collectors; import static ru.ulstu.core.util.StreamApiUtils.convert; -public class GrantDto { +public class GrantDto extends NameContainer { private final static int MAX_AUTHORS_LENGTH = 60; private Integer id; diff --git a/src/main/java/ru/ulstu/grant/repository/GrantRepository.java b/src/main/java/ru/ulstu/grant/repository/GrantRepository.java index 44c2cc0..26face4 100644 --- a/src/main/java/ru/ulstu/grant/repository/GrantRepository.java +++ b/src/main/java/ru/ulstu/grant/repository/GrantRepository.java @@ -1,11 +1,18 @@ package ru.ulstu.grant.repository; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import ru.ulstu.grant.model.Grant; +import ru.ulstu.name.BaseRepository; import java.util.List; -public interface GrantRepository extends JpaRepository { +public interface GrantRepository extends JpaRepository, BaseRepository { List findByStatus(Grant.GrantStatus status); + + @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); } diff --git a/src/main/java/ru/ulstu/grant/service/GrantService.java b/src/main/java/ru/ulstu/grant/service/GrantService.java index 45f9b2f..4972b6c 100644 --- a/src/main/java/ru/ulstu/grant/service/GrantService.java +++ b/src/main/java/ru/ulstu/grant/service/GrantService.java @@ -3,6 +3,7 @@ package ru.ulstu.grant.service; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.Errors; import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.service.DeadlineService; import ru.ulstu.file.model.FileDataDto; @@ -10,6 +11,7 @@ import ru.ulstu.file.service.FileService; import ru.ulstu.grant.model.Grant; import ru.ulstu.grant.model.GrantDto; import ru.ulstu.grant.repository.GrantRepository; +import ru.ulstu.name.BaseService; import ru.ulstu.paper.model.Paper; import ru.ulstu.paper.model.PaperDto; import ru.ulstu.paper.service.PaperService; @@ -27,6 +29,7 @@ import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; +import java.util.stream.Collectors; import static java.util.stream.Collectors.toList; import static org.springframework.util.ObjectUtils.isEmpty; @@ -34,7 +37,7 @@ import static ru.ulstu.core.util.StreamApiUtils.convert; import static ru.ulstu.grant.model.Grant.GrantStatus.APPLICATION; @Service -public class GrantService { +public class GrantService extends BaseService { private final static int MAX_DISPLAY_SIZE = 50; private final GrantRepository grantRepository; @@ -55,6 +58,7 @@ public class GrantService { EventService eventService, GrantNotificationService grantNotificationService) { this.grantRepository = grantRepository; + this.baseRepository = grantRepository; this.fileService = fileService; this.deadlineService = deadlineService; this.projectService = projectService; @@ -176,12 +180,35 @@ public class GrantService { return grant; } - public void save(GrantDto grantDto) throws IOException { + public boolean save(GrantDto grantDto, Errors errors) throws IOException { + grantDto.setName(grantDto.getTitle()); + filterEmptyDeadlines(grantDto); + checkEmptyDeadlines(grantDto, errors); + checkEmptyLeader(grantDto, errors); + checkUniqueName(grantDto, errors, grantDto.getId(), "title", "Грант с таким именем уже существует"); + if (errors.hasErrors()) { + return false; + } + if (isEmpty(grantDto.getId())) { create(grantDto); } else { update(grantDto); } + + return true; + } + + 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", "Не может быть пусто"); + } } public List getGrantAuthors(GrantDto grantDto) { @@ -261,4 +288,10 @@ public class GrantService { .filter(author -> Collections.frequency(authors, author) > 3) .collect(toList()); } + + public void filterEmptyDeadlines(GrantDto grantDto) { + grantDto.setDeadlines(grantDto.getDeadlines().stream() + .filter(dto -> dto.getDate() != null || !org.springframework.util.StringUtils.isEmpty(dto.getDescription())) + .collect(Collectors.toList())); + } } From d7c4e6b22264bbd76b35fae997fb8fbfeb328d1c Mon Sep 17 00:00:00 2001 From: "Artem.Arefev" Date: Tue, 21 May 2019 02:09:07 +0400 Subject: [PATCH 14/74] #91 base users dashboard --- .../repository/ConferenceRepository.java | 4 + .../conference/service/ConferenceService.java | 4 + .../service/ConferenceUserService.java | 2 - .../user/controller/UserMvcController.java | 5 + .../java/ru/ulstu/user/model/UserInfoNow.java | 50 ++++++++++ .../repository/UserSessionRepository.java | 3 + .../ru/ulstu/user/service/UserService.java | 37 ++++++- .../user/service/UserSessionService.java | 6 ++ .../utils/timetable/TimetableService.java | 97 +++++++++++++++++++ .../ru/ulstu/utils/timetable/model/Day.java | 27 ++++++ .../ulstu/utils/timetable/model/Lesson.java | 27 ++++++ .../ulstu/utils/timetable/model/Response.java | 16 +++ .../timetable/model/TimetableResponse.java | 22 +++++ .../ru/ulstu/utils/timetable/model/Week.java | 16 +++ .../resources/templates/users/dashboard.html | 24 +++++ .../fragments/userDashboardFragment.html | 18 ++++ 16 files changed, 355 insertions(+), 3 deletions(-) create mode 100644 src/main/java/ru/ulstu/user/model/UserInfoNow.java create mode 100644 src/main/java/ru/ulstu/utils/timetable/TimetableService.java create mode 100644 src/main/java/ru/ulstu/utils/timetable/model/Day.java create mode 100644 src/main/java/ru/ulstu/utils/timetable/model/Lesson.java create mode 100644 src/main/java/ru/ulstu/utils/timetable/model/Response.java create mode 100644 src/main/java/ru/ulstu/utils/timetable/model/TimetableResponse.java create mode 100644 src/main/java/ru/ulstu/utils/timetable/model/Week.java create mode 100644 src/main/resources/templates/users/dashboard.html create mode 100644 src/main/resources/templates/users/fragments/userDashboardFragment.html diff --git a/src/main/java/ru/ulstu/conference/repository/ConferenceRepository.java b/src/main/java/ru/ulstu/conference/repository/ConferenceRepository.java index 2b0a428..8f9e05f 100644 --- a/src/main/java/ru/ulstu/conference/repository/ConferenceRepository.java +++ b/src/main/java/ru/ulstu/conference/repository/ConferenceRepository.java @@ -29,4 +29,8 @@ public interface ConferenceRepository extends JpaRepository @Override @Query("SELECT title FROM Conference c WHERE (c.title = :name) AND (:id IS NULL OR c.id != :id) ") String findByNameAndNotId(@Param("name") String name, @Param("id") Integer id); + + @Query("SELECT c FROM Conference c LEFT JOIN c.users u WHERE (:user IS NULL OR u.user = :user) " + + "AND (u.participation = 'INTRAMURAL') AND (c.beginDate <= CURRENT_DATE) AND (c.endDate >= CURRENT_DATE)") + Conference findActiveByUser(@Param("user") User user); } diff --git a/src/main/java/ru/ulstu/conference/service/ConferenceService.java b/src/main/java/ru/ulstu/conference/service/ConferenceService.java index 38ce659..1a5db52 100644 --- a/src/main/java/ru/ulstu/conference/service/ConferenceService.java +++ b/src/main/java/ru/ulstu/conference/service/ConferenceService.java @@ -306,4 +306,8 @@ public class ConferenceService extends BaseService { .filter(dto -> dto.getDate() != null || !org.springframework.util.StringUtils.isEmpty(dto.getDescription())) .collect(Collectors.toList())); } + + public Conference getActiveConferenceByUser(User user) { + return conferenceRepository.findActiveByUser(user); + } } diff --git a/src/main/java/ru/ulstu/conference/service/ConferenceUserService.java b/src/main/java/ru/ulstu/conference/service/ConferenceUserService.java index f771b2a..16842c1 100644 --- a/src/main/java/ru/ulstu/conference/service/ConferenceUserService.java +++ b/src/main/java/ru/ulstu/conference/service/ConferenceUserService.java @@ -43,6 +43,4 @@ public class ConferenceUserService { newUser = conferenceUserRepository.save(newUser); return newUser; } - - } diff --git a/src/main/java/ru/ulstu/user/controller/UserMvcController.java b/src/main/java/ru/ulstu/user/controller/UserMvcController.java index 5bcbd13..d283a21 100644 --- a/src/main/java/ru/ulstu/user/controller/UserMvcController.java +++ b/src/main/java/ru/ulstu/user/controller/UserMvcController.java @@ -48,4 +48,9 @@ public class UserMvcController extends OdinController { User user = userSessionService.getUserBySessionId(sessionId); modelMap.addAttribute("userDto", userService.updateUserInformation(user, userDto)); } + + @GetMapping("/dashboard") + public void getUsersDashboard(ModelMap modelMap) { + modelMap.addAttribute("users", userService.getUsersInfo()); + } } diff --git a/src/main/java/ru/ulstu/user/model/UserInfoNow.java b/src/main/java/ru/ulstu/user/model/UserInfoNow.java new file mode 100644 index 0000000..7d69c56 --- /dev/null +++ b/src/main/java/ru/ulstu/user/model/UserInfoNow.java @@ -0,0 +1,50 @@ +package ru.ulstu.user.model; + +import ru.ulstu.conference.model.Conference; +import ru.ulstu.utils.timetable.model.Lesson; + +public class UserInfoNow { + private Lesson lesson; + private Conference conference; + private User user; + private boolean isOnline; + + public UserInfoNow(Lesson lesson, Conference conference, User user, boolean isOnline) { + this.lesson = lesson; + this.conference = conference; + this.user = user; + this.isOnline = isOnline; + } + + public Lesson getLesson() { + return lesson; + } + + public void setLesson(Lesson lesson) { + this.lesson = lesson; + } + + public Conference getConference() { + return conference; + } + + public void setConference(Conference conference) { + this.conference = conference; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public boolean isOnline() { + return isOnline; + } + + public void setOnline(boolean online) { + isOnline = online; + } +} diff --git a/src/main/java/ru/ulstu/user/repository/UserSessionRepository.java b/src/main/java/ru/ulstu/user/repository/UserSessionRepository.java index b922e4f..5319245 100644 --- a/src/main/java/ru/ulstu/user/repository/UserSessionRepository.java +++ b/src/main/java/ru/ulstu/user/repository/UserSessionRepository.java @@ -1,6 +1,7 @@ package ru.ulstu.user.repository; import org.springframework.data.jpa.repository.JpaRepository; +import ru.ulstu.user.model.User; import ru.ulstu.user.model.UserSession; import java.util.Date; @@ -10,4 +11,6 @@ public interface UserSessionRepository extends JpaRepository findAllByLogoutTimeIsNullAndLoginTimeBefore(Date date); + + List findAllByUserAndLogoutTimeIsNullAndLoginTimeBefore(User user, Date date); } diff --git a/src/main/java/ru/ulstu/user/service/UserService.java b/src/main/java/ru/ulstu/user/service/UserService.java index c889caa..334fbf5 100644 --- a/src/main/java/ru/ulstu/user/service/UserService.java +++ b/src/main/java/ru/ulstu/user/service/UserService.java @@ -3,6 +3,7 @@ package ru.ulstu.user.service; import com.google.common.collect.ImmutableMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.Lazy; import org.springframework.data.domain.Page; import org.springframework.data.domain.Sort; import org.springframework.mail.MailException; @@ -13,6 +14,7 @@ import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; +import ru.ulstu.conference.service.ConferenceService; import ru.ulstu.configuration.ApplicationProperties; import ru.ulstu.core.error.EntityIdIsNullException; import ru.ulstu.core.jpa.OffsetablePageRequest; @@ -30,6 +32,7 @@ import ru.ulstu.user.error.UserResetKeyError; import ru.ulstu.user.error.UserSendingMailException; import ru.ulstu.user.model.User; import ru.ulstu.user.model.UserDto; +import ru.ulstu.user.model.UserInfoNow; import ru.ulstu.user.model.UserListDto; import ru.ulstu.user.model.UserResetPasswordDto; import ru.ulstu.user.model.UserRole; @@ -38,8 +41,13 @@ import ru.ulstu.user.model.UserRoleDto; import ru.ulstu.user.repository.UserRepository; import ru.ulstu.user.repository.UserRoleRepository; import ru.ulstu.user.util.UserUtils; +import ru.ulstu.utils.timetable.TimetableService; +import ru.ulstu.utils.timetable.model.Lesson; import javax.mail.MessagingException; +import java.io.IOException; +import java.text.ParseException; +import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; @@ -62,19 +70,27 @@ public class UserService implements UserDetailsService { private final UserMapper userMapper; private final MailService mailService; private final ApplicationProperties applicationProperties; + private final TimetableService timetableService; + private final ConferenceService conferenceService; + private final UserSessionService userSessionService; public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder, UserRoleRepository userRoleRepository, UserMapper userMapper, MailService mailService, - ApplicationProperties applicationProperties) { + ApplicationProperties applicationProperties, + @Lazy ConferenceService conferenceRepository, + @Lazy UserSessionService userSessionService) throws ParseException { this.userRepository = userRepository; this.passwordEncoder = passwordEncoder; this.userRoleRepository = userRoleRepository; this.userMapper = userMapper; this.mailService = mailService; this.applicationProperties = applicationProperties; + this.conferenceService = conferenceRepository; + this.timetableService = new TimetableService(); + this.userSessionService = userSessionService; } private User getUserByEmail(String email) { @@ -341,4 +357,23 @@ public class UserService implements UserDetailsService { throw new UserSendingMailException(email); } } + + public List getUsersInfo() { + List usersInfoNow = new ArrayList<>(); + for (User user : userRepository.findAll()) { + Lesson lesson = null; + try { + lesson = timetableService.getCurrentLesson(user.getUserAbbreviate()); + } catch (IOException e) { + e.printStackTrace(); + } + usersInfoNow.add(new UserInfoNow( + lesson, + conferenceService.getActiveConferenceByUser(user), + user, + userSessionService.isOnline(user)) + ); + } + return usersInfoNow; + } } diff --git a/src/main/java/ru/ulstu/user/service/UserSessionService.java b/src/main/java/ru/ulstu/user/service/UserSessionService.java index ae289d0..17a7f5b 100644 --- a/src/main/java/ru/ulstu/user/service/UserSessionService.java +++ b/src/main/java/ru/ulstu/user/service/UserSessionService.java @@ -14,6 +14,8 @@ import ru.ulstu.user.model.UserSession; import ru.ulstu.user.model.UserSessionListDto; import ru.ulstu.user.repository.UserSessionRepository; +import java.util.Date; + import static ru.ulstu.core.util.StreamApiUtils.convert; @Service @@ -58,4 +60,8 @@ public class UserSessionService { public User getUserBySessionId(String sessionId) { return userSessionRepository.findOneBySessionId(sessionId).getUser(); } + + public boolean isOnline(User user) { + return !userSessionRepository.findAllByUserAndLogoutTimeIsNullAndLoginTimeBefore(user, new Date()).isEmpty(); + } } diff --git a/src/main/java/ru/ulstu/utils/timetable/TimetableService.java b/src/main/java/ru/ulstu/utils/timetable/TimetableService.java new file mode 100644 index 0000000..f17ea86 --- /dev/null +++ b/src/main/java/ru/ulstu/utils/timetable/TimetableService.java @@ -0,0 +1,97 @@ +package ru.ulstu.utils.timetable; + +import com.fasterxml.jackson.databind.ObjectMapper; +import ru.ulstu.utils.timetable.model.Lesson; +import ru.ulstu.utils.timetable.model.TimetableResponse; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; +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"; + 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() { + Calendar cal = Calendar.getInstance(); + cal.setTime(new Date()); + return (cal.get(Calendar.WEEK_OF_YEAR) + 1) % 2; + } + + private TimetableResponse getTimetableForUser(String userFIO) throws IOException { + URL url = new URL(TIMETABLE_URL + "/api/1.0/timetable?filter=" + URLEncoder.encode(userFIO, "UTF-8")); + HttpURLConnection con = (HttpURLConnection) url.openConnection(); + con.setRequestMethod("GET"); + + BufferedReader in = new BufferedReader( + new InputStreamReader(con.getInputStream())); + String inputLine; + StringBuilder content = new StringBuilder(); + while ((inputLine = in.readLine()) != null) { + content.append(inputLine); + } + in.close(); + + return new ObjectMapper().readValue(content.toString(), TimetableResponse.class); + } + + public Lesson getCurrentLesson(String userFio) throws IOException { + TimetableResponse response = getTimetableForUser(userFio); + int lessonNumber = getCurrentLessonNumber(); + if (lessonNumber < 0) { + return null; + } + + List lessons = response + .getResponse() + .getWeeks() + .get(getCurrentWeek()) + .getDays() + .get(getCurrentDay()) + .getLessons() + .get(lessonNumber); + + if (lessons.size() == 0) { + return null; + } + return new ObjectMapper().convertValue(lessons.get(0), Lesson.class); + } +} diff --git a/src/main/java/ru/ulstu/utils/timetable/model/Day.java b/src/main/java/ru/ulstu/utils/timetable/model/Day.java new file mode 100644 index 0000000..f548462 --- /dev/null +++ b/src/main/java/ru/ulstu/utils/timetable/model/Day.java @@ -0,0 +1,27 @@ +package ru.ulstu.utils.timetable.model; + +import java.util.List; + + +public class Day { + + private Integer day; + private List> lessons = null; + + public Integer getDay() { + return day; + } + + public void setDay(Integer day) { + this.day = day; + } + + public List> getLessons() { + return lessons; + } + + public void setLessons(List> lessons) { + this.lessons = lessons; + } +} + diff --git a/src/main/java/ru/ulstu/utils/timetable/model/Lesson.java b/src/main/java/ru/ulstu/utils/timetable/model/Lesson.java new file mode 100644 index 0000000..e651e1a --- /dev/null +++ b/src/main/java/ru/ulstu/utils/timetable/model/Lesson.java @@ -0,0 +1,27 @@ +package ru.ulstu.utils.timetable.model; + +public class Lesson { + private String group; + private String nameOfLesson; + private String teacher; + private String room; + + public Lesson() { + } + + public String getGroup() { + return group; + } + + public String getNameOfLesson() { + return nameOfLesson; + } + + public String getTeacher() { + return teacher; + } + + public String getRoom() { + return room; + } +} diff --git a/src/main/java/ru/ulstu/utils/timetable/model/Response.java b/src/main/java/ru/ulstu/utils/timetable/model/Response.java new file mode 100644 index 0000000..b5b9e97 --- /dev/null +++ b/src/main/java/ru/ulstu/utils/timetable/model/Response.java @@ -0,0 +1,16 @@ +package ru.ulstu.utils.timetable.model; + +import java.util.List; + +public class Response { + + private List weeks = null; + + public List getWeeks() { + return weeks; + } + + public void setWeeks(List weeks) { + this.weeks = weeks; + } +} diff --git a/src/main/java/ru/ulstu/utils/timetable/model/TimetableResponse.java b/src/main/java/ru/ulstu/utils/timetable/model/TimetableResponse.java new file mode 100644 index 0000000..118c979 --- /dev/null +++ b/src/main/java/ru/ulstu/utils/timetable/model/TimetableResponse.java @@ -0,0 +1,22 @@ +package ru.ulstu.utils.timetable.model; + +public class TimetableResponse { + private Response response; + private String error; + + public Response getResponse() { + return response; + } + + public void setResponse(Response response) { + this.response = response; + } + + public String getError() { + return error; + } + + public void setError(String error) { + this.error = error; + } +} diff --git a/src/main/java/ru/ulstu/utils/timetable/model/Week.java b/src/main/java/ru/ulstu/utils/timetable/model/Week.java new file mode 100644 index 0000000..19f3c50 --- /dev/null +++ b/src/main/java/ru/ulstu/utils/timetable/model/Week.java @@ -0,0 +1,16 @@ +package ru.ulstu.utils.timetable.model; + +import java.util.List; + +public class Week { + + private List days = null; + + public List getDays() { + return days; + } + + public void setDays(List days) { + this.days = days; + } +} diff --git a/src/main/resources/templates/users/dashboard.html b/src/main/resources/templates/users/dashboard.html new file mode 100644 index 0000000..8236734 --- /dev/null +++ b/src/main/resources/templates/users/dashboard.html @@ -0,0 +1,24 @@ + + + + + + +
+
+
+
+

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

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

+

+

+

Онлайн

+
+
+
+ + \ No newline at end of file From 8b52518c4a0411c760d7cac83153da69e4f2c628 Mon Sep 17 00:00:00 2001 From: Nightblade73 Date: Tue, 21 May 2019 15:53:42 +0400 Subject: [PATCH 15/74] #125 check method --- .../conference/service/ConferenceService.java | 7 +++++++ .../templates/conferences/conference.html | 14 +++++++++++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/main/java/ru/ulstu/conference/service/ConferenceService.java b/src/main/java/ru/ulstu/conference/service/ConferenceService.java index 38ce659..4ee4198 100644 --- a/src/main/java/ru/ulstu/conference/service/ConferenceService.java +++ b/src/main/java/ru/ulstu/conference/service/ConferenceService.java @@ -92,6 +92,7 @@ public class ConferenceService extends BaseService { conferenceDto.setName(conferenceDto.getTitle()); filterEmptyDeadlines(conferenceDto); checkEmptyFieldsOfDeadline(conferenceDto, errors); + checkEmptyFieldsOfDates(conferenceDto, errors); checkUniqueName(conferenceDto, errors, conferenceDto.getId(), @@ -301,6 +302,12 @@ 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) { conferenceDto.setDeadlines(conferenceDto.getDeadlines().stream() .filter(dto -> dto.getDate() != null || !org.springframework.util.StringUtils.isEmpty(dto.getDescription())) diff --git a/src/main/resources/templates/conferences/conference.html b/src/main/resources/templates/conferences/conference.html index d629d4e..201aa01 100644 --- a/src/main/resources/templates/conferences/conference.html +++ b/src/main/resources/templates/conferences/conference.html @@ -42,12 +42,20 @@ placeholder="http://"/> +

Incorrect description

+

+
+

Incorrect description

+

+
@@ -65,6 +73,7 @@
+

Incorrect title

@@ -94,6 +103,10 @@ +

Incorrect date

+

@@ -123,7 +136,6 @@
- From bab621677eb65e10da2a75ba66e8c016da6389c9 Mon Sep 17 00:00:00 2001 From: T-Midnight Date: Wed, 22 May 2019 15:10:51 +0400 Subject: [PATCH 16/74] #120 add methods for checking unique title and date of grant --- .../ru/ulstu/deadline/repository/DeadlineRepository.java | 7 +++++++ .../java/ru/ulstu/deadline/service/DeadlineService.java | 5 +++++ .../java/ru/ulstu/grant/repository/GrantRepository.java | 2 ++ src/main/java/ru/ulstu/name/BaseService.java | 7 +++++++ 4 files changed, 21 insertions(+) diff --git a/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java b/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java index f26c572..5b434b9 100644 --- a/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java +++ b/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java @@ -2,8 +2,15 @@ package ru.ulstu.deadline.repository; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; import ru.ulstu.deadline.model.Deadline; +import java.util.Date; + public interface DeadlineRepository extends JpaRepository { + @Query( + value = "SELECT date FROM Deadline d WHERE (d.grant_id = ?1) AND (d.date = ?2)", + nativeQuery = true) + Date findByGrantIdAndDate(Integer grant_id, Date date); } diff --git a/src/main/java/ru/ulstu/deadline/service/DeadlineService.java b/src/main/java/ru/ulstu/deadline/service/DeadlineService.java index 0ef8a4f..e82211d 100644 --- a/src/main/java/ru/ulstu/deadline/service/DeadlineService.java +++ b/src/main/java/ru/ulstu/deadline/service/DeadlineService.java @@ -5,6 +5,7 @@ import org.springframework.transaction.annotation.Transactional; import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.repository.DeadlineRepository; +import java.util.Date; import java.util.List; import java.util.stream.Collectors; @@ -46,4 +47,8 @@ public class DeadlineService { public void remove(Integer deadlineId) { deadlineRepository.delete(deadlineId); } + + public Date findByGrantIdAndDate(Integer id, Date date) { + return deadlineRepository.findByGrantIdAndDate(id, date); + } } diff --git a/src/main/java/ru/ulstu/grant/repository/GrantRepository.java b/src/main/java/ru/ulstu/grant/repository/GrantRepository.java index 26face4..ae9fcc8 100644 --- a/src/main/java/ru/ulstu/grant/repository/GrantRepository.java +++ b/src/main/java/ru/ulstu/grant/repository/GrantRepository.java @@ -12,6 +12,8 @@ public interface GrantRepository extends JpaRepository, BaseRepo List findByStatus(Grant.GrantStatus status); + Grant findByTitle(String title); + @Override @Query("SELECT title FROM Grant g WHERE (g.title = :name) AND (:id IS NULL OR g.id != :id) ") String findByNameAndNotId(@Param("name") String name, @Param("id") Integer id); diff --git a/src/main/java/ru/ulstu/name/BaseService.java b/src/main/java/ru/ulstu/name/BaseService.java index 6619385..fd63cbf 100644 --- a/src/main/java/ru/ulstu/name/BaseService.java +++ b/src/main/java/ru/ulstu/name/BaseService.java @@ -13,4 +13,11 @@ public abstract class BaseService { 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; + } } From c21739bfc627b1aad3de8edbec7e4ad7d5d8a0dc Mon Sep 17 00:00:00 2001 From: T-Midnight Date: Wed, 22 May 2019 15:12:45 +0400 Subject: [PATCH 17/74] #120 parse kias page --- src/test/java/IndexKiasTest.java | 67 +++++++++++++++++++++++++++++++ src/test/java/grant/KiasPage.java | 28 ++++++++++++- 2 files changed, 93 insertions(+), 2 deletions(-) create mode 100644 src/test/java/IndexKiasTest.java diff --git a/src/test/java/IndexKiasTest.java b/src/test/java/IndexKiasTest.java new file mode 100644 index 0000000..73dc646 --- /dev/null +++ b/src/test/java/IndexKiasTest.java @@ -0,0 +1,67 @@ +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Iterables; +import core.PageObject; +import core.TestTemplate; +import grant.KiasPage; +import org.junit.runner.RunWith; +import org.openqa.selenium.WebElement; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import ru.ulstu.NgTrackerApplication; +import ru.ulstu.deadline.model.Deadline; +import ru.ulstu.grant.model.Grant; +import ru.ulstu.grant.model.GrantDto; +import ru.ulstu.user.repository.UserRepository; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Map; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = NgTrackerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +public class IndexKiasTest extends TestTemplate { + 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 CONTEST_YEAR = "2019"; + + private final Map> navigationHolder = ImmutableMap.of( + new KiasPage(), Arrays.asList("Поиск по конкурсам", + String.format(BASE_URL, CONTEST_STATUS_ID, CONTEST_TYPE, CONTEST_YEAR)) + ); + + @Autowired + UserRepository userRepository; + + public List getNewGrantsDto() throws ParseException { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + getContext().goTo(page.getValue().get(1)); + KiasPage kiasPage = (KiasPage) getContext().initPage(page.getKey()); + List kiasGrants = new ArrayList<>(); + List newGrants = new ArrayList<>(); + do { + kiasGrants.addAll(kiasPage.getPageOfGrants()); + for (WebElement grant : kiasGrants) { + GrantDto grantDto = new GrantDto(); + grantDto.setTitle(kiasPage.getGrantTitle(grant)); + String deadlineDate = kiasPage.getFirstDeadline(grant); //10.06.2019 23:59 + SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm"); + Date date = formatter.parse(deadlineDate); + Deadline deadline = new Deadline(date, "Окончание приёма заявок"); + grantDto.setDeadlines(Arrays.asList(deadline)); + grantDto.setLeaderId(userRepository.findOneByLoginIgnoreCase("admin").getId()); + grantDto.setStatus(Grant.GrantStatus.LOADED_FROM_KIAS); + newGrants.add(grantDto); + } + kiasGrants.clear(); + } + while (kiasPage.checkPagination()); //проверка существования следующей страницы с грантами + + return newGrants; + } +} diff --git a/src/test/java/grant/KiasPage.java b/src/test/java/grant/KiasPage.java index 49b40d9..7723b01 100644 --- a/src/test/java/grant/KiasPage.java +++ b/src/test/java/grant/KiasPage.java @@ -4,7 +4,9 @@ import core.PageObject; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; +import java.util.ArrayList; import java.util.List; +import java.util.NoSuchElementException; public class KiasPage extends PageObject { @Override @@ -13,9 +15,31 @@ public class KiasPage extends PageObject { } public List getGrants() { - WebElement listContest = driver.findElement(By.tagName("tBody")); - return listContest.findElements(By.cssSelector("tr.tr")); + List grants = new ArrayList<>(); + do { + grants.addAll(getPageOfGrants()); + } + while (checkPagination()); + return grants; + } + + public List getPageOfGrants() { + WebElement listContest = driver.findElement(By.tagName("tBody")); + List grants = listContest.findElements(By.cssSelector("tr.tr")); + return grants; + } + + public boolean checkPagination() { + try { + if (driver.findElements(By.id("js-ctrlNext")).size() > 0) { + driver.findElement(By.id("js-ctrlNext")).click(); + return true; + } + } catch (NoSuchElementException e) { + return false; + } + return false; } public String getGrantTitle(WebElement grant) { From 5f214620bff80e208fc4b382be55d5070057cdd6 Mon Sep 17 00:00:00 2001 From: T-Midnight Date: Wed, 22 May 2019 15:16:20 +0400 Subject: [PATCH 18/74] #120 use loading from kias --- .../ulstu/grant/service/GrantScheduler.java | 22 +++++++++++++++ .../ru/ulstu/grant/service/GrantService.java | 27 +++++++++++++++++-- 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/src/main/java/ru/ulstu/grant/service/GrantScheduler.java b/src/main/java/ru/ulstu/grant/service/GrantScheduler.java index 1c38c4a..efe1e41 100644 --- a/src/main/java/ru/ulstu/grant/service/GrantScheduler.java +++ b/src/main/java/ru/ulstu/grant/service/GrantScheduler.java @@ -27,4 +27,26 @@ public class GrantScheduler { grantNotificationService.sendDeadlineNotifications(grantService.findAll(), IS_DEADLINE_NOTIFICATION_BEFORE_WEEK); log.debug("GrantScheduler.checkDeadlineBeforeWeek finished"); } + + @Scheduled(cron = "0 0 8 1 * ?", zone = "Europe/Samara") + public void loadGrantsFromKias() { + log.debug("GrantScheduler.loadGrantsFromKias started"); + // + // Метод для сохранения загруженных грантов + // + +// List grants = IndexKiasTest.getNewGrantsDto(); +// grants.forEach(grantDto -> { +// try { +// if (grantService.saveFromKias(grantDto)) { +// log.debug("GrantScheduler.loadGrantsFromKias new grant was loaded"); +// } else { +// log.debug("GrantScheduler.loadGrantsFromKias grant wasn't loaded, cause it's already exists"); +// } +// } catch (IOException e) { +// e.printStackTrace(); +// } +// }); + log.debug("GrantScheduler.loadGrantsFromKias finished"); + } } diff --git a/src/main/java/ru/ulstu/grant/service/GrantService.java b/src/main/java/ru/ulstu/grant/service/GrantService.java index 4972b6c..38c16c3 100644 --- a/src/main/java/ru/ulstu/grant/service/GrantService.java +++ b/src/main/java/ru/ulstu/grant/service/GrantService.java @@ -189,16 +189,31 @@ public class GrantService extends BaseService { if (errors.hasErrors()) { return false; } - if (isEmpty(grantDto.getId())) { create(grantDto); } else { update(grantDto); } - return true; } + public boolean saveFromKias(GrantDto grantDto) throws IOException { + grantDto.setName(grantDto.getTitle()); + String title = checkUniqueName(grantDto, grantDto.getId()); //проверка уникальности имени + if (title != null) { + Grant grantFromDB = grantRepository.findByTitle(title); //грант с таким же названием из бд + if (checkSameDeadline(grantDto, grantFromDB.getId())) { //если дедайны тоже совпадают + return false; + } else { //иначе грант уже был в системе, но в другом году, поэтому надо создать + create(grantDto); + return true; + } + } else { //иначе такого гранта ещё нет, поэтому надо создать + create(grantDto); + return true; + } + } + private void checkEmptyLeader(GrantDto grantDto, Errors errors) { if (grantDto.getLeaderId().equals(-1)) { errors.rejectValue("leaderId", "errorCode", "Укажите руководителя"); @@ -211,6 +226,14 @@ public class GrantService extends BaseService { } } + private boolean checkSameDeadline(GrantDto grantDto, Integer id) { + Date date = grantDto.getDeadlines().get(0).getDate(); //дата с сайта киас + if (deadlineService.findByGrantIdAndDate(id, date).compareTo(date) == 0) { //если есть такая строка с датой + return true; + } + return false; + } + public List getGrantAuthors(GrantDto grantDto) { List filteredUsers = userService.filterByAgeAndDegree(grantDto.isHasAge(), grantDto.isHasDegree()); if (grantDto.isWasLeader()) { From 457f1da98525439184bddad051aafbce2a710325 Mon Sep 17 00:00:00 2001 From: T-Midnight Date: Wed, 22 May 2019 15:45:23 +0400 Subject: [PATCH 19/74] #120 fix checkRun and checkStyle --- .../java/ru/ulstu/deadline/repository/DeadlineRepository.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java b/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java index 5b434b9..3f237e4 100644 --- a/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java +++ b/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java @@ -12,5 +12,5 @@ public interface DeadlineRepository extends JpaRepository { @Query( value = "SELECT date FROM Deadline d WHERE (d.grant_id = ?1) AND (d.date = ?2)", nativeQuery = true) - Date findByGrantIdAndDate(Integer grant_id, Date date); + Date findByGrantIdAndDate(Integer grantId, Date date); } From bd24525315e5c9f21b1345fde5c92615f8668582 Mon Sep 17 00:00:00 2001 From: ASH Date: Thu, 23 May 2019 00:15:03 +0400 Subject: [PATCH 20/74] #103 integration tests --- src/test/java/IndexTaskTest.java | 214 ++++++++++++++++++ src/test/java/students/TaskPage.java | 81 +++++++ .../java/students/TasksDashboardPage.java | 10 + src/test/java/students/TasksPage.java | 75 ++++++ 4 files changed, 380 insertions(+) create mode 100644 src/test/java/IndexTaskTest.java create mode 100644 src/test/java/students/TaskPage.java create mode 100644 src/test/java/students/TasksDashboardPage.java create mode 100644 src/test/java/students/TasksPage.java diff --git a/src/test/java/IndexTaskTest.java b/src/test/java/IndexTaskTest.java new file mode 100644 index 0000000..51b5e07 --- /dev/null +++ b/src/test/java/IndexTaskTest.java @@ -0,0 +1,214 @@ +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Iterables; +import core.PageObject; +import core.TestTemplate; +import org.junit.Assert; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.MethodSorters; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import ru.ulstu.NgTrackerApplication; +import ru.ulstu.configuration.ApplicationProperties; +import students.TaskPage; +import students.TasksDashboardPage; +import students.TasksPage; + +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Map; + +@RunWith(SpringRunner.class) +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@SpringBootTest(classes = NgTrackerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +public class IndexTaskTest extends TestTemplate { + private final Map> navigationHolder = ImmutableMap.of( + new TasksPage(), Arrays.asList("Список задач", "/students/tasks"), + new TasksDashboardPage(), Arrays.asList("Панель управления", "/students/dashboard"), + new TaskPage(), Arrays.asList("Создать задачу", "/students/task?id=0") + ); + + private final String TAG = "ATag"; + + @Autowired + private ApplicationProperties applicationProperties; + + + @Test + public void testACreateTask() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 2); + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + + TaskPage taskPage = (TaskPage) getContext().initPage(page.getKey()); + TasksPage tasksPage = (TasksPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 0).getKey()); + String taskName = "Task " + (new Date()).getTime(); + + taskPage.setName(taskName); + taskPage.addDeadlineDate("01.01.2020", 0); + taskPage.addDeadlineDescription("Description", 0); + taskPage.save(); + + Assert.assertTrue(tasksPage.findTask(taskName)); + } + + @Test + public void testBEditTaskName() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + TasksPage tasksPage = (TasksPage) getContext().initPage(page.getKey()); + TaskPage taskPage = (TaskPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 2).getKey()); + String taskNewName = "Task " + (new Date()).getTime(); + + tasksPage.goToFirstTask(); + taskPage.removeName(); + taskPage.setName(taskNewName); + taskPage.save(); + + Assert.assertTrue(tasksPage.findTask(taskNewName)); + } + + @Test + public void testCDeleteTask() throws InterruptedException { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + TasksPage tasksPage = (TasksPage) getContext().initPage(page.getKey()); + + Integer size = tasksPage.getTasks().size(); + tasksPage.deleteFirstTask(); + Thread.sleep(3000); + tasksPage.submit(); + + Assert.assertEquals(size - 1, tasksPage.getTasks().size()); + } + + @Test + public void testDAddDeadline() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + TasksPage tasksPage = (TasksPage) getContext().initPage(page.getKey()); + TaskPage taskPage = (TaskPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 2).getKey()); + + tasksPage.goToFirstTask(); + String taskId = taskPage.getId(); + Integer deadnum = taskPage.getDeadNum(); + + String descr = "Description"; + String date = "06.06.2019"; + String dateValue = "2019-06-06"; + + taskPage.clickAddDeadline(); + taskPage.addDeadlineDescription(descr, deadnum); + taskPage.addDeadlineDate(date, deadnum); + taskPage.save(); + + getContext().goTo(applicationProperties.getBaseUrl() + String.format("/students/task?id=%s", taskId)); + + Assert.assertTrue(taskPage.hasDeadline(descr, dateValue)); + } + + @Test + public void testEEditDeadline() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + TasksPage tasksPage = (TasksPage) getContext().initPage(page.getKey()); + TaskPage taskPage = (TaskPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 2).getKey()); + + tasksPage.goToFirstTask(); + String taskId = taskPage.getId(); + + String descr = "DescriptionTwo"; + String date = "12.12.2019"; + String dateValue = "2019-12-12"; + + taskPage.clearDeadlineDate(0); + taskPage.clearDeadlineDescription(0); + taskPage.addDeadlineDescription(descr, 0); + taskPage.addDeadlineDate(date, 0); + taskPage.save(); + + getContext().goTo(applicationProperties.getBaseUrl() + String.format("/students/task?id=%s", taskId)); + + Assert.assertTrue(taskPage.hasDeadline(descr, dateValue)); + } + + @Test + public void testFDeleteDeadline() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + TasksPage tasksPage = (TasksPage) getContext().initPage(page.getKey()); + TaskPage taskPage = (TaskPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 2).getKey()); + + tasksPage.goToFirstTask(); + String taskId = taskPage.getId(); + Integer deadNum = taskPage.getDeadNum(); + + taskPage.deleteDeadline(); + taskPage.save(); + + getContext().goTo(applicationProperties.getBaseUrl() + String.format("/students/task?id=%s", taskId)); + + Assert.assertEquals(deadNum - 1, (int) taskPage.getDeadNum()); + } + + @Test + public void testGCreateTaskWithTag() throws InterruptedException { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 2); + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + + TaskPage taskPage = (TaskPage) getContext().initPage(page.getKey()); + TasksPage tasksPage = (TasksPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 0).getKey()); + String taskName = "Task " + (new Date()).getTime(); + + taskPage.setName(taskName); + taskPage.setTag(TAG); + Thread.sleep(1000); + taskPage.addDeadlineDate("01.01.2020", 0); + taskPage.addDeadlineDescription("Description", 0); + taskPage.save(); + + Assert.assertTrue(tasksPage.findTaskByTag(taskName, TAG)); + } + + @Test + public void testHFindTagInFilter() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + TasksPage tasksPage = (TasksPage) getContext().initPage(page.getKey()); + + + Assert.assertTrue(tasksPage.findTag(TAG)); + } + + @Test + public void testIFilterByTag() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + TasksPage tasksPage = (TasksPage) getContext().initPage(page.getKey()); + tasksPage.selectTag(TAG); + + Assert.assertTrue(tasksPage.findTasksByTag(TAG)); + } + + @Test + public void testJFilterByStatus() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + TasksPage tasksPage = (TasksPage) getContext().initPage(page.getKey()); + + tasksPage.selectStatus(); + Assert.assertTrue(tasksPage.findAllStatus()); + } + + +} diff --git a/src/test/java/students/TaskPage.java b/src/test/java/students/TaskPage.java new file mode 100644 index 0000000..c0105b2 --- /dev/null +++ b/src/test/java/students/TaskPage.java @@ -0,0 +1,81 @@ +package students; + +import core.PageObject; +import org.openqa.selenium.By; +import org.openqa.selenium.Keys; +import org.openqa.selenium.WebElement; + +import java.util.List; + +public class TaskPage extends PageObject { + + @Override + public String getSubTitle() { + return driver.findElement(By.tagName("h3")).getText(); + } + + public void setName(String name) { + driver.findElement(By.id("title")).sendKeys(name); + } + + public void save() { + driver.findElement(By.id("sendMessageButton")).click(); + } + + public void addDeadlineDate(String deadDate, Integer deadNum) { + driver.findElement(By.id(String.format("deadlines%d.date", deadNum))).sendKeys(deadDate); + } + + public void addDeadlineDescription(String deadDescr, Integer deadNum) { + driver.findElement(By.id(String.format("deadlines%d.description", deadNum))).sendKeys(deadDescr); + } + + public void removeName() { + driver.findElement(By.id("title")).clear(); + } + + public String getId() { + return driver.findElement(By.id("id")).getAttribute("value"); + } + + public Integer getDeadNum() { + return driver.findElements(By.cssSelector("#task-form .form-group:nth-of-type(5) .row")).size(); + } + + public void clickAddDeadline() { + driver.findElement(By.cssSelector("#addDeadline")).click(); + } + + public List getDeadlines() { + return driver.findElements(By.cssSelector(".form-group:nth-of-type(5) .row")); + } + + public void deleteDeadline() { + driver.findElement(By.xpath("//*[@id=\"task-form\"]/div/div[1]/div[5]/div[1]/div[3]/a")).click(); + + } + + public void clearDeadlineDate(Integer deadNum) { + driver.findElement(By.id(String.format("deadlines%d.date", deadNum))).sendKeys(Keys.DELETE); + } + + public void clearDeadlineDescription(Integer deadNum) { + driver.findElement(By.id(String.format("deadlines%d.description", deadNum))).clear(); + } + + public boolean hasDeadline(String deadDescr, String deadValue) { + return getDeadlines() + .stream() + .anyMatch(webElement -> { + return webElement.findElement(By.cssSelector("input[type=\"text\"]")).getAttribute("value").equals(deadDescr) + && webElement.findElement(By.cssSelector("input[type=\"date\"]")).getAttribute("value").equals(deadValue); + }); + } + + public void setTag(String tag) { + driver.findElement(By.className("input-tag-name")).sendKeys(tag); + driver.findElement(By.className("input-tag-name")).sendKeys(Keys.ENTER); + } + + +} diff --git a/src/test/java/students/TasksDashboardPage.java b/src/test/java/students/TasksDashboardPage.java new file mode 100644 index 0000000..8cc6eda --- /dev/null +++ b/src/test/java/students/TasksDashboardPage.java @@ -0,0 +1,10 @@ +package students; + +import core.PageObject; + +public class TasksDashboardPage extends PageObject { + @Override + public String getSubTitle() { + return null; + } +} diff --git a/src/test/java/students/TasksPage.java b/src/test/java/students/TasksPage.java new file mode 100644 index 0000000..5c5d42c --- /dev/null +++ b/src/test/java/students/TasksPage.java @@ -0,0 +1,75 @@ +package students; + +import core.PageObject; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; + +import java.util.List; + +public class TasksPage extends PageObject { + + @Override + public String getSubTitle() { + return driver.findElement(By.tagName("h3")).getText(); + } + + public List getTasks() { + return driver.findElements(By.cssSelector("span.h6")); + } + + public List getTaskRows() { + return driver.findElements(By.className("task-row")); + } + + public void goToFirstTask() { + driver.findElement(By.xpath("//*[@id=\"tasks\"]/div/div[2]/div[1]/div/div/a[1]")).click(); + } + + public boolean findTask(String taskName) { + return getTasks().stream() + .anyMatch(webElement -> webElement.getText().equals(taskName)); + + } + + public void deleteFirstTask() { + js.executeScript("$('a[data-confirm]').click();"); + } + + public void submit() { + driver.findElement(By.xpath("//*[@id=\"dataConfirmOK\"]")).click(); + } + + public boolean findTag(String tag) { + driver.findElements(By.className("bootstrap-select")).get(2).findElement(By.className("btn")).click(); + driver.findElement(By.cssSelector(".bs-searchbox input")).sendKeys(tag); + return driver.findElement(By.xpath("//*[@id=\"tasks\"]/div/div[2]/div[2]/div[2]/div[2]/div/div[2]/ul")).findElement(By.className("text")).getText().equals(tag); + } + + public boolean findTaskByTag(String name, String tag) { + return getTasks().stream() + .anyMatch(webElement -> webElement.getText().equals(name) + && webElement.findElement(By.xpath("//*[@id=\"tasks\"]/div/div[2]/div[1]/div/div/a[1]/span[3]")).getText().equals(tag)); + } + + public boolean findTasksByTag(String tag) { + return getTaskRows().stream() + .allMatch(webElement -> webElement.findElement(By.cssSelector("span.text-muted")).getText().equals(tag)); + } + + public void selectTag(String tag) { + driver.findElements(By.className("bootstrap-select")).get(2).findElement(By.className("btn")).click(); + driver.findElement(By.cssSelector(".bs-searchbox input")).sendKeys(tag); + driver.findElement(By.xpath("//*[@id=\"tasks\"]/div/div[2]/div[2]/div[2]/div[2]/div/div[2]/ul/li/a")).click(); + } + + + public void selectStatus() { + driver.findElements(By.className("bootstrap-select")).get(1).findElement(By.className("btn")).click(); + driver.findElement(By.xpath("//*[@id=\"tasks\"]/div/div[2]/div[2]/div[2]/div[1]/div/div/ul/li[2]/a")).click(); + } + + public boolean findAllStatus() { + return getTaskRows().stream() + .allMatch(webElement -> webElement.findElement(By.cssSelector("div i.text-primary")).isDisplayed()); + } +} From 284a3f51e9539c27db16825145815006c1d510ab Mon Sep 17 00:00:00 2001 From: ASH Date: Thu, 23 May 2019 12:07:34 +0400 Subject: [PATCH 21/74] #104 mod tests filter and create tasks --- .../java/ru/ulstu/students/model/TaskDto.java | 20 ++ .../students/service/TaskServiceTest.java | 181 ++++++++++++++++++ 2 files changed, 201 insertions(+) create mode 100644 src/test/java/ru/ulstu/students/service/TaskServiceTest.java diff --git a/src/main/java/ru/ulstu/students/model/TaskDto.java b/src/main/java/ru/ulstu/students/model/TaskDto.java index 8d52e01..1d0eac0 100644 --- a/src/main/java/ru/ulstu/students/model/TaskDto.java +++ b/src/main/java/ru/ulstu/students/model/TaskDto.java @@ -10,6 +10,7 @@ import ru.ulstu.tags.model.Tag; import java.util.ArrayList; import java.util.Date; import java.util.List; +import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; @@ -135,6 +136,25 @@ public class TaskDto { this.tags = tags; } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + TaskDto taskDto = (TaskDto) o; + return Objects.equals(id, taskDto.id) && + Objects.equals(title, taskDto.title) && + Objects.equals(description, taskDto.description) && + status == taskDto.status && + Objects.equals(deadlines, taskDto.deadlines) && + Objects.equals(tagIds, taskDto.tagIds) && + Objects.equals(tags, taskDto.tags); + } + + @Override + public int hashCode() { + return Objects.hash(id, title, description, status, deadlines, createDate, updateDate, tagIds, tags); + } + public String getTagsString() { return StringUtils.abbreviate(tags .stream() diff --git a/src/test/java/ru/ulstu/students/service/TaskServiceTest.java b/src/test/java/ru/ulstu/students/service/TaskServiceTest.java new file mode 100644 index 0000000..e00570c --- /dev/null +++ b/src/test/java/ru/ulstu/students/service/TaskServiceTest.java @@ -0,0 +1,181 @@ +package ru.ulstu.students.service; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import org.springframework.data.domain.Sort; +import ru.ulstu.deadline.model.Deadline; +import ru.ulstu.deadline.service.DeadlineService; +import ru.ulstu.students.model.Task; +import ru.ulstu.students.model.TaskDto; +import ru.ulstu.students.model.TaskFilterDto; +import ru.ulstu.students.repository.TaskRepository; +import ru.ulstu.tags.model.Tag; +import ru.ulstu.tags.service.TagService; +import ru.ulstu.timeline.service.EventService; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class TaskServiceTest { + + @Mock + TaskRepository taskRepository; + + @Mock + private TagService tagService; + + @Mock + DeadlineService deadlineService; + + @Mock + EventService eventService; + + @InjectMocks + TaskService taskService; + + private final static Sort SORT = new Sort(Sort.Direction.DESC, "createDate"); + private final static Integer ID = 1; + private final static Task.TaskStatus STATUS = Task.TaskStatus.IN_WORK; + private final static String TITLE = "title"; + private final static String DESCR = "descr"; + private final static String TAG = "tag"; + + private List tasks; + private List tags; + private Task task; + private TaskFilterDto filterDto; + private TaskDto taskDto; + private List tasksDto; + private Tag tag; + private Tag tagNull; + private Deadline deadline; + private List deadlines; + + + @Before + public void setUp() throws Exception { + + tasks = new ArrayList<>(); + task = new Task(); + + task.setId(ID); + task.setTitle(TITLE); + task.setDescription(DESCR); + + + tag = new Tag(); + tag.setId(ID); + tag.setTagName(TAG); + + deadlines = new ArrayList<>(); + deadline = new Deadline(new Date(), DESCR); + deadline.setId(ID); + deadlines.add(deadline); + + tags = new ArrayList<>(); + tags.add(tag); + + tasks.add(task); + taskDto = new TaskDto(task); + + } + + @Test + public void findAll() { + + when(taskRepository.findAll(SORT)).thenReturn(tasks); + assertEquals(Collections.singletonList(task), taskService.findAll()); + } + + @Test + public void filter() { + when(tagService.findById(ID)).thenReturn(tag); + when(taskRepository.filterNew(STATUS, tag)).thenReturn(tasks); + + TaskFilterDto taskFilterDto = new TaskFilterDto(); + taskFilterDto.setTag(ID); + taskFilterDto.setOrder("new"); + taskFilterDto.setStatus(STATUS); + + assertEquals(Collections.singletonList(taskDto), taskService.filter(taskFilterDto)); + } + + @Test + public void create() throws IOException { + when(tagService.saveOrCreate(new ArrayList<>())).thenReturn(tags); + when(deadlineService.saveOrCreate(new ArrayList<>())).thenReturn(deadlines); + when(taskRepository.save(new Task())).thenReturn(task); + eventService.createFromTask(new Task()); + + taskDto.setTags(tags); + taskDto.setDeadlines(deadlines); + + Task newTask = new Task(); + task.setId(ID); + task.setTitle(TITLE); + task.setDescription(DESCR); + task.setTags(tags); + task.setDeadlines(deadlines); + + assertEquals(task.getId(), taskService.create(taskDto)); + } + + @Test + public void update() { + } + + @Test + public void delete() { + } + + @Test + public void save() { + } + + @Test + public void copyMainPart() { + } + + @Test + public void copyTaskWithNewDates() { + } + + @Test + public void copyTaskWithNewYear() { + } + + @Test + public void generateYearTasks() { + } + + @Test + public void checkRepeatingTags() { + } + + @Test + public void getTaskStatuses() { + } + + @Test + public void getTags() { + } + + @Test + public void findTasksByTag() { + } + + @Test + public void createPeriodTask() { + } +} \ No newline at end of file From 1c8359f900fef08760ad9dc30aaec1103fc867e3 Mon Sep 17 00:00:00 2001 From: Anton Romanov Date: Thu, 23 May 2019 13:54:44 +0400 Subject: [PATCH 22/74] #103 modify files permissions --- src/main/resources/drivers/chromedriver | Bin src/main/resources/drivers/geckodriver | Bin 2 files changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 src/main/resources/drivers/chromedriver mode change 100644 => 100755 src/main/resources/drivers/geckodriver diff --git a/src/main/resources/drivers/chromedriver b/src/main/resources/drivers/chromedriver old mode 100644 new mode 100755 diff --git a/src/main/resources/drivers/geckodriver b/src/main/resources/drivers/geckodriver old mode 100644 new mode 100755 From ef521123dd157ea0381d2b6699be4ac9569e295e Mon Sep 17 00:00:00 2001 From: ASH Date: Thu, 23 May 2019 14:31:34 +0400 Subject: [PATCH 23/74] #104 mod tests check repeatings --- .../java/ru/ulstu/students/model/TaskDto.java | 8 +++- .../ulstu/students/service/TaskService.java | 10 ++-- .../students/service/TaskServiceTest.java | 46 +++++++++++-------- 3 files changed, 38 insertions(+), 26 deletions(-) diff --git a/src/main/java/ru/ulstu/students/model/TaskDto.java b/src/main/java/ru/ulstu/students/model/TaskDto.java index 1d0eac0..2df691f 100644 --- a/src/main/java/ru/ulstu/students/model/TaskDto.java +++ b/src/main/java/ru/ulstu/students/model/TaskDto.java @@ -138,8 +138,12 @@ public class TaskDto { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + 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) && diff --git a/src/main/java/ru/ulstu/students/service/TaskService.java b/src/main/java/ru/ulstu/students/service/TaskService.java index 2be44cb..379314d 100644 --- a/src/main/java/ru/ulstu/students/service/TaskService.java +++ b/src/main/java/ru/ulstu/students/service/TaskService.java @@ -108,7 +108,7 @@ public class TaskService { } @Transactional - public void delete(Integer taskId) throws IOException { + public boolean delete(Integer taskId) throws IOException { if (taskRepository.exists(taskId)) { Task scheduleTask = taskRepository.findOne(taskId); Scheduler sch = schedulerRepository.findOneByTask(scheduleTask); @@ -116,7 +116,9 @@ public class TaskService { schedulerRepository.delete(sch.getId()); } taskRepository.delete(taskId); + return true; } + return false; } @@ -128,14 +130,14 @@ public class TaskService { } } - public void copyMainPart(Task newTask, Task task) { + private void copyMainPart(Task newTask, Task task) { newTask.setTitle(task.getTitle()); newTask.setTags(tagService.saveOrCreate(task.getTags())); newTask.setCreateDate(new Date()); newTask.setStatus(Task.TaskStatus.LOADED_FROM_KIAS); } - public Task copyTaskWithNewDates(Task task) { + private Task copyTaskWithNewDates(Task task) { Task newTask = new Task(); copyMainPart(newTask, task); Calendar cal1 = DateUtils.getCalendar(newTask.getCreateDate()); @@ -157,7 +159,7 @@ public class TaskService { }).collect(Collectors.toList()); } - public Task copyTaskWithNewYear(Task task) { + private Task copyTaskWithNewYear(Task task) { Task newTask = new Task(); copyMainPart(newTask, task); newTask.setDeadlines(newYearDeadlines(task.getDeadlines())); diff --git a/src/test/java/ru/ulstu/students/service/TaskServiceTest.java b/src/test/java/ru/ulstu/students/service/TaskServiceTest.java index e00570c..19eff12 100644 --- a/src/test/java/ru/ulstu/students/service/TaskServiceTest.java +++ b/src/test/java/ru/ulstu/students/service/TaskServiceTest.java @@ -7,11 +7,13 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.data.domain.Sort; +import ru.ulstu.core.util.DateUtils; import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.service.DeadlineService; import ru.ulstu.students.model.Task; import ru.ulstu.students.model.TaskDto; import ru.ulstu.students.model.TaskFilterDto; +import ru.ulstu.students.repository.SchedulerRepository; import ru.ulstu.students.repository.TaskRepository; import ru.ulstu.tags.model.Tag; import ru.ulstu.tags.service.TagService; @@ -21,9 +23,12 @@ import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Date; +import java.util.HashSet; import java.util.List; +import java.util.Set; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) @@ -32,6 +37,9 @@ public class TaskServiceTest { @Mock TaskRepository taskRepository; + @Mock + SchedulerRepository schedulerRepository; + @Mock private TagService tagService; @@ -50,6 +58,7 @@ public class TaskServiceTest { private final static String TITLE = "title"; private final static String DESCR = "descr"; private final static String TAG = "tag"; + private final static Date YEAR = DateUtils.clearTime(DateUtils.addYears(new Date(), 0)); private List tasks; private List tags; @@ -61,6 +70,7 @@ public class TaskServiceTest { private Tag tagNull; private Deadline deadline; private List deadlines; + private Set repeatingTags; @Before @@ -83,12 +93,17 @@ public class TaskServiceTest { deadline.setId(ID); deadlines.add(deadline); + task.setDeadlines(deadlines); + tags = new ArrayList<>(); tags.add(tag); tasks.add(task); taskDto = new TaskDto(task); + repeatingTags = new HashSet<>(); + repeatingTags.add(tag); + } @Test @@ -132,35 +147,26 @@ public class TaskServiceTest { } @Test - public void update() { - } + public void delete() throws IOException { + when(taskRepository.exists(ID)).thenReturn(true); + when(taskRepository.findOne(ID)).thenReturn(task); + when(schedulerRepository.findOneByTask(task)).thenReturn(null); - @Test - public void delete() { - } - - @Test - public void save() { - } - - @Test - public void copyMainPart() { - } - - @Test - public void copyTaskWithNewDates() { - } - - @Test - public void copyTaskWithNewYear() { + assertTrue(taskService.delete(ID)); } @Test public void generateYearTasks() { + when(taskService.checkRepeatingTags(false)).thenReturn(repeatingTags); + } @Test public void checkRepeatingTags() { + when(tagService.findById(ID)).thenReturn(tag); + when(taskRepository.findAllYear(DateUtils.clearTime(DateUtils.addYears(new Date(), -1)))).thenReturn(tasks); + + assertEquals(tag, taskService.checkRepeatingTags(false)); } @Test From 29cfadef02940976788796151f41132d557a5884 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B5=D0=BC=D0=B5=D0=BD=D0=BE=D0=B2=D0=B0=20=D0=9C?= =?UTF-8?q?=D0=B0=D1=80=D0=B8=D1=8F?= Date: Thu, 23 May 2019 15:02:55 +0400 Subject: [PATCH 24/74] #127 reference model, schema --- .../java/ru/ulstu/paper/model/Reference.java | 90 +++++++++++++++++++ .../db/changelog-20190523_000000-schema.xml | 34 +++++++ src/main/resources/db/changelog-master.xml | 1 + 3 files changed, 125 insertions(+) create mode 100644 src/main/java/ru/ulstu/paper/model/Reference.java create mode 100644 src/main/resources/db/changelog-20190523_000000-schema.xml diff --git a/src/main/java/ru/ulstu/paper/model/Reference.java b/src/main/java/ru/ulstu/paper/model/Reference.java new file mode 100644 index 0000000..1901f41 --- /dev/null +++ b/src/main/java/ru/ulstu/paper/model/Reference.java @@ -0,0 +1,90 @@ +package ru.ulstu.paper.model; + +import org.hibernate.validator.constraints.NotBlank; +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 { + + @NotBlank + private String authors; + + @Column(name = "publication_title") + private String publicationTitle; + + @Column(name = "publication_year") + private Integer publicationYear; + + private String publisher; + + private String pages; + + @Column(name = "journal_or_collection_title") + private String journalOrCollectionTitle; + + @Enumerated(value = EnumType.STRING) + @Column(name = "reference_type") + private ReferenceDto.ReferenceType referenceType = ReferenceDto.ReferenceType.ARTICLE; + + public String getAuthors() { + return authors; + } + + public void setAuthors(String authors) { + this.authors = authors; + } + + public String getPublicationTitle() { + return publicationTitle; + } + + public void setPublicationTitle(String publicationTitle) { + this.publicationTitle = publicationTitle; + } + + public Integer getPublicationYear() { + return publicationYear; + } + + public void setPublicationYear(Integer publicationYear) { + this.publicationYear = publicationYear; + } + + public String getPublisher() { + return publisher; + } + + public void setPublisher(String publisher) { + this.publisher = publisher; + } + + public String getPages() { + return pages; + } + + public void setPages(String pages) { + this.pages = pages; + } + + public String getJournalOrCollectionTitle() { + return journalOrCollectionTitle; + } + + public void setJournalOrCollectionTitle(String journalOrCollectionTitle) { + this.journalOrCollectionTitle = journalOrCollectionTitle; + } + + public ReferenceDto.ReferenceType getReferenceType() { + return referenceType; + } + + public void setReferenceType(ReferenceDto.ReferenceType referenceType) { + this.referenceType = referenceType; + } + +} diff --git a/src/main/resources/db/changelog-20190523_000000-schema.xml b/src/main/resources/db/changelog-20190523_000000-schema.xml new file mode 100644 index 0000000..2bdc788 --- /dev/null +++ b/src/main/resources/db/changelog-20190523_000000-schema.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/db/changelog-master.xml b/src/main/resources/db/changelog-master.xml index 18bd645..5011cc5 100644 --- a/src/main/resources/db/changelog-master.xml +++ b/src/main/resources/db/changelog-master.xml @@ -42,4 +42,5 @@ + \ No newline at end of file From 7c1b124c9470821b47c82642a7c6b945724efd04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B5=D0=BC=D0=B5=D0=BD=D0=BE=D0=B2=D0=B0=20=D0=9C?= =?UTF-8?q?=D0=B0=D1=80=D0=B8=D1=8F?= Date: Thu, 23 May 2019 15:48:46 +0400 Subject: [PATCH 25/74] #127 references tab, crud --- .../paper/controller/PaperController.java | 20 ++++ src/main/java/ru/ulstu/paper/model/Paper.java | 13 +++ .../java/ru/ulstu/paper/model/PaperDto.java | 25 ++++- .../java/ru/ulstu/paper/model/Reference.java | 2 - .../ru/ulstu/paper/model/ReferenceDto.java | 39 +++++++- .../paper/repository/ReferenceRepository.java | 8 ++ .../ru/ulstu/paper/service/PaperService.java | 57 +++++++++++ .../db/changelog-20190523_000000-schema.xml | 13 +-- src/main/resources/public/css/paper.css | 20 ++++ .../resources/templates/papers/paper.html | 97 ++++++++++++++++++- 10 files changed, 279 insertions(+), 15 deletions(-) create mode 100644 src/main/java/ru/ulstu/paper/repository/ReferenceRepository.java diff --git a/src/main/java/ru/ulstu/paper/controller/PaperController.java b/src/main/java/ru/ulstu/paper/controller/PaperController.java index 41d5586..beae772 100644 --- a/src/main/java/ru/ulstu/paper/controller/PaperController.java +++ b/src/main/java/ru/ulstu/paper/controller/PaperController.java @@ -16,6 +16,7 @@ import ru.ulstu.deadline.model.Deadline; import ru.ulstu.paper.model.Paper; import ru.ulstu.paper.model.PaperDto; import ru.ulstu.paper.model.PaperListDto; +import ru.ulstu.paper.model.ReferenceDto; import ru.ulstu.paper.service.LatexService; import ru.ulstu.paper.service.PaperService; import ru.ulstu.user.model.User; @@ -105,6 +106,15 @@ public class PaperController { return "/papers/paper"; } + @PostMapping(value = "/paper", params = "addReference") + public String addReference(@Valid PaperDto paperDto, Errors errors) { + if (errors.hasErrors()) { + return "/papers/paper"; + } + paperDto.getReferences().add(new ReferenceDto()); + return "/papers/paper"; + } + @ModelAttribute("allStatuses") public List getPaperStatuses() { return paperService.getPaperStatuses(); @@ -129,6 +139,16 @@ public class PaperController { return years; } + @ModelAttribute("allFormatStandards") + public List getFormatStandards() { + return paperService.getFormatStandards(); + } + + @ModelAttribute("allReferenceTypes") + public List getReferenceTypes() { + return paperService.getReferenceTypes(); + } + @PostMapping("/generatePdf") public ResponseEntity getPdfFile(PaperDto paper) throws IOException, InterruptedException { HttpHeaders headers = new HttpHeaders(); diff --git a/src/main/java/ru/ulstu/paper/model/Paper.java b/src/main/java/ru/ulstu/paper/model/Paper.java index 15ee4b4..413c5db 100644 --- a/src/main/java/ru/ulstu/paper/model/Paper.java +++ b/src/main/java/ru/ulstu/paper/model/Paper.java @@ -123,6 +123,11 @@ public class Paper extends BaseEntity implements UserContainer { @ManyToMany(mappedBy = "papers") private List grants; + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @JoinColumn(name = "paper_id", unique = true) + @Fetch(FetchMode.SUBSELECT) + private List references = new ArrayList<>(); + public PaperStatus getStatus() { return status; } @@ -248,6 +253,14 @@ public class Paper extends BaseEntity implements UserContainer { return getAuthors(); } + public List getReferences() { + return references; + } + + public void setReferences(List references) { + this.references = references; + } + public Optional getNextDeadline() { return deadlines .stream() diff --git a/src/main/java/ru/ulstu/paper/model/PaperDto.java b/src/main/java/ru/ulstu/paper/model/PaperDto.java index 11d6dfc..8474a34 100644 --- a/src/main/java/ru/ulstu/paper/model/PaperDto.java +++ b/src/main/java/ru/ulstu/paper/model/PaperDto.java @@ -38,6 +38,8 @@ public class PaperDto { private Set authors; private Integer filterAuthorId; private String latexText; + private List references = new ArrayList<>(); + private ReferenceDto.FormatStandard formatStandard = ReferenceDto.FormatStandard.GOST; public PaperDto() { deadlines.add(new Deadline()); @@ -57,7 +59,9 @@ public class PaperDto { @JsonProperty("locked") Boolean locked, @JsonProperty("files") List files, @JsonProperty("authorIds") Set authorIds, - @JsonProperty("authors") Set authors) { + @JsonProperty("authors") Set authors, + @JsonProperty("references") List references, + @JsonProperty("formatStandard") ReferenceDto.FormatStandard formatStandard) { this.id = id; this.title = title; this.status = status; @@ -71,6 +75,8 @@ public class PaperDto { this.locked = locked; this.files = files; this.authors = authors; + this.references = references; + this.formatStandard = formatStandard; } public PaperDto(Paper paper) { @@ -88,6 +94,7 @@ public class PaperDto { this.files = convert(paper.getFiles(), FileDataDto::new); this.authorIds = convert(paper.getAuthors(), user -> user.getId()); this.authors = convert(paper.getAuthors(), UserDto::new); + this.references = convert(paper.getReferences(), ReferenceDto::new); } public Integer getId() { @@ -216,4 +223,20 @@ public class PaperDto { public void setFilterAuthorId(Integer filterAuthorId) { this.filterAuthorId = filterAuthorId; } + + public List getReferences() { + return references; + } + + public void setReferences(List references) { + this.references = references; + } + + public ReferenceDto.FormatStandard getFormatStandard() { + return formatStandard; + } + + public void setFormatStandard(ReferenceDto.FormatStandard formatStandard) { + this.formatStandard = formatStandard; + } } diff --git a/src/main/java/ru/ulstu/paper/model/Reference.java b/src/main/java/ru/ulstu/paper/model/Reference.java index 1901f41..289cdc1 100644 --- a/src/main/java/ru/ulstu/paper/model/Reference.java +++ b/src/main/java/ru/ulstu/paper/model/Reference.java @@ -1,6 +1,5 @@ package ru.ulstu.paper.model; -import org.hibernate.validator.constraints.NotBlank; import ru.ulstu.core.model.BaseEntity; import javax.persistence.Column; @@ -11,7 +10,6 @@ import javax.persistence.Enumerated; @Entity public class Reference extends BaseEntity { - @NotBlank private String authors; @Column(name = "publication_title") diff --git a/src/main/java/ru/ulstu/paper/model/ReferenceDto.java b/src/main/java/ru/ulstu/paper/model/ReferenceDto.java index 8d71ae5..1705e08 100644 --- a/src/main/java/ru/ulstu/paper/model/ReferenceDto.java +++ b/src/main/java/ru/ulstu/paper/model/ReferenceDto.java @@ -34,6 +34,7 @@ public class ReferenceDto { } } + private Integer id; private String authors; private String publicationTitle; private Integer publicationYear; @@ -42,9 +43,11 @@ public class ReferenceDto { private String journalOrCollectionTitle; private ReferenceType referenceType; private FormatStandard formatStandard; + private boolean deleted; @JsonCreator public ReferenceDto( + @JsonProperty("id") Integer id, @JsonProperty("authors") String authors, @JsonProperty("publicationTitle") String publicationTitle, @JsonProperty("publicationYear") Integer publicationYear, @@ -52,7 +55,9 @@ public class ReferenceDto { @JsonProperty("pages") String pages, @JsonProperty("journalOrCollectionTitle") String journalOrCollectionTitle, @JsonProperty("referenceType") ReferenceType referenceType, - @JsonProperty("formatStandard") FormatStandard formatStandard) { + @JsonProperty("formatStandard") FormatStandard formatStandard, + @JsonProperty("isDeleted") boolean deleted) { + this.id = id; this.authors = authors; this.publicationTitle = publicationTitle; this.publicationYear = publicationYear; @@ -61,6 +66,22 @@ public class ReferenceDto { this.journalOrCollectionTitle = journalOrCollectionTitle; this.referenceType = referenceType; this.formatStandard = formatStandard; + this.deleted = deleted; + } + + public ReferenceDto(Reference reference) { + this.id = reference.getId(); + this.authors = reference.getAuthors(); + this.publicationTitle = reference.getPublicationTitle(); + this.publicationYear = reference.getPublicationYear(); + this.publisher = reference.getPublisher(); + this.pages = reference.getPages(); + this.journalOrCollectionTitle = reference.getJournalOrCollectionTitle(); + this.referenceType = reference.getReferenceType(); + } + + public ReferenceDto() { + referenceType = ReferenceType.ARTICLE; } public String getAuthors() { @@ -126,4 +147,20 @@ public class ReferenceDto { public void setFormatStandard(FormatStandard formatStandard) { this.formatStandard = formatStandard; } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public boolean getDeleted() { + return deleted; + } + + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } } diff --git a/src/main/java/ru/ulstu/paper/repository/ReferenceRepository.java b/src/main/java/ru/ulstu/paper/repository/ReferenceRepository.java new file mode 100644 index 0000000..68e97d4 --- /dev/null +++ b/src/main/java/ru/ulstu/paper/repository/ReferenceRepository.java @@ -0,0 +1,8 @@ +package ru.ulstu.paper.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import ru.ulstu.paper.model.Reference; + +public interface ReferenceRepository extends JpaRepository { + void deleteById(Integer id); +} diff --git a/src/main/java/ru/ulstu/paper/service/PaperService.java b/src/main/java/ru/ulstu/paper/service/PaperService.java index db810f5..8658015 100644 --- a/src/main/java/ru/ulstu/paper/service/PaperService.java +++ b/src/main/java/ru/ulstu/paper/service/PaperService.java @@ -10,8 +10,10 @@ import ru.ulstu.file.service.FileService; import ru.ulstu.paper.model.Paper; import ru.ulstu.paper.model.PaperDto; import ru.ulstu.paper.model.PaperListDto; +import ru.ulstu.paper.model.Reference; import ru.ulstu.paper.model.ReferenceDto; import ru.ulstu.paper.repository.PaperRepository; +import ru.ulstu.paper.repository.ReferenceRepository; import ru.ulstu.timeline.service.EventService; import ru.ulstu.user.model.User; import ru.ulstu.user.service.UserService; @@ -39,6 +41,7 @@ import static ru.ulstu.paper.model.ReferenceDto.ReferenceType.ARTICLE; import static ru.ulstu.paper.model.ReferenceDto.ReferenceType.BOOK; @Service +@Transactional public class PaperService { private final static int MAX_DISPLAY_SIZE = 40; private final static String PAPER_FORMATTED_TEMPLATE = "%s %s"; @@ -49,14 +52,17 @@ public class PaperService { private final DeadlineService deadlineService; private final FileService fileService; private final EventService eventService; + private final ReferenceRepository referenceRepository; public PaperService(PaperRepository paperRepository, + ReferenceRepository referenceRepository, FileService fileService, PaperNotificationService paperNotificationService, UserService userService, DeadlineService deadlineService, EventService eventService) { this.paperRepository = paperRepository; + this.referenceRepository = referenceRepository; this.fileService = fileService; this.paperNotificationService = paperNotificationService; this.userService = userService; @@ -117,6 +123,7 @@ public class PaperService { paper.setTitle(paperDto.getTitle()); paper.setUpdateDate(new Date()); paper.setDeadlines(deadlineService.saveOrCreate(paperDto.getDeadlines())); + paper.setReferences(saveOrCreateReferences(paperDto.getReferences())); paper.setFiles(fileService.saveOrCreate(paperDto.getFiles().stream() .filter(f -> !f.isDeleted()) .collect(toList()))); @@ -127,6 +134,43 @@ public class PaperService { return paper; } + public List saveOrCreateReferences(List references) { + return references + .stream() + .filter(reference -> !reference.getDeleted()) + .map(reference -> reference.getId() != null ? updateReference(reference) : createReference(reference)) + .collect(Collectors.toList()); + } + + @Transactional + public Reference updateReference(ReferenceDto referenceDto) { + Reference updateReference = referenceRepository.findOne(referenceDto.getId()); + updateReference.setAuthors(referenceDto.getAuthors()); + updateReference.setJournalOrCollectionTitle(referenceDto.getJournalOrCollectionTitle()); + updateReference.setPages(referenceDto.getPages()); + updateReference.setPublicationTitle(referenceDto.getPublicationTitle()); + updateReference.setPublicationYear(referenceDto.getPublicationYear()); + updateReference.setPublisher(referenceDto.getPublisher()); + updateReference.setReferenceType(referenceDto.getReferenceType()); + referenceRepository.save(updateReference); + return updateReference; + } + + @Transactional + public Reference createReference(ReferenceDto referenceDto) { + Reference newReference = new Reference(); + newReference.setAuthors(referenceDto.getAuthors()); + newReference.setJournalOrCollectionTitle(referenceDto.getJournalOrCollectionTitle()); + newReference.setPages(referenceDto.getPages()); + newReference.setPublicationTitle(referenceDto.getPublicationTitle()); + newReference.setPublicationYear(referenceDto.getPublicationYear()); + newReference.setPublisher(referenceDto.getPublisher()); + newReference.setReferenceType(referenceDto.getReferenceType()); + newReference = referenceRepository.save(newReference); + return newReference; + } + + @Transactional public Integer update(PaperDto paperDto) throws IOException { Paper paper = paperRepository.findOne(paperDto.getId()); @@ -139,6 +183,11 @@ public class PaperService { fileService.delete(file.getId()); } paperRepository.save(copyFromDto(paper, paperDto)); + for (ReferenceDto referenceDto : paperDto.getReferences().stream() + .filter(f -> f.getDeleted() && f.getId() != null) + .collect(toList())) { + referenceRepository.deleteById(referenceDto.getId()); + } eventService.updatePaperDeadlines(paper); paper.getAuthors().forEach(author -> { @@ -168,6 +217,14 @@ public class PaperService { return Arrays.asList(Paper.PaperType.values()); } + public List getFormatStandards() { + return Arrays.asList(ReferenceDto.FormatStandard.values()); + } + + public List getReferenceTypes() { + return Arrays.asList(ReferenceDto.ReferenceType.values()); + } + @Transactional public Paper create(String title, User user, Date deadlineDate) { Paper paper = new Paper(); diff --git a/src/main/resources/db/changelog-20190523_000000-schema.xml b/src/main/resources/db/changelog-20190523_000000-schema.xml index 2bdc788..aca880f 100644 --- a/src/main/resources/db/changelog-20190523_000000-schema.xml +++ b/src/main/resources/db/changelog-20190523_000000-schema.xml @@ -7,20 +7,13 @@ - - - - - - - - - + + + - diff --git a/src/main/resources/public/css/paper.css b/src/main/resources/public/css/paper.css index 824209f..1be8c1f 100644 --- a/src/main/resources/public/css/paper.css +++ b/src/main/resources/public/css/paper.css @@ -6,4 +6,24 @@ .nav-tabs { margin-bottom: 20px; +} + +#nav-references label, #nav-references select, #nav-references input { + display: inline-block; + vertical-align: middle; +} + +#nav-references .collapse-heading { + border: 1px solid #ddd; + border-radius: 4px; + padding: 5px 15px; + background-color: #efefef; +} + +#nav-references .collapse-heading a { + text-decoration: none; +} + +#nav-references a:hover { + text-decoration: none; } \ No newline at end of file diff --git a/src/main/resources/templates/papers/paper.html b/src/main/resources/templates/papers/paper.html index d408913..ef4217d 100644 --- a/src/main/resources/templates/papers/paper.html +++ b/src/main/resources/templates/papers/paper.html @@ -31,6 +31,9 @@ href="#nav-main" role="tab" aria-controls="nav-main" aria-selected="true">Статья Latex + References
+
@@ -378,7 +474,6 @@ $('#pdfBtn').prop('disabled', false); } } -
From c303d65c8d8c02fc0d86c4ec332067e334cfe7ec Mon Sep 17 00:00:00 2001 From: Anton Romanov Date: Thu, 23 May 2019 16:02:44 +0400 Subject: [PATCH 26/74] #120 move to services --- build.gradle | 2 +- .../java/ru/ulstu/grant/page/KiasPage.java | 52 ++ .../ulstu/grant/service/GrantScheduler.java | 24 +- .../ru/ulstu/grant/service/GrantService.java | 20 +- .../ru/ulstu/grant/service/KiasService.java | 83 +++ .../ru/ulstu/user/service/UserService.java | 693 +++++++++--------- src/main/resources/drivers/chromedriver | Bin src/main/resources/drivers/geckodriver | Bin 8 files changed, 512 insertions(+), 362 deletions(-) create mode 100644 src/main/java/ru/ulstu/grant/page/KiasPage.java create mode 100644 src/main/java/ru/ulstu/grant/service/KiasService.java mode change 100644 => 100755 src/main/resources/drivers/chromedriver mode change 100644 => 100755 src/main/resources/drivers/geckodriver diff --git a/build.gradle b/build.gradle index 38de2c7..71c9977 100644 --- a/build.gradle +++ b/build.gradle @@ -126,6 +126,6 @@ dependencies { compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.6.0' testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test' - testCompile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '3.3.1' + compile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '3.3.1' } \ No newline at end of file diff --git a/src/main/java/ru/ulstu/grant/page/KiasPage.java b/src/main/java/ru/ulstu/grant/page/KiasPage.java new file mode 100644 index 0000000..4353684 --- /dev/null +++ b/src/main/java/ru/ulstu/grant/page/KiasPage.java @@ -0,0 +1,52 @@ +package ru.ulstu.grant.page; + +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; + +import java.util.ArrayList; +import java.util.List; +import java.util.NoSuchElementException; + +public class KiasPage { + private WebDriver driver; + public KiasPage(WebDriver webDriver) { + this.driver = webDriver; + } + + public List getGrants() { + List grants = new ArrayList<>(); + do { + grants.addAll(getPageOfGrants()); + } + while (checkPagination()); + + return grants; + } + + public List getPageOfGrants() { + WebElement listContest = driver.findElement(By.tagName("tBody")); + List grants = listContest.findElements(By.cssSelector("tr.tr")); + return grants; + } + + public boolean checkPagination() { + try { + if (driver.findElements(By.id("js-ctrlNext")).size() > 0) { + driver.findElement(By.id("js-ctrlNext")).click(); + return true; + } + } catch (NoSuchElementException e) { + return false; + } + return false; + } + + public String getGrantTitle(WebElement grant) { + return grant.findElement(By.cssSelector("td.tertiary")).findElement(By.tagName("a")).getText(); + } + + public String getFirstDeadline(WebElement grant) { + return grant.findElement(By.xpath("./td[5]")).getText(); + } +} diff --git a/src/main/java/ru/ulstu/grant/service/GrantScheduler.java b/src/main/java/ru/ulstu/grant/service/GrantScheduler.java index efe1e41..fb236af 100644 --- a/src/main/java/ru/ulstu/grant/service/GrantScheduler.java +++ b/src/main/java/ru/ulstu/grant/service/GrantScheduler.java @@ -5,6 +5,9 @@ import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; +import java.io.IOException; +import java.text.ParseException; + @Service public class GrantScheduler { private final static boolean IS_DEADLINE_NOTIFICATION_BEFORE_WEEK = true; @@ -31,22 +34,11 @@ public class GrantScheduler { @Scheduled(cron = "0 0 8 1 * ?", zone = "Europe/Samara") public void loadGrantsFromKias() { log.debug("GrantScheduler.loadGrantsFromKias started"); - // - // Метод для сохранения загруженных грантов - // - -// List grants = IndexKiasTest.getNewGrantsDto(); -// grants.forEach(grantDto -> { -// try { -// if (grantService.saveFromKias(grantDto)) { -// log.debug("GrantScheduler.loadGrantsFromKias new grant was loaded"); -// } else { -// log.debug("GrantScheduler.loadGrantsFromKias grant wasn't loaded, cause it's already exists"); -// } -// } catch (IOException e) { -// e.printStackTrace(); -// } -// }); + try { + grantService.createFromKias(); + } catch (ParseException | IOException e) { + e.printStackTrace(); + } log.debug("GrantScheduler.loadGrantsFromKias finished"); } } diff --git a/src/main/java/ru/ulstu/grant/service/GrantService.java b/src/main/java/ru/ulstu/grant/service/GrantService.java index 38c16c3..8d65da7 100644 --- a/src/main/java/ru/ulstu/grant/service/GrantService.java +++ b/src/main/java/ru/ulstu/grant/service/GrantService.java @@ -1,6 +1,8 @@ package ru.ulstu.grant.service; import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.Errors; @@ -23,6 +25,7 @@ import ru.ulstu.user.model.User; import ru.ulstu.user.service.UserService; import java.io.IOException; +import java.text.ParseException; import java.util.Arrays; import java.util.Collections; import java.util.Date; @@ -39,6 +42,7 @@ import static ru.ulstu.grant.model.Grant.GrantStatus.APPLICATION; @Service 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 ProjectService projectService; @@ -48,6 +52,7 @@ public class GrantService extends BaseService { private final PaperService paperService; private final EventService eventService; private final GrantNotificationService grantNotificationService; + private final KiasService kiasService; public GrantService(GrantRepository grantRepository, FileService fileService, @@ -56,8 +61,10 @@ public class GrantService extends BaseService { UserService userService, PaperService paperService, EventService eventService, - GrantNotificationService grantNotificationService) { + GrantNotificationService grantNotificationService, + KiasService kiasService) { this.grantRepository = grantRepository; + this.kiasService = kiasService; this.baseRepository = grantRepository; this.fileService = fileService; this.deadlineService = deadlineService; @@ -317,4 +324,15 @@ public class GrantService extends BaseService { .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"); + } + } + } } diff --git a/src/main/java/ru/ulstu/grant/service/KiasService.java b/src/main/java/ru/ulstu/grant/service/KiasService.java new file mode 100644 index 0000000..6ff0bd9 --- /dev/null +++ b/src/main/java/ru/ulstu/grant/service/KiasService.java @@ -0,0 +1,83 @@ +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.deadline.model.Deadline; +import ru.ulstu.grant.model.Grant; +import ru.ulstu.grant.model.GrantDto; +import ru.ulstu.grant.page.KiasPage; +import ru.ulstu.user.service.UserService; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +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 int CONTEST_YEAR = Calendar.getInstance().get(Calendar.YEAR); + + 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; + private WebDriver webDriver; + + public KiasService(UserService userService) { + System.setProperty(DRIVER_TYPE, getDriverExecutablePath()); + this.userService = userService; + final ChromeOptions chromeOptions = new ChromeOptions(); + chromeOptions.addArguments("--headless"); + webDriver = new ChromeDriver(chromeOptions); + } + + public List getNewGrantsDto() throws ParseException { + webDriver.get(String.format(BASE_URL, CONTEST_STATUS_ID, CONTEST_TYPE, CONTEST_YEAR)); + KiasPage kiasPage = new KiasPage(webDriver); + List kiasGrants = new ArrayList<>(); + List newGrants = new ArrayList<>(); + do { + kiasGrants.addAll(kiasPage.getPageOfGrants()); + for (WebElement grant : kiasGrants) { + GrantDto grantDto = new GrantDto(); + grantDto.setTitle(kiasPage.getGrantTitle(grant)); + String deadlineDate = kiasPage.getFirstDeadline(grant); //10.06.2019 23:59 + SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm"); + Date date = formatter.parse(deadlineDate); + Deadline deadline = new Deadline(date, "Окончание приёма заявок"); + grantDto.setDeadlines(Arrays.asList(deadline)); + grantDto.setLeaderId(userService.findOneByLoginIgnoreCase("admin").getId()); + grantDto.setStatus(Grant.GrantStatus.LOADED_FROM_KIAS); + newGrants.add(grantDto); + } + kiasGrants.clear(); + } + while (kiasPage.checkPagination()); //проверка существования следующей страницы с грантами + + return newGrants; + } + + private String getDriverExecutablePath() { + return KiasService.class.getClassLoader().getResource( + String.format(DRIVER_LOCATION, getDriverExecutable(isWindows()))).getFile(); + } + + private String getDriverExecutable(boolean isWindows) { + return isWindows ? WINDOWS_DRIVER : LINUX_DRIVER; + } + + private boolean isWindows() { + return System.getProperty("os.name").toLowerCase().contains("windows"); + } +} diff --git a/src/main/java/ru/ulstu/user/service/UserService.java b/src/main/java/ru/ulstu/user/service/UserService.java index c889caa..30eeb19 100644 --- a/src/main/java/ru/ulstu/user/service/UserService.java +++ b/src/main/java/ru/ulstu/user/service/UserService.java @@ -1,344 +1,349 @@ -package ru.ulstu.user.service; - -import com.google.common.collect.ImmutableMap; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Sort; -import org.springframework.mail.MailException; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.StringUtils; -import ru.ulstu.configuration.ApplicationProperties; -import ru.ulstu.core.error.EntityIdIsNullException; -import ru.ulstu.core.jpa.OffsetablePageRequest; -import ru.ulstu.core.model.BaseEntity; -import ru.ulstu.core.model.response.PageableItems; -import ru.ulstu.user.error.UserActivationError; -import ru.ulstu.user.error.UserEmailExistsException; -import ru.ulstu.user.error.UserIdExistsException; -import ru.ulstu.user.error.UserIsUndeadException; -import ru.ulstu.user.error.UserLoginExistsException; -import ru.ulstu.user.error.UserNotActivatedException; -import ru.ulstu.user.error.UserNotFoundException; -import ru.ulstu.user.error.UserPasswordsNotValidOrNotMatchException; -import ru.ulstu.user.error.UserResetKeyError; -import ru.ulstu.user.error.UserSendingMailException; -import ru.ulstu.user.model.User; -import ru.ulstu.user.model.UserDto; -import ru.ulstu.user.model.UserListDto; -import ru.ulstu.user.model.UserResetPasswordDto; -import ru.ulstu.user.model.UserRole; -import ru.ulstu.user.model.UserRoleConstants; -import ru.ulstu.user.model.UserRoleDto; -import ru.ulstu.user.repository.UserRepository; -import ru.ulstu.user.repository.UserRoleRepository; -import ru.ulstu.user.util.UserUtils; - -import javax.mail.MessagingException; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -@Service -@Transactional -public class UserService implements UserDetailsService { - private static final String INVITE_USER_EXCEPTION = "Во время отправки приглашения произошла ошибка"; - - private final Logger log = LoggerFactory.getLogger(UserService.class); - private final UserRepository userRepository; - private final PasswordEncoder passwordEncoder; - private final UserRoleRepository userRoleRepository; - private final UserMapper userMapper; - private final MailService mailService; - private final ApplicationProperties applicationProperties; - - public UserService(UserRepository userRepository, - PasswordEncoder passwordEncoder, - UserRoleRepository userRoleRepository, - UserMapper userMapper, - MailService mailService, - ApplicationProperties applicationProperties) { - this.userRepository = userRepository; - this.passwordEncoder = passwordEncoder; - this.userRoleRepository = userRoleRepository; - this.userMapper = userMapper; - this.mailService = mailService; - this.applicationProperties = applicationProperties; - } - - private User getUserByEmail(String email) { - return userRepository.findOneByEmailIgnoreCase(email); - } - - private User getUserByActivationKey(String activationKey) { - return userRepository.findOneByActivationKey(activationKey); - } - - public User getUserByLogin(String login) { - return userRepository.findOneByLoginIgnoreCase(login); - } - - @Transactional(readOnly = true) - public UserDto getUserWithRolesById(Integer userId) { - final User userEntity = userRepository.findOneWithRolesById(userId); - if (userEntity == null) { - throw new UserNotFoundException(userId.toString()); - } - return userMapper.userEntityToUserDto(userEntity); - } - - @Transactional(readOnly = true) - public PageableItems getAllUsers(int offset, int count) { - final Page page = userRepository.findAll(new OffsetablePageRequest(offset, count, new Sort("id"))); - return new PageableItems<>(page.getTotalElements(), userMapper.userEntitiesToUserListDtos(page.getContent())); - } - - // TODO: read only active users - public List findAll() { - return userRepository.findAll(); - } - - @Transactional(readOnly = true) - public PageableItems getUserRoles() { - final List roles = userRoleRepository.findAll().stream() - .map(UserRoleDto::new) - .sorted(Comparator.comparing(UserRoleDto::getViewValue)) - .collect(Collectors.toList()); - return new PageableItems<>(roles.size(), roles); - } - - public UserDto createUser(UserDto userDto) { - if (userDto.getId() != null) { - throw new UserIdExistsException(); - } - if (getUserByLogin(userDto.getLogin()) != null) { - throw new UserLoginExistsException(userDto.getLogin()); - } - if (getUserByEmail(userDto.getEmail()) != null) { - throw new UserEmailExistsException(userDto.getEmail()); - } - if (!userDto.isPasswordsValid()) { - throw new UserPasswordsNotValidOrNotMatchException(""); - } - User user = userMapper.userDtoToUserEntity(userDto); - user.setActivated(false); - user.setActivationKey(UserUtils.generateActivationKey()); - user.setRoles(Collections.singleton(new UserRole(UserRoleConstants.USER))); - user.setPassword(passwordEncoder.encode(userDto.getPassword())); - user = userRepository.save(user); - mailService.sendActivationEmail(user); - log.debug("Created Information for User: {}", user.getLogin()); - return userMapper.userEntityToUserDto(user); - } - - public UserDto activateUser(String activationKey) { - final User user = getUserByActivationKey(activationKey); - if (user == null) { - throw new UserActivationError(activationKey); - } - user.setActivated(true); - user.setActivationKey(null); - user.setActivationDate(null); - log.debug("Activated user: {}", user.getLogin()); - return userMapper.userEntityToUserDto(userRepository.save(user)); - } - - public UserDto updateUser(UserDto userDto) { - if (userDto.getId() == null) { - throw new EntityIdIsNullException(); - } - if (!Objects.equals( - Optional.ofNullable(getUserByEmail(userDto.getEmail())) - .map(BaseEntity::getId).orElse(userDto.getId()), - userDto.getId())) { - throw new UserEmailExistsException(userDto.getEmail()); - } - if (!Objects.equals( - Optional.ofNullable(getUserByLogin(userDto.getLogin())) - .map(BaseEntity::getId).orElse(userDto.getId()), - userDto.getId())) { - throw new UserLoginExistsException(userDto.getLogin()); - } - User user = userRepository.findOne(userDto.getId()); - if (user == null) { - throw new UserNotFoundException(userDto.getId().toString()); - } - if (applicationProperties.getUndeadUserLogin().equalsIgnoreCase(user.getLogin())) { - userDto.setLogin(applicationProperties.getUndeadUserLogin()); - userDto.setActivated(true); - userDto.setRoles(Collections.singletonList(new UserRoleDto(UserRoleConstants.ADMIN))); - } - user.setLogin(userDto.getLogin()); - user.setFirstName(userDto.getFirstName()); - user.setLastName(userDto.getLastName()); - user.setEmail(userDto.getEmail()); - if (userDto.isActivated() != user.getActivated()) { - if (userDto.isActivated()) { - user.setActivationKey(null); - user.setActivationDate(null); - } else { - user.setActivationKey(UserUtils.generateActivationKey()); - user.setActivationDate(new Date()); - } - } - user.setActivated(userDto.isActivated()); - final Set roles = userMapper.rolesFromDto(userDto.getRoles()); - user.setRoles(roles.isEmpty() - ? Collections.singleton(new UserRole(UserRoleConstants.USER)) - : roles); - if (!StringUtils.isEmpty(userDto.getOldPassword())) { - if (!userDto.isPasswordsValid() || !userDto.isOldPasswordValid()) { - throw new UserPasswordsNotValidOrNotMatchException(""); - } - if (!passwordEncoder.matches(userDto.getOldPassword(), user.getPassword())) { - throw new UserPasswordsNotValidOrNotMatchException(""); - } - user.setPassword(passwordEncoder.encode(userDto.getPassword())); - log.debug("Changed password for User: {}", user.getLogin()); - } - user = userRepository.save(user); - log.debug("Changed Information for User: {}", user.getLogin()); - return userMapper.userEntityToUserDto(user); - } - - public UserDto updateUserInformation(User user, UserDto updateUser) { - user.setFirstName(updateUser.getFirstName()); - user.setLastName(updateUser.getLastName()); - user.setEmail(updateUser.getEmail()); - user.setLogin(updateUser.getLogin()); - user = userRepository.save(user); - log.debug("Updated Information for User: {}", user.getLogin()); - return userMapper.userEntityToUserDto(user); - } - - public void changeUserPassword(User user, Map payload) { - if (!payload.get("password").equals(payload.get("confirmPassword"))) { - throw new UserPasswordsNotValidOrNotMatchException(""); - } - if (!passwordEncoder.matches(payload.get("oldPassword"), user.getPassword())) { - throw new UserPasswordsNotValidOrNotMatchException("Старый пароль введен неправильно"); - } - user.setPassword(passwordEncoder.encode(payload.get("password"))); - log.debug("Changed password for User: {}", user.getLogin()); - userRepository.save(user); - - mailService.sendChangePasswordMail(user); - } - - public boolean requestUserPasswordReset(String email) { - User user = userRepository.findOneByEmailIgnoreCase(email); - if (user == null) { - throw new UserNotFoundException(email); - } - if (!user.getActivated()) { - throw new UserNotActivatedException(); - } - user.setResetKey(UserUtils.generateResetKey()); - user.setResetDate(new Date()); - user = userRepository.save(user); - mailService.sendPasswordResetMail(user); - log.debug("Created Reset Password Request for User: {}", user.getLogin()); - return true; - } - - public boolean completeUserPasswordReset(String key, UserResetPasswordDto userResetPasswordDto) { - if (!userResetPasswordDto.isPasswordsValid()) { - throw new UserPasswordsNotValidOrNotMatchException(""); - } - User user = userRepository.findOneByResetKey(key); - if (user == null) { - throw new UserResetKeyError(key); - } - user.setPassword(passwordEncoder.encode(userResetPasswordDto.getPassword())); - user.setResetKey(null); - user.setResetDate(null); - user = userRepository.save(user); - log.debug("Reset Password for User: {}", user.getLogin()); - return true; - } - - public UserDto deleteUser(Integer userId) { - final User user = userRepository.findOne(userId); - if (user == null) { - throw new UserNotFoundException(userId.toString()); - } - if (applicationProperties.getUndeadUserLogin().equalsIgnoreCase(user.getLogin())) { - throw new UserIsUndeadException(user.getLogin()); - } - userRepository.delete(user); - log.debug("Deleted User: {}", user.getLogin()); - return userMapper.userEntityToUserDto(user); - } - - @Override - public UserDetails loadUserByUsername(String username) { - final User user = userRepository.findOneByLoginIgnoreCase(username); - if (user == null) { - throw new UserNotFoundException(username); - } - if (!user.getActivated()) { - throw new UserNotActivatedException(); - } - return new org.springframework.security.core.userdetails.User(user.getLogin(), - user.getPassword(), - Optional.ofNullable(user.getRoles()).orElse(Collections.emptySet()).stream() - .map(role -> new SimpleGrantedAuthority(role.getName())) - .collect(Collectors.toList())); - } - - public List findByIds(List ids) { - return userRepository.findAll(ids); - } - - public User findById(Integer id) { - return userRepository.findOne(id); - } - - public User getCurrentUser() { - String login = UserUtils.getCurrentUserLogin(); - User user = userRepository.findOneByLoginIgnoreCase(login); - if (user == null) { - throw new UserNotFoundException(login); - } - return user; - } - - public List filterByAgeAndDegree(boolean hasDegree, boolean hasAge) { - return userRepository.filterByAgeAndDegree(hasDegree, hasAge); - } - - public void inviteUser(String email) throws UserSendingMailException { - if (userRepository.findOneByEmailIgnoreCase(email) != null) { - throw new UserEmailExistsException(email); - } - - String password = UserUtils.generatePassword(); - - User user = new User(); - user.setPassword(passwordEncoder.encode(password)); - user.setLogin(email); - user.setEmail(email); - user.setFirstName("user"); - user.setLastName("user"); - user.setActivated(true); - userRepository.save(user); - - Map variables = ImmutableMap.of("password", password, "email", email); - try { - mailService.sendInviteMail(variables, email); - } catch (MessagingException | MailException e) { - throw new UserSendingMailException(email); - } - } -} +package ru.ulstu.user.service; + +import com.google.common.collect.ImmutableMap; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Sort; +import org.springframework.mail.MailException; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; +import ru.ulstu.configuration.ApplicationProperties; +import ru.ulstu.core.error.EntityIdIsNullException; +import ru.ulstu.core.jpa.OffsetablePageRequest; +import ru.ulstu.core.model.BaseEntity; +import ru.ulstu.core.model.response.PageableItems; +import ru.ulstu.grant.model.GrantDto; +import ru.ulstu.user.error.UserActivationError; +import ru.ulstu.user.error.UserEmailExistsException; +import ru.ulstu.user.error.UserIdExistsException; +import ru.ulstu.user.error.UserIsUndeadException; +import ru.ulstu.user.error.UserLoginExistsException; +import ru.ulstu.user.error.UserNotActivatedException; +import ru.ulstu.user.error.UserNotFoundException; +import ru.ulstu.user.error.UserPasswordsNotValidOrNotMatchException; +import ru.ulstu.user.error.UserResetKeyError; +import ru.ulstu.user.error.UserSendingMailException; +import ru.ulstu.user.model.User; +import ru.ulstu.user.model.UserDto; +import ru.ulstu.user.model.UserListDto; +import ru.ulstu.user.model.UserResetPasswordDto; +import ru.ulstu.user.model.UserRole; +import ru.ulstu.user.model.UserRoleConstants; +import ru.ulstu.user.model.UserRoleDto; +import ru.ulstu.user.repository.UserRepository; +import ru.ulstu.user.repository.UserRoleRepository; +import ru.ulstu.user.util.UserUtils; + +import javax.mail.MessagingException; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +@Service +@Transactional +public class UserService implements UserDetailsService { + private static final String INVITE_USER_EXCEPTION = "Во время отправки приглашения произошла ошибка"; + + private final Logger log = LoggerFactory.getLogger(UserService.class); + private final UserRepository userRepository; + private final PasswordEncoder passwordEncoder; + private final UserRoleRepository userRoleRepository; + private final UserMapper userMapper; + private final MailService mailService; + private final ApplicationProperties applicationProperties; + + public UserService(UserRepository userRepository, + PasswordEncoder passwordEncoder, + UserRoleRepository userRoleRepository, + UserMapper userMapper, + MailService mailService, + ApplicationProperties applicationProperties) { + this.userRepository = userRepository; + this.passwordEncoder = passwordEncoder; + this.userRoleRepository = userRoleRepository; + this.userMapper = userMapper; + this.mailService = mailService; + this.applicationProperties = applicationProperties; + } + + private User getUserByEmail(String email) { + return userRepository.findOneByEmailIgnoreCase(email); + } + + private User getUserByActivationKey(String activationKey) { + return userRepository.findOneByActivationKey(activationKey); + } + + public User getUserByLogin(String login) { + return userRepository.findOneByLoginIgnoreCase(login); + } + + @Transactional(readOnly = true) + public UserDto getUserWithRolesById(Integer userId) { + final User userEntity = userRepository.findOneWithRolesById(userId); + if (userEntity == null) { + throw new UserNotFoundException(userId.toString()); + } + return userMapper.userEntityToUserDto(userEntity); + } + + @Transactional(readOnly = true) + public PageableItems getAllUsers(int offset, int count) { + final Page page = userRepository.findAll(new OffsetablePageRequest(offset, count, new Sort("id"))); + return new PageableItems<>(page.getTotalElements(), userMapper.userEntitiesToUserListDtos(page.getContent())); + } + + // TODO: read only active users + public List findAll() { + return userRepository.findAll(); + } + + @Transactional(readOnly = true) + public PageableItems getUserRoles() { + final List roles = userRoleRepository.findAll().stream() + .map(UserRoleDto::new) + .sorted(Comparator.comparing(UserRoleDto::getViewValue)) + .collect(Collectors.toList()); + return new PageableItems<>(roles.size(), roles); + } + + public UserDto createUser(UserDto userDto) { + if (userDto.getId() != null) { + throw new UserIdExistsException(); + } + if (getUserByLogin(userDto.getLogin()) != null) { + throw new UserLoginExistsException(userDto.getLogin()); + } + if (getUserByEmail(userDto.getEmail()) != null) { + throw new UserEmailExistsException(userDto.getEmail()); + } + if (!userDto.isPasswordsValid()) { + throw new UserPasswordsNotValidOrNotMatchException(""); + } + User user = userMapper.userDtoToUserEntity(userDto); + user.setActivated(false); + user.setActivationKey(UserUtils.generateActivationKey()); + user.setRoles(Collections.singleton(new UserRole(UserRoleConstants.USER))); + user.setPassword(passwordEncoder.encode(userDto.getPassword())); + user = userRepository.save(user); + mailService.sendActivationEmail(user); + log.debug("Created Information for User: {}", user.getLogin()); + return userMapper.userEntityToUserDto(user); + } + + public UserDto activateUser(String activationKey) { + final User user = getUserByActivationKey(activationKey); + if (user == null) { + throw new UserActivationError(activationKey); + } + user.setActivated(true); + user.setActivationKey(null); + user.setActivationDate(null); + log.debug("Activated user: {}", user.getLogin()); + return userMapper.userEntityToUserDto(userRepository.save(user)); + } + + public UserDto updateUser(UserDto userDto) { + if (userDto.getId() == null) { + throw new EntityIdIsNullException(); + } + if (!Objects.equals( + Optional.ofNullable(getUserByEmail(userDto.getEmail())) + .map(BaseEntity::getId).orElse(userDto.getId()), + userDto.getId())) { + throw new UserEmailExistsException(userDto.getEmail()); + } + if (!Objects.equals( + Optional.ofNullable(getUserByLogin(userDto.getLogin())) + .map(BaseEntity::getId).orElse(userDto.getId()), + userDto.getId())) { + throw new UserLoginExistsException(userDto.getLogin()); + } + User user = userRepository.findOne(userDto.getId()); + if (user == null) { + throw new UserNotFoundException(userDto.getId().toString()); + } + if (applicationProperties.getUndeadUserLogin().equalsIgnoreCase(user.getLogin())) { + userDto.setLogin(applicationProperties.getUndeadUserLogin()); + userDto.setActivated(true); + userDto.setRoles(Collections.singletonList(new UserRoleDto(UserRoleConstants.ADMIN))); + } + user.setLogin(userDto.getLogin()); + user.setFirstName(userDto.getFirstName()); + user.setLastName(userDto.getLastName()); + user.setEmail(userDto.getEmail()); + if (userDto.isActivated() != user.getActivated()) { + if (userDto.isActivated()) { + user.setActivationKey(null); + user.setActivationDate(null); + } else { + user.setActivationKey(UserUtils.generateActivationKey()); + user.setActivationDate(new Date()); + } + } + user.setActivated(userDto.isActivated()); + final Set roles = userMapper.rolesFromDto(userDto.getRoles()); + user.setRoles(roles.isEmpty() + ? Collections.singleton(new UserRole(UserRoleConstants.USER)) + : roles); + if (!StringUtils.isEmpty(userDto.getOldPassword())) { + if (!userDto.isPasswordsValid() || !userDto.isOldPasswordValid()) { + throw new UserPasswordsNotValidOrNotMatchException(""); + } + if (!passwordEncoder.matches(userDto.getOldPassword(), user.getPassword())) { + throw new UserPasswordsNotValidOrNotMatchException(""); + } + user.setPassword(passwordEncoder.encode(userDto.getPassword())); + log.debug("Changed password for User: {}", user.getLogin()); + } + user = userRepository.save(user); + log.debug("Changed Information for User: {}", user.getLogin()); + return userMapper.userEntityToUserDto(user); + } + + public UserDto updateUserInformation(User user, UserDto updateUser) { + user.setFirstName(updateUser.getFirstName()); + user.setLastName(updateUser.getLastName()); + user.setEmail(updateUser.getEmail()); + user.setLogin(updateUser.getLogin()); + user = userRepository.save(user); + log.debug("Updated Information for User: {}", user.getLogin()); + return userMapper.userEntityToUserDto(user); + } + + public void changeUserPassword(User user, Map payload) { + if (!payload.get("password").equals(payload.get("confirmPassword"))) { + throw new UserPasswordsNotValidOrNotMatchException(""); + } + if (!passwordEncoder.matches(payload.get("oldPassword"), user.getPassword())) { + throw new UserPasswordsNotValidOrNotMatchException("Старый пароль введен неправильно"); + } + user.setPassword(passwordEncoder.encode(payload.get("password"))); + log.debug("Changed password for User: {}", user.getLogin()); + userRepository.save(user); + + mailService.sendChangePasswordMail(user); + } + + public boolean requestUserPasswordReset(String email) { + User user = userRepository.findOneByEmailIgnoreCase(email); + if (user == null) { + throw new UserNotFoundException(email); + } + if (!user.getActivated()) { + throw new UserNotActivatedException(); + } + user.setResetKey(UserUtils.generateResetKey()); + user.setResetDate(new Date()); + user = userRepository.save(user); + mailService.sendPasswordResetMail(user); + log.debug("Created Reset Password Request for User: {}", user.getLogin()); + return true; + } + + public boolean completeUserPasswordReset(String key, UserResetPasswordDto userResetPasswordDto) { + if (!userResetPasswordDto.isPasswordsValid()) { + throw new UserPasswordsNotValidOrNotMatchException(""); + } + User user = userRepository.findOneByResetKey(key); + if (user == null) { + throw new UserResetKeyError(key); + } + user.setPassword(passwordEncoder.encode(userResetPasswordDto.getPassword())); + user.setResetKey(null); + user.setResetDate(null); + user = userRepository.save(user); + log.debug("Reset Password for User: {}", user.getLogin()); + return true; + } + + public UserDto deleteUser(Integer userId) { + final User user = userRepository.findOne(userId); + if (user == null) { + throw new UserNotFoundException(userId.toString()); + } + if (applicationProperties.getUndeadUserLogin().equalsIgnoreCase(user.getLogin())) { + throw new UserIsUndeadException(user.getLogin()); + } + userRepository.delete(user); + log.debug("Deleted User: {}", user.getLogin()); + return userMapper.userEntityToUserDto(user); + } + + @Override + public UserDetails loadUserByUsername(String username) { + final User user = userRepository.findOneByLoginIgnoreCase(username); + if (user == null) { + throw new UserNotFoundException(username); + } + if (!user.getActivated()) { + throw new UserNotActivatedException(); + } + return new org.springframework.security.core.userdetails.User(user.getLogin(), + user.getPassword(), + Optional.ofNullable(user.getRoles()).orElse(Collections.emptySet()).stream() + .map(role -> new SimpleGrantedAuthority(role.getName())) + .collect(Collectors.toList())); + } + + public List findByIds(List ids) { + return userRepository.findAll(ids); + } + + public User findById(Integer id) { + return userRepository.findOne(id); + } + + public User getCurrentUser() { + String login = UserUtils.getCurrentUserLogin(); + User user = userRepository.findOneByLoginIgnoreCase(login); + if (user == null) { + throw new UserNotFoundException(login); + } + return user; + } + + public List filterByAgeAndDegree(boolean hasDegree, boolean hasAge) { + return userRepository.filterByAgeAndDegree(hasDegree, hasAge); + } + + public void inviteUser(String email) throws UserSendingMailException { + if (userRepository.findOneByEmailIgnoreCase(email) != null) { + throw new UserEmailExistsException(email); + } + + String password = UserUtils.generatePassword(); + + User user = new User(); + user.setPassword(passwordEncoder.encode(password)); + user.setLogin(email); + user.setEmail(email); + user.setFirstName("user"); + user.setLastName("user"); + user.setActivated(true); + userRepository.save(user); + + Map variables = ImmutableMap.of("password", password, "email", email); + try { + mailService.sendInviteMail(variables, email); + } catch (MessagingException | MailException e) { + throw new UserSendingMailException(email); + } + } + + public User findOneByLoginIgnoreCase(String login) { + return userRepository.findOneByLoginIgnoreCase(login); + } +} diff --git a/src/main/resources/drivers/chromedriver b/src/main/resources/drivers/chromedriver old mode 100644 new mode 100755 diff --git a/src/main/resources/drivers/geckodriver b/src/main/resources/drivers/geckodriver old mode 100644 new mode 100755 From 82e454a50b8b209d0e0eb771e62ea3a864c0dbcc Mon Sep 17 00:00:00 2001 From: ASH Date: Thu, 23 May 2019 16:17:04 +0400 Subject: [PATCH 27/74] #104 mod tests generate task --- .../ulstu/students/service/TaskService.java | 4 ++- .../students/service/TaskServiceTest.java | 26 ++++++++++++++++--- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/src/main/java/ru/ulstu/students/service/TaskService.java b/src/main/java/ru/ulstu/students/service/TaskService.java index 379314d..d080d37 100644 --- a/src/main/java/ru/ulstu/students/service/TaskService.java +++ b/src/main/java/ru/ulstu/students/service/TaskService.java @@ -186,7 +186,7 @@ public class TaskService { } @Transactional - public void generateYearTasks() { + public List generateYearTasks() { Set tags = checkRepeatingTags(false); List tasks = new ArrayList<>(); tags.forEach(tag -> { @@ -202,7 +202,9 @@ public class TaskService { Task newTask = copyTaskWithNewYear(task); taskRepository.save(newTask); }); + return tasks; } + return null; } diff --git a/src/test/java/ru/ulstu/students/service/TaskServiceTest.java b/src/test/java/ru/ulstu/students/service/TaskServiceTest.java index 19eff12..1ba04c4 100644 --- a/src/test/java/ru/ulstu/students/service/TaskServiceTest.java +++ b/src/test/java/ru/ulstu/students/service/TaskServiceTest.java @@ -21,6 +21,7 @@ import ru.ulstu.timeline.service.EventService; import java.io.IOException; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashSet; @@ -157,16 +158,35 @@ public class TaskServiceTest { @Test public void generateYearTasks() { - when(taskService.checkRepeatingTags(false)).thenReturn(repeatingTags); + when(tagService.getTags()).thenReturn(tags); + tasks.get(0).setTags(tags); + when(taskRepository.findAllYear(DateUtils.clearTime(DateUtils.addYears(new Date(), -1)))).thenReturn(tasks); + tasks.get(0).setCreateDate(DateUtils.clearTime(DateUtils.addYears(new Date(), -1))); + when(taskRepository.findByTag(tag)).thenReturn(tasks); + Task newTask = new Task(); + newTask.setTitle(tasks.get(0).getTitle()); + newTask.setTags(tasks.get(0).getTags()); + newTask.setCreateDate(new Date()); + newTask.setStatus(Task.TaskStatus.LOADED_FROM_KIAS); + + Deadline newDeadline = new Deadline(); + newDeadline.setDescription(deadline.getDescription()); + newDeadline.setDate(DateUtils.addYears(deadline.getDate(), 1)); + newTask.setDeadlines(Arrays.asList(newDeadline)); + + when(taskRepository.save(newTask)).thenReturn(task); + + assertEquals(Arrays.asList(task), taskService.generateYearTasks()); } @Test public void checkRepeatingTags() { - when(tagService.findById(ID)).thenReturn(tag); + when(tagService.getTags()).thenReturn(tags); + tasks.get(0).setTags(tags); when(taskRepository.findAllYear(DateUtils.clearTime(DateUtils.addYears(new Date(), -1)))).thenReturn(tasks); - assertEquals(tag, taskService.checkRepeatingTags(false)); + assertEquals(new HashSet(Arrays.asList(tag)), taskService.checkRepeatingTags(false)); } @Test From 181086c9db9e7eb5683c520d4a89110d6561b38f Mon Sep 17 00:00:00 2001 From: Anton Romanov Date: Thu, 23 May 2019 16:36:48 +0400 Subject: [PATCH 28/74] #120 disable start browser on run application --- src/main/java/ru/ulstu/grant/service/KiasService.java | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/main/java/ru/ulstu/grant/service/KiasService.java b/src/main/java/ru/ulstu/grant/service/KiasService.java index 6ff0bd9..449b948 100644 --- a/src/main/java/ru/ulstu/grant/service/KiasService.java +++ b/src/main/java/ru/ulstu/grant/service/KiasService.java @@ -32,17 +32,16 @@ public class KiasService { private final static String DRIVER_TYPE = "webdriver.chrome.driver"; private final UserService userService; - private WebDriver webDriver; public KiasService(UserService userService) { - System.setProperty(DRIVER_TYPE, getDriverExecutablePath()); this.userService = userService; - final ChromeOptions chromeOptions = new ChromeOptions(); - chromeOptions.addArguments("--headless"); - webDriver = new ChromeDriver(chromeOptions); } public List getNewGrantsDto() throws ParseException { + System.setProperty(DRIVER_TYPE, getDriverExecutablePath()); + final ChromeOptions chromeOptions = new ChromeOptions(); + chromeOptions.addArguments("--headless"); + WebDriver webDriver = new ChromeDriver(chromeOptions); webDriver.get(String.format(BASE_URL, CONTEST_STATUS_ID, CONTEST_TYPE, CONTEST_YEAR)); KiasPage kiasPage = new KiasPage(webDriver); List kiasGrants = new ArrayList<>(); @@ -64,7 +63,7 @@ public class KiasService { kiasGrants.clear(); } while (kiasPage.checkPagination()); //проверка существования следующей страницы с грантами - + webDriver.quit(); return newGrants; } From ab17b9f1521e498d7bea148935e48cfa675f1b5e Mon Sep 17 00:00:00 2001 From: ASH Date: Thu, 23 May 2019 16:45:09 +0400 Subject: [PATCH 29/74] #104 mod tests period task --- .../ulstu/students/service/TaskService.java | 3 +- .../students/service/TaskServiceTest.java | 47 +++++++++++-------- 2 files changed, 30 insertions(+), 20 deletions(-) diff --git a/src/main/java/ru/ulstu/students/service/TaskService.java b/src/main/java/ru/ulstu/students/service/TaskService.java index d080d37..e89aedf 100644 --- a/src/main/java/ru/ulstu/students/service/TaskService.java +++ b/src/main/java/ru/ulstu/students/service/TaskService.java @@ -249,8 +249,9 @@ public class TaskService { } @Transactional - public void createPeriodTask(Scheduler scheduler) { + public Task createPeriodTask(Scheduler scheduler) { Task newTask = copyTaskWithNewDates(scheduler.getTask()); taskRepository.save(newTask); + return newTask; } } diff --git a/src/test/java/ru/ulstu/students/service/TaskServiceTest.java b/src/test/java/ru/ulstu/students/service/TaskServiceTest.java index 1ba04c4..8edfc77 100644 --- a/src/test/java/ru/ulstu/students/service/TaskServiceTest.java +++ b/src/test/java/ru/ulstu/students/service/TaskServiceTest.java @@ -10,6 +10,7 @@ import org.springframework.data.domain.Sort; import ru.ulstu.core.util.DateUtils; import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.service.DeadlineService; +import ru.ulstu.students.model.Scheduler; import ru.ulstu.students.model.Task; import ru.ulstu.students.model.TaskDto; import ru.ulstu.students.model.TaskFilterDto; @@ -26,7 +27,6 @@ import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; -import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -64,14 +64,12 @@ public class TaskServiceTest { private List tasks; private List tags; private Task task; - private TaskFilterDto filterDto; + private Task taskForSchedule; private TaskDto taskDto; - private List tasksDto; private Tag tag; - private Tag tagNull; private Deadline deadline; private List deadlines; - private Set repeatingTags; + private Scheduler scheduler; @Before @@ -102,8 +100,14 @@ public class TaskServiceTest { tasks.add(task); taskDto = new TaskDto(task); - repeatingTags = new HashSet<>(); - repeatingTags.add(tag); + taskForSchedule = new Task(); + taskForSchedule.setTitle(TITLE); + taskForSchedule.setDescription(DESCR); + + scheduler = new Scheduler(); + scheduler.setDate(new Date()); + scheduler.setTask(taskForSchedule); + } @@ -171,8 +175,10 @@ public class TaskServiceTest { newTask.setStatus(Task.TaskStatus.LOADED_FROM_KIAS); Deadline newDeadline = new Deadline(); + newDeadline.setId(ID); newDeadline.setDescription(deadline.getDescription()); newDeadline.setDate(DateUtils.addYears(deadline.getDate(), 1)); + when(deadlineService.create(newDeadline)).thenReturn(newDeadline); newTask.setDeadlines(Arrays.asList(newDeadline)); when(taskRepository.save(newTask)).thenReturn(task); @@ -189,19 +195,22 @@ public class TaskServiceTest { assertEquals(new HashSet(Arrays.asList(tag)), taskService.checkRepeatingTags(false)); } - @Test - public void getTaskStatuses() { - } - - @Test - public void getTags() { - } - - @Test - public void findTasksByTag() { - } - @Test public void createPeriodTask() { + Task newTask = new Task(); + newTask.setTitle(scheduler.getTask().getTitle()); + newTask.setTags(scheduler.getTask().getTags()); + newTask.setCreateDate(new Date()); + + Deadline newDeadline = new Deadline(); + newDeadline.setId(ID); + newDeadline.setDescription(deadline.getDescription()); + newDeadline.setDate(DateUtils.addYears(deadline.getDate(), 1)); + when(deadlineService.create(newDeadline)).thenReturn(newDeadline); + newTask.setDeadlines(Arrays.asList(newDeadline)); + + when(taskRepository.save(newTask)).thenReturn(taskForSchedule); + + assertEquals(taskForSchedule, taskService.createPeriodTask(scheduler)); } } \ No newline at end of file From 512a805e8c4c4fa26cb58027ff2efc173e179c4a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B5=D0=BC=D0=B5=D0=BD=D0=BE=D0=B2=D0=B0=20=D0=9C?= =?UTF-8?q?=D0=B0=D1=80=D0=B8=D1=8F?= Date: Thu, 23 May 2019 17:26:22 +0400 Subject: [PATCH 30/74] #127 references formatting --- .../paper/controller/PaperController.java | 5 +++ .../ru/ulstu/paper/service/PaperService.java | 11 +++++ src/main/resources/public/css/paper.css | 4 ++ src/main/resources/public/js/core.js | 1 + .../resources/templates/papers/paper.html | 45 +++++++++++++++++++ 5 files changed, 66 insertions(+) diff --git a/src/main/java/ru/ulstu/paper/controller/PaperController.java b/src/main/java/ru/ulstu/paper/controller/PaperController.java index beae772..e10135f 100644 --- a/src/main/java/ru/ulstu/paper/controller/PaperController.java +++ b/src/main/java/ru/ulstu/paper/controller/PaperController.java @@ -157,6 +157,11 @@ public class PaperController { return new ResponseEntity<>(latexService.generatePdfFromLatexFile(paper), headers, HttpStatus.OK); } + @PostMapping("/getFormattedReferences") + public ResponseEntity getFormattedReferences(PaperDto paperDto) { + return new ResponseEntity<>(paperService.getFormattedReferences(paperDto), new HttpHeaders(), HttpStatus.OK); + } + private void filterEmptyDeadlines(PaperDto paperDto) { paperDto.setDeadlines(paperDto.getDeadlines().stream() .filter(dto -> dto.getDate() != null || !isEmpty(dto.getDescription())) diff --git a/src/main/java/ru/ulstu/paper/service/PaperService.java b/src/main/java/ru/ulstu/paper/service/PaperService.java index 8658015..8a59486 100644 --- a/src/main/java/ru/ulstu/paper/service/PaperService.java +++ b/src/main/java/ru/ulstu/paper/service/PaperService.java @@ -344,6 +344,17 @@ public class PaperService { : getSpringerReference(referenceDto); } + public String getFormattedReferences(PaperDto paperDto) { + return String.join("\r\n", paperDto.getReferences() + .stream() + .filter(r -> !r.getDeleted()) + .map(r -> { + r.setFormatStandard(paperDto.getFormatStandard()); + return getFormattedReference(r); + }) + .collect(Collectors.toList())); + } + public String getGostReference(ReferenceDto referenceDto) { return MessageFormat.format(referenceDto.getReferenceType() == BOOK ? "{0} {1} - {2}{3}. - {4}с." : "{0} {1}{5} {2}{3}. С. {4}.", referenceDto.getAuthors(), diff --git a/src/main/resources/public/css/paper.css b/src/main/resources/public/css/paper.css index 1be8c1f..386c5af 100644 --- a/src/main/resources/public/css/paper.css +++ b/src/main/resources/public/css/paper.css @@ -26,4 +26,8 @@ #nav-references a:hover { text-decoration: none; +} + +#nav-references #formattedReferencesArea { + height: 150px; } \ No newline at end of file diff --git a/src/main/resources/public/js/core.js b/src/main/resources/public/js/core.js index 58e68f4..cc42258 100644 --- a/src/main/resources/public/js/core.js +++ b/src/main/resources/public/js/core.js @@ -4,6 +4,7 @@ var urlFileUpload = "/api/1.0/files/uploadTmpFile"; var urlFileDownload = "/api/1.0/files/download/"; var urlPdfGenerating = "/papers/generatePdf"; +var urlReferencesFormatting = "/papers/getFormattedReferences"; var urlFileDownloadTmp = "/api/1.0/files/download-tmp/"; /* exported MessageTypesEnum */ diff --git a/src/main/resources/templates/papers/paper.html b/src/main/resources/templates/papers/paper.html index ef4217d..e80fe85 100644 --- a/src/main/resources/templates/papers/paper.html +++ b/src/main/resources/templates/papers/paper.html @@ -260,7 +260,33 @@ class="btn btn-primary" value="Добавить источник"/> +
+
+ + + +
+ +
+ +
+ +
+ +
+
@@ -474,6 +500,25 @@ $('#pdfBtn').prop('disabled', false); } } + + 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); + } + } + } From 24a1276005ecaac2d95bd0ca20ad5eddd353c778 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B5=D0=BC=D0=B5=D0=BD=D0=BE=D0=B2=D0=B0=20=D0=9C?= =?UTF-8?q?=D0=B0=D1=80=D0=B8=D1=8F?= Date: Fri, 24 May 2019 00:14:46 +0400 Subject: [PATCH 31/74] #127 autocomplete --- .../paper/controller/PaperController.java | 6 + .../ulstu/paper/model/AutoCompleteData.java | 42 ++++++ .../paper/repository/ReferenceRepository.java | 15 ++ .../ru/ulstu/paper/service/PaperService.java | 10 ++ src/main/resources/public/css/paper.css | 7 + .../resources/templates/papers/paper.html | 139 ++++++++++++------ 6 files changed, 172 insertions(+), 47 deletions(-) create mode 100644 src/main/java/ru/ulstu/paper/model/AutoCompleteData.java diff --git a/src/main/java/ru/ulstu/paper/controller/PaperController.java b/src/main/java/ru/ulstu/paper/controller/PaperController.java index e10135f..29da57d 100644 --- a/src/main/java/ru/ulstu/paper/controller/PaperController.java +++ b/src/main/java/ru/ulstu/paper/controller/PaperController.java @@ -13,6 +13,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import ru.ulstu.conference.service.ConferenceService; import ru.ulstu.deadline.model.Deadline; +import ru.ulstu.paper.model.AutoCompleteData; import ru.ulstu.paper.model.Paper; import ru.ulstu.paper.model.PaperDto; import ru.ulstu.paper.model.PaperListDto; @@ -162,6 +163,11 @@ public class PaperController { return new ResponseEntity<>(paperService.getFormattedReferences(paperDto), new HttpHeaders(), HttpStatus.OK); } + @ModelAttribute("autocompleteData") + public AutoCompleteData getAutocompleteData() { + return paperService.getAutoCompleteData(); + } + private void filterEmptyDeadlines(PaperDto paperDto) { paperDto.setDeadlines(paperDto.getDeadlines().stream() .filter(dto -> dto.getDate() != null || !isEmpty(dto.getDescription())) diff --git a/src/main/java/ru/ulstu/paper/model/AutoCompleteData.java b/src/main/java/ru/ulstu/paper/model/AutoCompleteData.java new file mode 100644 index 0000000..b70a780 --- /dev/null +++ b/src/main/java/ru/ulstu/paper/model/AutoCompleteData.java @@ -0,0 +1,42 @@ +package ru.ulstu.paper.model; + +import java.util.ArrayList; + +public class AutoCompleteData { + ArrayList authors = new ArrayList<>(); + ArrayList publicationTitles = new ArrayList<>(); + ArrayList publishers = new ArrayList<>(); + ArrayList journalOrCollectionTitles = new ArrayList<>(); + + public ArrayList getAuthors() { + return authors; + } + + public void setAuthors(ArrayList authors) { + this.authors = authors; + } + + public ArrayList getPublicationTitles() { + return publicationTitles; + } + + public void setPublicationTitles(ArrayList publicationTitles) { + this.publicationTitles = publicationTitles; + } + + public ArrayList getPublishers() { + return publishers; + } + + public void setPublishers(ArrayList publishers) { + this.publishers = publishers; + } + + public ArrayList getJournalOrCollectionTitles() { + return journalOrCollectionTitles; + } + + public void setJournalOrCollectionTitles(ArrayList journalOrCollectionTitles) { + this.journalOrCollectionTitles = journalOrCollectionTitles; + } +} diff --git a/src/main/java/ru/ulstu/paper/repository/ReferenceRepository.java b/src/main/java/ru/ulstu/paper/repository/ReferenceRepository.java index 68e97d4..1d4321b 100644 --- a/src/main/java/ru/ulstu/paper/repository/ReferenceRepository.java +++ b/src/main/java/ru/ulstu/paper/repository/ReferenceRepository.java @@ -1,8 +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.ArrayList; + public interface ReferenceRepository extends JpaRepository { void deleteById(Integer id); + + @Query("SELECT DISTINCT r.authors FROM Reference r") + ArrayList findDistinctAuthors(); + + @Query("SELECT DISTINCT r.publicationTitle FROM Reference r") + ArrayList findDistinctPublicationTitles(); + + @Query("SELECT DISTINCT r.publisher FROM Reference r") + ArrayList findDistinctPublishers(); + + @Query("SELECT DISTINCT r.journalOrCollectionTitle FROM Reference r where r.journalOrCollectionTitle <> ''") + ArrayList findDistinctJournalOrCollectionTitles(); } diff --git a/src/main/java/ru/ulstu/paper/service/PaperService.java b/src/main/java/ru/ulstu/paper/service/PaperService.java index 8a59486..f452c2f 100644 --- a/src/main/java/ru/ulstu/paper/service/PaperService.java +++ b/src/main/java/ru/ulstu/paper/service/PaperService.java @@ -7,6 +7,7 @@ import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.service.DeadlineService; import ru.ulstu.file.model.FileDataDto; import ru.ulstu.file.service.FileService; +import ru.ulstu.paper.model.AutoCompleteData; import ru.ulstu.paper.model.Paper; import ru.ulstu.paper.model.PaperDto; import ru.ulstu.paper.model.PaperListDto; @@ -378,4 +379,13 @@ public class PaperService { public List findAllCompletedByType(Paper.PaperType type) { return paperRepository.findByTypeAndStatus(type, Paper.PaperStatus.COMPLETED); } + + public AutoCompleteData getAutoCompleteData() { + AutoCompleteData autoCompleteData = new AutoCompleteData(); + autoCompleteData.setAuthors(referenceRepository.findDistinctAuthors()); + autoCompleteData.setJournalOrCollectionTitles(referenceRepository.findDistinctJournalOrCollectionTitles()); + autoCompleteData.setPublicationTitles(referenceRepository.findDistinctPublicationTitles()); + autoCompleteData.setPublishers(referenceRepository.findDistinctPublishers()); + return autoCompleteData; + } } diff --git a/src/main/resources/public/css/paper.css b/src/main/resources/public/css/paper.css index 386c5af..b4b3f85 100644 --- a/src/main/resources/public/css/paper.css +++ b/src/main/resources/public/css/paper.css @@ -30,4 +30,11 @@ #nav-references #formattedReferencesArea { height: 150px; +} + +.ui-autocomplete { + max-height: 200px; + max-width: 400px; + overflow-y: scroll; + overflow-x: hidden; } \ No newline at end of file diff --git a/src/main/resources/templates/papers/paper.html b/src/main/resources/templates/papers/paper.html index e80fe85..2755aba 100644 --- a/src/main/resources/templates/papers/paper.html +++ b/src/main/resources/templates/papers/paper.html @@ -4,6 +4,10 @@ layout:decorator="default" xmlns:th="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/html"> + + + + @@ -74,54 +78,56 @@ th:field="*{comment}"> -
- - -
+
+ + +
-
- -
- -
- -
-
- -
-
- + +
+ +
+ +
+
+ +
+
+ - + aria-hidden="true"> + +
+
+

Incorrect title

-
-

Incorrect title

-
-
- + -
-
- - -

Incorrect title

-
+ +
+ + +

Incorrect title

+
@@ -215,14 +221,14 @@
@@ -235,7 +241,7 @@
@@ -248,7 +254,7 @@
@@ -519,6 +525,45 @@ } } } + + + From 01bcac2680f4b0e64e5fd69b03d3679d7c0bd759 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B5=D0=BC=D0=B5=D0=BD=D0=BE=D0=B2=D0=B0=20=D0=9C?= =?UTF-8?q?=D0=B0=D1=80=D0=B8=D1=8F?= Date: Fri, 24 May 2019 00:26:38 +0400 Subject: [PATCH 32/74] #127 allow nullable year --- src/main/java/ru/ulstu/paper/service/PaperService.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/ru/ulstu/paper/service/PaperService.java b/src/main/java/ru/ulstu/paper/service/PaperService.java index f452c2f..cfb1a0a 100644 --- a/src/main/java/ru/ulstu/paper/service/PaperService.java +++ b/src/main/java/ru/ulstu/paper/service/PaperService.java @@ -361,7 +361,7 @@ public class PaperService { referenceDto.getAuthors(), referenceDto.getPublicationTitle(), StringUtils.isEmpty(referenceDto.getPublisher()) ? "" : referenceDto.getPublisher() + ", ", - referenceDto.getPublicationYear().toString(), + referenceDto.getPublicationYear() != null ? referenceDto.getPublicationYear().toString() : "", referenceDto.getPages(), StringUtils.isEmpty(referenceDto.getJournalOrCollectionTitle()) ? "." : " // " + referenceDto.getJournalOrCollectionTitle() + "."); } @@ -369,7 +369,7 @@ public class PaperService { public String getSpringerReference(ReferenceDto referenceDto) { return MessageFormat.format("{0} ({1}) {2}.{3} {4}pp {5}", referenceDto.getAuthors(), - referenceDto.getPublicationYear().toString(), + referenceDto.getPublicationYear() != null ? referenceDto.getPublicationYear().toString() : "", referenceDto.getPublicationTitle(), referenceDto.getReferenceType() == ARTICLE ? " " + referenceDto.getJournalOrCollectionTitle() + "," : "", StringUtils.isEmpty(referenceDto.getPublisher()) ? "" : referenceDto.getPublisher() + ", ", From 8bb9e3a84469d2ff8529a463459f91497cf9600a Mon Sep 17 00:00:00 2001 From: "Artem.Arefev" Date: Fri, 24 May 2019 01:52:50 +0400 Subject: [PATCH 33/74] #89 jquery --- src/main/resources/public/js/users.js | 38 +++++++++---------- .../resources/templates/resetRequest.html | 12 +++--- 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/src/main/resources/public/js/users.js b/src/main/resources/public/js/users.js index 1ea26e3..e31d3ad 100644 --- a/src/main/resources/public/js/users.js +++ b/src/main/resources/public/js/users.js @@ -1,7 +1,7 @@ function changePassword() { - oldPassword = document.getElementById("oldPassword").value - password = document.getElementById("password").value - confirmPassword = document.getElementById("confirmPassword").value + oldPassword = $("#oldPassword").val() + password = $("#password").val() + confirmPassword = $("#confirmPassword").val() if ([oldPassword.length, password.length, confirmPassword.length].includes(0)) { showFeedbackMessage("Заполните все поля", MessageTypesEnum.WARNING); @@ -23,7 +23,7 @@ function changePassword() { }), method: "POST", success: function() { - document.getElementById("closeModalPassword").click(); + $("#closeModalPassword").click(); showFeedbackMessage("Пароль был обновлен", MessageTypesEnum.SUCCESS) }, @@ -34,7 +34,7 @@ function changePassword() { } function inviteUser() { - email = document.getElementById("email").value; + email = $("#email").val(); if (!isEmailValid(email)) { showFeedbackMessage("Некорректный почтовый ящик", MessageTypesEnum.WARNING); return; @@ -45,7 +45,7 @@ function inviteUser() { contentType: "application/json; charset=utf-8", method: "POST", success: function() { - document.getElementById("closeModalInvite").click(); + $("#closeModalInvite").click(); showFeedbackMessage("Пользователь был успешно приглашен", MessageTypesEnum.SUCCESS) }, error: function(errorData) { @@ -55,13 +55,13 @@ function inviteUser() { } function requestResetPassword() { - email = document.getElementById("emailReset").value + email = $("#emailReset").val() if (!isEmailValid(email)) { showFeedbackMessage("Некорректный почтовый ящик", MessageTypesEnum.WARNING); return; } - document.getElementById("dvloader").hidden = false; + $("#dvloader").show(); $.ajax({ url:"/api/1.0/users/password-reset-request?email=" + email, @@ -69,27 +69,27 @@ function requestResetPassword() { method: "POST", success: function() { showFeedbackMessage("Проверочный код был отправлен на указанный почтовый ящик", MessageTypesEnum.SUCCESS) - document.getElementById("passwordNew").hidden = false - document.getElementById("passwordConfirm").hidden = false - document.getElementById("btnReset").hidden = false - document.getElementById("resetKey").hidden = false - document.getElementById("emailReset").hidden = true - document.getElementById("btnSend").hidden = true - document.getElementById("dvloader").hidden = true; + $("#passwordNew").show() + $("#passwordConfirm").show() + $("#btnReset").show() + $("#resetKey").show() + $("#emailReset").hide() + $("#btnSend").hide() + $("#dvloader").hide() }, error: function(errorData) { showFeedbackMessage(errorData.responseJSON.error.message, MessageTypesEnum.WARNING) - document.getElementById("dvloader").hidden = true; + $("#dvloader").hide() } }) } function resetPassword() { - passwordNew = document.getElementById("passwordNew").value; - passwordConfirm = document.getElementById("passwordConfirm").value; - resetKey = document.getElementById("resetKey").value; + passwordNew = $("#passwordNew").val(); + passwordConfirm = $("#passwordConfirm").val(); + resetKey = $("#resetKey").val(); if ([passwordNew, passwordConfirm, resetKey].includes("")) { showFeedbackMessage("Заполните все поля", MessageTypesEnum.WARNING); diff --git a/src/main/resources/templates/resetRequest.html b/src/main/resources/templates/resetRequest.html index 73bff76..4a2aeab 100644 --- a/src/main/resources/templates/resetRequest.html +++ b/src/main/resources/templates/resetRequest.html @@ -10,7 +10,7 @@
@@ -25,22 +25,22 @@
+ placeholder="Новый пароль" style="display:none"/>
+ placeholder="Подтвердите пароль" style="display:none"/>
+ placeholder="Код подтверждения" style="display:none"/>
- + -