#4--2 merge with dev

This commit is contained in:
Anton Romanov 2019-04-11 22:37:32 +04:00
parent bd3513118c
commit cafb3abcee
30 changed files with 746 additions and 85 deletions

View File

@ -1,16 +1,11 @@
image: ubuntu:18.04 image: romanov73/is:ng-tracker-container
cache:
key: "$CI_PROJECT_ID"
paths:
- .gradle/
variables: variables:
GRADLE_OPTS: "-Dorg.gradle.daemon=false" GRADLE_OPTS: "-Dorg.gradle.daemon=false"
before_script: before_script:
- 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )' - service postgresql stop
- apt-get install openjdk-8-jdk git -y - service postgresql start
- eval $(ssh-agent -s) - eval $(ssh-agent -s)
- echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null
- mkdir -p ~/.ssh - mkdir -p ~/.ssh
@ -20,12 +15,14 @@ before_script:
build: build:
stage: build stage: build
script: ./gradlew assemble script: ./gradlew assemble
cache:
key: "$CI_PROJECT_ID" checkRun:
policy: push stage: test
paths: script: ./gradlew bootRun -Dng-tracker.check-run=true
- build
- .gradle checkStyle:
stage: test
script: ./gradlew check
deploy: deploy:
stage: deploy stage: deploy
@ -33,12 +30,6 @@ deploy:
- sh deploy/gdccloud/deploy.sh - sh deploy/gdccloud/deploy.sh
only: only:
- dev - dev
cache:
key: "$CI_PROJECT_ID"
policy: pull
paths:
- build
- .gradle
environment: environment:
name: staging name: staging
url: http://193.110.3.124:8080 url: http://193.110.3.124:8080

View File

@ -0,0 +1,50 @@
## Краткое описание задачи
```
Что требуется сделать
```
## `Опционально` Список верстаемых страниц
```
Будут затронуты страницы:
* page1.html
* page2.html
* page3.html
```
## `Опционально` Список затрагиваемых модулей
```
При реализации задачи потребуется также реализовать методы контроллера
```
## `Опционально` Список реализуемых функций
```
После выполнения задачи станет доступным:
* просмотр `entity_name`
* редактирование `entity_name`
* валидация `entity_name`
```
## `Опционально` Сценарии работы
```
Сценарий просмотра:
1. Зайти на главную страницу приложения
2. Перейти в раздел `section_name`
3. Перейти к списку `entity_name`
4. Выбрать нужную `entity_name` и нажать на нее
Сценарий редактирования:
1. Зайти на главную страницу приложения
2. Перейти в раздел `section_name`
3. Перейти к списку `entity_name`
4. Выбрать нужную `entity_name` и нажать на нее
5. Внести нужные правки в поля и сохранить
```
## Описание конечного результата, дающего возможность проверки выполнения задачи: компоненты проекта, сценарии работы
```
* Сверстаны страницы page1.hml, page2.hml, page3.hml
* Реализован контроллер для обслуживания страниц
* Сохранение в БД еще не реализовано
* Валидация происходит по полям `field1, field2`
* Сценарий просмотра проверяется при ручном внечении записей в БД
```

View File

@ -30,6 +30,10 @@ bootRun.dependsOn checkstyleMain
sourceCompatibility = 1.8 sourceCompatibility = 1.8
targetCompatibility = 1.8 targetCompatibility = 1.8
bootRun {
systemProperties = System.properties
}
checkstyle { checkstyle {
project.ext.checkstyleVersion = '8.8' project.ext.checkstyleVersion = '8.8'

View File

@ -2,13 +2,30 @@ package ru.ulstu;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import ru.ulstu.configuration.ApplicationProperties;
import ru.ulstu.core.repository.JpaDetachableRepositoryImpl; import ru.ulstu.core.repository.JpaDetachableRepositoryImpl;
@SpringBootApplication @SpringBootApplication
@EnableJpaRepositories(repositoryBaseClass = JpaDetachableRepositoryImpl.class) @EnableJpaRepositories(repositoryBaseClass = JpaDetachableRepositoryImpl.class)
public class NgTrackerApplication { public class NgTrackerApplication {
private final ApplicationProperties applicationProperties;
public NgTrackerApplication(ApplicationProperties applicationProperties) {
this.applicationProperties = applicationProperties;
}
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(NgTrackerApplication.class, args); SpringApplication.run(NgTrackerApplication.class, args);
} }
@EventListener(ApplicationReadyEvent.class)
public void doSomethingAfterStartup() {
System.out.println("hello world, I have just started up");
if (applicationProperties.isCheckRun()) {
System.exit(0);
}
}
} }

View File

@ -2,10 +2,28 @@ package ru.ulstu.conference.controller;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import ru.ulstu.conference.model.ConferenceDto;
import ru.ulstu.conference.model.ConferenceFilterDto;
import ru.ulstu.conference.service.ConferenceService; import ru.ulstu.conference.service.ConferenceService;
import ru.ulstu.deadline.model.Deadline;
import springfox.documentation.annotations.ApiIgnore; import springfox.documentation.annotations.ApiIgnore;
import javax.validation.Valid;
import java.io.IOException;
import java.util.stream.Collectors;
import static org.springframework.util.StringUtils.isEmpty;
import static ru.ulstu.core.controller.Navigation.CONFERENCES_PAGE;
import static ru.ulstu.core.controller.Navigation.CONFERENCE_PAGE;
import static ru.ulstu.core.controller.Navigation.REDIRECT_TO;
@Controller() @Controller()
@RequestMapping(value = "/conferences") @RequestMapping(value = "/conferences")
@ApiIgnore @ApiIgnore
@ -13,7 +31,49 @@ public class ConferenceController {
private final ConferenceService conferenceService; private final ConferenceService conferenceService;
public ConferenceController(ConferenceService paperService) { public ConferenceController(ConferenceService conferenceService) {
this.conferenceService = paperService; this.conferenceService = conferenceService;
}
@GetMapping("/conferences")
public void getConferences(ModelMap modelMap) {
modelMap.put("filteredConferences", new ConferenceFilterDto(conferenceService.findAllDto()));
}
@GetMapping("/conference")
public void getConference(ModelMap modelMap, @RequestParam(value = "id") Integer id) {
if (id != null && id > 0) {
modelMap.put("conferenceDto", conferenceService.findOneDto(id));
} else {
modelMap.put("conferenceDto", new ConferenceDto());
}
}
@PostMapping(value = "/conference", params = "save")
public String save(@Valid ConferenceDto conferenceDto, Errors errors) throws IOException {
filterEmptyDeadlines(conferenceDto);
if (conferenceDto.getDeadlines().isEmpty()) {
errors.rejectValue("deadlines", "errorCode", "Не может быть пустым");
}
if (errors.hasErrors())
return CONFERENCE_PAGE;
conferenceService.save(conferenceDto);
return String.format(REDIRECT_TO, CONFERENCES_PAGE);
}
@PostMapping(value = "/conference", params = "addDeadline")
public String addDeadline(@Valid ConferenceDto conferenceDto, Errors errors) {
filterEmptyDeadlines(conferenceDto);
if (errors.hasErrors())
return CONFERENCE_PAGE;
conferenceDto.getDeadlines().add(new Deadline());
return CONFERENCE_PAGE;
}
private void filterEmptyDeadlines(ConferenceDto conferenceDto) {
conferenceDto.setDeadlines(conferenceDto.getDeadlines().stream()
.filter(dto -> dto.getDate() != null || !isEmpty(dto.getDescription()))
.collect(Collectors.toList()));
} }
} }

View File

@ -1,11 +1,143 @@
package ru.ulstu.conference.model; package ru.ulstu.conference.model;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.format.annotation.DateTimeFormat;
import ru.ulstu.core.model.BaseEntity; import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.paper.model.Paper;
import ru.ulstu.user.model.User;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table; import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Entity @Entity
@Table(name = "conference") @Table(name = "conference")
public class Conference extends BaseEntity { public class Conference extends BaseEntity {
@NotBlank
private String title;
private String description;
private String url;
private int ping;
@Column(name = "begin_date")
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date beginDate;
@Column(name = "end_date")
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date endDate;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "conference_id", unique = true)
@Fetch(FetchMode.SUBSELECT)
@OrderBy("date")
private List<Deadline> deadlines = new ArrayList<>();
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "paper_conference",
joinColumns = {@JoinColumn(name = "conference_id")},
inverseJoinColumns = {@JoinColumn(name = "paper_id")})
private Set<Paper> papers = new HashSet<>();
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "users_conference",
joinColumns = {@JoinColumn(name = "conference_id")},
inverseJoinColumns = {@JoinColumn(name = "users_id")})
private Set<User> users = new HashSet<>();
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getPing() {
return ping;
}
public void setPing(int ping) {
this.ping = ping;
}
public Date getBeginDate() {
return beginDate;
}
public void setBeginDate(Date beginDate) {
this.beginDate = beginDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public List<Deadline> getDeadlines() {
return deadlines;
}
public void setDeadlines(List<Deadline> deadlines) {
this.deadlines = deadlines;
}
public Set<Paper> getPapers() {
return papers;
}
public void setPapers(Set<Paper> papers) {
this.papers = papers;
}
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
} }

View File

@ -1,4 +1,197 @@
package ru.ulstu.conference.model; package ru.ulstu.conference.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;
import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.paper.model.PaperDto;
import ru.ulstu.user.model.UserDto;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.Size;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static ru.ulstu.core.util.StreamApiUtils.convert;
public class ConferenceDto { public class ConferenceDto {
private Integer id;
@NotEmpty
@Size(min = 2, max = 400)
private String title;
@Size(max = 500)
private String description = "";
@Size(max = 255)
private String url = "";
private int ping = 0;
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date beginDate = new Date();
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date endDate = new Date();
@NotEmpty
private List<Deadline> deadlines = new ArrayList<>();
private Set<Integer> userIds = new HashSet<>();
private Set<Integer> paperIds = new HashSet<>();
private Set<PaperDto> papers = new HashSet<>();
private Set<UserDto> users = new HashSet<>();
private Integer filterUserId;
public ConferenceDto() {
deadlines.add(new Deadline());
}
@JsonCreator
public ConferenceDto(@JsonProperty("id") Integer id,
@JsonProperty("title") String title,
@JsonProperty("description") String description,
@JsonProperty("url") String url,
@JsonProperty("ping") Integer ping,
@JsonProperty("beginDate") Date beginDate,
@JsonProperty("endDate") Date endDate,
@JsonProperty("deadlines") List<Deadline> deadlines,
@JsonProperty("userIds") Set<Integer> userIds,
@JsonProperty("paperIds") Set<Integer> paperIds,
@JsonProperty("users") Set<UserDto> users,
@JsonProperty("papers") Set<PaperDto> papers) {
this.id = id;
this.title = title;
this.description = description;
this.url = url;
this.ping = ping;
this.beginDate = beginDate;
this.endDate = endDate;
this.deadlines = deadlines;
this.userIds = userIds;
this.paperIds = paperIds;
this.users = users;
this.papers = papers;
}
public ConferenceDto(Conference conference) {
this.id = conference.getId();
this.title = conference.getTitle();
this.description = conference.getDescription();
this.url = conference.getUrl();
this.ping = conference.getPing();
this.beginDate = conference.getBeginDate();
this.endDate = conference.getEndDate();
this.deadlines = conference.getDeadlines();
this.userIds = convert(conference.getUsers(), user -> user.getId());
this.paperIds = convert(conference.getPapers(), paper -> paper.getId());
this.users = convert(conference.getUsers(), UserDto::new);
this.papers = convert(conference.getPapers(), PaperDto::new);
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getPing() {
return ping;
}
public void setPing(int ping) {
this.ping = ping;
}
public Date getBeginDate() {
return beginDate;
}
public void setBeginDate(Date beginDate) {
this.beginDate = beginDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public List<Deadline> getDeadlines() {
return deadlines;
}
public void setDeadlines(List<Deadline> deadlines) {
this.deadlines = deadlines;
}
public Set<Integer> getUserIds() {
return userIds;
}
public void setUserIds(Set<Integer> userIds) {
this.userIds = userIds;
}
public Set<Integer> getPaperIds() {
return paperIds;
}
public void setPaperIds(Set<Integer> paperIds) {
this.paperIds = paperIds;
}
public Set<PaperDto> getPapers() {
return papers;
}
public void setPapers(Set<PaperDto> papers) {
this.papers = papers;
}
public Set<UserDto> getUsers() {
return users;
}
public void setUsers(Set<UserDto> users) {
this.users = users;
}
public Integer getFilterUserId() {
return filterUserId;
}
public void setFilterUserId(Integer filterUserId) {
this.filterUserId = filterUserId;
}
} }

View File

@ -1,4 +1,47 @@
package ru.ulstu.conference.model; package ru.ulstu.conference.model;
import java.util.List;
public class ConferenceFilterDto { public class ConferenceFilterDto {
private List<ConferenceDto> conferences;
private Integer filterAuthorId;
private Integer year;
public ConferenceFilterDto() {
}
public ConferenceFilterDto(List<ConferenceDto> conferenceDtos, Integer filterAuthorId, Integer year) {
this.conferences = conferenceDtos;
this.filterAuthorId = filterAuthorId;
this.year = year;
}
public ConferenceFilterDto(List<ConferenceDto> conferenceDtos) {
this(conferenceDtos, null, null);
}
public List<ConferenceDto> getConferences() {
return conferences;
}
public void setConferences(List<ConferenceDto> conferences) {
this.conferences = conferences;
}
public Integer getFilterAuthorId() {
return filterAuthorId;
}
public void setFilterAuthorId(Integer filterAuthorId) {
this.filterAuthorId = filterAuthorId;
}
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
} }

View File

@ -1,11 +1,23 @@
package ru.ulstu.conference.service; package ru.ulstu.conference.service;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.ulstu.conference.model.Conference;
import ru.ulstu.conference.model.ConferenceDto;
import ru.ulstu.conference.repository.ConferenceRepository; import ru.ulstu.conference.repository.ConferenceRepository;
import ru.ulstu.deadline.service.DeadlineService; import ru.ulstu.deadline.service.DeadlineService;
import java.io.IOException;
import java.util.List;
import static org.springframework.util.ObjectUtils.isEmpty;
import static ru.ulstu.core.util.StreamApiUtils.convert;
@Service @Service
public class ConferenceService { public class ConferenceService {
private final static int MAX_DISPLAY_SIZE = 40;
private final ConferenceRepository conferenceRepository; private final ConferenceRepository conferenceRepository;
private final DeadlineService deadlineService; private final DeadlineService deadlineService;
@ -14,4 +26,59 @@ public class ConferenceService {
this.conferenceRepository = conferenceRepository; this.conferenceRepository = conferenceRepository;
this.deadlineService = deadlineService; this.deadlineService = deadlineService;
} }
public List<Conference> findAll() {
return conferenceRepository.findAll();
}
public List<ConferenceDto> findAllDto() {
List<ConferenceDto> conferences = convert(findAll(), ConferenceDto::new);
conferences.forEach(conferenceDto -> conferenceDto.setTitle(StringUtils.abbreviate(conferenceDto.getTitle(), MAX_DISPLAY_SIZE)));
return conferences;
}
public ConferenceDto findOneDto(Integer id) {
return new ConferenceDto(conferenceRepository.findOne(id));
}
public void save(ConferenceDto conferenceDto) throws IOException {
if (isEmpty(conferenceDto.getId())) {
create(conferenceDto);
} else {
update(conferenceDto);
}
}
@Transactional
public Integer create(ConferenceDto conferenceDto) throws IOException {
Conference newConference = copyFromDto(new Conference(), conferenceDto);
newConference = conferenceRepository.save(newConference);
return newConference.getId();
}
@Transactional
public Integer update(ConferenceDto conferenceDto) throws IOException {
Conference conference = conferenceRepository.findOne(conferenceDto.getId());
conferenceRepository.save(copyFromDto(conference, conferenceDto));
return conference.getId();
}
private Conference copyFromDto(Conference conference, ConferenceDto conferenceDto) throws IOException {
conference.setTitle(conferenceDto.getTitle());
conference.setDescription(conferenceDto.getDescription());
conference.setUrl(conferenceDto.getUrl());
conference.setPing(0);
conference.setBeginDate(conferenceDto.getBeginDate());
conference.setEndDate(conferenceDto.getEndDate());
conference.setDeadlines(deadlineService.saveOrCreate(conferenceDto.getDeadlines()));
return conference;
}
} }

View File

@ -11,12 +11,16 @@ import org.springframework.validation.annotation.Validated;
public class ApplicationProperties { public class ApplicationProperties {
@NotBlank @NotBlank
private String baseUrl; private String baseUrl;
@NotBlank @NotBlank
private String undeadUserLogin; private String undeadUserLogin;
private boolean devMode; private boolean devMode;
private boolean useHttps; private boolean useHttps;
private boolean checkRun;
public boolean isUseHttps() { public boolean isUseHttps() {
return useHttps; return useHttps;
} }
@ -48,4 +52,12 @@ public class ApplicationProperties {
public void setDevMode(boolean devMode) { public void setDevMode(boolean devMode) {
this.devMode = devMode; this.devMode = devMode;
} }
public boolean isCheckRun() {
return checkRun;
}
public void setCheckRun(boolean checkRun) {
this.checkRun = checkRun;
}
} }

View File

@ -20,7 +20,6 @@ import ru.ulstu.user.error.UserNotActivatedException;
import ru.ulstu.user.error.UserNotFoundException; import ru.ulstu.user.error.UserNotFoundException;
import ru.ulstu.user.error.UserPasswordsNotValidOrNotMatchException; import ru.ulstu.user.error.UserPasswordsNotValidOrNotMatchException;
import ru.ulstu.user.error.UserResetKeyError; import ru.ulstu.user.error.UserResetKeyError;
import ru.ulstu.user.model.User;
import ru.ulstu.user.service.UserService; import ru.ulstu.user.service.UserService;
import java.util.Set; import java.util.Set;
@ -28,7 +27,6 @@ import java.util.stream.Collectors;
@ControllerAdvice @ControllerAdvice
public class AdviceController { public class AdviceController {
private final static String USER_NAME_TEMPLATE = "%s %s %s";
private final Logger log = LoggerFactory.getLogger(AdviceController.class); private final Logger log = LoggerFactory.getLogger(AdviceController.class);
private final UserService userService; private final UserService userService;
@ -38,11 +36,7 @@ public class AdviceController {
@ModelAttribute("currentUser") @ModelAttribute("currentUser")
public String getCurrentUser() { public String getCurrentUser() {
User user = userService.getCurrentUser(); return userService.getCurrentUser().getUserAbbreviate();
return String.format(USER_NAME_TEMPLATE,
user.getLastName(),
user.getFirstName().substring(0, 1),
user.getPatronymic().substring(0, 1));
} }
private Response<Void> handleException(ErrorConstants error) { private Response<Void> handleException(ErrorConstants error) {

View File

@ -0,0 +1,19 @@
package ru.ulstu.core.controller;
import org.springframework.validation.Errors;
public class Navigation {
public static final String REDIRECT_TO = "redirect:%s";
public static final String GRANTS_PAGE = "/grants/grants";
public static final String GRANT_PAGE = "/grants/grant";
public static final String CONFERENCES_PAGE = "/conferences/conferences";
public static final String CONFERENCE_PAGE = "/conferences/conference";
public static String hasErrors(Errors errors, String page) {
if (errors.hasErrors()) {
return page;
}
return null;
}
}

View File

@ -23,10 +23,9 @@ import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static org.springframework.util.StringUtils.isEmpty; import static org.springframework.util.StringUtils.isEmpty;
import static ru.ulstu.grant.controller.Navigation.GRANTS_PAGE; import static ru.ulstu.core.controller.Navigation.GRANTS_PAGE;
import static ru.ulstu.grant.controller.Navigation.GRANT_PAGE; import static ru.ulstu.core.controller.Navigation.GRANT_PAGE;
import static ru.ulstu.grant.controller.Navigation.REDIRECT_TO; import static ru.ulstu.core.controller.Navigation.REDIRECT_TO;
@Controller() @Controller()
@RequestMapping(value = "/grants") @RequestMapping(value = "/grants")

View File

@ -1,7 +0,0 @@
package ru.ulstu.grant.controller;
public class Navigation {
public static final String REDIRECT_TO = "redirect:%s";
public static final String GRANTS_PAGE = "/grants/grants";
public static final String GRANT_PAGE = "/grants/grant";
}

View File

@ -9,21 +9,6 @@ import ru.ulstu.user.model.User;
import java.util.List; import java.util.List;
public interface GrantRepository extends JpaRepository<Grant, Integer> { public interface GrantRepository extends JpaRepository<Grant, Integer> {
// @Query(value = "SELECT u.last_name " +
// "FROM users u, grants g " +
// "WHERE (g.leader_id = u.id) " +
// "AND (u.birth_date < 35) " +
// "AND (u.degree = 'CANDIDATE')" +
// "Group by u.last_name",
// nativeQuery = true)
// List<User> filter(@Param("leader") Integer leader, @Param("birthYear") Date birthYear, @Param("degree") String degree);
@Query("SELECT u.lastName FROM User u, Grant g WHERE (g.leader = u.id OR :leader IS FALSE) " +
"AND (extract(year from interval (age(birth_date::date))) < 35 OR :birthDate IS FALSE) " +
"AND (u.degree = 'CANDIDATE' OR :degree IS FALSE)" +
"GROUP BY u.lastName")
List<User> filterUsers(@Param("leader") boolean leader,
@Param("birthDate") boolean birthDate,
@Param("degree") boolean degree);
List<Grant> findByStatus(Grant.GrantStatus status);
} }

View File

@ -21,6 +21,7 @@ import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
import static org.springframework.util.ObjectUtils.isEmpty; import static org.springframework.util.ObjectUtils.isEmpty;
import static ru.ulstu.core.util.StreamApiUtils.convert; import static ru.ulstu.core.util.StreamApiUtils.convert;
@ -145,7 +146,20 @@ public class GrantService {
} }
public List<UserDto> filterUsers(GrantUserFilterDto filterDto) { public List<UserDto> filterUsers(GrantUserFilterDto filterDto) {
return convert(grantRepository.filterUsers( List<User> filteredUsers = userService.filterByAgeAndDegree(filterDto.isBirthDate(), filterDto.isDegree());
filterDto.isLeader(), filterDto.isBirthDate(), filterDto.isDegree()), UserDto::new); if (filterDto.isLeader()) {
filteredUsers = filteredUsers
.stream()
.filter(getCompletedGrantLeaders()::contains)
.collect(Collectors.toList());
}
return convert(filteredUsers, UserDto::new);
}
private List<User> getCompletedGrantLeaders() {
return grantRepository.findByStatus(Grant.GrantStatus.COMPLETED)
.stream()
.map(Grant::getLeader)
.collect(Collectors.toList());
} }
} }

View File

@ -51,7 +51,7 @@ public class PaperController {
@GetMapping("/dashboard") @GetMapping("/dashboard")
public void getDashboard(ModelMap modelMap) { public void getDashboard(ModelMap modelMap) {
modelMap.put("papers", paperService.findAllActive()); modelMap.put("papers", paperService.findAllActiveDto());
} }
@GetMapping("/paper") @GetMapping("/paper")

View File

@ -61,4 +61,9 @@ public class PaperRestController {
public Response<List<PaperDto>> filter(@RequestBody @Valid PaperFilterDto paperFilterDto) throws IOException { public Response<List<PaperDto>> filter(@RequestBody @Valid PaperFilterDto paperFilterDto) throws IOException {
return new Response<>(paperService.filter(paperFilterDto)); return new Response<>(paperService.filter(paperFilterDto));
} }
@GetMapping("formatted-list")
public Response<List<String>> getFormattedPaperList() {
return new Response<>(paperService.getFormattedPaperList());
}
} }

View File

@ -21,6 +21,7 @@ import java.util.Date;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toList;
import static org.springframework.util.ObjectUtils.isEmpty; import static org.springframework.util.ObjectUtils.isEmpty;
@ -34,6 +35,7 @@ import static ru.ulstu.paper.model.Paper.PaperStatus.ON_PREPARATION;
@Service @Service
public class PaperService { public class PaperService {
private final static int MAX_DISPLAY_SIZE = 40; private final static int MAX_DISPLAY_SIZE = 40;
private final static String PAPER_FORMATTED_TEMPLATE = "%s %s";
private final PaperNotificationService paperNotificationService; private final PaperNotificationService paperNotificationService;
private final PaperRepository paperRepository; private final PaperRepository paperRepository;
@ -66,13 +68,17 @@ public class PaperService {
return papers; return papers;
} }
public List<PaperDto> findAllActive() { public List<Paper> findAllActive() {
return findAllDto() return findAll()
.stream() .stream()
.filter(paper -> paper.getStatus() != COMPLETED && paper.getStatus() != FAILED) .filter(paper -> paper.getStatus() != COMPLETED && paper.getStatus() != FAILED)
.collect(toList()); .collect(toList());
} }
public List<PaperDto> findAllActiveDto() {
return convert(findAllActive(), PaperDto::new);
}
public PaperDto findOneDto(Integer id) { public PaperDto findOneDto(Integer id) {
return new PaperDto(paperRepository.findOne(id)); return new PaperDto(paperRepository.findOne(id));
} }
@ -212,4 +218,25 @@ public class PaperService {
public List<User> getPaperAuthors() { public List<User> getPaperAuthors() {
return userService.findAll(); return userService.findAll();
} }
public List<String> getFormattedPaperList() {
return findAllCompleted()
.stream()
.map(paper -> String.format(PAPER_FORMATTED_TEMPLATE, paper.getTitle(), getAuthors(paper)))
.collect(toList());
}
private List<Paper> findAllCompleted() {
return findAll()
.stream()
.filter(paper -> paper.getStatus() == COMPLETED)
.collect(toList());
}
private String getAuthors(Paper paper) {
return paper.getAuthors()
.stream()
.map(User::getUserAbbreviate)
.collect(Collectors.joining(", "));
}
} }

View File

@ -26,6 +26,8 @@ import java.util.Set;
@Entity @Entity
@Table(name = "users") @Table(name = "users")
public class User extends BaseEntity { public class User extends BaseEntity {
private final static String USER_ABBREVIATE_TEMPLATE = "%s %s%s";
@NotNull @NotNull
@Pattern(regexp = Constants.LOGIN_REGEX) @Pattern(regexp = Constants.LOGIN_REGEX)
@Size(min = 1, max = 50) @Size(min = 1, max = 50)
@ -226,4 +228,11 @@ public class User extends BaseEntity {
public void setDegree(UserDegree degree) { public void setDegree(UserDegree degree) {
this.degree = degree; this.degree = degree;
} }
public String getUserAbbreviate() {
return String.format(USER_ABBREVIATE_TEMPLATE,
lastName == null ? "" : lastName,
firstName == null ? "" : firstName.substring(0, 1) + ".",
patronymic == null ? "" : patronymic.substring(0, 1) + ".");
}
} }

View File

@ -2,6 +2,8 @@ package ru.ulstu.user.repository;
import org.springframework.data.jpa.repository.EntityGraph; import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import ru.ulstu.user.model.User; import ru.ulstu.user.model.User;
import java.util.Date; import java.util.Date;
@ -25,4 +27,11 @@ public interface UserRepository extends JpaRepository<User, Integer> {
@EntityGraph(attributePaths = "roles") @EntityGraph(attributePaths = "roles")
User findOneWithRolesByLogin(String login); User findOneWithRolesByLogin(String login);
@Query("SELECT u FROM User u " +
"WHERE (YEAR(u.birthDate) - YEAR(CURRENT_DATE) < 35 OR :hasAge = FALSE) " +
"AND (u.degree = 'CANDIDATE' OR :hasDegree = FALSE)" +
"ORDER BY u.lastName")
List<User> filterByAgeAndDegree(@Param("hasAge") boolean hasAge,
@Param("hasDegree") boolean hasDegree);
} }

View File

@ -324,4 +324,8 @@ public class UserService implements UserDetailsService {
} }
return user; return user;
} }
public List<User> filterByAgeAndDegree(boolean hasDegree, boolean hasAge) {
return userRepository.filterByAgeAndDegree(hasDegree, hasAge);
}
} }

View File

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

View File

@ -14,12 +14,12 @@
<changeSet author="tanya" id="20190402_000000-2"> <changeSet author="tanya" id="20190402_000000-2">
<createTable tableName="grants_authors"> <createTable tableName="grants_authors">
<column name="grant_id" type="integer"/> <column name="grant_id" type="integer"/>
<column name="author_id" type="integer"/> <column name="authors_id" type="integer"/>
</createTable> </createTable>
<addForeignKeyConstraint baseTableName="grants_authors" baseColumnNames="grant_id" <addForeignKeyConstraint baseTableName="grants_authors" baseColumnNames="grant_id"
constraintName="fk_grants_grants_authors" referencedTableName="grant" constraintName="fk_grants_grants_authors" referencedTableName="grants"
referencedColumnNames="id"/> referencedColumnNames="id"/>
<addForeignKeyConstraint baseTableName="grants_authors" baseColumnNames="author_id" <addForeignKeyConstraint baseTableName="grants_authors" baseColumnNames="authors_id"
constraintName="fk_user_grants_authors" referencedTableName="users" constraintName="fk_user_grants_authors" referencedTableName="users"
referencedColumnNames="id"/> referencedColumnNames="id"/>
</changeSet> </changeSet>

View File

@ -24,4 +24,6 @@
<include file="db/changelog-20190331_000000-schema.xml"/> <include file="db/changelog-20190331_000000-schema.xml"/>
<include file="db/changelog-20190331_000010-schema.xml"/> <include file="db/changelog-20190331_000010-schema.xml"/>
<include file="db/common/changelog-20190312_130000-schema.xml"/> <include file="db/common/changelog-20190312_130000-schema.xml"/>
<include file="db/changelog-20190402_000000-schema.xml"/>
<include file="db/changelog-20190404_000000-schema.xml"/>
</databaseChangeLog> </databaseChangeLog>

View File

@ -777,11 +777,25 @@ ul.social-buttons li a:active, ul.social-buttons li a:focus, ul.social-buttons l
box-shadow: 0 5px 20px rgba(0, 0, 0, 0.05); box-shadow: 0 5px 20px rgba(0, 0, 0, 0.05);
} }
@media (min-width: 1500px) {
.col-xl-3 {
max-width: 20%;
}
.container {
max-width: 1340px;
}
}
.toolbar-button { .toolbar-button {
width: 100%; width: 100%;
margin: 5px; margin: 5px;
} }
.img-fluid {
width: 100% !important;
}
/* --------------------------------------------------- /* ---------------------------------------------------
FEEDBACK STYLE FEEDBACK STYLE
----------------------------------------------------- */ ----------------------------------------------------- */

View File

@ -18,47 +18,61 @@
<hr/> <hr/>
<div class="row"> <div class="row">
<div class="col-lg-12"> <div class="col-lg-12">
<form id="conference-form" method="post"> <form id="conference-form" method="post"
th:action="@{'/conferences/conference?id='+ *{id == null ? '' : id} + ''}"
th:object="${conferenceDto}">
<div class="row"> <div class="row">
<div class="col-md-7 col-sm-12"> <div class="col-md-7 col-sm-12">
<input type="hidden" name="id"/> <input type="hidden" name="id" th:field="*{id}"/>
<div class="form-group"> <div class="form-group">
<label for="title">Название:</label> <label for="title">Название:</label>
<input class="form-control" id="title" type="text" <input class="form-control" th:field="*{title}" id="title" type="text"
placeholder="Название конференции"/> placeholder="Название конференции"/>
<p th:if="${#fields.hasErrors('title')}" th:errors="*{title}"
class="alert alert-danger">Incorrect title</p>
<p class="help-block text-danger"></p>
</div> </div>
<div class="form-group"> <div class="form-group">
<label for="url">URL:</label> <label for="url">URL:</label>
<input class="form-control" id="url" type="text" <input class="form-control" th:field="*{url}" id="url" type="text"
placeholder="URL адрес"/> placeholder="URL адрес"/>
</div> </div>
<div class="form-group"> <div class="form-group">
<label for="description">Описание:</label> <label for="description">Описание:</label>
<textarea class="form-control" rows="8" id="description"> <textarea class="form-control" rows="8" th:field="*{description}" id="description">
</textarea> </textarea>
</div> </div>
<div class="form-group"> <div class="form-group">
<label for="deadlines">Дедлайны:</label> <label for="deadlines">Дедлайны:</label>
<div class="deadline-list form-control list-group" id="deadlines"> <div class="deadline-list form-control list-group" id="deadlines">
<div class="deadline d-flex p-0 list-group-item list-group-horizontal"
<div class="deadline d-flex p-0 list-group-item list-group-horizontal"> th:each="deadline, rowStat : *{deadlines}">
<input type="hidden" th:field="*{deadlines[__${rowStat.index}__].id}"/>
<input class="deadline-text col-md list-group-item" type="text" <input class="deadline-text col-md list-group-item" type="text"
placeholder="Текст дедлайна"/> placeholder="Описание"
<input class="list-group-item" type="date"/> th:field="*{deadlines[__${rowStat.index}__].description}"/>
<input class="list-group-item" type="date" name="deadline"
th:field="*{deadlines[__${rowStat.index}__].date}"/>
<img class="icon icon-delete grey-border" src="/img/conference/delete.png" <img class="icon icon-delete grey-border" src="/img/conference/delete.png"
alt="Удалить"/> alt="Удалить"
th:onclick="|$('#deadlines${rowStat.index}\\.description').val('');
$('#deadlines${rowStat.index}\\.date').val('');
$('#addDeadline').click();|"/>
</div> </div>
</div> </div>
</div> </div>
<p th:if="${#fields.hasErrors('deadlines')}" th:errors="*{deadlines}"
class="alert alert-danger">Incorrect title</p>
<p class="help-block text-danger"></p>
<div class="form-group d-flex justify-content-end"> <div class="form-group d-flex justify-content-end">
<input type="submit" id="add-deadline" name="add-deadline" <input type="submit" id="addDeadline" name="addDeadline"
class="btn btn-primary" class="btn btn-primary"
value="Добавить дедлайн"/> value="Добавить дедлайн"/>
</div> </div>
@ -70,11 +84,13 @@
<div class="row" id="dates"> <div class="row" id="dates">
<div class="d-flex col justify-content-between dates-panel"> <div class="d-flex col justify-content-between dates-panel">
<div class="date"> <div class="date">
<input class="grey-border form-control" type="date" id="date-begin"/> <input class="grey-border form-control" type="date"
th:field="*{beginDate}" id="begin-date"/>
</div> </div>
<div class="date"> <div class="date">
<input class="grey-border form-control" type="date" id="date-end"/> <input class="grey-border form-control" type="date"
th:field="*{endDate}" id="end-date"/>
</div> </div>
</div> </div>
</div> </div>

View File

@ -7,7 +7,7 @@
<body> <body>
<div layout:fragment="content"> <div layout:fragment="content">
<form id="conferences-form" method="post"> <form id="conferences-form" method="post" th:action="@{'/conferences/conferences'}">
<section id="conferences"> <section id="conferences">
<div class="container"> <div class="container">
<div class="row" id="conference-list"> <div class="row" id="conference-list">
@ -19,7 +19,9 @@
<hr/> <hr/>
<div class="row"> <div class="row">
<div class="col-md-9 col-sm-12"> <div class="col-md-9 col-sm-12">
<th:block th:each="conference : ${filteredConferences.conferences}">
<div th:replace="conferences/fragments/confLineFragment :: confLine(conference=${conference})"/>
</th:block>
</div> </div>
<div class="col-md-3 col-sm-12"> <div class="col-md-3 col-sm-12">
<div class="filter"> <div class="filter">

View File

@ -6,9 +6,8 @@
<body> <body>
<div th:fragment="confLine (conference)" class="row text-left paper-row" style="background-color: white;"> <div th:fragment="confLine (conference)" class="row text-left paper-row" style="background-color: white;">
<div class="col"> <div class="col">
<a href="/conference"> <a th:href="@{'conference?id='+${conference.id}}">
<span class="h6"></span> <span class="h6" th:text="${conference.title}"/>
<span class="text-muted"></span>
</a> </a>
<input class="id-class" type="hidden"/> <input class="id-class" type="hidden"/>
<a class="remove-paper pull-right d-none" <a class="remove-paper pull-right d-none"

View File

@ -21,7 +21,7 @@
<div class="col-12 col-sm-12 col-md-12 col-lg-4 col-xl-3"> <div class="col-12 col-sm-12 col-md-12 col-lg-4 col-xl-3">
<a href="./conference?id=0" class="btn btn-light toolbar-button"> <a href="./conference?id=0" class="btn btn-light toolbar-button">
<i class="fa fa-plus-circle" aria-hidden="true"></i> <i class="fa fa-plus-circle" aria-hidden="true"></i>
Добавить конференцию</a> Новая конференцию</a>
</div> </div>
</div> </div>