add paper create strategy

This commit is contained in:
Anton Romanov 2018-11-08 19:36:50 +04:00
parent def4f97784
commit bd78be93ab
12 changed files with 184 additions and 21 deletions

View File

@ -17,6 +17,8 @@ class ControllersConfiguration {
config.addAllowedHeader("*"); config.addAllowedHeader("*");
config.addAllowedMethod("GET"); config.addAllowedMethod("GET");
config.addAllowedMethod("POST"); config.addAllowedMethod("POST");
config.addAllowedMethod("PUT");
config.addAllowedMethod("OPTIONAL");
config.addAllowedMethod("DELETE"); config.addAllowedMethod("DELETE");
source.registerCorsConfiguration("/**", config); source.registerCorsConfiguration("/**", config);
return new CorsFilter(source); return new CorsFilter(source);

View File

@ -0,0 +1,9 @@
package ru.ulstu.core.model;
import ru.ulstu.user.model.User;
import java.util.List;
public interface UserContainer {
List<User> getUsers();
}

View File

@ -43,4 +43,10 @@ public class DateUtils {
public static Date localTimeToDate(LocalTime localTime) { public static Date localTimeToDate(LocalTime localTime) {
return Date.from(localTime.atDate(LocalDate.now()).atZone(ZoneId.systemDefault()).toInstant()); return Date.from(localTime.atDate(LocalDate.now()).atZone(ZoneId.systemDefault()).toInstant());
} }
public static Date addDays(Date date, int count) {
Calendar cal = getCalendar(date);
cal.add(Calendar.DAY_OF_MONTH, count);
return cal.getTime();
}
} }

View File

@ -32,7 +32,7 @@ public class PaperController {
@GetMapping @GetMapping
public Response<List<PaperDto>> getPapers() { public Response<List<PaperDto>> getPapers() {
return new Response<>(paperService.findAll()); return new Response<>(paperService.findAllDto());
} }
@PostMapping @PostMapping

View File

@ -2,15 +2,17 @@ package ru.ulstu.paper.model;
import org.hibernate.validator.constraints.NotBlank; import org.hibernate.validator.constraints.NotBlank;
import ru.ulstu.core.model.BaseEntity; import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.core.model.UserContainer;
import ru.ulstu.file.model.FileData; import ru.ulstu.file.model.FileData;
import ru.ulstu.user.model.User; import ru.ulstu.user.model.User;
import javax.persistence.*; import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
@Entity @Entity
public class Paper extends BaseEntity { public class Paper extends BaseEntity implements UserContainer {
public enum PaperStatus { public enum PaperStatus {
ATTENTION("Обратить внимание"), ON_PREPARATION("На подготовке"), DRAFT("Черновик"), COMPLETED("Завершена"); ATTENTION("Обратить внимание"), ON_PREPARATION("На подготовке"), DRAFT("Черновик"), COMPLETED("Завершена");
@ -29,27 +31,27 @@ public class Paper extends BaseEntity {
private String title; private String title;
@Enumerated(value = EnumType.STRING) @Enumerated(value = EnumType.STRING)
private PaperStatus status; private PaperStatus status = PaperStatus.DRAFT;
@Column(name = "create_date") @Column(name = "create_date")
private Date createDate; private Date createDate = new Date();
@Column(name = "update_date") @Column(name = "update_date")
private Date updateDate; private Date updateDate = new Date();
@Column(name = "deadline_date") @Column(name = "deadline_date")
private Date deadlineDate; private Date deadlineDate;
private String comment; private String comment;
private Boolean locked; private Boolean locked = false;
@ManyToOne @ManyToOne
@JoinColumn(name = "file_id") @JoinColumn(name = "file_id")
private FileData fileData; private FileData fileData;
@ManyToMany @ManyToMany(fetch = FetchType.EAGER)
private List<User> authors; private List<User> authors = new ArrayList<>();
public PaperStatus getStatus() { public PaperStatus getStatus() {
return status; return status;
@ -122,4 +124,9 @@ public class Paper extends BaseEntity {
public void setAuthors(List<User> authors) { public void setAuthors(List<User> authors) {
this.authors = authors; this.authors = authors;
} }
@Override
public List<User> getUsers() {
return getAuthors();
}
} }

View File

@ -1,5 +1,6 @@
package ru.ulstu.paper.service; package ru.ulstu.paper.service;
import com.google.common.collect.ImmutableMap;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import ru.ulstu.file.service.FileService; import ru.ulstu.file.service.FileService;
@ -7,22 +8,24 @@ import ru.ulstu.paper.model.Paper;
import ru.ulstu.paper.model.PaperDto; import ru.ulstu.paper.model.PaperDto;
import ru.ulstu.paper.model.PaperStatusDto; import ru.ulstu.paper.model.PaperStatusDto;
import ru.ulstu.paper.repository.PaperRepository; import ru.ulstu.paper.repository.PaperRepository;
import ru.ulstu.user.model.User;
import ru.ulstu.user.model.UserDto; import ru.ulstu.user.model.UserDto;
import ru.ulstu.user.service.MailService; import ru.ulstu.user.service.MailService;
import java.io.IOException; import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static ru.ulstu.core.util.StreamApiUtils.convert; import static ru.ulstu.core.util.StreamApiUtils.convert;
@Service @Service
public class PaperService { public class PaperService {
public final MailService mailService;
private final PaperRepository paperRepository; private final PaperRepository paperRepository;
private final FileService fileService; private final FileService fileService;
public final MailService mailService;
public PaperService(PaperRepository paperRepository, public PaperService(PaperRepository paperRepository,
@ -32,9 +35,8 @@ public class PaperService {
this.mailService = mailService; this.mailService = mailService;
} }
public List<PaperDto> findAll() { public List<Paper> findAll() {
List<Paper> allPapers = paperRepository.findAll(); return paperRepository.findAll().stream().sorted((paper1, paper2) -> {
allPapers = allPapers.stream().sorted((paper1, paper2) -> {
int statusCompareResult = int statusCompareResult =
Integer.valueOf(Arrays.asList(Paper.PaperStatus.values()).indexOf(paper1.getStatus())) Integer.valueOf(Arrays.asList(Paper.PaperStatus.values()).indexOf(paper1.getStatus()))
.compareTo(Integer.valueOf(Arrays.asList(Paper.PaperStatus.values()).indexOf(paper2.getStatus()))); .compareTo(Integer.valueOf(Arrays.asList(Paper.PaperStatus.values()).indexOf(paper2.getStatus())));
@ -43,7 +45,10 @@ public class PaperService {
} }
return paper1.getTitle().compareTo(paper2.getTitle()); return paper1.getTitle().compareTo(paper2.getTitle());
}).collect(Collectors.toList()); }).collect(Collectors.toList());
return convert(allPapers, PaperDto::new); }
public List<PaperDto> findAllDto() {
return convert(findAll(), PaperDto::new);
} }
@Transactional @Transactional
@ -67,8 +72,8 @@ public class PaperService {
@Transactional @Transactional
public Integer update(PaperDto paperDto) throws IOException { public Integer update(PaperDto paperDto) throws IOException {
Paper paper = paperRepository.findOne(paperDto.getId()); Paper paper = paperRepository.findOne(paperDto.getId());
if(paper != null && paper.getStatus() != paperDto.getStatus()){ if (paper != null && paper.getStatus() != paperDto.getStatus()) {
sendMessageAboutStatusChange(paper.getStatus(),paperDto); sendMessageAboutStatusChange(paper.getStatus(), paperDto);
} }
if (paperDto.getTmpFileName() != null && paper.getFileData() != null) { if (paperDto.getTmpFileName() != null && paper.getFileData() != null) {
fileService.deleteFile(paper.getFileData()); fileService.deleteFile(paper.getFileData());
@ -86,14 +91,30 @@ public class PaperService {
} }
public List<PaperStatusDto> getPaperStatuses() { public List<PaperStatusDto> getPaperStatuses() {
return convert(Arrays.asList(Paper.PaperStatus.values()), status ->new PaperStatusDto(status)); return convert(Arrays.asList(Paper.PaperStatus.values()), status -> new PaperStatusDto(status));
} }
private void sendMessageAboutStatusChange(Paper.PaperStatus oldStatus, PaperDto paper){ private void sendMessageAboutStatusChange(Paper.PaperStatus oldStatus, PaperDto paper) {
for (UserDto user: paper.getAuthors()) { for (UserDto user : paper.getAuthors()) {
mailService.sendEmail(user.getEmail(), "Обновление статуса статьи", mailService.sendEmail(user.getEmail(), "Обновление статуса статьи",
"Статус статьи " + paper.getTitle() + " сменился с " + oldStatus.getName() "Статус статьи " + paper.getTitle() + " сменился с " + oldStatus.getName()
+ " на " + paper.getStatus().getName()); + " на " + paper.getStatus().getName());
} }
} }
@Transactional
public Paper create(String title, User user, Date deadlineDate) {
Paper paper = new Paper();
paper.setTitle(title);
paper.getAuthors().add(user);
paper.setDeadlineDate(deadlineDate);
paper.setCreateDate(new Date());
paper.setUpdateDate(new Date());
paper.setStatus(Paper.PaperStatus.DRAFT);
paper = paperRepository.save(paper);
Map<String, Object> variables = ImmutableMap.of("paper", paper);
mailService.sendEmailFromTemplate(variables, user, "paperCreateNotification", "Создана статья");
return paper;
}
} }

View File

@ -0,0 +1,28 @@
package ru.ulstu.strategy.api;
import ru.ulstu.core.model.UserContainer;
import ru.ulstu.user.model.User;
import java.util.List;
import java.util.stream.Collectors;
public abstract class EntityCreateStrategy<T extends UserContainer> {
protected abstract List<T> getActiveEntities();
protected abstract void createEntity(User user);
protected void createDefaultEntityIfNeed(List<User> allUsers, List<? extends UserContainer> entities) {
allUsers.forEach(user -> {
if (entities
.stream()
.filter(entity -> entity.getUsers().contains(user))
.collect(Collectors.toSet()).isEmpty()) {
createEntity(user);
}
});
}
public void createEntityIfNeed(List<User> allUsers) {
createDefaultEntityIfNeed(allUsers, getActiveEntities());
}
}

View File

@ -0,0 +1,35 @@
package ru.ulstu.strategy.api;
import org.springframework.stereotype.Service;
import ru.ulstu.core.util.DateUtils;
import ru.ulstu.paper.model.Paper;
import ru.ulstu.paper.service.PaperService;
import ru.ulstu.user.model.User;
import ru.ulstu.user.service.UserService;
import java.util.Date;
import java.util.List;
@Service
public class PaperCreateStrategy extends EntityCreateStrategy<Paper> {
private static final String DEFAULT_NAME = "Статья создана автоматически";
private static final int DEFAULT_DEADLINE_DAYS = 14;
private final PaperService paperService;
private final UserService userService;
public PaperCreateStrategy(PaperService paperService,
UserService userService) {
this.paperService = paperService;
this.userService = userService;
}
@Override
protected List<Paper> getActiveEntities() {
return paperService.findAll();
}
@Override
protected void createEntity(User user) {
paperService.create(DEFAULT_NAME, user, DateUtils.addDays(new Date(), DEFAULT_DEADLINE_DAYS));
}
}

View File

@ -0,0 +1,26 @@
package ru.ulstu.strategy.api;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import ru.ulstu.user.service.UserService;
import java.util.List;
@Service
public class StrategyEntityCreateExecutor {
private final List<EntityCreateStrategy> entityCreateStrategies;
private final UserService userService;
public StrategyEntityCreateExecutor(List<EntityCreateStrategy> entityCreateStrategies,
UserService userService) {
this.entityCreateStrategies = entityCreateStrategies;
this.userService = userService;
}
//@Scheduled(cron = "0 0 8 * * *")
@Scheduled(cron = "0 */5 * * * *")
public void scheduleExecuteStrategies() {
entityCreateStrategies.forEach(strategy -> strategy.createEntityIfNeed(userService.findAll()));
}
}

View File

@ -77,6 +77,11 @@ public class UserService implements UserDetailsService {
return new PageableItems<>(page.getTotalElements(), userMapper.userEntitiesToUserListDtos(page.getContent())); return new PageableItems<>(page.getTotalElements(), userMapper.userEntitiesToUserListDtos(page.getContent()));
} }
// TODO: read only active users
public List<User> findAll() {
return userRepository.findAll();
}
@Transactional(readOnly = true) @Transactional(readOnly = true)
public PageableItems<UserRoleDto> getUserRoles() { public PageableItems<UserRoleDto> getUserRoles() {
final List<UserRoleDto> roles = userRoleRepository.findAll().stream() final List<UserRoleDto> roles = userRoleRepository.findAll().stream()

View File

@ -16,8 +16,8 @@ logging.level.ru.ulstu=DEBUG
# Mail Settings # Mail Settings
spring.mail.host=smtp.yandex.ru spring.mail.host=smtp.yandex.ru
spring.mail.port=465 spring.mail.port=465
spring.mail.username=balance@soft.kitchen spring.mail.username=nio17.ulstu@yandex.ru
spring.mail.password=fkvfpbalance spring.mail.password=nio17.ulstu.ru
spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.ssl.enable=true spring.mail.properties.mail.smtp.ssl.enable=true
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory

View File

@ -0,0 +1,24 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Уведомление о создании статьи</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="shortcut icon" th:href="@{|${baseUrl}/favicon.ico|}"/>
</head>
<body>
<p>
Уважаемый(ая) <span th:text="${user.firstName + ' ' + user.lastName}">Ivan Ivanov</span>
</p>
<p>
Вам нужно поработать над статьей "<span th:text="${paper.title}">Title</span>".
</p>
<p>
Срок исполнения: <span th:text="${#dates.format(paper.deadlineDate, 'dd.MM.yyyy HH:mm')}"></span>.
</p>
<p>
Regards,
<br/>
<em>NG-tracker.</em>
</p>
</body>
</html>